aboutsummaryrefslogtreecommitdiffstats
path: root/server/sonar-process/src/main/java/org/sonar/process/ProcessEntryPoint.java
blob: 79ec79f74b75188701077da383a5c6a61b5b5a5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*
 * SonarQube, open source software quality management tool.
 * Copyright (C) 2008-2014 SonarSource
 * mailto:contact AT sonarsource DOT com
 *
 * SonarQube is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * SonarQube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.process;

import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ProcessEntryPoint implements ProcessMXBean {

  public static final String PROPERTY_PROCESS_KEY = "process.key";
  public static final String PROPERTY_AUTOKILL_DISABLED = "process.autokill.disabled";
  public static final String PROPERTY_AUTOKILL_PING_TIMEOUT = "process.autokill.pingTimeout";
  public static final String PROPERTY_AUTOKILL_PING_INTERVAL = "process.autokill.pingInterval";
  public static final String PROPERTY_TERMINATION_TIMEOUT = "process.terminationTimeout";

  private final Props props;
  private final Lifecycle lifecycle = new Lifecycle();
  private volatile MonitoredProcess monitoredProcess;
  private volatile long lastPing = 0L;
  private volatile StopperThread stopperThread;
  private final SystemExit exit;
  private Thread shutdownHook = new Thread(new Runnable() {
    @Override
    public void run() {
      exit.setInShutdownHook();
      terminate();
    }
  });

  ProcessEntryPoint(Props props, SystemExit exit) {
    this.props = props;
    this.exit = exit;
  }

  public Props getProps() {
    return props;
  }

  /**
   * Launch process and waits until it's down
   */
  public void launch(MonitoredProcess mp) {
    if (!lifecycle.tryToMoveTo(State.STARTING)) {
      throw new IllegalStateException("Already started");
    }
    monitoredProcess = mp;

    // TODO check if these properties are available in System Info
    JmxUtils.registerMBean(this, props.nonNullValue(PROPERTY_PROCESS_KEY));
    Runtime.getRuntime().addShutdownHook(shutdownHook);
    if (!props.valueAsBoolean(PROPERTY_AUTOKILL_DISABLED, false)) {
      // mainly for Java Debugger
      scheduleAutokill();
    }

    try {
      monitoredProcess.start();
      if (lifecycle.tryToMoveTo(State.STARTED)) {
        monitoredProcess.awaitTermination();
      }
    } catch (Exception ignored) {
    } finally {
      terminate();
    }
  }

  @Override
  public boolean isReady() {
    return lifecycle.getState() == State.STARTED;
  }

  @Override
  public void ping() {
    lastPing = System.currentTimeMillis();
  }

  /**
   * Blocks until stopped in a timely fashion (see {@link org.sonar.process.StopperThread})
   */
  @Override
  public void terminate() {
    if (lifecycle.tryToMoveTo(State.STOPPING)) {
      stopperThread = new StopperThread(monitoredProcess, Long.parseLong(props.nonNullValue(PROPERTY_TERMINATION_TIMEOUT)));
      stopperThread.start();
    }
    try {
      // stopperThread is not null for sure
      // join() does nothing if thread already finished
      stopperThread.join();
      lifecycle.tryToMoveTo(State.STOPPED);
    } catch (InterruptedException e) {
      // nothing to do, the process is going to be exited
    }
    exit.exit(0);
  }

  private void scheduleAutokill() {
    final long autokillPingTimeoutMs = props.valueAsInt(PROPERTY_AUTOKILL_PING_TIMEOUT);
    long autokillPingIntervalMs = props.valueAsInt(PROPERTY_AUTOKILL_PING_INTERVAL);
    Runnable autokiller = new Runnable() {
      @Override
      public void run() {
        long time = System.currentTimeMillis();
        if (time - lastPing > autokillPingTimeoutMs) {
          LoggerFactory.getLogger(getClass()).info(String.format(
            "Did not receive any ping during %d seconds. Shutting down.", autokillPingTimeoutMs / 1000));
          terminate();
        }
      }
    };
    lastPing = System.currentTimeMillis();
    ScheduledExecutorService monitor = Executors.newScheduledThreadPool(1);
    monitor.scheduleWithFixedDelay(autokiller, autokillPingIntervalMs, autokillPingIntervalMs, TimeUnit.MILLISECONDS);
  }

  State getState() {
    return lifecycle.getState();
  }

  Thread getShutdownHook() {
    return shutdownHook;
  }

  public static ProcessEntryPoint createForArguments(String[] args) {
    Props props = ConfigurationUtils.loadPropsFromCommandLineArgs(args);
    return new ProcessEntryPoint(props, new SystemExit());
  }
}