Skip to content

Commit 675ad33

Browse files
authored
Merge pull request #1332 from iyashu/fix-reflector-shutdown
fix reflector graceful shutdown by closing underlying watch
2 parents 7488415 + 5f377e6 commit 675ad33

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

util/src/main/java/io/kubernetes/client/informer/cache/ReflectorRunnable.java

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import io.kubernetes.client.openapi.models.V1ObjectMeta;
2121
import io.kubernetes.client.util.CallGeneratorParams;
2222
import io.kubernetes.client.util.Watchable;
23+
import java.io.IOException;
2324
import java.net.ConnectException;
2425
import java.time.Duration;
2526
import java.util.List;
@@ -88,24 +89,30 @@ public void run() {
8889
}
8990
while (true) {
9091
if (!isActive.get()) {
91-
if (watch != null) {
92-
watch.close();
93-
return;
94-
}
92+
closeWatch();
93+
return;
9594
}
9695

9796
try {
9897
if (log.isDebugEnabled()) {
9998
log.debug(
10099
"{}#Start watch with resource version {}", apiTypeClass, lastSyncResourceVersion);
101100
}
102-
watch =
101+
Watchable<ApiType> newWatch =
103102
listerWatcher.watch(
104103
new CallGeneratorParams(
105104
Boolean.TRUE,
106105
lastSyncResourceVersion,
107106
Long.valueOf(Duration.ofMinutes(5).toMillis()).intValue()));
108-
watchHandler(watch);
107+
108+
synchronized (this) {
109+
if (!isActive.get()) {
110+
newWatch.close();
111+
continue;
112+
}
113+
watch = newWatch;
114+
}
115+
watchHandler(newWatch);
109116
} catch (Throwable t) {
110117
if (isConnectException(t)) {
111118
// If this is "connection refused" error, it means that most likely
@@ -132,10 +139,7 @@ public void run() {
132139
this.exceptionHandler.accept(apiTypeClass, t);
133140
return;
134141
} finally {
135-
if (watch != null) {
136-
watch.close();
137-
watch = null;
138-
}
142+
closeWatch();
139143
}
140144
}
141145
} catch (Throwable t) {
@@ -144,7 +148,19 @@ public void run() {
144148
}
145149

146150
public void stop() {
147-
isActive.set(false);
151+
try {
152+
isActive.set(false);
153+
closeWatch();
154+
} catch (Throwable t) {
155+
this.exceptionHandler.accept(apiTypeClass, t);
156+
}
157+
}
158+
159+
private synchronized void closeWatch() throws IOException {
160+
if (watch != null) {
161+
watch.close();
162+
watch = null;
163+
}
148164
}
149165

150166
private void syncWith(List<? extends KubernetesObject> items, String resourceVersion) {

0 commit comments

Comments
 (0)