Stops a node (which is running in a different VM) by setting its status to
{@link Status#SHUTDOWN_PENDING}. Waits for the node to actually shut down
and returns the exit status (0 is for success else failure).
961388
private int stop(final String[] args) throws IOException {
    setWorkingDir(args);
    final Path statusFile = getStatusPath();
    int exitStatus = 1;

    // determine the current state of the node
    readStatus(false, statusFile);
    if (this.status != null) {
      // upon reading the status file, request the Cache Server to shutdown
      // if it has not already...
      if (this.status.state != Status.SHUTDOWN) {
        // copy server PID and not use own PID; see bug #39707
        this.status = Status.create(this.baseName, Status.SHUTDOWN_PENDING,
            this.status.pid, statusFile);
        this.status.write();
      }

      // poll the Cache Server for a response to our shutdown request
      // (passes through if the Cache Server has already shutdown)
      pollCacheServerForShutdown(statusFile);

      // after polling, determine the status of the Cache Server one last time
      // and determine how to exit...
      if (this.status.state == Status.SHUTDOWN) {
        System.out.println(MessageFormat.format(LAUNCHER_STOPPED,
            this.baseName, getHostNameAndDir()));
        Status.delete(statusFile);
        exitStatus = 0;
      } else {
        System.out.println(MessageFormat.format(LAUNCHER_TIMEOUT_WAITING_FOR_SHUTDOWN,
            this.baseName, this.hostName, this.status));
      }
    } else if (Files.exists(statusFile)) {
      throw new IllegalStateException(MessageFormat.format(
          LAUNCHER_NO_AVAILABLE_STATUS, this.statusName));
    } else {
      System.out.println(MessageFormat.format(LAUNCHER_NO_STATUS_FILE,
          this.workingDir, this.hostName));
    }
    return exitStatus;
  }
624947
public Status getImpliedStatus(final ExecutableNode node) {
    // If it's running or finished with 'SUCCEEDED', than don't even
    // bother starting this job.
    if (Status.isStatusRunning(node.getStatus())
        || node.getStatus() == Status.SUCCEEDED) {
      return null;
    }

    // Go through the node's dependencies. If all of the previous job's
    // statuses is finished and not FAILED or KILLED, than we can safely
    // run this job.
    Status status = Status.READY;

    // Check if condition on job status is satisfied
    switch (checkConditionOnJobStatus(node)) {
      case FAILED:
        this.logger.info("Condition on job status: " + node.getConditionOnJobStatus() + " is "
            + "evaluated to false for " + node.getId());
        status = Status.CANCELLED;
        break;
      // Condition not satisfied yet, need to wait
      case PENDING:
        return null;
      default:
        break;
    }

    if (status != Status.CANCELLED && !isConditionOnRuntimeVariableMet(node)) {
      status = Status.CANCELLED;
    }

    // If it's disabled but ready to run, we want to make sure it continues
    // being disabled.
    if (node.getStatus() == Status.DISABLED
        || node.getStatus() == Status.SKIPPED) {
      return Status.SKIPPED;
    }

    // If the flow has failed, and we want to finish only the currently running
    // jobs, we just
    // kill everything else. We also kill, if the flow has been cancelled.
    if (this.flowFailed
        && this.failureAction == ExecutionOptions.FailureAction.FINISH_CURRENTLY_RUNNING) {
      return Status.CANCELLED;
    } else if (isKilled()) {
      return Status.CANCELLED;
    }

    return status;
  }
935707
public synchronized void stop() throws DatastoreEmulatorException {
    // We intentionally don't check the internal state. If people want to try and stop the server
    // multiple times that's fine.
    stopEmulatorInternal();
    if (state != State.STOPPED) {
      state = State.STOPPED;
      if (projectDirectory != null) {
        try {
          Process process =
              new ProcessBuilder("rm", "-r", projectDirectory.getAbsolutePath()).start();
          if (process.waitFor() != 0) {
            throw new IOException(
                "Temporary project directory deletion exited with " + process.exitValue());
          }
        } catch (IOException e) {
          throw new IllegalStateException("Could not delete temporary project directory", e);
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
          throw new IllegalStateException("Could not delete temporary project directory", e);
        }
      }
    }
  }
1314181
def stop(vm_name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The stop action must be called with -a or --action.'
        )

    conn = get_conn()

    __utils__['cloud.fire_event'](
        'event',
        'stop instance',
        'salt/cloud/{0}/stopping'.format(vm_name),
        args={'name': vm_name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    result = conn.ex_stop_node(
        conn.ex_get_node(vm_name)
    )

    __utils__['cloud.fire_event'](
        'event',
        'stop instance',
        'salt/cloud/{0}/stopped'.format(vm_name),
        args={'name': vm_name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return result
1056671
def stop_vm(self):
        
        if self.vagrant is not None:
            if self.destroy:
                self.vagrant.destroy()
                shutil.rmtree(self.vagrant.root, ignore_errors=True)
                self.vagrant = None
            else:
                self.vagrant.halt()
39251
@Invalidate
    public void stop() throws InterruptedException {
        unregisterQuietly(vertxRegistration);
        unregisterQuietly(busRegistration);
        CountDownLatch latch = new CountDownLatch(1);
        vertx.close(v -> latch.countDown());
        latch.await();
        vertx = null;
    }
1248252
@Override
    public void stop()
    {
        // On linux, this doesn't entirely shut down Cassandra, just the RPC server.
        // jsvc takes care of taking the rest down
        logger.info("Cassandra shutting down...");
        if (nativeTransportService != null)
            nativeTransportService.destroy();
        StorageService.instance.setRpcReady(false);

        // On windows, we need to stop the entire system as prunsrv doesn't have the jsvc hooks
        // We rely on the shutdown hook to drain the node
        if (FBUtilities.isWindows)
            System.exit(0);
    }
953376
public void shutdown() {
        if (m_done.compareAndSet(false, true)) {
            m_es.shutdown();
            m_buses.shutdown();
            DeleteNode deleteHost = new DeleteNode(joinZKPath(HOST_DN, m_hostId));
            DeleteNode deleteCandidate = new DeleteNode(m_candidate);
            try {
                m_es.awaitTermination(365, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                throw loggedDistributerException(e, "interrupted while waiting for executor termination");
            }
            try {
                m_buses.awaitTermination(365, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                throw loggedDistributerException(e, "interrupted while waiting for executor termination");
            }
            deleteHost.onComplete();
            deleteCandidate.onComplete();
        }
    }
190826
@Override
    public void stop() throws EngineTerminationException, InternalException {
        synchronized (STOP_LOCK) {
            if (!userCodeRunning) {
                return;
            }

            vm().suspend();
            try {
                OUTER:
                for (ThreadReference thread : vm().allThreads()) {
                    // could also tag the thread (e.g. using name), to find it easier
                    for (StackFrame frame : thread.frames()) {
                        if (remoteAgent.equals(frame.location().declaringType().name()) &&
                                (    "invoke".equals(frame.location().method().name())
                                || "varValue".equals(frame.location().method().name()))) {
                            ObjectReference thiz = frame.thisObject();
                            Field inClientCode = thiz.referenceType().fieldByName("inClientCode");
                            Field expectingStop = thiz.referenceType().fieldByName("expectingStop");
                            Field stopException = thiz.referenceType().fieldByName("stopException");
                            if (((BooleanValue) thiz.getValue(inClientCode)).value()) {
                                thiz.setValue(expectingStop, vm().mirrorOf(true));
                                ObjectReference stopInstance = (ObjectReference) thiz.getValue(stopException);

                                vm().resume();
                                debug("Attempting to stop the client code...\n");
                                thread.stop(stopInstance);
                                thiz.setValue(expectingStop, vm().mirrorOf(false));
                            }

                            break OUTER;
                        }
                    }
                }
            } catch (ClassNotLoadedException | IncompatibleThreadStateException | InvalidTypeException ex) {
                throw new InternalException("Exception on remote stop: " + ex);
            } finally {
                vm().resume();
            }
        }
    }
1262660
protected boolean doShutdown() {
        if (state == State.NOT_RUNNING) {
            LOGGER.debug("Engine already shut down.");
            return true;
        }
        LOGGER.debug("Shutting down engine...");
        final Lock lock = this.lock.writeLock();
        try {
            lock.lock();
            state = State.STOPPING;

            if (!repositories.isEmpty()) {
                // Now go through all of the repositories and request they all be shutdown ...
                Queue<Future<Boolean>> repoFutures = new LinkedList<Future<Boolean>>();
                Queue<String> repoNames = new LinkedList<String>();
                for (JcrRepository repository : repositories.values()) {
                    if (repository != null) {
                        repoNames.add(repository.getName());
                        repoFutures.add(repository.shutdown());
                    }
                }

                // Now block while each is shutdown ...
                while (repoFutures.peek() != null) {
                    String repoName = repoNames.poll();
                    try {
                        // Get the results from the future (this will return only when the shutdown has completed) ...
                        repoFutures.poll().get();

                        // We've successfully shut down, so remove it from the map ...
                        repositories.remove(repoName);
                    } catch (ExecutionException | InterruptedException e) {
                        Logger.getLogger(getClass()).error(e, JcrI18n.failedToShutdownDeployedRepository, repoName);
                    }
                }
            }

            if (repositories.isEmpty()) {
                // All repositories were properly shutdown, so now stop the service for starting and shutting down the repos ...
                repositoryStarterService.shutdown();
                repositoryStarterService = null;

                // Do not clear the set of repositories, so that restarting will work just fine ...
                this.state = State.NOT_RUNNING;
            } else {
                // Could not shut down all repositories, so keep running ..
                this.state = State.RUNNING;
            }
        } catch (RuntimeException e) {
            this.state = State.RUNNING;
            throw e;
        } finally {
            lock.unlock();
        }
        return this.state != State.RUNNING;
    }
1260125
@Override
	public final void stop() throws JMSException
    {
    	externalAccessLock.readLock().lock();
    	try
		{
    		checkNotClosed();
    		if (!started)
    			return;
    		started = false;
		}
    	finally
    	{
    		externalAccessLock.readLock().unlock();
    	}
    	transportEndpoint.blockingRequest(new StopConnectionQuery());
    	waitForDeliverySync();
    }
1299380
protected void shutdown() throws InterruptedException {
        if (m_deadConnectionFuture != null) {
            m_deadConnectionFuture.cancel(false);
            try {m_deadConnectionFuture.get();} catch (Throwable t) {}
        }
        if (m_topologyCheckFuture != null) {
            m_topologyCheckFuture.cancel(false);
            try {m_topologyCheckFuture.get();} catch (Throwable t) {}
        }
        if (m_maxConnectionUpdater != null) {
            m_maxConnectionUpdater.cancel(false);
        }
        if (m_acceptor != null) {
            m_acceptor.shutdown();
        }
        if (m_adminAcceptor != null)
        {
            m_adminAcceptor.shutdown();
        }
        if (m_snapshotDaemon != null) {
            m_snapshotDaemon.shutdown();
        }

        if (m_migratePartitionLeaderExecutor != null) {
            m_migratePartitionLeaderExecutor.shutdown();
        }
        m_notifier.shutdown();
    }
111414
public void shutdown() {
    shouldRun = false;
    try {
      if (infoServer != null) infoServer.stop();
    } catch (Exception e) {
      LOG.warn("Exception shutting down SecondaryNameNode", e);
    }
    try {
      if (checkpointImage != null) checkpointImage.close();
    } catch(IOException e) {
      LOG.warn(StringUtils.stringifyException(e));
    }
  }
464604
static void exit(int status) {
        boolean runMoreFinalizers = false;
        synchronized (lock) {
            if (status != 0) runFinalizersOnExit = false;
            switch (state) {
            case RUNNING:       /* Initiate shutdown */
                state = HOOKS;
                break;
            case HOOKS:         /* Stall and halt */
                break;
            case FINALIZERS:
                if (status != 0) {
                    /* Halt immediately on nonzero status */
                    halt(status);
                } else {
                    /* Compatibility with old behavior:
                     * Run more finalizers and then halt
                     */
                    runMoreFinalizers = runFinalizersOnExit;
                }
                break;
            }
        }
        if (runMoreFinalizers) {
            runAllFinalizers();
            halt(status);
        }
        synchronized (Shutdown.class) {
            /* Synchronize on the class object, causing any other thread
             * that attempts to initiate shutdown to stall indefinitely
             */
            sequence();
            halt(status);
        }
    }
320619
def stop(self):
        

        self._hw_virtualization = False
        yield from self._stop_ubridge()
        yield from self._stop_remote_console()
        vm_state = yield from self._get_vm_state()
        if vm_state == "running" or vm_state == "paused" or vm_state == "stuck":
            if self.acpi_shutdown:
                # use ACPI to shutdown the VM
                result = yield from self._control_vm("acpipowerbutton")
                trial = 0
                while True:
                    vm_state = yield from self._get_vm_state()
                    if vm_state == "poweroff":
                        break
                    yield from asyncio.sleep(1)
                    trial += 1
                    if trial >= 120:
                        yield from self._control_vm("poweroff")
                        break
                self.status = "stopped"
                log.debug("ACPI shutdown result: {}".format(result))
            else:
                # power off the VM
                result = yield from self._control_vm("poweroff")
                self.status = "stopped"
                log.debug("Stop result: {}".format(result))

            log.info("VirtualBox VM '{name}' [{id}] stopped".format(name=self.name, id=self.id))
            yield from asyncio.sleep(0.5)  # give some time for VirtualBox to unlock the VM
            try:
                # deactivate the first serial port
                yield from self._modify_vm("--uart1 off")
            except VirtualBoxError as e:
                log.warn("Could not deactivate the first serial port: {}".format(e))

            for adapter_number in range(0, self._adapters):
                nio = self._ethernet_adapters[adapter_number].get_nio(0)
                if nio:
                    yield from self._modify_vm("--nictrace{} off".format(adapter_number + 1))
                    yield from self._modify_vm("--cableconnected{} off".format(adapter_number + 1))
                    yield from self._modify_vm("--nic{} null".format(adapter_number + 1))
        yield from super().stop()
1312911
public ReturnCode shutdown() throws InterruptedException {
        delegateCreated.await();
        // If we have a delegate, call shutdown to stop the server
        if (launcherDelegate != null && launcherDelegate.shutdown()) {
            // if shutdown stopped the server, we need to wait until we can obtain
            // the server lock (the serverLock is released in the finally block of
            // the go() method.. )
            return serverLock.waitForStop();
        }

        // Server did not propertly start (no delegate), so stop is fine.
        return ReturnCode.OK;
    }
537644
@Stop(priority = 110)
   public void stop() {
      if (trace) {
         log.tracef("Stopping LocalTopologyManager on %s", transport.getAddress());
      }
      running = false;
      for (LocalCacheStatus cache : runningCaches.values()) {
         cache.getTopologyUpdatesExecutor().shutdownNow();
      }
      withinThreadExecutor.shutdown();
   }