Skip to content

Commit

Permalink
Add TERM handling
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
fatmcgav authored and Gavin Williams committed Oct 18, 2021
1 parent 86fb969 commit c5b5b1e
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions client/src/main/java/hudson/plugins/swarm/Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand Down Expand Up @@ -187,6 +188,34 @@ private static void validateOptions(Options options) {
*/
static void run(SwarmClient swarmClient, Options options, String... args)
throws InterruptedException {

// Gracefully handle TERM request
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
logger.info("Interrupting threads");
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
for (Thread th : runningThreads) {
if (th != Thread.currentThread() && !th.isDaemon()
&& th.getClass().getName().startsWith("hudson.plugins.swarm")) {
logger.info("Interrupting '" + th.getClass() + "' termination");
th.interrupt();
}
}
for (Thread th : runningThreads) {
try {
if (th != Thread.currentThread() && !th.isDaemon() && th.isInterrupted()) {
logger.info("Waiting '" + th.getName() + "' termination");
th.join();
}
} catch (InterruptedException ex) {
logger.info("Shutdown interrupted");
}
}
logger.info("Shutdown finished");
}
});

logger.info("Connecting to Jenkins controller");
URL url = swarmClient.getUrl();

Expand Down

0 comments on commit c5b5b1e

Please sign in to comment.