1 package org.argeo.cms.internal.kernel;
2
3 import org.apache.commons.logging.Log;
4 import org.apache.commons.logging.LogFactory;
5 import org.osgi.framework.Bundle;
6 import org.osgi.framework.FrameworkEvent;
7 import org.osgi.framework.FrameworkUtil;
8 import org.osgi.framework.launch.Framework;
9
10
11 class CmsShutdown extends Thread {
12 public final int EXIT_OK = 0;
13 public final int EXIT_ERROR = 1;
14 public final int EXIT_TIMEOUT = 2;
15 public final int EXIT_UNKNOWN = 3;
16
17 private final Log log = LogFactory.getLog(CmsShutdown.class);
18
19
20 private final Framework framework;
21
22
23 private long timeout = 10 * 60 * 1000;
24
25 public CmsShutdown() {
26 super("CMS Shutdown Hook");
27 framework = (Framework) FrameworkUtil.getBundle(CmsShutdown.class).getBundleContext().getBundle(0);
28 }
29
30 @Override
31 public void run() {
32 if (framework.getState() != Bundle.ACTIVE) {
33 return;
34 }
35
36 if (log.isDebugEnabled())
37 log.debug("Shutting down OSGi framework...");
38 try {
39
40 framework.stop();
41
42 FrameworkEvent shutdownEvent = framework.waitForStop(timeout);
43 int stoppedType = shutdownEvent.getType();
44 Runtime runtime = Runtime.getRuntime();
45 if (stoppedType == FrameworkEvent.STOPPED) {
46
47
48 } else if (stoppedType == FrameworkEvent.ERROR) {
49 log.error("The OSGi framework stopped with an error");
50 runtime.halt(EXIT_ERROR);
51 } else if (stoppedType == FrameworkEvent.WAIT_TIMEDOUT) {
52 log.error("The OSGi framework hasn't stopped after " + timeout + "ms."
53 + " Forcibly terminating the JVM...");
54 runtime.halt(EXIT_TIMEOUT);
55 } else {
56 log.error("Unknown state of OSGi framework after " + timeout + "ms."
57 + " Forcibly terminating the JVM... (" + shutdownEvent + ")");
58 runtime.halt(EXIT_UNKNOWN);
59 }
60 } catch (Exception e) {
61 e.printStackTrace();
62 log.error("Unexpected exception " + e + " in shutdown hook. " + " Forcibly terminating the JVM...");
63 Runtime.getRuntime().halt(EXIT_UNKNOWN);
64 }
65 }
66
67 }