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