You are viewing a plain text version of this content. The canonical link for it is here.
Posted to common-commits@hadoop.apache.org by vi...@apache.org on 2013/06/17 08:39:35 UTC

svn commit: r1493650 [1/2] - in /hadoop/common/trunk/hadoop-common-project/hadoop-common: ./ dev-support/ src/main/java/org/apache/hadoop/service/ src/test/java/org/apache/hadoop/service/

Author: vinodkv
Date: Mon Jun 17 06:39:33 2013
New Revision: 1493650

URL: http://svn.apache.org/r1493650
Log:
HADOOP-9649. Promoted YARN service life-cycle libraries into Hadoop Common for usage across all Hadoop projects. Contributed by Zhijie Shen.

Added:
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/AbstractService.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/CompositeService.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LifecycleEvent.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LoggingStateChangeListener.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/Service.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceOperations.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateChangeListener.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateException.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateModel.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/package-info.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableService.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableStateChangeListener.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/ServiceAssert.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestGlobalStateChangeListener.java
    hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestServiceLifecycle.java
Modified:
    hadoop/common/trunk/hadoop-common-project/hadoop-common/CHANGES.txt
    hadoop/common/trunk/hadoop-common-project/hadoop-common/dev-support/findbugsExcludeFile.xml

Modified: hadoop/common/trunk/hadoop-common-project/hadoop-common/CHANGES.txt
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/CHANGES.txt?rev=1493650&r1=1493649&r2=1493650&view=diff
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/CHANGES.txt (original)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/CHANGES.txt Mon Jun 17 06:39:33 2013
@@ -454,6 +454,9 @@ Release 2.1.0-beta - UNRELEASED
     HADOOP-9625. HADOOP_OPTS not picked up by hadoop command.
     (Paul Han via arpit)
 
+    HADOOP-9649. Promoted YARN service life-cycle libraries into Hadoop Common
+    for usage across all Hadoop projects. (Zhijie Shen via vinodkv)
+
   OPTIMIZATIONS
 
     HADOOP-9150. Avoid unnecessary DNS resolution attempts for logical URIs

Modified: hadoop/common/trunk/hadoop-common-project/hadoop-common/dev-support/findbugsExcludeFile.xml
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/dev-support/findbugsExcludeFile.xml?rev=1493650&r1=1493649&r2=1493650&view=diff
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/dev-support/findbugsExcludeFile.xml (original)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/dev-support/findbugsExcludeFile.xml Mon Jun 17 06:39:33 2013
@@ -320,4 +320,17 @@
        <Field name="in" />
        <Bug pattern="IS2_INCONSISTENT_SYNC" />
      </Match>
