Skip to content

Commit

Permalink
only notify change when kube config exists, isnt empty and complete (#…
Browse files Browse the repository at this point in the history
…190)

Signed-off-by: Andre Dietisheim <[email protected]>
  • Loading branch information
adietish committed Jul 26, 2023
1 parent f766930 commit 1403c31
Showing 1 changed file with 36 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,19 @@

import com.intellij.openapi.diagnostic.Logger;
import io.fabric8.kubernetes.api.model.Config;
import io.fabric8.kubernetes.client.internal.KubeConfigUtils;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.function.Consumer;

public class ConfigWatcher implements Runnable {

Expand All @@ -43,8 +46,7 @@ public ConfigWatcher(Path config, Listener listener) {

@Override
public void run() {
runOnConfigChange(() -> {
Config config = loadConfig();
runOnConfigChange((Config config) -> {
if (config != null) {
listener.onUpdate(this, config);
}
Expand All @@ -59,14 +61,13 @@ protected Config loadConfig() {
}
}

private void runOnConfigChange(Runnable runnable) {
private void runOnConfigChange(Consumer<Config> consumer) {
try (WatchService service = newWatchService()) {
registerWatchService(service);
WatchKey key;
while ((key = service.take()) != null) {
key.pollEvents().stream()
.filter(this::isConfigPath)
.forEach((Void) -> runnable.run());
.forEach((event) -> consumer.accept(loadConfig(getPath(event))));
key.reset();
}
} catch (IOException | InterruptedException e) {
Expand All @@ -90,11 +91,39 @@ private void registerWatchService(WatchService service) throws IOException {
service);
}

protected boolean isConfigPath(WatchEvent<?> event) {
Path path = getWatchedPath().resolve((Path) event.context());
protected boolean isConfigPath(Path path) {
return path.equals(config);
}

/**
* Returns {@link Config} for the given path if the kube config file
* <ul>
* <li>exists and</li>
* <li>is not empty and</li>
* <li>is valid yaml</li>
* </ul>
* Returns {@code null} otherwise.
*
* @param path the path to the kube config
* @return returns true if the kube config that the event points to exists, is not empty and is valid yaml
*/
private Config loadConfig(Path path) {
try {
if (Files.exists(path)
&& isConfigPath(path)
&& Files.size(path) > 0) {
return KubeConfigUtils.parseConfig(path.toFile());
}
} catch (Exception e) {
// only catch
}
return null;
}

private Path getPath(WatchEvent<?> event) {
return getWatchedPath().resolve((Path) event.context());
}

private Path getWatchedPath() {
return config.getParent();
}
Expand Down

0 comments on commit 1403c31

Please sign in to comment.