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