From 425a32044b65f0f0f0e71eeb2d79242a6101f058 Mon Sep 17 00:00:00 2001 From: Nikola Grcevski <6207777+grcevski@users.noreply.github.com> Date: Wed, 17 Aug 2022 13:02:29 -0400 Subject: [PATCH] Clean-up file watcher keys. (#89429) Clean-up all open watcher keys in FileSettingsService. --- .../service/FileSettingsService.java | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/reservedstate/service/FileSettingsService.java b/server/src/main/java/org/elasticsearch/reservedstate/service/FileSettingsService.java index 627ff1141c5d2..7dd98e0b180be 100644 --- a/server/src/main/java/org/elasticsearch/reservedstate/service/FileSettingsService.java +++ b/server/src/main/java/org/elasticsearch/reservedstate/service/FileSettingsService.java @@ -63,6 +63,7 @@ public class FileSettingsService extends AbstractLifecycleComponent implements C private volatile FileUpdateState fileUpdateState = null; private volatile WatchKey settingsDirWatchKey = null; + private volatile WatchKey configDirWatchKey = null; private volatile boolean active = false; private volatile boolean initialState = true; @@ -207,6 +208,17 @@ boolean watching() { return this.watchService != null; } + private void cleanupWatchKeys() { + if (settingsDirWatchKey != null) { + settingsDirWatchKey.cancel(); + settingsDirWatchKey = null; + } + if (configDirWatchKey != null) { + configDirWatchKey.cancel(); + configDirWatchKey = null; + } + } + synchronized void startWatcher(ClusterState clusterState, boolean onStartup) { if (watching() || active == false) { refreshExistingFileStateIfNeeded(clusterState); @@ -246,10 +258,11 @@ synchronized void startWatcher(ClusterState clusterState, boolean onStartup) { // We watch the config directory always, even if initially we had an operator directory // it can be deleted and created later. The config directory never goes away, we only // register it once for watching. - enableSettingsWatcher(null, operatorSettingsDir().getParent()); + configDirWatchKey = enableSettingsWatcher(configDirWatchKey, operatorSettingsDir().getParent()); } catch (Exception e) { if (watchService != null) { try { + cleanupWatchKeys(); this.watchService.close(); } catch (Exception ignore) {} finally { this.watchService = null; @@ -323,10 +336,7 @@ synchronized void stopWatcher() { logger.debug("stopping watcher ..."); if (watching()) { try { - if (settingsDirWatchKey != null) { - settingsDirWatchKey.cancel(); - settingsDirWatchKey = null; - } + cleanupWatchKeys(); fileUpdateState = null; watchService.close(); if (watcherThreadLatch != null) {