Builds a runnable to shut down a work unit after a configurable delay once handoff
has completed. If the cluster has been instructed to shut down and the last work unit
has been handed off, this task also directs this Ordasity instance to shut down.
506853
private Runnable shutdownAfterHandoff(final String workUnit)
    {
        final Cluster cluster = this.cluster;
        final Logger log = LOG;
        return new Runnable() {
            @Override
            public void run() {
                String str = cluster.getHandoffResult(workUnit);
                log.info("Shutting down {} following handoff to {}.",
                        workUnit, (str == null) ? "(None)" : str);
                cluster.shutdownWork(workUnit, /*doLog =*/ false);

                if (cluster.hasState(NodeState.Draining) && cluster.myWorkUnits.isEmpty()) {
                    cluster.shutdown();
                }
            }
        };
    }
486355
protected void scheduleRunAsync(Runnable runnable, long delay, TimeUnit unit) {
		rpcServer.scheduleRunAsync(runnable, unit.toMillis(delay));
	}
460774
@Override
  public void shutdown() throws InterruptedException {
    try {
      channel.close();
      for(Map.Entry<String, Sender> entry: senders.entrySet()) {
        entry.getValue().shutdown();
      }
      senders.clear();

      for(Map.Entry<String, ChannelHandlerContext> entry:
          receivers.entrySet()) {
        entry.getValue().close();
      }
      receivers.clear();

    } finally {
      try {
        long quietPeriodSec = 0;
        long timeoutSec = 10;
        io.netty.util.concurrent.Future wf =
          workerGroup.shutdownGracefully(quietPeriodSec, timeoutSec,
                                         TimeUnit.SECONDS);
        io.netty.util.concurrent.Future bf =
          bossGroup.shutdownGracefully(quietPeriodSec, timeoutSec,
                                       TimeUnit.SECONDS);
        wf.await();
        bf.await();
        LOG.debug("Shutdown complete: {}", hostPort);
      } catch (InterruptedException ex) {
        LOG.debug("Interrupted while shutting down NioEventLoopGroup", ex);
      }
    }
  }
120419
public static synchronized void addOperation(Runnable runnable, boolean preserveForNextShutdown) {
        shutdownOperations.add(runnable);
        if(preserveForNextShutdown) {
            preservedShutdownOperations.add(runnable);
        }
    }
1067752
public void completeShutdown() {
        setState(NodeState.Shutdown);
        shutdownAllWorkUnits();
        deleteFromZk();
        if (claimer != null) {
            claimer.interrupt();
                try {
                    claimer.join();
                } catch (InterruptedException e) {
                    LOG.warn("Shutdown of Claimer interrupted");
                }
        }
        // The connection watcher will attempt to reconnect - unregister it
        if (connectionWatcher != null) {
            zk.unregister(connectionWatcher);
        }
        try {
            zk.close();
        } catch (Exception e) {
            LOG.warn("Zookeeper reported exception on shutdown.", e);
        }
        listener.onLeave();
    }
970150
@Override
  public ManagedChannelImpl shutdown() {
    channelLogger.log(ChannelLogLevel.DEBUG, "shutdown() called");
    if (!shutdown.compareAndSet(false, true)) {
      return this;
    }

    // Put gotoState(SHUTDOWN) as early into the syncContext's queue as possible.
    // delayedTransport.shutdown() may also add some tasks into the queue. But some things inside
    // delayedTransport.shutdown() like setting delayedTransport.shutdown = true are not run in the
    // syncContext's queue and should not be blocked, so we do not drain() immediately here.
    final class Shutdown implements Runnable {
      @Override
      public void run() {
        channelLogger.log(ChannelLogLevel.INFO, "Entering SHUTDOWN state");
        channelStateManager.gotoState(SHUTDOWN);
      }
    }

    syncContext.executeLater(new Shutdown());

    uncommittedRetriableStreamsRegistry.onShutdown(SHUTDOWN_STATUS);
    final class CancelIdleTimer implements Runnable {
      @Override
      public void run() {
        cancelIdleTimer(/* permanent= */ true);
      }
    }

    syncContext.execute(new CancelIdleTimer());
    return this;
  }
704354
public void shutdown() {
        final int taskCount = runningTasks.size();
        for (int i = 0; i < taskCount; ++i) {
            int key = runningTasks.keyAt(i);
            LoadBitmapTask t = runningTasks.get(key);
            t.cancel(true);
        }
        runningTasks.clear();
    }
