-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
SchedulerImpl.java
315 lines (280 loc) · 9.81 KB
/
SchedulerImpl.java
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.application;
import java.util.EnumMap;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.application.command.CommandFactory;
import org.sonar.application.command.EsCommand;
import org.sonar.application.command.JavaCommand;
import org.sonar.application.config.AppSettings;
import org.sonar.application.config.ClusterSettings;
import org.sonar.application.process.Lifecycle;
import org.sonar.application.process.ProcessEventListener;
import org.sonar.application.process.ProcessLauncher;
import org.sonar.application.process.ProcessLifecycleListener;
import org.sonar.application.process.ProcessMonitor;
import org.sonar.application.process.SQProcess;
import org.sonar.process.ProcessId;
public class SchedulerImpl implements Scheduler, ProcessEventListener, ProcessLifecycleListener, AppStateListener {
private static final Logger LOG = LoggerFactory.getLogger(SchedulerImpl.class);
private final AppSettings settings;
private final AppReloader appReloader;
private final CommandFactory commandFactory;
private final ProcessLauncher processLauncher;
private final AppState appState;
private final NodeLifecycle nodeLifecycle = new NodeLifecycle();
private final CountDownLatch keepAlive = new CountDownLatch(1);
private final AtomicBoolean restartRequested = new AtomicBoolean(false);
private final AtomicBoolean restartDisabled = new AtomicBoolean(false);
private final EnumMap<ProcessId, SQProcess> processesById = new EnumMap<>(ProcessId.class);
private final AtomicInteger operationalCountDown = new AtomicInteger();
private final AtomicInteger stopCountDown = new AtomicInteger(0);
private StopperThread stopperThread;
private RestarterThread restarterThread;
private long processWatcherDelayMs = SQProcess.DEFAULT_WATCHER_DELAY_MS;
public SchedulerImpl(AppSettings settings, AppReloader appReloader, CommandFactory commandFactory,
ProcessLauncher processLauncher,
AppState appState) {
this.settings = settings;
this.appReloader = appReloader;
this.commandFactory = commandFactory;
this.processLauncher = processLauncher;
this.appState = appState;
this.appState.addListener(this);
}
SchedulerImpl setProcessWatcherDelayMs(long l) {
this.processWatcherDelayMs = l;
return this;
}
@Override
public void schedule() {
if (!nodeLifecycle.tryToMoveTo(NodeLifecycle.State.STARTING)) {
return;
}
processesById.clear();
for (ProcessId processId : ClusterSettings.getEnabledProcesses(settings)) {
SQProcess process = SQProcess.builder(processId)
.addProcessLifecycleListener(this)
.addEventListener(this)
.setWatcherDelayMs(processWatcherDelayMs)
.build();
processesById.put(process.getProcessId(), process);
}
operationalCountDown.set(processesById.size());
tryToStartAll();
}
private void tryToStartAll() {
tryToStartEs();
tryToStartWeb();
tryToStartCe();
}
private void tryToStartEs() {
SQProcess process = processesById.get(ProcessId.ELASTICSEARCH);
if (process != null) {
tryToStartEsProcess(process, commandFactory::createEsCommand);
}
}
private void tryToStartWeb() {
SQProcess process = processesById.get(ProcessId.WEB_SERVER);
if (process == null || !isEsClientStartable()) {
return;
}
if (appState.isOperational(ProcessId.WEB_SERVER, false)) {
tryToStartJavaProcess(process, () -> commandFactory.createWebCommand(false));
} else if (appState.tryToLockWebLeader()) {
tryToStartJavaProcess(process, () -> commandFactory.createWebCommand(true));
} else {
Optional<String> leader = appState.getLeaderHostName();
if (leader.isPresent()) {
LOG.info("Waiting for initialization from " + leader.get());
} else {
LOG.error("Initialization failed. All nodes must be restarted");
}
}
}
private void tryToStartCe() {
SQProcess process = processesById.get(ProcessId.COMPUTE_ENGINE);
if (process != null && appState.isOperational(ProcessId.WEB_SERVER, false) && isEsClientStartable()) {
tryToStartJavaProcess(process, commandFactory::createCeCommand);
}
}
private boolean isEsClientStartable() {
boolean requireLocalEs = ClusterSettings.isLocalElasticsearchEnabled(settings);
return appState.isOperational(ProcessId.ELASTICSEARCH, requireLocalEs);
}
private void tryToStartJavaProcess(SQProcess process, Supplier<JavaCommand> commandSupplier) {
tryToStart(process, () -> {
JavaCommand command = commandSupplier.get();
return processLauncher.launch(command);
});
}
private void tryToStartEsProcess(SQProcess process, Supplier<EsCommand> commandSupplier) {
tryToStart(process, () -> {
EsCommand command = commandSupplier.get();
return processLauncher.launch(command);
});
}
private void tryToStart(SQProcess process, Supplier<ProcessMonitor> processMonitorSupplier) {
try {
process.start(processMonitorSupplier);
} catch (RuntimeException e) {
// failed to start command -> stop everything
terminate();
throw e;
}
}
private void stopAll() {
// order is important for non-cluster mode
stopProcess(ProcessId.COMPUTE_ENGINE);
stopProcess(ProcessId.WEB_SERVER);
stopProcess(ProcessId.ELASTICSEARCH);
}
/**
* Request for graceful stop then blocks until process is stopped.
* Returns immediately if the process is disabled in configuration.
*/
private void stopProcess(ProcessId processId) {
SQProcess process = processesById.get(processId);
if (process != null) {
process.stop(1, TimeUnit.MINUTES);
}
}
/**
* Blocks until all processes are stopped. Pending restart, if
* any, is disabled.
*/
@Override
public void terminate() {
// disable ability to request for restart
restartRequested.set(false);
restartDisabled.set(true);
if (nodeLifecycle.tryToMoveTo(NodeLifecycle.State.STOPPING)) {
LOG.info("Stopping SonarQube");
}
stopAll();
if (stopperThread != null) {
stopperThread.interrupt();
}
if (restarterThread != null) {
restarterThread.interrupt();
}
keepAlive.countDown();
}
@Override
public void awaitTermination() {
try {
keepAlive.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public void onProcessEvent(ProcessId processId, Type type) {
if (type == Type.OPERATIONAL) {
onProcessOperational(processId);
} else if (type == Type.ASK_FOR_RESTART && restartRequested.compareAndSet(false, true)) {
stopAsync();
}
}
private void onProcessOperational(ProcessId processId) {
LOG.info("Process[{}] is up", processId.getKey());
appState.setOperational(processId);
if (operationalCountDown.decrementAndGet() == 0 && nodeLifecycle.tryToMoveTo(NodeLifecycle.State.OPERATIONAL)) {
LOG.info("SonarQube is up");
}
}
@Override
public void onAppStateOperational(ProcessId processId) {
if (nodeLifecycle.getState() == NodeLifecycle.State.STARTING) {
tryToStartAll();
}
}
@Override
public void onProcessState(ProcessId processId, Lifecycle.State to) {
switch (to) {
case STOPPED:
onProcessStop(processId);
break;
case STARTING:
stopCountDown.incrementAndGet();
break;
default:
// Nothing to do
break;
}
}
private void onProcessStop(ProcessId processId) {
LOG.info("Process [{}] is stopped", processId.getKey());
if (stopCountDown.decrementAndGet() == 0 && nodeLifecycle.tryToMoveTo(NodeLifecycle.State.STOPPED)) {
if (!restartDisabled.get() &&
restartRequested.compareAndSet(true, false)) {
LOG.info("SonarQube is restarting");
restartAsync();
} else {
LOG.info("SonarQube is stopped");
// all processes are stopped, no restart requested
// Let's clean-up resources
terminate();
}
} else if (nodeLifecycle.tryToMoveTo(NodeLifecycle.State.STOPPING)) {
// this is the first process stopping
stopAsync();
}
}
private void stopAsync() {
stopperThread = new StopperThread();
stopperThread.start();
}
private void restartAsync() {
restarterThread = new RestarterThread();
restarterThread.start();
}
private class RestarterThread extends Thread {
public RestarterThread() {
super("Restarter");
}
@Override
public void run() {
try {
appReloader.reload(settings);
schedule();
} catch (Exception e) {
LOG.error("Fail to restart", e);
terminate();
}
}
}
private class StopperThread extends Thread {
public StopperThread() {
super("Stopper");
}
@Override
public void run() {
stopAll();
}
}
}