2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.config.yang.shutdown.impl;
10 import com.google.common.base.Optional;
11 import org.opendaylight.controller.config.shutdown.ShutdownService;
12 import org.osgi.framework.Bundle;
13 import org.osgi.framework.BundleException;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
17 public class ShutdownServiceImpl implements ShutdownService, AutoCloseable {
18 private final ShutdownService impl;
19 private final ShutdownRuntimeRegistration registration;
21 public ShutdownServiceImpl(String secret, Bundle systemBundle,
22 ShutdownRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
24 throw new IllegalArgumentException("Secret cannot be null");
26 impl = new Impl(secret, systemBundle);
27 registration = rootRuntimeBeanRegistratorWrapper.register(new MXBeanImpl(impl));
31 public void shutdown(String inputSecret, Optional<String> reason) {
32 impl.shutdown(inputSecret, reason);
41 class Impl implements ShutdownService {
42 private static final Logger logger = LoggerFactory.getLogger(Impl.class);
43 private final String secret;
44 private final Bundle systemBundle;
46 Impl(String secret, Bundle systemBundle) {
48 this.systemBundle = systemBundle;
52 public void shutdown(String inputSecret, Optional<String> reason) {
53 logger.warn("Shutdown issued with secret {} and reason {}", inputSecret, reason);
55 Thread.sleep(1000); // prevent brute force attack
56 } catch (InterruptedException e) {
57 Thread.currentThread().interrupt();
58 logger.warn("Shutdown process interrupted", e);
60 if (this.secret.equals(inputSecret)) {
61 logger.info("Server is shutting down");
63 Thread stopSystemBundle = new Thread() {
67 // wait so that JMX response is received
70 } catch (BundleException e) {
71 logger.warn("Can not stop OSGi server", e);
72 } catch (InterruptedException e) {
73 logger.warn("Shutdown process interrupted", e);
77 stopSystemBundle.start();
80 logger.warn("Unauthorized attempt to shut down server");
81 throw new IllegalArgumentException("Invalid secret");
87 class MXBeanImpl implements ShutdownRuntimeMXBean {
88 private final ShutdownService impl;
90 MXBeanImpl(ShutdownService impl) {
95 public void shutdown(String inputSecret, String nullableReason) {
96 Optional<String> optionalReason;
97 if (nullableReason == null) {
98 optionalReason = Optional.absent();
100 optionalReason = Optional.of(nullableReason);
102 impl.shutdown(inputSecret, optionalReason);