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