|
| 1 | +package shutdown; |
| 2 | + |
| 3 | +import commons.CommonRails; |
| 4 | + |
| 5 | +import java.io.File; |
| 6 | +import java.net.Socket; |
| 7 | + |
| 8 | +/** |
| 9 | + * Centralises all JVM shutdown hook registration and shutdown printing via CommonRails. |
| 10 | + * The bash script performs the actual OS-level kills silently; all console output goes |
| 11 | + * through CommonRails.printShutdownSignal / printSystemComponent. |
| 12 | + */ |
| 13 | +public class ShutdownHooks |
| 14 | +{ |
| 15 | + public static final int[] PORTS = { 49152, 49155, 5512, 6682 }; |
| 16 | + |
| 17 | + public static void register() |
| 18 | + { |
| 19 | + Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHooks::run, "ShutdownHook")); |
| 20 | + } |
| 21 | + |
| 22 | + private static void run() |
| 23 | + { |
| 24 | + ShutdownHooks owner = new ShutdownHooks(); |
| 25 | + |
| 26 | + CommonRails.printSystemComponent(owner, owner.hashCode(), "[shutdown] Closing server ports: 49152 49155 5512 6682"); |
| 27 | + |
| 28 | + for (int port : PORTS) |
| 29 | + CommonRails.printShutdownSignal(owner, port, "SIGTERM"); |
| 30 | + |
| 31 | + // run script silently — it performs the actual kills |
| 32 | + try |
| 33 | + { |
| 34 | + String script = new File("scripts/shutdown.sh").getAbsolutePath(); |
| 35 | + Process proc = new ProcessBuilder("bash", script) |
| 36 | + .redirectOutput(ProcessBuilder.Redirect.DISCARD) |
| 37 | + .redirectError(ProcessBuilder.Redirect.DISCARD) |
| 38 | + .start(); |
| 39 | + |
| 40 | + // grace period mirrors the script's sleep 2 |
| 41 | + Thread.sleep(2000); |
| 42 | + |
| 43 | + // report any ports that needed SIGKILL |
| 44 | + for (int port : PORTS) |
| 45 | + { |
| 46 | + if (portStillOpen(port)) |
| 47 | + CommonRails.printShutdownSignal(owner, port, "SIGKILL"); |
| 48 | + } |
| 49 | + |
| 50 | + proc.waitFor(); |
| 51 | + } |
| 52 | + catch (Exception e) |
| 53 | + { |
| 54 | + CommonRails.EXCEPTION_SINK.accept(e); |
| 55 | + } |
| 56 | + |
| 57 | + CommonRails.printSystemComponent(owner, owner.hashCode(), "[shutdown] Done."); |
| 58 | + } |
| 59 | + |
| 60 | + private static boolean portStillOpen(final int PORT) |
| 61 | + { |
| 62 | + try (Socket s = new Socket("localhost", PORT)) { return true; } |
| 63 | + catch (Exception e) { return false; } |
| 64 | + } |
| 65 | +} |
0 commit comments