Add shutdown hook before starting web server to be able to stop

HA-Bridge from the command line (using SIGTERM signal).
This commit is contained in:
gaudryc
2019-01-03 18:36:56 +01:00
parent ce220d999a
commit 7490cf72a3
2 changed files with 58 additions and 1 deletions

View File

@@ -44,7 +44,8 @@ public class HABridge {
Version theVersion;
@SuppressWarnings("unused")
HttpClientPool thePool;
ShutdownHook shutdownHook = null;
log.info("HA Bridge startup sequence...");
theVersion = new Version();
// Singleton initialization
@@ -68,6 +69,14 @@ public class HABridge {
// setup system control api first
theSystem = new SystemControl(bridgeSettings, theVersion);
theSystem.setupServer();
// Add shutdown hook to be able to properly stop server
if (shutdownHook != null) {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
shutdownHook = new ShutdownHook(bridgeSettings, theSystem);
Runtime.getRuntime().addShutdownHook(shutdownHook);
// setup the UDP Datagram socket to be used by the HueMulator and the upnpListener
udpSender = UDPDatagramSender.createUDPDatagramSender(bridgeSettings.getBridgeSettingsDescriptor().getUpnpResponsePort());
if(udpSender == null) {

View File

@@ -0,0 +1,48 @@
package com.bwssystems.HABridge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class implements the shutdown hook used to properly stop server from the
* command line (sending SIGTERM), or while shutting down the host machine.
*
* @author gaudryc
*/
public class ShutdownHook extends Thread {
private final BridgeSettings bridgeSettings;
private final SystemControl theSystem;
/**
* Constructor
*
* @param bridgeSettings
* bridge settings
* @param theSystem
*/
public ShutdownHook(final BridgeSettings bridgeSettings, final SystemControl theSystem) {
this.bridgeSettings = bridgeSettings;
this.theSystem = theSystem;
}
@Override
public void run() {
Logger log = LoggerFactory.getLogger(ShutdownHook.class);
log.info("Shutdown requested...");
if (bridgeSettings != null) {
if (!bridgeSettings.getBridgeControl().isStop() && (theSystem != null)) {
log.info("Forcing system stop...");
theSystem.stop();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
log.error("Sleep error: " + e.getMessage());
}
} else {
log.info("Already stopped");
}
}
}
}