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