Skip to content

Commit dc49946

Browse files
fatmcgavGavin Williams
authored andcommitted
Add TERM handling
This is useful to gracefully stop the Jenkins swarm process, for example when running in Kubernetes in conjunction with a preStop lifecycle hook. Signed-off-by: Gavin Williams <gavin.williams@elastic.co>
1 parent 86fb969 commit dc49946

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

client/src/main/java/hudson/plugins/swarm/Client.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,34 @@ private static void validateOptions(Options options) {
187187
*/
188188
static void run(SwarmClient swarmClient, Options options, String... args)
189189
throws InterruptedException {
190+
191+
// Gracefully handle TERM request
192+
Runtime.getRuntime().addShutdownHook(new Thread() {
193+
@Override
194+
public void run() {
195+
logger.info("Interrupting threads");
196+
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
197+
for (Thread th : runningThreads) {
198+
if (th != Thread.currentThread() && !th.isDaemon()
199+
&& th.getClass().getName().startsWith("hudson.plugins.swarm")) {
200+
logger.info("Interrupting '" + th.getClass() + "' termination");
201+
th.interrupt();
202+
}
203+
}
204+
for (Thread th : runningThreads) {
205+
try {
206+
if (th != Thread.currentThread() && !th.isDaemon() && th.isInterrupted()) {
207+
logger.info("Waiting '" + th.getName() + "' termination");
208+
th.join();
209+
}
210+
} catch (InterruptedException ex) {
211+
logger.info("Shutdown interrupted");
212+
}
213+
}
214+
logger.info("Shutdown finished");
215+
}
216+
});
217+
190218
logger.info("Connecting to Jenkins controller");
191219
URL url = swarmClient.getUrl();
192220

0 commit comments

Comments
 (0)