-
Notifications
You must be signed in to change notification settings - Fork 460
/
ContainerStateMonitor.java
415 lines (377 loc) · 19 KB
/
ContainerStateMonitor.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.controller;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.StabilityMonitor;
import org.jboss.msc.service.StartException;
import static org.jboss.as.controller.logging.ControllerLogger.ROOT_LOGGER;
/**
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
final class ContainerStateMonitor {
private final ServiceRegistry serviceRegistry;
private final StabilityMonitor monitor;
private final Set<ServiceController<?>> failed = new HashSet<ServiceController<?>>();
private final Set<ServiceController<?>> problems = new HashSet<ServiceController<?>>();
private Set<ServiceName> previousMissingDepSet = new HashSet<ServiceName>();
private Set<ServiceController<?>> previousFailedSet = new HashSet<>();
ContainerStateMonitor(final ServiceRegistry registry, final StabilityMonitor stabilityMonitor) {
serviceRegistry = registry;
monitor = stabilityMonitor;
}
/**
* Log a report of any problematic container state changes and reset container state change history
* so another run of this method or of {@link #awaitContainerStateChangeReport(long, java.util.concurrent.TimeUnit)}
* will produce a report not including any changes included in a report returned by this run.
*/
void logContainerStateChangesAndReset() {
ContainerStateChangeReport changeReport = createContainerStateChangeReport(true);
if (changeReport != null) {
final String msg = createChangeReportLogMessage(changeReport, false);
ROOT_LOGGER.info(msg);
}
}
StabilityMonitor getStabilityMonitor() {
return monitor;
}
/**
* Await service container stability ignoring thread interruption.
*
* @param timeout maximum period to wait for service container stability
* @param timeUnit unit in which {@code timeout} is expressed
*
* @throws java.util.concurrent.TimeoutException if service container stability is not reached before the specified timeout
*/
void awaitStabilityUninterruptibly(long timeout, TimeUnit timeUnit) throws TimeoutException {
boolean interrupted = false;
try {
long toWait = timeUnit.toMillis(timeout);
long msTimeout = System.currentTimeMillis() + toWait;
while (true) {
if (interrupted) {
toWait = msTimeout - System.currentTimeMillis();
}
try {
if (toWait <= 0 || !monitor.awaitStability(toWait, TimeUnit.MILLISECONDS, failed, problems)) {
throw new TimeoutException();
}
break;
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Await service container stability.
*
* @param timeout maximum period to wait for service container stability
* @param timeUnit unit in which {@code timeout} is expressed
*
* @throws java.lang.InterruptedException if the thread is interrupted while awaiting service container stability
* @throws java.util.concurrent.TimeoutException if service container stability is not reached before the specified timeout
*/
void awaitStability(long timeout, TimeUnit timeUnit) throws InterruptedException, TimeoutException {
if (!monitor.awaitStability(timeout, timeUnit, failed, problems)) {
throw new TimeoutException();
}
}
/**
* Await service container stability and then report on container state changes. Does not reset change history,
* so another run of this method with no intervening call to {@link #logContainerStateChangesAndReset()}
* will produce a report including any changes included in a report returned by the first run.
*
* @param timeout maximum period to wait for service container stability
* @param timeUnit unit in which {@code timeout} is expressed
*
* @return a change report, or {@code null} if there is nothing to report
*
* @throws java.lang.InterruptedException if the thread is interrupted while awaiting service container stability
* @throws java.util.concurrent.TimeoutException if service container stability is not reached before the specified timeout
*/
ContainerStateChangeReport awaitContainerStateChangeReport(long timeout, TimeUnit timeUnit) throws InterruptedException, TimeoutException {
if (monitor.awaitStability(timeout, timeUnit, failed, problems)) {
return createContainerStateChangeReport(false);
}
throw new TimeoutException();
}
/**
* Creates a data structure reporting recent favorable and unfavorable changes in the state of installed services.
*
* @param resetHistory {@code true} if history tracking state used for detecting what has changed on the next
* invocation of this method should be reset (meaning the next run will detect
* more changes); {@code false} if the current history should be retained
* (meaning the next run will act as if this run never happened)
*
* @return the report, or {@code null} if there is nothing noteworthy to report; i.e. no newly failed or missing
* services and no newly corrected services
*/
private synchronized ContainerStateChangeReport createContainerStateChangeReport(boolean resetHistory) {
final Map<ServiceName, Set<ServiceName>> missingDeps;
if (problems.isEmpty()) {
missingDeps = Collections.emptyMap();
} else {
missingDeps =new HashMap<ServiceName, Set<ServiceName>>(problems.size());
for (ServiceController<?> controller : problems) {
if (controller.getState() != ServiceController.State.REMOVED) {
for (ServiceName missing : controller.getImmediateUnavailableDependencies()) {
Set<ServiceName> dependents = missingDeps.get(missing);
if (dependents == null) {
dependents = new HashSet<ServiceName>();
missingDeps.put(missing, dependents);
}
dependents.add(controller.getName());
}
} // else it's no longer a problem
}
}
final Set<ServiceName> previousMissing = previousMissingDepSet;
// no longer missing deps...
final Map<ServiceName, Boolean> noLongerMissingServices;
if (previousMissing.isEmpty()) {
noLongerMissingServices = Collections.emptyMap();
} else {
noLongerMissingServices = new TreeMap<ServiceName, Boolean>();
for (ServiceName name : previousMissing) {
if (!missingDeps.containsKey(name)) {
ServiceController<?> controller = serviceRegistry.getService(name);
noLongerMissingServices.put(name, controller != null);
}
}
}
// newly missing deps
final Map<ServiceName, MissingDependencyInfo> missingServices;
if (missingDeps.isEmpty()) {
missingServices = Collections.emptyMap();
} else {
missingServices = new TreeMap<ServiceName, MissingDependencyInfo>();
for (Map.Entry<ServiceName, Set<ServiceName>> entry : missingDeps.entrySet()) {
final ServiceName name = entry.getKey();
if (!previousMissing.contains(name)) {
ServiceController<?> controller = serviceRegistry.getService(name);
boolean unavailable = controller != null;
missingServices.put(name, new MissingDependencyInfo(name, unavailable, entry.getValue()));
}
}
}
final Set<ServiceController<?>> currentFailedControllers;
final Set<ServiceController<?>> newFailedControllers;
if (failed.isEmpty()) {
currentFailedControllers = newFailedControllers = Collections.emptySet();
} else {
currentFailedControllers = new HashSet<>(failed.size());
newFailedControllers = new HashSet<>(failed.size());
for (ServiceController<?> controller : failed) {
if (controller.getState() != ServiceController.State.REMOVED) {
currentFailedControllers.add(controller);
if (!previousFailedSet.contains(controller)) {
newFailedControllers.add(controller);
}
} // else it's no longer failed since it's gone
}
}
if (resetHistory) {
previousMissingDepSet = new HashSet<ServiceName>(missingDeps.keySet());
previousFailedSet = new HashSet<>(currentFailedControllers);
failed.clear();
problems.clear();
}
boolean needReport = !missingServices.isEmpty() || !currentFailedControllers.isEmpty() || !noLongerMissingServices.isEmpty();
return needReport ? new ContainerStateChangeReport(missingServices, currentFailedControllers, newFailedControllers, noLongerMissingServices) : null;
}
static String createChangeReportLogMessage(ContainerStateChangeReport changeReport, boolean forException) {
final StringBuilder msg = new StringBuilder();
msg.append(forException ? ControllerLogger.ROOT_LOGGER.serviceStatusReportFailureHeader() : ControllerLogger.ROOT_LOGGER.serviceStatusReportHeader());
if (!changeReport.getMissingServices().isEmpty()) {
msg.append(ControllerLogger.ROOT_LOGGER.serviceStatusReportDependencies());
for (Map.Entry<ServiceName, MissingDependencyInfo> entry : changeReport.getMissingServices().entrySet()) {
if (!entry.getValue().isUnavailable()) {
msg.append(ControllerLogger.ROOT_LOGGER.serviceStatusReportMissing(entry.getKey(), createDependentsString(entry.getValue().getDependents())));
} else {
msg.append(ControllerLogger.ROOT_LOGGER.serviceStatusReportUnavailable(entry.getKey(), createDependentsString(entry.getValue().getDependents())));
}
}
}
if (!forException && !changeReport.getNoLongerMissingServices().isEmpty()) {
msg.append(ControllerLogger.ROOT_LOGGER.serviceStatusReportCorrected());
for (Map.Entry<ServiceName, Boolean> entry : changeReport.getNoLongerMissingServices().entrySet()) {
if (entry.getValue()) {
msg.append(ControllerLogger.ROOT_LOGGER.serviceStatusReportAvailable(entry.getKey()));
} else {
msg.append(ControllerLogger.ROOT_LOGGER.serviceStatusReportNoLongerRequired(entry.getKey()));
}
}
}
Set<ServiceController<?>> failedSet = forException ? changeReport.getNewFailedControllers() : changeReport.getFailedControllers();
if (!failedSet.isEmpty()) {
msg.append(ControllerLogger.ROOT_LOGGER.serviceStatusReportFailed());
for (ServiceController<?> controller : failedSet) {
msg.append(" ").append(controller.getName());
//noinspection ThrowableResultOfMethodCallIgnored
final StartException startException = controller.getStartException();
if (startException != null) {
// This is a bit of inside knowledge of StartException. Its toString() prefixes
// the main data with 'org...StartException in org.foo.bar: " stuff that
// will be redundant in the overall output we are creating so we omit that if we can.
String exMsg = startException.getLocalizedMessage();
if (exMsg == null || exMsg.length() == 0) {
exMsg = startException.toString();
}
msg.append(": ").append(exMsg);
}
msg.append('\n');
}
}
return msg.toString();
}
static class ContainerStateChangeReport {
private final Map<ServiceName, MissingDependencyInfo> missingServices;
private final Set<ServiceController<?>> failedControllers;
private final Set<ServiceController<?>> newFailedControllers;
private final Map<ServiceName, Boolean> noLongerMissingServices;
private ContainerStateChangeReport(final Map<ServiceName, MissingDependencyInfo> missingServices,
final Set<ServiceController<?>> failedControllers,
final Set<ServiceController<?>> newFailedControllers,
final Map<ServiceName, Boolean> noLongerMissingServices) {
this.missingServices = missingServices;
this.failedControllers = failedControllers;
this.newFailedControllers = newFailedControllers;
this.noLongerMissingServices = noLongerMissingServices;
}
/**
* Gets all controllers that had {@link ServiceController.State#START_FAILED failed to start}
* with an exception in the service start method at the time this report was created.
*
* @return the failed controllers. Will not return {@code null}
*/
final Set<ServiceController<?>> getFailedControllers() {
return failedControllers;
}
/**
* Gets controllers that had {@link ServiceController.State#START_FAILED failed to start}
* with an exception in the service start method at the time this report was created and were
* not included in the report prior to the last {@link #logContainerStateChangesAndReset() reset}
* of the ContainerStateMonitor.
*
* @return the failed controllers. Will not return {@code null}
*/
final Set<ServiceController<?>> getNewFailedControllers() {
return newFailedControllers;
}
/**
* Gets information about all services that had missing dependencies at the time this report was created.
*
* @return a map of the service name of the service that has missing dependencies to
* information about those missing dependencies
*/
Map<ServiceName, MissingDependencyInfo> getMissingServices() {
return missingServices;
}
/**
* Gets services that had previously been reported as missing but were no longer considered to be missing
* at the time this report was created.
* @return a map of the service name of the no-longer-missing service to a boolean indicating
* whether or not the service now exists ({@code true} if it does.) If {@code false}
* the service is no longer "missing" because it is no longer depended upon
*/
Map<ServiceName, Boolean> getNoLongerMissingServices() {
return noLongerMissingServices;
}
/**
* Gets whether this report contains anything other than no longer missing services.
* @return {@code true} if {@link #getNewFailedControllers()} or {@link #getMissingServices()} will return a non-empty collection
*/
boolean hasNewProblems() {
return !newFailedControllers.isEmpty() || !missingServices.isEmpty();
}
}
private static String createDependentsString(final Set<ServiceName> serviceNames) {
if(serviceNames.size() <= 4) {
return serviceNames.toString();
} else {
final StringBuilder ret = new StringBuilder("[");
int count = 0;
Iterator<ServiceName> it = serviceNames.iterator();
while (count < 4) {
final ServiceName val = it.next();
ret.append(val);
ret.append(", ");
++count;
}
ret.append(ControllerLogger.ROOT_LOGGER.andNMore(serviceNames.size() - 3));
ret.append(" ]");
return ret.toString();
}
}
/** Encapsulates information about dependencies that a service is missing. */
static class MissingDependencyInfo {
private final ServiceName serviceName;
private final boolean unavailable;
private final Set<ServiceName> dependents;
private MissingDependencyInfo(ServiceName serviceName, boolean unavailable, final Set<ServiceName> dependents) {
this.serviceName = serviceName;
this.unavailable = unavailable;
this.dependents = dependents;
}
/**
* Gets the name of the service that was missing dependencies.
*
* @return the name. Will not return {@code null}
*/
ServiceName getServiceName() {
return serviceName;
}
/**
* Gets whether the service that was missing dependencies was still installed when this report was created.
* Note that "installed" does not mean "started."
*
* @return {@code true} if the service was still installed.
*/
boolean isUnavailable() {
return unavailable;
}
/**
* Gets the name of the services the service depends on that were missing.
* @return the missing services. Will not return {@code null}
*/
Set<ServiceName> getDependents() {
return Collections.unmodifiableSet(dependents);
}
}
}