1296387
private void shutdownIfComplete() {
        // only shut down if you have updated build results AND profile information
        if (!buildProfileComplete.get() || !buildResultComplete.get()) {
            return;
        }

        MetricsDispatcher dispatcher = this.dispatcherSupplier.get();
        logger.info("Shutting down dispatcher");
        try {
            dispatcher.stopAsync().awaitTerminated(TIMEOUT_MS, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            logger.debug("Timed out after {}ms while waiting for metrics dispatcher to terminate", TIMEOUT_MS);
        } catch (IllegalStateException e) {
            logger.debug("Could not stop metrics dispatcher service (error message: {})", getRootCauseMessage(e));
        }

        Optional<String> receipt = dispatcher.receipt();
        if (receipt.isPresent()) {
            logger.warn(receipt.get());
        }
    }
1342298
public static boolean shutdownExecutorService(ExecutorService executorService) {
    if (executorService == null) {
      return false;
    }
    //If it hasn't already shutdown, do shutdown.
    if (!executorService.isShutdown()) {
      executorService.shutdown();
    }

    try {
      //Wait for clean termination
      if (executorService.awaitTermination(5, TimeUnit.SECONDS)) {
        return true;
      }

      //If not already terminated (via shutdownNow) do shutdownNow.
      if (!executorService.isTerminated()) {
        executorService.shutdownNow();
      }

      if (executorService.awaitTermination(5, TimeUnit.SECONDS)) {
        return true;
      }

      if (LOGGER.isDebugEnabled()) {
        List<Runnable> tasks = executorService.shutdownNow();
        if (!tasks.isEmpty()) {
          LOGGER.debug("ExecutorService was not cleanly shutdown, after waiting for 10 seconds. Number of remaining tasks:" + tasks.size());
        }
      }
    } catch (InterruptedException e) {
      executorService.shutdownNow();
      //Preserve interrupted status
      Thread.currentThread().interrupt();
    }
    return false;
  }
318046
public synchronized void stop() throws IOException, TimeoutException {
    if (this.stopped) {
      return;
    }

    LOGGER.info("Stopping the " + GobblinAWSClusterLauncher.class.getSimpleName());

    try {
      if (this.clusterId.isPresent()) {
        sendShutdownRequest();
      }

      disconnectHelixManager();
    } finally {
      try {
        if (this.clusterId.isPresent()) {
          cleanUpClusterWorkDirectory(this.clusterId.get());
        }
      } finally {
        this.closer.close();
      }
    }

    this.countDownLatch.countDown();
    this.stopped = true;
  }
976240
public static void shutdown(@Nonnull final ExecutorService executorService, @Nonnegative final long duration,
			@Nonnull final TimeUnit unit) {
		Check.notNull(executorService, "executorService");
		Check.notNull(duration, "duration");
		Check.notNull(unit, "unit");

		executorService.shutdown();
		try {
			if (!executorService.awaitTermination(duration, unit)) {
				LOG.info(String.format("Executor did not terminate in %s %s.", duration, unit.name().toLowerCase()));
				final List<Runnable> droppedTasks = executorService.shutdownNow();
				LOG.info("Executor was abruptly shut down. " + droppedTasks.size() + " tasks will not be executed.");
			}
			unregisterIfPossible(executorService);
		} catch (final InterruptedException e) {
			LOG.warn("Executor termination failed: " + e.getLocalizedMessage(), e);
		}
	}
443683
@Override
	public CompletableFuture<Acknowledge> deregisterApplication(
			final ApplicationStatus finalStatus,
			@Nullable final String diagnostics) {
		log.info("Shut down cluster because application is in {}, diagnostics {}.", finalStatus, diagnostics);

		try {
			internalDeregisterApplication(finalStatus, diagnostics);
		} catch (ResourceManagerException e) {
			log.warn("Could not properly shutdown the application.", e);
		}

		return CompletableFuture.completedFuture(Acknowledge.get());
	}
197071
public void shutdownWork(String workUnit, boolean doLog /*true*/ ) {
        if (doLog) {
            LOG.info("Shutting down {}: {}...", config.workUnitName, workUnit);
        }
        myWorkUnits.remove(workUnit);
        claimedForHandoff.remove(workUnit);
        balancingPolicy.onShutdownWork(workUnit);
        try {
            listener.shutdownWork(workUnit);
        } finally {
            ZKUtils.deleteAtomic(zk, workUnitClaimPath(workUnit), myNodeID);
        }
    }
54779
@Override
  public void runAfter(@Pin Consumer<? super Cancel> task, 
                       long delay, 
                       TimeUnit unit,
                       Result<? super Cancel> result)
  {
    Objects.requireNonNull(task);
    Objects.requireNonNull(unit);

    TimerListener listener = new TimerListener(task, null);

    // _timerMap.put(task, listener);
    
    listener.alarm().runAfter(unit.toMillis(delay));
    
    result.ok(listener);
  }
514270
public void shutdownBlocking() throws InterruptedException
    {
        executor.shutdown();
        executor.awaitTermination();
        allocator.shutdown();
        allocator.awaitTermination();
    }
1004253
def close(self, **kwargs):
        
        self.scale_down(self.cluster.scheduler.workers)
        return self.cluster.close(**kwargs)
612689
private AsyncCallback shutdownASG() {
    Optional<List<String>> optionalLaunchConfigurationNames = Optional
        .of(Arrays.asList(this.masterLaunchConfigName, this.workerLaunchConfigName));
    Optional<List<String>> optionalAutoScalingGroupNames = Optional
        .of(Arrays.asList(this.masterAutoScalingGroupName, this.workerAutoScalingGroupName));

    return new AWSShutdownHandler(this.awsSdkClient,
        optionalLaunchConfigurationNames,
        optionalAutoScalingGroupNames);
  }