+
+     <!-- Synchronization performed on util.concurrent instance. -->
+     <Match>
+       <Class name="org.apache.hadoop.service.AbstractService" />
+       <Method name="stop" />
+       <Bug code="JLM" />
+     </Match>
+
+     <Match>
+       <Class name="org.apache.hadoop.service.AbstractService" />
+       <Method name="waitForServiceToStop" />
+       <Bug code="JLM" />
+     </Match>
  </FindBugsFilter>

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/AbstractService.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/AbstractService.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/AbstractService.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/AbstractService.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,500 @@
+/**
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements.  See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership.  The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License.  You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package org.apache.hadoop.service;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+import org.apache.hadoop.conf.Configuration;
+
+import com.google.common.annotations.VisibleForTesting;
+
+/**
+ * This is the base implementation class for services.
+ */
+@Public
+@Evolving
+public abstract class AbstractService implements Service {
+
+  private static final Log LOG = LogFactory.getLog(AbstractService.class);
+
+  /**
+   * Service name.
+   */
+  private final String name;
+
+  /** service state */
+  private final ServiceStateModel stateModel;
+
+  /**
+   * Service start time. Will be zero until the service is started.
+   */
+  private long startTime;
+
+  /**
+   * The configuration. Will be null until the service is initialized.
+   */
+  private volatile Configuration config;
+
+  /**
+   * List of state change listeners; it is final to ensure
+   * that it will never be null.
+   */
+  private final ServiceOperations.ServiceListeners listeners
+    = new ServiceOperations.ServiceListeners();
+  /**
+   * Static listeners to all events across all services
+   */
+  private static ServiceOperations.ServiceListeners globalListeners
+    = new ServiceOperations.ServiceListeners();
+
+  /**
+   * The cause of any failure -will be null.
+   * if a service did not stop due to a failure.
+   */
+  private Exception failureCause;
+
+  /**
+   * the state in which the service was when it failed.
+   * Only valid when the service is stopped due to a failure
+   */
+  private STATE failureState = null;
+
+  /**
+   * object used to co-ordinate {@link #waitForServiceToStop(long)}
+   * across threads.
+   */
+  private final AtomicBoolean terminationNotification =
+    new AtomicBoolean(false);
+
+  /**
+   * History of lifecycle transitions
+   */
+  private final List<LifecycleEvent> lifecycleHistory
+    = new ArrayList<LifecycleEvent>(5);
+
+  /**
+   * Map of blocking dependencies
+   */
+  private final Map<String,String> blockerMap = new HashMap<String, String>();
+
+  private final Object stateChangeLock = new Object();
+ 
+  /**
+   * Construct the service.
+   * @param name service name
+   */
+  public AbstractService(String name) {
+    this.name = name;
+    stateModel = new ServiceStateModel(name);
+  }
+
+  @Override
+  public final STATE getServiceState() {
+    return stateModel.getState();
+  }
+
+  @Override
+  public final synchronized Throwable getFailureCause() {
+    return failureCause;
+  }
+
+  @Override
+  public synchronized STATE getFailureState() {
+    return failureState;
+  }
+
+  /**
+   * Set the configuration for this service.
+   * This method is called during {@link #init(Configuration)}
+   * and should only be needed if for some reason a service implementation
+   * needs to override that initial setting -for example replacing
+   * it with a new subclass of {@link Configuration}
+   * @param conf new configuration.
+   */
+  protected void setConfig(Configuration conf) {
+    this.config = conf;
+  }
+
+  /**
+   * {@inheritDoc}
+   * This invokes {@link #serviceInit}
+   * @param conf the configuration of the service. This must not be null
+   * @throws ServiceStateException if the configuration was null,
+   * the state change not permitted, or something else went wrong
+   */
+  @Override
+  public void init(Configuration conf) {
+    if (conf == null) {
+      throw new ServiceStateException("Cannot initialize service "
+                                      + getName() + ": null configuration");
+    }
+    if (isInState(STATE.INITED)) {
+      return;
+    }
+    synchronized (stateChangeLock) {
+      if (enterState(STATE.INITED) != STATE.INITED) {
+        setConfig(conf);
+        try {
+          serviceInit(config);
+          if (isInState(STATE.INITED)) {
+            //if the service ended up here during init,
+            //notify the listeners
+            notifyListeners();
+          }
+        } catch (Exception e) {
+          noteFailure(e);
+          ServiceOperations.stopQuietly(LOG, this);
+          throw ServiceStateException.convert(e);
+        }
+      }
+    }
+  }
+
+  /**
+   * {@inheritDoc}
+   * @throws ServiceStateException if the current service state does not permit
+   * this action
+   */
+  @Override
+  public void start() {
+    if (isInState(STATE.STARTED)) {
+      return;
+    }
+    //enter the started state
+    synchronized (stateChangeLock) {
+      if (stateModel.enterState(STATE.STARTED) != STATE.STARTED) {
+        try {
+          startTime = System.currentTimeMillis();
+          serviceStart();
+          if (isInState(STATE.STARTED)) {
+            //if the service started (and isn't now in a later state), notify
+            if (LOG.isDebugEnabled()) {
+              LOG.debug("Service " + getName() + " is started");
+            }
+            notifyListeners();
+          }
+        } catch (Exception e) {
+          noteFailure(e);
+          ServiceOperations.stopQuietly(LOG, this);
+          throw ServiceStateException.convert(e);
+        }
+      }
+    }
+  }
+
+  /**
+   * {@inheritDoc}
+   */
+  @Override
+  public void stop() {
+    if (isInState(STATE.STOPPED)) {
+      return;
+    }
+    synchronized (stateChangeLock) {
+      if (enterState(STATE.STOPPED) != STATE.STOPPED) {
+        try {
+          serviceStop();
+        } catch (Exception e) {
+          //stop-time exceptions are logged if they are the first one,
+          noteFailure(e);
+          throw ServiceStateException.convert(e);
+        } finally {
+          //report that the service has terminated
+          terminationNotification.set(true);
+          synchronized (terminationNotification) {
+            terminationNotification.notifyAll();
+          }
+          //notify anything listening for events
+          notifyListeners();
+        }
+      } else {
+        //already stopped: note it
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Ignoring re-entrant call to stop()");
+        }
+      }
+    }
+  }
+
+  /**
+   * Relay to {@link #stop()}
+   * @throws IOException
+   */
+  @Override
+  public final void close() throws IOException {
+    stop();
+  }
+
+  /**
+   * Failure handling: record the exception
+   * that triggered it -if there was not one already.
+   * Services are free to call this themselves.
+   * @param exception the exception
+   */
+  protected final void noteFailure(Exception exception) {
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("noteFailure " + exception, null);
+    }
+    if (exception == null) {
+      //make sure failure logic doesn't itself cause problems
+      return;
+    }
+    //record the failure details, and log it
+    synchronized (this) {
+      if (failureCause == null) {
+        failureCause = exception;
+        failureState = getServiceState();
+        LOG.info("Service " + getName()
+                 + " failed in state " + failureState
+                 + "; cause: " + exception,
+                 exception);
+      }
+    }
+  }
+
+  @Override
+  public final boolean waitForServiceToStop(long timeout) {
+    boolean completed = terminationNotification.get();
+    while (!completed) {
+      try {
+        synchronized(terminationNotification) {
+          terminationNotification.wait(timeout);
+        }
+        // here there has been a timeout, the object has terminated,
+        // or there has been a spurious wakeup (which we ignore)
+        completed = true;
+      } catch (InterruptedException e) {
+        // interrupted; have another look at the flag
+        completed = terminationNotification.get();
+      }
+    }
+    return terminationNotification.get();
+  }
+
+  /* ===================================================================== */
+  /* Override Points */
+  /* ===================================================================== */
+
+  /**
+   * All initialization code needed by a service.
+   *
+   * This method will only ever be called once during the lifecycle of
+   * a specific service instance.
+   *
+   * Implementations do not need to be synchronized as the logic
+   * in {@link #init(Configuration)} prevents re-entrancy.
+   *
+   * The base implementation checks to see if the subclass has created
+   * a new configuration instance, and if so, updates the base class value
+   * @param conf configuration
+   * @throws Exception on a failure -these will be caught,
+   * possibly wrapped, and wil; trigger a service stop
+   */
+  protected void serviceInit(Configuration conf) throws Exception {
+    if (conf != config) {
+      LOG.debug("Config has been overridden during init");
+      setConfig(conf);
+    }
+  }
+
+  /**
+   * Actions called during the INITED to STARTED transition.
+   *
+   * This method will only ever be called once during the lifecycle of
+   * a specific service instance.
+   *
+   * Implementations do not need to be synchronized as the logic
+   * in {@link #start()} prevents re-entrancy.
+   *
+   * @throws Exception if needed -these will be caught,
+   * wrapped, and trigger a service stop
+   */
+  protected void serviceStart() throws Exception {
+
+  }
+
+  /**
+   * Actions called during the transition to the STOPPED state.
+   *
+   * This method will only ever be called once during the lifecycle of
+   * a specific service instance.
+   *
+   * Implementations do not need to be synchronized as the logic
+   * in {@link #stop()} prevents re-entrancy.
+   *
+   * Implementations MUST write this to be robust against failures, including
+   * checks for null references -and for the first failure to not stop other
+   * attempts to shut down parts of the service.
+   *
+   * @throws Exception if needed -these will be caught and logged.
+   */
+  protected void serviceStop() throws Exception {
+
+  }
+
+  @Override
+  public void registerServiceListener(ServiceStateChangeListener l) {
+    listeners.add(l);
+  }
+
+  @Override
+  public void unregisterServiceListener(ServiceStateChangeListener l) {
+    listeners.remove(l);
+  }
+
+  /**
+   * Register a global listener, which receives notifications
+   * from the state change events of all services in the JVM
+   * @param l listener
+   */
+  public static void registerGlobalListener(ServiceStateChangeListener l) {
+    globalListeners.add(l);
+  }
+
+  /**
+   * unregister a global listener.
+   * @param l listener to unregister
+   * @return true if the listener was found (and then deleted)
+   */
+  public static boolean unregisterGlobalListener(ServiceStateChangeListener l) {
+    return globalListeners.remove(l);
+  }
+
+  /**
+   * Package-scoped method for testing -resets the global listener list
+   */
+  @VisibleForTesting
+  static void resetGlobalListeners() {
+    globalListeners.reset();
+  }
+
+  @Override
+  public String getName() {
+    return name;
+  }
+
+  @Override
+  public synchronized Configuration getConfig() {
+    return config;
+  }
+
+  @Override
+  public long getStartTime() {
+    return startTime;
+  }
+
+  /**
+   * Notify local and global listeners of state changes.
+   * Exceptions raised by listeners are NOT passed up.
+   */
+  private void notifyListeners() {
+    try {
+      listeners.notifyListeners(this);
+      globalListeners.notifyListeners(this);
+    } catch (Throwable e) {
+      LOG.warn("Exception while notifying listeners of " + this + ": " + e,
+               e);
+    }
+  }
+
+  /**
+   * Add a state change event to the lifecycle history
+   */
+  private void recordLifecycleEvent() {
+    LifecycleEvent event = new LifecycleEvent();
+    event.time = System.currentTimeMillis();
+    event.state = getServiceState();
+    lifecycleHistory.add(event);
+  }
+
+  @Override
+  public synchronized List<LifecycleEvent> getLifecycleHistory() {
+    return new ArrayList<LifecycleEvent>(lifecycleHistory);
+  }
+
+  /**
+   * Enter a state; record this via {@link #recordLifecycleEvent}
+   * and log at the info level.
+   * @param newState the proposed new state
+   * @return the original state
+   * it wasn't already in that state, and the state model permits state re-entrancy.
+   */
+  private STATE enterState(STATE newState) {
+    assert stateModel != null : "null state in " + name + " " + this.getClass();
+    STATE oldState = stateModel.enterState(newState);
+    if (oldState != newState) {
+      if (LOG.isDebugEnabled()) {
+        LOG.debug(
+          "Service: " + getName() + " entered state " + getServiceState());
+      }
+      recordLifecycleEvent();
+    }
+    return oldState;
+  }
+
+  @Override
+  public final boolean isInState(Service.STATE expected) {
+    return stateModel.isInState(expected);
+  }
+
+  @Override
+  public String toString() {
+    return "Service " + name + " in state " + stateModel;
+  }
+
+  /**
+   * Put a blocker to the blocker map -replacing any
+   * with the same name.
+   * @param name blocker name
+   * @param details any specifics on the block. This must be non-null.
+   */
+  protected void putBlocker(String name, String details) {
+    synchronized (blockerMap) {
+      blockerMap.put(name, details);
+    }
+  }
+
+  /**
+   * Remove a blocker from the blocker map -
+   * this is a no-op if the blocker is not present
+   * @param name the name of the blocker
+   */
+  public void removeBlocker(String name) {
+    synchronized (blockerMap) {
+      blockerMap.remove(name);
+    }
+  }
+
+  @Override
+  public Map<String, String> getBlockers() {
+    synchronized (blockerMap) {
+      Map<String, String> map = new HashMap<String, String>(blockerMap);
+      return map;
+    }
+  }
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/CompositeService.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/CompositeService.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/CompositeService.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/CompositeService.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.service;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+import org.apache.hadoop.conf.Configuration;
+
+/**
+ * Composition of services.
+ */
+@Public
+@Evolving
+public class CompositeService extends AbstractService {
+
+  private static final Log LOG = LogFactory.getLog(CompositeService.class);
+
+  /**
+   * Policy on shutdown: attempt to close everything (purest) or
+   * only try to close started services (which assumes
+   * that the service implementations may not handle the stop() operation
+   * except when started.
+   * Irrespective of this policy, if a child service fails during
+   * its init() or start() operations, it will have stop() called on it.
+   */
+  protected static final boolean STOP_ONLY_STARTED_SERVICES = false;
+
+  private final List<Service> serviceList = new ArrayList<Service>();
+
+  public CompositeService(String name) {
+    super(name);
+  }
+
+  /**
+   * Get an unmodifiable list of services
+   * @return a list of child services at the time of invocation -
+   * added services will not be picked up.
+   */
+  public List<Service> getServices() {
+    synchronized (serviceList) {
+      return Collections.unmodifiableList(serviceList);
+    }
+  }
+
+  protected void addService(Service service) {
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("Adding service " + service.getName());
+    }
+    synchronized (serviceList) {
+      serviceList.add(service);
+    }
+  }
+
+  protected synchronized boolean removeService(Service service) {
+    synchronized (serviceList) {
+      return serviceList.add(service);
+    }
+  }
+
+  protected void serviceInit(Configuration conf) throws Exception {
+    List<Service> services = getServices();
+    if (LOG.isDebugEnabled()) {
+      LOG.debug(getName() + ": initing services, size=" + services.size());
+    }
+    for (Service service : services) {
+      service.init(conf);
+    }
+    super.serviceInit(conf);
+  }
+
+  protected void serviceStart() throws Exception {
+    List<Service> services = getServices();
+    if (LOG.isDebugEnabled()) {
+      LOG.debug(getName() + ": starting services, size=" + services.size());
+    }
+    for (Service service : services) {
+      // start the service. If this fails that service
+      // will be stopped and an exception raised
+      service.start();
+    }
+    super.serviceStart();
+  }
+
+  protected void serviceStop() throws Exception {
+    //stop all services that were started
+    int numOfServicesToStop = serviceList.size();
+    if (LOG.isDebugEnabled()) {
+      LOG.debug(getName() + ": stopping services, size=" + numOfServicesToStop);
+    }
+    stop(numOfServicesToStop, STOP_ONLY_STARTED_SERVICES);
+    super.serviceStop();
+  }
+
+  /**
+   * Stop the services in reverse order
+   *
+   * @param numOfServicesStarted index from where the stop should work
+   * @param stopOnlyStartedServices flag to say "only start services that are
+   * started, not those that are NOTINITED or INITED.
+   * @throws RuntimeException the first exception raised during the
+   * stop process -<i>after all services are stopped</i>
+   */
+  private synchronized void stop(int numOfServicesStarted,
+                                 boolean stopOnlyStartedServices) {
+    // stop in reverse order of start
+    Exception firstException = null;
+    List<Service> services = getServices();
+    for (int i = numOfServicesStarted - 1; i >= 0; i--) {
+      Service service = services.get(i);
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("Stopping service #" + i + ": " + service);
+      }
+      STATE state = service.getServiceState();
+      //depending on the stop police
+      if (state == STATE.STARTED 
+         || (!stopOnlyStartedServices && state == STATE.INITED)) {
+        Exception ex = ServiceOperations.stopQuietly(LOG, service);
+        if (ex != null && firstException == null) {
+          firstException = ex;
+        }
+      }
+    }
+    //after stopping all services, rethrow the first exception raised
+    if (firstException != null) {
+      throw ServiceStateException.convert(firstException);
+    }
+  }
+
+  /**
+   * JVM Shutdown hook for CompositeService which will stop the give
+   * CompositeService gracefully in case of JVM shutdown.
+   */
+  public static class CompositeServiceShutdownHook implements Runnable {
+
+    private CompositeService compositeService;
+
+    public CompositeServiceShutdownHook(CompositeService compositeService) {
+      this.compositeService = compositeService;
+    }
+
+    @Override
+    public void run() {
+      ServiceOperations.stopQuietly(compositeService);
+    }
+  }
+
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LifecycleEvent.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LifecycleEvent.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LifecycleEvent.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LifecycleEvent.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.service;
+
+import java.io.Serializable;
+
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+
+/**
+ * A serializable lifecycle event: the time a state
+ * transition occurred, and what state was entered.
+ */
+@Public
+@Evolving
+public class LifecycleEvent implements Serializable {
+  
+  private static final long serialVersionUID = 1648576996238247836L;
+
+  /**
+   * Local time in milliseconds when the event occurred
+   */
+  public long time;
+  /**
+   * new state
+   */
+  public Service.STATE state;
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LoggingStateChangeListener.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LoggingStateChangeListener.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LoggingStateChangeListener.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/LoggingStateChangeListener.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.hadoop.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+
+/**
+ * This is a state change listener that logs events at INFO level
+ */
+@Public
+@Evolving
+public class LoggingStateChangeListener implements ServiceStateChangeListener {
+
+  private static final Log LOG = LogFactory.getLog(LoggingStateChangeListener.class);
+
+  private final Log log;
+
+  /**
+   * Log events to the given log
+   * @param log destination for events
+   */
+  public LoggingStateChangeListener(Log log) {
+    //force an NPE if a null log came in
+    log.isDebugEnabled();
+    this.log = log;
+  }
+
+  /**
+   * Log events to the static log for this class
+   */
+  public LoggingStateChangeListener() {
+    this(LOG);
+  }
+
+  /**
+   * Callback for a state change event: log it
+   * @param service the service that has changed.
+   */
+  @Override
+  public void stateChanged(Service service) {
+    log.info("Entry to state "  + service.getServiceState()
+                 + " for " + service.getName());
+  }
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/Service.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/Service.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/Service.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/Service.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,225 @@
+/**
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements.  See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership.  The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License.  You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package org.apache.hadoop.service;
+
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+import org.apache.hadoop.conf.Configuration;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Service LifeCycle.
+ */
+@Public
+@Evolving
+public interface Service extends Closeable {
+
+  /**
+   * Service states
+   */
+  public enum STATE {
+    /** Constructed but not initialized */
+    NOTINITED(0, "NOTINITED"),
+
+    /** Initialized but not started or stopped */
+    INITED(1, "INITED"),
+
+    /** started and not stopped */
+    STARTED(2, "STARTED"),
+
+    /** stopped. No further state transitions are permitted */
+    STOPPED(3, "STOPPED");
+
+    /**
+     * An integer value for use in array lookup and JMX interfaces.
+     * Although {@link Enum#ordinal()} could do this, explicitly
+     * identify the numbers gives more stability guarantees over time.
+     */
+    private final int value;
+
+    /**
+     * A name of the state that can be used in messages
+     */
+    private final String statename;
+
+    private STATE(int value, String name) {
+      this.value = value;
+      this.statename = name;
+    }
+
+    /**
+     * Get the integer value of a state
+     * @return the numeric value of the state
+     */
+    public int getValue() {
+      return value;
+    }
+
+    /**
+     * Get the name of a state
+     * @return the state's name
+     */
+    @Override
+    public String toString() {
+      return statename;
+    }
+  }
+
+  /**
+   * Initialize the service.
+   *
+   * The transition MUST be from {@link STATE#NOTINITED} to {@link STATE#INITED}
+   * unless the operation failed and an exception was raised, in which case
+   * {@link #stop()} MUST be invoked and the service enter the state
+   * {@link STATE#STOPPED}.
+   * @param config the configuration of the service
+   * @throws RuntimeException on any failure during the operation
+
+   */
+  void init(Configuration config);
+
+
+  /**
+   * Start the service.
+   *
+   * The transition MUST be from {@link STATE#INITED} to {@link STATE#STARTED}
+   * unless the operation failed and an exception was raised, in which case
+   * {@link #stop()} MUST be invoked and the service enter the state
+   * {@link STATE#STOPPED}.
+   * @throws RuntimeException on any failure during the operation
+   */
+
+  void start();
+
+  /**
+   * Stop the service. This MUST be a no-op if the service is already
+   * in the {@link STATE#STOPPED} state. It SHOULD be a best-effort attempt
+   * to stop all parts of the service.
+   *
+   * The implementation must be designed to complete regardless of the service
+   * state, including the initialized/uninitialized state of all its internal
+   * fields.
+   * @throws RuntimeException on any failure during the stop operation
+   */
+  void stop();
+
+  /**
+   * A version of stop() that is designed to be usable in Java7 closure
+   * clauses.
+   * Implementation classes MUST relay this directly to {@link #stop()}
+   * @throws IOException never
+   * @throws RuntimeException on any failure during the stop operation
+   */
+  void close() throws IOException;
+
+  /**
+   * Register a listener to the service state change events.
+   * If the supplied listener is already listening to this service,
+   * this method is a no-op.
+   * @param listener a new listener
+   */
+  void registerServiceListener(ServiceStateChangeListener listener);
+
+  /**
+   * Unregister a previously registered listener of the service state
+   * change events. No-op if the listener is already unregistered.
+   * @param listener the listener to unregister.
+   */
+  void unregisterServiceListener(ServiceStateChangeListener listener);
+
+  /**
+   * Get the name of this service.
+   * @return the service name
+   */
+  String getName();
+
+  /**
+   * Get the configuration of this service.
+   * This is normally not a clone and may be manipulated, though there are no
+   * guarantees as to what the consequences of such actions may be
+   * @return the current configuration, unless a specific implentation chooses
+   * otherwise.
+   */
+  Configuration getConfig();
+
+  /**
+   * Get the current service state
+   * @return the state of the service
+   */
+  STATE getServiceState();
+
+  /**
+   * Get the service start time
+   * @return the start time of the service. This will be zero if the service
+   * has not yet been started.
+   */
+  long getStartTime();
+
+  /**
+   * Query to see if the service is in a specific state.
+   * In a multi-threaded system, the state may not hold for very long.
+   * @param state the expected state
+   * @return true if, at the time of invocation, the service was in that state.
+   */
+  boolean isInState(STATE state);
+
+  /**
+   * Get the first exception raised during the service failure. If null,
+   * no exception was logged
+   * @return the failure logged during a transition to the stopped state
+   */
+  Throwable getFailureCause();
+
+  /**
+   * Get the state in which the failure in {@link #getFailureCause()} occurred.
+   * @return the state or null if there was no failure
+   */
+  STATE getFailureState();
+
+  /**
+   * Block waiting for the service to stop; uses the termination notification
+   * object to do so.
+   *
+   * This method will only return after all the service stop actions
+   * have been executed (to success or failure), or the timeout elapsed
+   * This method can be called before the service is inited or started; this is
+   * to eliminate any race condition with the service stopping before
+   * this event occurs.
+   * @param timeout timeout in milliseconds. A value of zero means "forever"
+   * @return true iff the service stopped in the time period
+   */
+  boolean waitForServiceToStop(long timeout);
+
+  /**
+   * Get a snapshot of the lifecycle history; it is a static list
+   * @return a possibly empty but never null list of lifecycle events.
+   */
+  public List<LifecycleEvent> getLifecycleHistory();
+
+  /**
+   * Get the blockers on a service -remote dependencies
+   * that are stopping the service from being <i>live</i>.
+   * @return a (snapshotted) map of blocker name-&gt;description values
+   */
+  public Map<String, String> getBlockers();
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceOperations.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceOperations.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceOperations.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceOperations.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,154 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+
+/**
+ * This class contains a set of methods to work with services, especially
+ * to walk them through their lifecycle.
+ */
+@Public
+@Evolving
+public final class ServiceOperations {
+  private static final Log LOG = LogFactory.getLog(AbstractService.class);
+
+  private ServiceOperations() {
+  }
+
+  /**
+   * Stop a service.
+   * <p/>Do nothing if the service is null or not
+   * in a state in which it can be/needs to be stopped.
+   * <p/>
+   * The service state is checked <i>before</i> the operation begins.
+   * This process is <i>not</i> thread safe.
+   * @param service a service or null
+   */
+  public static void stop(Service service) {
+    if (service != null) {
+      service.stop();
+    }
+  }
+
+  /**
+   * Stop a service; if it is null do nothing. Exceptions are caught and
+   * logged at warn level. (but not Throwables). This operation is intended to
+   * be used in cleanup operations
+   *
+   * @param service a service; may be null
+   * @return any exception that was caught; null if none was.
+   */
+  public static Exception stopQuietly(Service service) {
+    return stopQuietly(LOG, service);
+  }
+
+  /**
+   * Stop a service; if it is null do nothing. Exceptions are caught and
+   * logged at warn level. (but not Throwables). This operation is intended to
+   * be used in cleanup operations
+   *
+   * @param log the log to warn at
+   * @param service a service; may be null
+   * @return any exception that was caught; null if none was.
+   * @see ServiceOperations#stopQuietly(Service)
+   */
+  public static Exception stopQuietly(Log log, Service service) {
+    try {
+      stop(service);
+    } catch (Exception e) {
+      log.warn("When stopping the service " + service.getName()
+               + " : " + e,
+               e);
+      return e;
+    }
+    return null;
+  }
+
+
+  /**
+   * Class to manage a list of {@link ServiceStateChangeListener} instances,
+   * including a notification loop that is robust against changes to the list
+   * during the notification process.
+   */
+  public static class ServiceListeners {
+    /**
+     * List of state change listeners; it is final to guarantee
+     * that it will never be null.
+     */
+    private final List<ServiceStateChangeListener> listeners =
+      new ArrayList<ServiceStateChangeListener>();
+
+    /**
+     * Thread-safe addition of a new listener to the end of a list.
+     * Attempts to re-register a listener that is already registered
+     * will be ignored.
+     * @param l listener
+     */
+    public synchronized void add(ServiceStateChangeListener l) {
+      if(!listeners.contains(l)) {
+        listeners.add(l);
+      }
+    }
+
+    /**
+     * Remove any registration of a listener from the listener list.
+     * @param l listener
+     * @return true if the listener was found (and then removed)
+     */
+    public synchronized boolean remove(ServiceStateChangeListener l) {
+      return listeners.remove(l);
+    }
+
+    /**
+     * Reset the listener list
+     */
+    public synchronized void reset() {
+      listeners.clear();
+    }
+
+    /**
+     * Change to a new state and notify all listeners.
+     * This method will block until all notifications have been issued.
+     * It caches the list of listeners before the notification begins,
+     * so additions or removal of listeners will not be visible.
+     * @param service the service that has changed state
+     */
+    public void notifyListeners(Service service) {
+      //take a very fast snapshot of the callback list
+      //very much like CopyOnWriteArrayList, only more minimal
+      ServiceStateChangeListener[] callbacks;
+      synchronized (this) {
+        callbacks = listeners.toArray(new ServiceStateChangeListener[listeners.size()]);
+      }
+      //iterate through the listeners outside the synchronized method,
+      //ensuring that listener registration/unregistration doesn't break anything
+      for (ServiceStateChangeListener l : callbacks) {
+        l.stateChanged(service);
+      }
+    }
+  }
+
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateChangeListener.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateChangeListener.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateChangeListener.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateChangeListener.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,50 @@
+/**
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements.  See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership.  The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License.  You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package org.apache.hadoop.service;
+
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Stable;
+
+/**
+ * Interface to notify state changes of a service.
+ */
+@Public
+@Stable
+public interface ServiceStateChangeListener {
+
+  /**
+   * Callback to notify of a state change. The service will already
+   * have changed state before this callback is invoked.
+   *
+   * This operation is invoked on the thread that initiated the state change,
+   * while the service itself in in a sychronized section.
+   * <ol>
+   *   <li>Any long-lived operation here will prevent the service state
+   *   change from completing in a timely manner.</li>
+   *   <li>If another thread is somehow invoked from the listener, and
+   *   that thread invokes the methods of the service (including
+   *   subclass-specific methods), there is a risk of a deadlock.</li>
+   * </ol>
+   *
+   *
+   * @param service the service that has changed.
+   */
+  void stateChanged(Service service);
+
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateException.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateException.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateException.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateException.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.hadoop.service;
+
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+
+/**
+ * Exception that is raised on state change operations.
+ */
+@Public
+@Evolving
+public class ServiceStateException extends RuntimeException {
+
+  private static final long serialVersionUID = 1110000352259232646L;
+
+  public ServiceStateException(String message) {
+    super(message);
+  }
+
+  public ServiceStateException(String message, Throwable cause) {
+    super(message, cause);
+  }
+
+  public ServiceStateException(Throwable cause) {
+    super(cause);
+  }
+
+  /**
+   * Convert any exception into a {@link RuntimeException}.
+   * If the caught exception is already of that type, it is typecast to a
+   * {@link RuntimeException} and returned.
+   *
+   * All other exception types are wrapped in a new instance of
+   * ServiceStateException
+   * @param fault exception or throwable
+   * @return a ServiceStateException to rethrow
+   */
+  public static RuntimeException convert(Throwable fault) {
+    if (fault instanceof RuntimeException) {
+      return (RuntimeException) fault;
+    } else {
+      return new ServiceStateException(fault);
+    }
+  }
+
+  /**
+   * Convert any exception into a {@link RuntimeException}.
+   * If the caught exception is already of that type, it is typecast to a
+   * {@link RuntimeException} and returned.
+   *
+   * All other exception types are wrapped in a new instance of
+   * ServiceStateException
+   * @param text text to use if a new exception is created
+   * @param fault exception or throwable
+   * @return a ServiceStateException to rethrow
+   */
+  public static RuntimeException convert(String text, Throwable fault) {
+    if (fault instanceof RuntimeException) {
+      return (RuntimeException) fault;
+    } else {
+      return new ServiceStateException(text, fault);
+    }
+  }
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateModel.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateModel.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateModel.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/ServiceStateModel.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.hadoop.service;
+
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+
+/**
+ * Implements the service state model.
+ */
+@Public
+@Evolving
+public class ServiceStateModel {
+
+  /**
+   * Map of all valid state transitions
+   * [current] [proposed1, proposed2, ...]
+   */
+  private static final boolean[][] statemap =
+    {
+      //                uninited inited started stopped
+      /* uninited  */    {false, true,  false,  true},
+      /* inited    */    {false, true,  true,   true},
+      /* started   */    {false, false, true,   true},
+      /* stopped   */    {false, false, false,  true},
+    };
+
+  /**
+   * The state of the service
+   */
+  private volatile Service.STATE state;
+
+  /**
+   * The name of the service: used in exceptions
+   */
+  private String name;
+
+  /**
+   * Create the service state model in the {@link Service.STATE#NOTINITED}
+   * state.
+   */
+  public ServiceStateModel(String name) {
+    this(name, Service.STATE.NOTINITED);
+  }
+
+  /**
+   * Create a service state model instance in the chosen state
+   * @param state the starting state
+   */
+  public ServiceStateModel(String name, Service.STATE state) {
+    this.state = state;
+    this.name = name;
+  }
+
+  /**
+   * Query the service state. This is a non-blocking operation.
+   * @return the state
+   */
+  public Service.STATE getState() {
+    return state;
+  }
+
+  /**
+   * Query that the state is in a specific state
+   * @param proposed proposed new state
+   * @return the state
+   */
+  public boolean isInState(Service.STATE proposed) {
+    return state.equals(proposed);
+  }
+
+  /**
+   * Verify that that a service is in a given state.
+   * @param expectedState the desired state
+   * @throws ServiceStateException if the service state is different from
+   * the desired state
+   */
+  public void ensureCurrentState(Service.STATE expectedState) {
+    if (state != expectedState) {
+      throw new ServiceStateException(name+ ": for this operation, the " +
+                                      "current service state must be "
+                                      + expectedState
+                                      + " instead of " + state);
+    }
+  }
+
+  /**
+   * Enter a state -thread safe.
+   *
+   * @param proposed proposed new state
+   * @return the original state
+   * @throws ServiceStateException if the transition is not permitted
+   */
+  public synchronized Service.STATE enterState(Service.STATE proposed) {
+    checkStateTransition(name, state, proposed);
+    Service.STATE oldState = state;
+    //atomic write of the new state
+    state = proposed;
+    return oldState;
+  }
+
+  /**
+   * Check that a state tansition is valid and
+   * throw an exception if not
+   * @param name name of the service (can be null)
+   * @param state current state
+   * @param proposed proposed new state
+   */
+  public static void checkStateTransition(String name,
+                                          Service.STATE state,
+                                          Service.STATE proposed) {
+    if (!isValidStateTransition(state, proposed)) {
+      throw new ServiceStateException(name + " cannot enter state "
+                                      + proposed + " from state " + state);
+    }
+  }
+
+  /**
+   * Is a state transition valid?
+   * There are no checks for current==proposed
+   * as that is considered a non-transition.
+   *
+   * using an array kills off all branch misprediction costs, at the expense
+   * of cache line misses.
+   *
+   * @param current current state
+   * @param proposed proposed new state
+   * @return true if the transition to a new state is valid
+   */
+  public static boolean isValidStateTransition(Service.STATE current,
+                                               Service.STATE proposed) {
+    boolean[] row = statemap[current.getValue()];
+    return row[proposed.getValue()];
+  }
+
+  /**
+   * return the state text as the toString() value
+   * @return the current state's description
+   */
+  @Override
+  public String toString() {
+    return (name.isEmpty() ? "" : ((name) + ": "))
+            + state.toString();
+  }
+
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/package-info.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/package-info.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/package-info.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/package-info.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,21 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+@InterfaceAudience.Public
+package org.apache.hadoop.service;
+import org.apache.hadoop.classification.InterfaceAudience;
+

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableService.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableService.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableService.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableService.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,122 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.hadoop.service;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.service.AbstractService;
+import org.apache.hadoop.service.Service;
+
+/**
+ * This is a service that can be configured to break on any of the lifecycle
+ * events, so test the failure handling of other parts of the service
+ * infrastructure.
+ *
+ * It retains a counter to the number of times each entry point is called -
+ * these counters are incremented before the exceptions are raised and
+ * before the superclass state methods are invoked.
+ *
+ */
+
+
+public class BreakableService extends AbstractService {
+
+  private boolean failOnInit;
+  private boolean failOnStart;
+  private boolean failOnStop;
+  private int[] counts = new int[4];
+
+  public BreakableService() {
+    this(false, false, false);
+  }
+
+  public BreakableService(boolean failOnInit,
+                          boolean failOnStart,
+                          boolean failOnStop) {
+    super("BreakableService");
+    this.failOnInit = failOnInit;
+    this.failOnStart = failOnStart;
+    this.failOnStop = failOnStop;
+    inc(STATE.NOTINITED);
+  }
+
+  private int convert(STATE state) {
+    return state.getValue();
+  }
+
+  private void inc(STATE state) {
+    int index = convert(state);
+    counts[index] ++;
+  }
+
+  public int getCount(STATE state) {
+    return counts[convert(state)];
+  }
+
+  private void maybeFail(boolean fail, String action) {
+    if (fail) {
+      throw new BrokenLifecycleEvent(this, action);
+    }
+  }
+
+  @Override
+  protected void serviceInit(Configuration conf) throws Exception {
+    inc(STATE.INITED);
+    maybeFail(failOnInit, "init");
+    super.serviceInit(conf);
+  }
+
+  @Override
+  protected void serviceStart() {
+    inc(STATE.STARTED);
+    maybeFail(failOnStart, "start");
+  }
+
+  @Override
+  protected void serviceStop() {
+    inc(STATE.STOPPED);
+    maybeFail(failOnStop, "stop");
+  }
+
+  public void setFailOnInit(boolean failOnInit) {
+    this.failOnInit = failOnInit;
+  }
+
+  public void setFailOnStart(boolean failOnStart) {
+    this.failOnStart = failOnStart;
+  }
+
+  public void setFailOnStop(boolean failOnStop) {
+    this.failOnStop = failOnStop;
+  }
+
+  /**
+   * The exception explicitly raised on a failure
+   */
+  public static class BrokenLifecycleEvent extends RuntimeException {
+
+    final STATE state;
+
+    public BrokenLifecycleEvent(Service service, String action) {
+      super("Lifecycle Failure during " + action + " state is "
+            + service.getServiceState());
+      state = service.getServiceState();
+    }
+  }
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableStateChangeListener.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableStateChangeListener.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableStateChangeListener.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/BreakableStateChangeListener.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.hadoop.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.service.Service;
+import org.apache.hadoop.service.ServiceStateChangeListener;
+
+/**
+ * A state change listener that logs the number of state change events received,
+ * and the last state invoked.
+ *
+ * It can be configured to fail during a state change event
+ */
+public class BreakableStateChangeListener
+    implements ServiceStateChangeListener {
+
+  private final String name;
+
+  private int eventCount;
+  private int failureCount;
+  private Service lastService;
+  private Service.STATE lastState = Service.STATE.NOTINITED;
+  //no callbacks are ever received for this event, so it
+  //can be used as an 'undefined'.
+  private Service.STATE failingState = Service.STATE.NOTINITED;
+  private List<Service.STATE> stateEventList = new ArrayList<Service.STATE>(4);
+
+  public BreakableStateChangeListener() {
+    this( "BreakableStateChangeListener");
+  }
+
+  public BreakableStateChangeListener(String name) {
+    this.name = name;
+  }
+
+  @Override
+  public synchronized void stateChanged(Service service) {
+    eventCount++;
+    lastService = service;
+    lastState = service.getServiceState();
+    stateEventList.add(lastState);
+    if (lastState == failingState) {
+      failureCount++;
+      throw new BreakableService.BrokenLifecycleEvent(service,
+                                                      "Failure entering "
+                                                      + lastState
+                                                      + " for "
+                                                      + service.getName());
+    }
+  }
+
+  public synchronized int getEventCount() {
+    return eventCount;
+  }
+
+  public synchronized Service getLastService() {
+    return lastService;
+  }
+
+  public synchronized Service.STATE getLastState() {
+    return lastState;
+  }
+
+  public synchronized void setFailingState(Service.STATE failingState) {
+    this.failingState = failingState;
+  }
+
+  public synchronized int getFailureCount() {
+    return failureCount;
+  }
+
+  public List<Service.STATE> getStateEventList() {
+    return stateEventList;
+  }
+
+  @Override
+  public synchronized String toString() {
+    String s =
+      name + " - event count = " + eventCount + " last state " + lastState;
+    StringBuilder history = new StringBuilder(stateEventList.size()*10);
+    for (Service.STATE state: stateEventList) {
+      history.append(state).append(" ");
+    }
+    return s + " [ " + history + "]";
+  }
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/ServiceAssert.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/ServiceAssert.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/ServiceAssert.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/ServiceAssert.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,80 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.service;
+
+import org.apache.hadoop.service.Service;
+import org.junit.Assert;
+
+/**
+ * A set of assertions about the state of any service
+ */
+public class ServiceAssert extends Assert {
+
+  public static void assertServiceStateCreated(Service service) {
+    assertServiceInState(service, Service.STATE.NOTINITED);
+  }
+
+  public static void assertServiceStateInited(Service service) {
+    assertServiceInState(service, Service.STATE.INITED);
+  }
+
+  public static void assertServiceStateStarted(Service service) {
+    assertServiceInState(service, Service.STATE.STARTED);
+  }
+
+  public static void assertServiceStateStopped(Service service) {
+    assertServiceInState(service, Service.STATE.STOPPED);
+  }
+
+  public static void assertServiceInState(Service service, Service.STATE state) {
+    assertNotNull("Null service", service);
+    assertEquals("Service in wrong state: " + service, state,
+                 service.getServiceState());
+  }
+
+  /**
+   * Assert that the breakable service has entered a state exactly the number
+   * of time asserted.
+   * @param service service -if null an assertion is raised.
+   * @param state state to check.
+   * @param expected expected count.
+   */
+  public static void assertStateCount(BreakableService service,
+                        Service.STATE state,
+                        int expected) {
+    assertNotNull("Null service", service);
+    int actual = service.getCount(state);
+    if (expected != actual) {
+      fail("Expected entry count for state [" + state +"] of " + service
+               + " to be " + expected + " but was " + actual);
+    }
+  }
+
+  /**
+   * Assert that a service configuration contains a specific key; the value
+   * is ignored.
+   * @param service service to check
+   * @param key key to look for
+   */
+  public static void assertServiceConfigurationContains(Service service,
+                                                        String key) {
+    assertNotNull("No option "+ key + " in service configuration",
+                  service.getConfig().get(key));
+  }
+}

Added: hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestGlobalStateChangeListener.java
URL: http://svn.apache.org/viewvc/hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestGlobalStateChangeListener.java?rev=1493650&view=auto
==============================================================================
--- hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestGlobalStateChangeListener.java (added)
+++ hadoop/common/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/service/TestGlobalStateChangeListener.java Mon Jun 17 06:39:33 2013
@@ -0,0 +1,224 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.hadoop.service;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.service.AbstractService;
+import org.apache.hadoop.service.LoggingStateChangeListener;
+import org.apache.hadoop.service.Service;
+import org.apache.hadoop.service.ServiceStateChangeListener;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Test global state changes. It is critical for all tests to clean up the
+ * global listener afterwards to avoid interfering with follow-on tests.
+ *
+ * One listener, {@link #listener} is defined which is automatically
+ * unregistered on cleanup. All other listeners must be unregistered in the
+ * finally clauses of the tests.
+ */
+public class TestGlobalStateChangeListener extends ServiceAssert {
+
+  BreakableStateChangeListener listener = new BreakableStateChangeListener("listener");
+
+
+  private void register() {
+    register(listener);
+  }
+
+  private boolean unregister() {
+    return unregister(listener);
+  }
+
+  private void register(ServiceStateChangeListener l) {
+    AbstractService.registerGlobalListener(l);
+  }
+
+  private boolean unregister(ServiceStateChangeListener l) {
+    return AbstractService.unregisterGlobalListener(l);
+  }
+
+  /**
+   * After every test case reset the list of global listeners.
+   */
+  @After
+  public void cleanup() {
+    AbstractService.resetGlobalListeners();
+  }
+
+  /**
+   * Assert that the last state of the listener is that the test expected.
+   * @param breakable a breakable listener
+   * @param state the expected state
+   */
+  public void assertListenerState(BreakableStateChangeListener breakable,
+                                  Service.STATE state) {
+    assertEquals("Wrong state in " + breakable, state, breakable.getLastState());
+  }
+
+  /**
+   * Assert that the number of state change notifications matches expectations.
+   * @param breakable the listener
+   * @param count the expected count.
+   */
+  public void assertListenerEventCount(BreakableStateChangeListener breakable,
+                                       int count) {
+    assertEquals("Wrong event count in " + breakable, count,
+                 breakable.getEventCount());
+  }
+
+  /**
+   * Test that register/unregister works
+   */
+  @Test
+  public void testRegisterListener() {
+    register();
+    assertTrue("listener not registered", unregister());
+  }
+
+  /**
+   * Test that double registration results in one registration only.
+   */
+  @Test
+  public void testRegisterListenerTwice() {
+    register();
+    register();
+    assertTrue("listener not registered", unregister());
+    //there should be no listener to unregister the second time
+    assertFalse("listener double registered", unregister());
+  }
+
+  /**
+   * Test that the {@link BreakableStateChangeListener} is picking up
+   * the state changes and that its last event field is as expected.
+   */
+  @Test
+  public void testEventHistory() {
+    register();
+    BreakableService service = new BreakableService();
+    assertListenerState(listener, Service.STATE.NOTINITED);
+    assertEquals(0, listener.getEventCount());
+    service.init(new Configuration());
+    assertListenerState(listener, Service.STATE.INITED);
+    assertSame(service, listener.getLastService());
+    assertListenerEventCount(listener, 1);
+
+    service.start();
+    assertListenerState(listener, Service.STATE.STARTED);
+    assertListenerEventCount(listener, 2);
+
+    service.stop();
+    assertListenerState(listener, Service.STATE.STOPPED);
+    assertListenerEventCount(listener, 3);
+  }
+
+  /**
+   * This test triggers a failure in the listener - the expectation is that the
+   * service has already reached it's desired state, purely because the
+   * notifications take place afterwards.
+   *
+   */
+  @Test
+  public void testListenerFailure() {
+    listener.setFailingState(Service.STATE.INITED);
+    register();
+    BreakableStateChangeListener l2 = new BreakableStateChangeListener();
+    register(l2);
+    BreakableService service = new BreakableService();
+    service.init(new Configuration());
+    //expected notifications to fail
+
+    //still should record its invocation
+    assertListenerState(listener, Service.STATE.INITED);
+    assertListenerEventCount(listener, 1);
+
+    //and second listener didn't get notified of anything
+    assertListenerEventCount(l2, 0);
+
+    //service should still consider itself started
+    assertServiceStateInited(service);
+    service.start();
+    service.stop();
+  }
+
+  /**
+   * Create a chain of listeners and set one in the middle to fail; verify that
+   * those in front got called, and those after did not.
+   */
+  @Test
+  public void testListenerChain() {
+
+    //create and register the listeners
+    LoggingStateChangeListener logListener = new LoggingStateChangeListener();
+    register(logListener);
+    BreakableStateChangeListener l0 = new BreakableStateChangeListener("l0");
+    register(l0);
+    listener.setFailingState(Service.STATE.STARTED);
+    register();
+    BreakableStateChangeListener l3 = new BreakableStateChangeListener("l3");
+    register(l3);
+
+    //create and init a service.
+    BreakableService service = new BreakableService();
+    service.init(new Configuration());
+    assertServiceStateInited(service);
+    assertListenerState(l0, Service.STATE.INITED);
+    assertListenerState(listener, Service.STATE.INITED);
+    assertListenerState(l3, Service.STATE.INITED);
+
+    service.start();
+    //expect that listener l1 and the failing listener are in start, but
+    //not the final one
+    assertServiceStateStarted(service);
+    assertListenerState(l0, Service.STATE.STARTED);
+    assertListenerEventCount(l0, 2);
+    assertListenerState(listener, Service.STATE.STARTED);
+    assertListenerEventCount(listener, 2);
+    //this is the listener that is not expected to have been invoked
+    assertListenerState(l3, Service.STATE.INITED);
+    assertListenerEventCount(l3, 1);
+
+    //stop the service
+    service.stop();
+    //listeners are all updated
+    assertListenerEventCount(l0, 3);
+    assertListenerEventCount(listener, 3);
+    assertListenerEventCount(l3, 2);
+    //can all be unregistered in any order
+    unregister(logListener);
+    unregister(l0);
+    unregister(l3);
+
+    //check that the listeners are all unregistered, even
+    //though they were registered in a different order.
+    //rather than do this by doing unregister checks, a new service is created
+    service = new BreakableService();
+    //this service is initialized
+    service.init(new Configuration());
+    //it is asserted that the event count has not changed for the unregistered
+    //listeners
+    assertListenerEventCount(l0, 3);
+    assertListenerEventCount(l3, 2);
+    //except for the one listener that was not unregistered, which
+    //has incremented by one
+    assertListenerEventCount(listener, 4);
+  }
+
+}