001/* 002 * Copyright (C) 2012 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014package com.google.common.util.concurrent; 015 016import static com.google.common.base.Preconditions.checkArgument; 017import static com.google.common.base.Preconditions.checkNotNull; 018import static com.google.common.base.Preconditions.checkState; 019import static com.google.common.base.Predicates.equalTo; 020import static com.google.common.base.Predicates.in; 021import static com.google.common.base.Predicates.instanceOf; 022import static com.google.common.base.Predicates.not; 023import static com.google.common.util.concurrent.MoreExecutors.directExecutor; 024import static com.google.common.util.concurrent.Service.State.FAILED; 025import static com.google.common.util.concurrent.Service.State.NEW; 026import static com.google.common.util.concurrent.Service.State.RUNNING; 027import static com.google.common.util.concurrent.Service.State.STARTING; 028import static com.google.common.util.concurrent.Service.State.STOPPING; 029import static com.google.common.util.concurrent.Service.State.TERMINATED; 030import static java.util.concurrent.TimeUnit.MILLISECONDS; 031 032import com.google.common.annotations.Beta; 033import com.google.common.annotations.GwtIncompatible; 034import com.google.common.base.Function; 035import com.google.common.base.MoreObjects; 036import com.google.common.base.Stopwatch; 037import com.google.common.collect.Collections2; 038import com.google.common.collect.ImmutableCollection; 039import com.google.common.collect.ImmutableList; 040import com.google.common.collect.ImmutableMap; 041import com.google.common.collect.ImmutableMultimap; 042import com.google.common.collect.ImmutableSet; 043import com.google.common.collect.ImmutableSetMultimap; 044import com.google.common.collect.Lists; 045import com.google.common.collect.Maps; 046import com.google.common.collect.MultimapBuilder; 047import com.google.common.collect.Multimaps; 048import com.google.common.collect.Multiset; 049import com.google.common.collect.Ordering; 050import com.google.common.collect.SetMultimap; 051import com.google.common.util.concurrent.ListenerCallQueue.Callback; 052import com.google.common.util.concurrent.Service.State; 053import com.google.errorprone.annotations.CanIgnoreReturnValue; 054import com.google.j2objc.annotations.WeakOuter; 055import java.lang.ref.WeakReference; 056import java.util.ArrayList; 057import java.util.Collections; 058import java.util.EnumSet; 059import java.util.List; 060import java.util.Map; 061import java.util.Map.Entry; 062import java.util.concurrent.Executor; 063import java.util.concurrent.TimeUnit; 064import java.util.concurrent.TimeoutException; 065import java.util.logging.Level; 066import java.util.logging.Logger; 067import javax.annotation.concurrent.GuardedBy; 068 069/** 070 * A manager for monitoring and controlling a set of {@linkplain Service services}. This class 071 * provides methods for {@linkplain #startAsync() starting}, {@linkplain #stopAsync() stopping} and 072 * {@linkplain #servicesByState inspecting} a collection of {@linkplain Service services}. 073 * Additionally, users can monitor state transitions with the {@linkplain Listener listener} 074 * mechanism. 075 * 076 * <p>While it is recommended that service lifecycles be managed via this class, state transitions 077 * initiated via other mechanisms do not impact the correctness of its methods. For example, if the 078 * services are started by some mechanism besides {@link #startAsync}, the listeners will be invoked 079 * when appropriate and {@link #awaitHealthy} will still work as expected. 080 * 081 * <p>Here is a simple example of how to use a {@code ServiceManager} to start a server. 082 * <pre> {@code 083 * class Server { 084 * public static void main(String[] args) { 085 * Set<Service> services = ...; 086 * ServiceManager manager = new ServiceManager(services); 087 * manager.addListener(new Listener() { 088 * public void stopped() {} 089 * public void healthy() { 090 * // Services have been initialized and are healthy, start accepting requests... 091 * } 092 * public void failure(Service service) { 093 * // Something failed, at this point we could log it, notify a load balancer, or take 094 * // some other action. For now we will just exit. 095 * System.exit(1); 096 * } 097 * }, 098 * MoreExecutors.directExecutor()); 099 * 100 * Runtime.getRuntime().addShutdownHook(new Thread() { 101 * public void run() { 102 * // Give the services 5 seconds to stop to ensure that we are responsive to shutdown 103 * // requests. 104 * try { 105 * manager.stopAsync().awaitStopped(5, TimeUnit.SECONDS); 106 * } catch (TimeoutException timeout) { 107 * // stopping timed out 108 * } 109 * } 110 * }); 111 * manager.startAsync(); // start all the services asynchronously 112 * } 113 * }}</pre> 114 * 115 * <p>This class uses the ServiceManager's methods to start all of its services, to respond to 116 * service failure and to ensure that when the JVM is shutting down all the services are stopped. 117 * 118 * @author Luke Sandberg 119 * @since 14.0 120 */ 121@Beta 122@GwtIncompatible 123public final class ServiceManager { 124 private static final Logger logger = Logger.getLogger(ServiceManager.class.getName()); 125 private static final Callback<Listener> HEALTHY_CALLBACK = 126 new Callback<Listener>("healthy()") { 127 @Override 128 void call(Listener listener) { 129 listener.healthy(); 130 } 131 }; 132 private static final Callback<Listener> STOPPED_CALLBACK = 133 new Callback<Listener>("stopped()") { 134 @Override 135 void call(Listener listener) { 136 listener.stopped(); 137 } 138 }; 139 140 /** 141 * A listener for the aggregate state changes of the services that are under management. Users 142 * that need to listen to more fine-grained events (such as when each particular 143 * {@linkplain Service service} starts, or terminates), should attach {@linkplain Service.Listener 144 * service listeners} to each individual service. 145 * 146 * @author Luke Sandberg 147 * @since 15.0 (present as an interface in 14.0) 148 */ 149 @Beta // Should come out of Beta when ServiceManager does 150 public abstract static class Listener { 151 /** 152 * Called when the service initially becomes healthy. 153 * 154 * <p>This will be called at most once after all the services have entered the 155 * {@linkplain State#RUNNING running} state. If any services fail during start up or 156 * {@linkplain State#FAILED fail}/{@linkplain State#TERMINATED terminate} before all other 157 * services have started {@linkplain State#RUNNING running} then this method will not be called. 158 */ 159 public void healthy() {} 160 161 /** 162 * Called when the all of the component services have reached a terminal state, either 163 * {@linkplain State#TERMINATED terminated} or {@linkplain State#FAILED failed}. 164 */ 165 public void stopped() {} 166 167 /** 168 * Called when a component service has {@linkplain State#FAILED failed}. 169 * 170 * @param service The service that failed. 171 */ 172 public void failure(Service service) {} 173 } 174 175 /** 176 * An encapsulation of all of the state that is accessed by the {@linkplain ServiceListener 177 * service listeners}. This is extracted into its own object so that {@link ServiceListener} could 178 * be made {@code static} and its instances can be safely constructed and added in the 179 * {@link ServiceManager} constructor without having to close over the partially constructed 180 * {@link ServiceManager} instance (i.e. avoid leaking a pointer to {@code this}). 181 */ 182 private final ServiceManagerState state; 183 private final ImmutableList<Service> services; 184 185 /** 186 * Constructs a new instance for managing the given services. 187 * 188 * @param services The services to manage 189 * 190 * @throws IllegalArgumentException if not all services are {@linkplain State#NEW new} or if there 191 * are any duplicate services. 192 */ 193 public ServiceManager(Iterable<? extends Service> services) { 194 ImmutableList<Service> copy = ImmutableList.copyOf(services); 195 if (copy.isEmpty()) { 196 // Having no services causes the manager to behave strangely. Notably, listeners are never 197 // fired. To avoid this we substitute a placeholder service. 198 logger.log( 199 Level.WARNING, 200 "ServiceManager configured with no services. Is your application configured properly?", 201 new EmptyServiceManagerWarning()); 202 copy = ImmutableList.<Service>of(new NoOpService()); 203 } 204 this.state = new ServiceManagerState(copy); 205 this.services = copy; 206 WeakReference<ServiceManagerState> stateReference = 207 new WeakReference<ServiceManagerState>(state); 208 for (Service service : copy) { 209 service.addListener(new ServiceListener(service, stateReference), directExecutor()); 210 // We check the state after adding the listener as a way to ensure that our listener was added 211 // to a NEW service. 212 checkArgument(service.state() == NEW, "Can only manage NEW services, %s", service); 213 } 214 // We have installed all of our listeners and after this point any state transition should be 215 // correct. 216 this.state.markReady(); 217 } 218 219 /** 220 * Registers a {@link Listener} to be {@linkplain Executor#execute executed} on the given 221 * executor. The listener will not have previous state changes replayed, so it is suggested that 222 * listeners are added before any of the managed services are {@linkplain Service#startAsync 223 * started}. 224 * 225 * <p>{@code addListener} guarantees execution ordering across calls to a given listener but not 226 * across calls to multiple listeners. Specifically, a given listener will have its callbacks 227 * invoked in the same order as the underlying service enters those states. Additionally, at most 228 * one of the listener's callbacks will execute at once. However, multiple listeners' callbacks 229 * may execute concurrently, and listeners may execute in an order different from the one in which 230 * they were registered. 231 * 232 * <p>RuntimeExceptions thrown by a listener will be caught and logged. Any exception thrown 233 * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException}) will be caught and 234 * logged. 235 * 236 * <p>For fast, lightweight listeners that would be safe to execute in any thread, consider 237 * calling {@link #addListener(Listener)}. 238 * 239 * @param listener the listener to run when the manager changes state 240 * @param executor the executor in which the listeners callback methods will be run. 241 */ 242 public void addListener(Listener listener, Executor executor) { 243 state.addListener(listener, executor); 244 } 245 246 /** 247 * Registers a {@link Listener} to be run when this {@link ServiceManager} changes state. The 248 * listener will not have previous state changes replayed, so it is suggested that listeners are 249 * added before any of the managed services are {@linkplain Service#startAsync started}. 250 * 251 * <p>{@code addListener} guarantees execution ordering across calls to a given listener but not 252 * across calls to multiple listeners. Specifically, a given listener will have its callbacks 253 * invoked in the same order as the underlying service enters those states. Additionally, at most 254 * one of the listener's callbacks will execute at once. However, multiple listeners' callbacks 255 * may execute concurrently, and listeners may execute in an order different from the one in which 256 * they were registered. 257 * 258 * <p>RuntimeExceptions thrown by a listener will be caught and logged. 259 * 260 * @param listener the listener to run when the manager changes state 261 */ 262 public void addListener(Listener listener) { 263 state.addListener(listener, directExecutor()); 264 } 265 266 /** 267 * Initiates service {@linkplain Service#startAsync startup} on all the services being managed. It 268 * is only valid to call this method if all of the services are {@linkplain State#NEW new}. 269 * 270 * @return this 271 * @throws IllegalStateException if any of the Services are not {@link State#NEW new} when the 272 * method is called. 273 */ 274 @CanIgnoreReturnValue 275 public ServiceManager startAsync() { 276 for (Service service : services) { 277 State state = service.state(); 278 checkState(state == NEW, "Service %s is %s, cannot start it.", service, state); 279 } 280 for (Service service : services) { 281 try { 282 state.tryStartTiming(service); 283 service.startAsync(); 284 } catch (IllegalStateException e) { 285 // This can happen if the service has already been started or stopped (e.g. by another 286 // service or listener). Our contract says it is safe to call this method if 287 // all services were NEW when it was called, and this has already been verified above, so we 288 // don't propagate the exception. 289 logger.log(Level.WARNING, "Unable to start Service " + service, e); 290 } 291 } 292 return this; 293 } 294 295 /** 296 * Waits for the {@link ServiceManager} to become {@linkplain #isHealthy() healthy}. The manager 297 * will become healthy after all the component services have reached the {@linkplain State#RUNNING 298 * running} state. 299 * 300 * @throws IllegalStateException if the service manager reaches a state from which it cannot 301 * become {@linkplain #isHealthy() healthy}. 302 */ 303 public void awaitHealthy() { 304 state.awaitHealthy(); 305 } 306 307 /** 308 * Waits for the {@link ServiceManager} to become {@linkplain #isHealthy() healthy} for no more 309 * than the given time. The manager will become healthy after all the component services have 310 * reached the {@linkplain State#RUNNING running} state. 311 * 312 * @param timeout the maximum time to wait 313 * @param unit the time unit of the timeout argument 314 * @throws TimeoutException if not all of the services have finished starting within the deadline 315 * @throws IllegalStateException if the service manager reaches a state from which it cannot 316 * become {@linkplain #isHealthy() healthy}. 317 */ 318 public void awaitHealthy(long timeout, TimeUnit unit) throws TimeoutException { 319 state.awaitHealthy(timeout, unit); 320 } 321 322 /** 323 * Initiates service {@linkplain Service#stopAsync shutdown} if necessary on all the services 324 * being managed. 325 * 326 * @return this 327 */ 328 @CanIgnoreReturnValue 329 public ServiceManager stopAsync() { 330 for (Service service : services) { 331 service.stopAsync(); 332 } 333 return this; 334 } 335 336 /** 337 * Waits for the all the services to reach a terminal state. After this method returns all 338 * services will either be {@linkplain Service.State#TERMINATED terminated} or 339 * {@linkplain Service.State#FAILED failed}. 340 */ 341 public void awaitStopped() { 342 state.awaitStopped(); 343 } 344 345 /** 346 * Waits for the all the services to reach a terminal state for no more than the given time. After 347 * this method returns all services will either be {@linkplain Service.State#TERMINATED 348 * terminated} or {@linkplain Service.State#FAILED failed}. 349 * 350 * @param timeout the maximum time to wait 351 * @param unit the time unit of the timeout argument 352 * @throws TimeoutException if not all of the services have stopped within the deadline 353 */ 354 public void awaitStopped(long timeout, TimeUnit unit) throws TimeoutException { 355 state.awaitStopped(timeout, unit); 356 } 357 358 /** 359 * Returns true if all services are currently in the {@linkplain State#RUNNING running} state. 360 * 361 * <p>Users who want more detailed information should use the {@link #servicesByState} method to 362 * get detailed information about which services are not running. 363 */ 364 public boolean isHealthy() { 365 for (Service service : services) { 366 if (!service.isRunning()) { 367 return false; 368 } 369 } 370 return true; 371 } 372 373 /** 374 * Provides a snapshot of the current state of all the services under management. 375 * 376 * <p>N.B. This snapshot is guaranteed to be consistent, i.e. the set of states returned will 377 * correspond to a point in time view of the services. 378 */ 379 public ImmutableMultimap<State, Service> servicesByState() { 380 return state.servicesByState(); 381 } 382 383 /** 384 * Returns the service load times. This value will only return startup times for services that 385 * have finished starting. 386 * 387 * @return Map of services and their corresponding startup time in millis, the map entries will be 388 * ordered by startup time. 389 */ 390 public ImmutableMap<Service, Long> startupTimes() { 391 return state.startupTimes(); 392 } 393 394 @Override 395 public String toString() { 396 return MoreObjects.toStringHelper(ServiceManager.class) 397 .add("services", Collections2.filter(services, not(instanceOf(NoOpService.class)))) 398 .toString(); 399 } 400 401 /** 402 * An encapsulation of all the mutable state of the {@link ServiceManager} that needs to be 403 * accessed by instances of {@link ServiceListener}. 404 */ 405 private static final class ServiceManagerState { 406 final Monitor monitor = new Monitor(); 407 408 @GuardedBy("monitor") 409 final SetMultimap<State, Service> servicesByState = 410 MultimapBuilder.enumKeys(State.class).linkedHashSetValues().build(); 411 412 @GuardedBy("monitor") 413 final Multiset<State> states = servicesByState.keys(); 414 415 @GuardedBy("monitor") 416 final Map<Service, Stopwatch> startupTimers = Maps.newIdentityHashMap(); 417 418 /** 419 * These two booleans are used to mark the state as ready to start. 420 * 421 * <p>{@link #ready}: is set by {@link #markReady} to indicate that all listeners have been 422 * correctly installed 423 * 424 * <p>{@link #transitioned}: is set by {@link #transitionService} to indicate that some 425 * transition has been performed. 426 * 427 * <p>Together, they allow us to enforce that all services have their listeners installed prior 428 * to any service performing a transition, then we can fail in the ServiceManager constructor 429 * rather than in a Service.Listener callback. 430 */ 431 @GuardedBy("monitor") 432 boolean ready; 433 434 @GuardedBy("monitor") 435 boolean transitioned; 436 437 final int numberOfServices; 438 439 /** 440 * Controls how long to wait for all the services to either become healthy or reach a state from 441 * which it is guaranteed that it can never become healthy. 442 */ 443 final Monitor.Guard awaitHealthGuard = new AwaitHealthGuard(); 444 445 @WeakOuter 446 final class AwaitHealthGuard extends Monitor.Guard { 447 AwaitHealthGuard() { 448 super(ServiceManagerState.this.monitor); 449 } 450 451 @Override 452 public boolean isSatisfied() { 453 // All services have started or some service has terminated/failed. 454 return states.count(RUNNING) == numberOfServices 455 || states.contains(STOPPING) 456 || states.contains(TERMINATED) 457 || states.contains(FAILED); 458 } 459 } 460 461 /** 462 * Controls how long to wait for all services to reach a terminal state. 463 */ 464 final Monitor.Guard stoppedGuard = new StoppedGuard(); 465 466 @WeakOuter 467 final class StoppedGuard extends Monitor.Guard { 468 StoppedGuard() { 469 super(ServiceManagerState.this.monitor); 470 } 471 472 @Override 473 public boolean isSatisfied() { 474 return states.count(TERMINATED) + states.count(FAILED) == numberOfServices; 475 } 476 } 477 478 /** The listeners to notify during a state transition. */ 479 @GuardedBy("monitor") 480 final List<ListenerCallQueue<Listener>> listeners = 481 Collections.synchronizedList(new ArrayList<ListenerCallQueue<Listener>>()); 482 483 /** 484 * It is implicitly assumed that all the services are NEW and that they will all remain NEW 485 * until all the Listeners are installed and {@link #markReady()} is called. It is our caller's 486 * responsibility to only call {@link #markReady()} if all services were new at the time this 487 * method was called and when all the listeners were installed. 488 */ 489 ServiceManagerState(ImmutableCollection<Service> services) { 490 this.numberOfServices = services.size(); 491 servicesByState.putAll(NEW, services); 492 } 493 494 /** 495 * Attempts to start the timer immediately prior to the service being started via 496 * {@link Service#startAsync()}. 497 */ 498 void tryStartTiming(Service service) { 499 monitor.enter(); 500 try { 501 Stopwatch stopwatch = startupTimers.get(service); 502 if (stopwatch == null) { 503 startupTimers.put(service, Stopwatch.createStarted()); 504 } 505 } finally { 506 monitor.leave(); 507 } 508 } 509 510 /** 511 * Marks the {@link State} as ready to receive transitions. Returns true if no transitions have 512 * been observed yet. 513 */ 514 void markReady() { 515 monitor.enter(); 516 try { 517 if (!transitioned) { 518 // nothing has transitioned since construction, good. 519 ready = true; 520 } else { 521 // This should be an extremely rare race condition. 522 List<Service> servicesInBadStates = Lists.newArrayList(); 523 for (Service service : servicesByState().values()) { 524 if (service.state() != NEW) { 525 servicesInBadStates.add(service); 526 } 527 } 528 throw new IllegalArgumentException( 529 "Services started transitioning asynchronously before " 530 + "the ServiceManager was constructed: " 531 + servicesInBadStates); 532 } 533 } finally { 534 monitor.leave(); 535 } 536 } 537 538 void addListener(Listener listener, Executor executor) { 539 checkNotNull(listener, "listener"); 540 checkNotNull(executor, "executor"); 541 monitor.enter(); 542 try { 543 // no point in adding a listener that will never be called 544 if (!stoppedGuard.isSatisfied()) { 545 listeners.add(new ListenerCallQueue<Listener>(listener, executor)); 546 } 547 } finally { 548 monitor.leave(); 549 } 550 } 551 552 void awaitHealthy() { 553 monitor.enterWhenUninterruptibly(awaitHealthGuard); 554 try { 555 checkHealthy(); 556 } finally { 557 monitor.leave(); 558 } 559 } 560 561 void awaitHealthy(long timeout, TimeUnit unit) throws TimeoutException { 562 monitor.enter(); 563 try { 564 if (!monitor.waitForUninterruptibly(awaitHealthGuard, timeout, unit)) { 565 throw new TimeoutException( 566 "Timeout waiting for the services to become healthy. The " 567 + "following services have not started: " 568 + Multimaps.filterKeys(servicesByState, in(ImmutableSet.of(NEW, STARTING)))); 569 } 570 checkHealthy(); 571 } finally { 572 monitor.leave(); 573 } 574 } 575 576 void awaitStopped() { 577 monitor.enterWhenUninterruptibly(stoppedGuard); 578 monitor.leave(); 579 } 580 581 void awaitStopped(long timeout, TimeUnit unit) throws TimeoutException { 582 monitor.enter(); 583 try { 584 if (!monitor.waitForUninterruptibly(stoppedGuard, timeout, unit)) { 585 throw new TimeoutException( 586 "Timeout waiting for the services to stop. The following " 587 + "services have not stopped: " 588 + Multimaps.filterKeys(servicesByState, not(in(EnumSet.of(TERMINATED, FAILED))))); 589 } 590 } finally { 591 monitor.leave(); 592 } 593 } 594 595 ImmutableMultimap<State, Service> servicesByState() { 596 ImmutableSetMultimap.Builder<State, Service> builder = ImmutableSetMultimap.builder(); 597 monitor.enter(); 598 try { 599 for (Entry<State, Service> entry : servicesByState.entries()) { 600 if (!(entry.getValue() instanceof NoOpService)) { 601 builder.put(entry); 602 } 603 } 604 } finally { 605 monitor.leave(); 606 } 607 return builder.build(); 608 } 609 610 ImmutableMap<Service, Long> startupTimes() { 611 List<Entry<Service, Long>> loadTimes; 612 monitor.enter(); 613 try { 614 loadTimes = Lists.newArrayListWithCapacity(startupTimers.size()); 615 // N.B. There will only be an entry in the map if the service has started 616 for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) { 617 Service service = entry.getKey(); 618 Stopwatch stopWatch = entry.getValue(); 619 if (!stopWatch.isRunning() && !(service instanceof NoOpService)) { 620 loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS))); 621 } 622 } 623 } finally { 624 monitor.leave(); 625 } 626 Collections.sort( 627 loadTimes, 628 Ordering.natural() 629 .onResultOf( 630 new Function<Entry<Service, Long>, Long>() { 631 @Override 632 public Long apply(Map.Entry<Service, Long> input) { 633 return input.getValue(); 634 } 635 })); 636 return ImmutableMap.copyOf(loadTimes); 637 } 638 639 /** 640 * Updates the state with the given service transition. 641 * 642 * <p>This method performs the main logic of ServiceManager in the following steps. 643 * <ol> 644 * <li>Update the {@link #servicesByState()} 645 * <li>Update the {@link #startupTimers} 646 * <li>Based on the new state queue listeners to run 647 * <li>Run the listeners (outside of the lock) 648 * </ol> 649 */ 650 void transitionService(final Service service, State from, State to) { 651 checkNotNull(service); 652 checkArgument(from != to); 653 monitor.enter(); 654 try { 655 transitioned = true; 656 if (!ready) { 657 return; 658 } 659 // Update state. 660 checkState( 661 servicesByState.remove(from, service), 662 "Service %s not at the expected location in the state map %s", 663 service, 664 from); 665 checkState( 666 servicesByState.put(to, service), 667 "Service %s in the state map unexpectedly at %s", 668 service, 669 to); 670 // Update the timer 671 Stopwatch stopwatch = startupTimers.get(service); 672 if (stopwatch == null) { 673 // This means the service was started by some means other than ServiceManager.startAsync 674 stopwatch = Stopwatch.createStarted(); 675 startupTimers.put(service, stopwatch); 676 } 677 if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) { 678 // N.B. if we miss the STARTING event then we may never record a startup time. 679 stopwatch.stop(); 680 if (!(service instanceof NoOpService)) { 681 logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch}); 682 } 683 } 684 // Queue our listeners 685 686 // Did a service fail? 687 if (to == FAILED) { 688 fireFailedListeners(service); 689 } 690 691 if (states.count(RUNNING) == numberOfServices) { 692 // This means that the manager is currently healthy. N.B. If other threads call isHealthy 693 // they are not guaranteed to get 'true', because any service could fail right now. 694 fireHealthyListeners(); 695 } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) { 696 fireStoppedListeners(); 697 } 698 } finally { 699 monitor.leave(); 700 // Run our executors outside of the lock 701 executeListeners(); 702 } 703 } 704 705 @GuardedBy("monitor") 706 void fireStoppedListeners() { 707 STOPPED_CALLBACK.enqueueOn(listeners); 708 } 709 710 @GuardedBy("monitor") 711 void fireHealthyListeners() { 712 HEALTHY_CALLBACK.enqueueOn(listeners); 713 } 714 715 @GuardedBy("monitor") 716 void fireFailedListeners(final Service service) { 717 new Callback<Listener>("failed({service=" + service + "})") { 718 @Override 719 void call(Listener listener) { 720 listener.failure(service); 721 } 722 }.enqueueOn(listeners); 723 } 724 725 /** Attempts to execute all the listeners in {@link #listeners}. */ 726 void executeListeners() { 727 checkState( 728 !monitor.isOccupiedByCurrentThread(), 729 "It is incorrect to execute listeners with the monitor held."); 730 // iterate by index to avoid concurrent modification exceptions 731 for (int i = 0; i < listeners.size(); i++) { 732 listeners.get(i).execute(); 733 } 734 } 735 736 @GuardedBy("monitor") 737 void checkHealthy() { 738 if (states.count(RUNNING) != numberOfServices) { 739 IllegalStateException exception = 740 new IllegalStateException( 741 "Expected to be healthy after starting. The following services are not running: " 742 + Multimaps.filterKeys(servicesByState, not(equalTo(RUNNING)))); 743 throw exception; 744 } 745 } 746 } 747 748 /** 749 * A {@link Service} that wraps another service and times how long it takes for it to start and 750 * also calls the {@link ServiceManagerState#transitionService(Service, State, State)}, to record 751 * the state transitions. 752 */ 753 private static final class ServiceListener extends Service.Listener { 754 final Service service; 755 // We store the state in a weak reference to ensure that if something went wrong while 756 // constructing the ServiceManager we don't pointlessly keep updating the state. 757 final WeakReference<ServiceManagerState> state; 758 759 ServiceListener(Service service, WeakReference<ServiceManagerState> state) { 760 this.service = service; 761 this.state = state; 762 } 763 764 @Override 765 public void starting() { 766 ServiceManagerState state = this.state.get(); 767 if (state != null) { 768 state.transitionService(service, NEW, STARTING); 769 if (!(service instanceof NoOpService)) { 770 logger.log(Level.FINE, "Starting {0}.", service); 771 } 772 } 773 } 774 775 @Override 776 public void running() { 777 ServiceManagerState state = this.state.get(); 778 if (state != null) { 779 state.transitionService(service, STARTING, RUNNING); 780 } 781 } 782 783 @Override 784 public void stopping(State from) { 785 ServiceManagerState state = this.state.get(); 786 if (state != null) { 787 state.transitionService(service, from, STOPPING); 788 } 789 } 790 791 @Override 792 public void terminated(State from) { 793 ServiceManagerState state = this.state.get(); 794 if (state != null) { 795 if (!(service instanceof NoOpService)) { 796 logger.log( 797 Level.FINE, 798 "Service {0} has terminated. Previous state was: {1}", 799 new Object[] {service, from}); 800 } 801 state.transitionService(service, from, TERMINATED); 802 } 803 } 804 805 @Override 806 public void failed(State from, Throwable failure) { 807 ServiceManagerState state = this.state.get(); 808 if (state != null) { 809 // Log before the transition, so that if the process exits in response to server failure, 810 // there is a higher likelihood that the cause will be in the logs. 811 boolean log = !(service instanceof NoOpService); 812 if (log) { 813 logger.log( 814 Level.SEVERE, 815 "Service " + service + " has failed in the " + from + " state.", 816 failure); 817 } 818 state.transitionService(service, from, FAILED); 819 } 820 } 821 } 822 823 /** 824 * A {@link Service} instance that does nothing. This is only useful as a placeholder to ensure 825 * that the {@link ServiceManager} functions properly even when it is managing no services. 826 * 827 * <p>The use of this class is considered an implementation detail of ServiceManager and as such 828 * it is excluded from {@link #servicesByState}, {@link #startupTimes}, {@link #toString} and all 829 * logging statements. 830 */ 831 private static final class NoOpService extends AbstractService { 832 @Override 833 protected void doStart() { 834 notifyStarted(); 835 } 836 837 @Override 838 protected void doStop() { 839 notifyStopped(); 840 } 841 } 842 843 /** This is never thrown but only used for logging. */ 844 private static final class EmptyServiceManagerWarning extends Throwable {} 845}