Send the shutdown command to a mongod or mongos on given port.

    This function can be called as a separate thread.
548876
def shutdown_host(port, username=None, password=None, authdb=None):
    
    host = 'localhost:%i' % port
    try:
        mc = MongoConnection(host)
        try:
            if username and password and authdb:
                if authdb != "admin":
                    raise RuntimeError("given username/password is not for "
                                       "admin database")
                else:
                    try:
                        mc.admin.authenticate(name=username, password=password)
                    except OperationFailure:
                        # perhaps auth is not required
                        pass

            mc.admin.command('shutdown', force=True)
        except AutoReconnect:
            pass
        except OperationFailure:
            print("Error: cannot authenticate to shut down %s." % host)
            return

    except ConnectionFailure:
        pass
    else:
        mc.close()
57472
def shutdown(self):
        ''''''
        if self._proxy:
            os.sync()
            self._proxy(*self._args)
981707
def shutdown(self, reason = ConnectionClosed()):
        
        if self._shutdown:
            raise ShutdownError()
        
        self.stop()
       
        self._closing = True
        for connection in self.connections:
            connection.close()
        self.connections = set()
        self._shutdown = True
        if isinstance(reason, ConnectionClosed):
            logger.info("server shutdown")
        else:
            logger.warn("server shutdown, reason %s" % str(reason))
1222790
def gracefulShutdown(self):
        """"""
        if not self.bf.perspective:
            log.msg("No active connection, shutting down NOW")
            reactor.stop()
            return

        log.msg(
            "Telling the master we want to shutdown after any running builds are finished")
        d = self.bf.perspective.callRemote("shutdown")

        def _shutdownfailed(err):
            if err.check(AttributeError):
                log.msg(
                    "Master does not support worker initiated shutdown.  Upgrade master to 0.8.3 or later to use this feature.")
            else:
                log.msg('callRemote("shutdown") failed')
                log.err(err)

        d.addErrback(_shutdownfailed)
        return d
581291
def shutdown(self, exitcode=0, exitmsg=None):
        '''
        
        '''
        if hasattr(self, 'minion') and 'proxymodule' in self.minion.opts:
            proxy_fn = self.minion.opts['proxymodule'].loaded_base_name + '.shutdown'
            self.minion.opts['proxymodule'][proxy_fn](self.minion.opts)
        self.action_log_info('Shutting down')
        super(ProxyMinion, self).shutdown(
            exitcode, ('The Salt {0} is shutdown. {1}'.format(
                self.__class__.__name__, (exitmsg or '')).strip()))
1085478
function disconnect(cb) {
  if (connection) {
    log.logger.debug('Mongoose disconnected');
    connection.close(cb);
  } else {
    cb();
  }
}
1074824
public static void shutdown(GSSCredential cred, GlobusURL gassURL)
	throws IOException, GSSException {

	OutputStream output     = null;
	InputStream input       = null;
	Socket socket           = null;

	try {

	    if (gassURL.getProtocol().equalsIgnoreCase("https")) {

		GSSManager manager = ExtendedGSSManager.getInstance();

		ExtendedGSSContext context =
		    (ExtendedGSSContext)manager.createContext(null,
							      GSSConstants.MECH_OID,
							      cred,
							      GSSContext.DEFAULT_LIFETIME);

		context.setOption(GSSConstants.GSS_MODE,
				  GSIConstants.MODE_SSL);

		GssSocketFactory factory = GssSocketFactory.getDefault();

		socket = factory.createSocket(gassURL.getHost(),
					      gassURL.getPort(),
					      context);

		((GssSocket)socket).setAuthorization(SelfAuthorization.getInstance());
	    } else {
                SocketFactory factory = SocketFactory.getDefault();
		socket = factory.createSocket(gassURL.getHost(),
                                              gassURL.getPort());
	    }

	    output = socket.getOutputStream();
	    input  = socket.getInputStream();

	    String msg =  GASSProtocol.SHUTDOWN(SHUTDOWN_STR,
						gassURL.getHost());


            if (logger.isTraceEnabled()) {
                logger.trace("Shutdown msg: " + msg);
            }

	    output.write( msg.getBytes() );
	    output.flush();

	    HttpResponse rp = new HttpResponse(input);
	    if (rp.httpCode == -1 && rp.httpMsg == null) {
		/* this is a workaround for C gass-server.
		 * The server just shuts down - it does
		 * not send the reply */
	    } else if (rp.httpCode != 200) {
		throw new IOException("Remote shutdown failed (" + rp.httpCode + " " + rp.httpMsg + ")");
	    }

	} finally {
	    try {
		if (output != null) output.close();
		if (input != null) input.close();
		if (socket != null) socket.close();
	    } catch(Exception e) {}
	}
    }
153866
def send_packed_command(self, command):
        ""
        if not self._sock:
            self.connect()
        try:
            if isinstance(command, str):
                command = [command]
            for item in command:
                self._sock.sendall(item)
        except socket.timeout:
            self.disconnect()
            raise TimeoutError("Timeout writing to socket")
        except socket.error:
            e = sys.exc_info()[1]
            self.disconnect()
            if len(e.args) == 1:
                errno, errmsg = 'UNKNOWN', e.args[0]
            else:
                errno = e.args[0]
                errmsg = e.args[1]
            raise ConnectionError("Error %s while writing to socket. %s." %
                                  (errno, errmsg))
        except:  # noqa: E722
            self.disconnect()
            raise
424792
def shutdown(self):
        """"""
        if self.ZMQcontext and not self.ZMQcontext.closed:
            scoop.SHUTDOWN_REQUESTED = True
            self.socket.send(SHUTDOWN)
            
            # pyzmq would issue an 'no module named zmqerror' on windows
            # without this
            try:
                self.direct_socket.__del__()
                self.socket.__del__()
                self.infoSocket.__del__()
            except AttributeError:
                # Older versions of pyzmq doesn't have the __del__ method
                pass

            self.ZMQcontext.destroy()
471999
def shutdown(self):
        """"""

        if self.verbose:
            print(self.socket.getsockname(), 'xx', self.peername)

        try:
            self.socket.shutdown(socket.SHUT_RDWR)
        except IOError as err:
            assert err.errno is _ENOTCONN, "unexpected IOError: %s" % err
            # remote peer has already closed the connection,
            # just ignore the exceeption
            pass
530549
function shutdown(opts, cb) {
  if(typeof opts === 'function') {
    cb = opts;
    opts = null;
  }
  opts = opts || {};
  var code = opts.code || 0
    , i = -1
    , snapshots = this.state.conf.get(ConfigKey.SAVE)
    , save = typeof opts.save === 'boolean' ? opts.save : null;

  if(save === null) {
    save = snapshots && snapshots.length > 0;
  }

  /* istanbul ignore next: always in test environment */
  if(process.env.NODE_ENV === Constants.TEST) {
    save = false;
  }

  // cannot save a potentially inconsistent data set
  if(ScriptManager.busy && ScriptManager.written) {
    save = false;
  }

  if(Persistence.loading && save) {
    save = false;
    this.log.warning('save skipped while db load in progress');
  }

  this.state.scheduler.kill();

  function iterate() {
    var conn = this.state.getClient(++i);
    if(!conn) return onClose();
    this.log.verbose('terminating client connection %s', conn.client.id);
    conn.close(function onClose() {
      --i;
      iterate();
    });
  }

  function onShutdownComplete() {
    if(this._daemonized) {
      daemon.pid.remove(this.conf);
    }
    this.log.notice('ready to exit, ciao');
    /* istanbul ignore next: always in test environment */
    if(cb === process.exit
      && process.env.NODE_ENV === Constants.TEST
      && !this._daemonized) {
      return;
    }
    cb(code);
  }

  function onClose() {
    // not saving to disc, explicit nosave
    // or not snapshotting (no save points)
    if(!save) return onShutdownComplete();
    this.log.notice('saving the final rdb snapshot before exiting');
    Persistence.saveSync(this.state.store, this.state.conf);
    onShutdownComplete();
    //Persistence.save(this.state.store, this.state.conf, onShutdownComplete);
  }

  this.log.verbose('not accepting connections')

  // TODO: prevent/handle not running error when not listening!
  // TODO: can possibly test the output of address() to know if we
  // TODO: are listening or not. all logic should be the same just
  // TODO: need to skip the call to close()

  // the close callback can fire before the disconnect listener
  // for the last client connection, so onClose is called when the
  // last connection is actually closed, allows us to assert on
  // client connection length
  if(this._tcp) {
    this._tcp.close();
  }

  if(this._unix) {
    this._unix.close();
  }

  onShutdownComplete = onShutdownComplete.bind(this);
  onClose = onClose.bind(this);
  iterate = iterate.bind(this);
  iterate();
}
257445
def shutdown(self, msg):
        """"""
        try:
            self.cleanup()

            self.history.append("Completed on: %s" % time.asctime())
            self.history.append("Elapsed time: %s" % self.get_delta_etime())

            if self.debug:
                print(">>>>> shutdown: Number of open file descriptors: %s" % get_open_fds())

            retcode = self.send_email(msg)
            if self.debug:
                print("send_mail retcode", retcode)

            # Write file with the list of exceptions:
            if self.exceptions:
                dump_file = os.path.join(self.flow.workdir, "_exceptions")
                with open(dump_file, "wt") as fh:
                    fh.writelines(self.exceptions)
                    fh.write("Shutdown message:\n%s" % msg)

            lines = []
            app = lines.append
            app("Submitted on: %s" % time.ctime(self.start_time))
            app("Completed on: %s" % time.asctime())
            app("Elapsed time: %s" % str(self.get_delta_etime()))

            if self.flow.all_ok:
                app("Flow completed successfully")
            else:
                app("Flow %s didn't complete successfully" % repr(self.flow.workdir))
                app("use `abirun.py FLOWDIR debug` to analyze the problem.")
                app("Shutdown message:\n%s" % msg)

            print("")
            print("\n".join(lines))
            print("")

            self._do_customer_service()

            if self.flow.all_ok:
                print("Calling flow.finalize()...")
                self.flow.finalize()
                #print("finalized:", self.flow.finalized)
                if self.rmflow:
                    app("Flow directory will be removed...")
                    try:
                        self.flow.rmtree()
                    except Exception:
                        logger.warning("Ignoring exception while trying to remove flow dir.")

        finally:
            # Shutdown the scheduler thus allowing the process to exit.
            logger.debug('This should be the shutdown of the scheduler')

            # Unschedule all the jobs before calling shutdown
            #self.sched.print_jobs()
            if not has_sched_v3:
                for job in self.sched.get_jobs():
                    self.sched.unschedule_job(job)
            #self.sched.print_jobs()

            self.sched.shutdown()
17991
def shutdown(server, graceful=True):
    
    ioloop = IOLoop.instance()

    logging.info("Stopping server...")
    # Stop listening for new connections
    server.stop()

    def final_stop():
        ioloop.stop()
        logging.info("Stopped.")
        sys.exit(0)

    def poll_stop(counts={'remaining': None, 'previous': None}):
        remaining = len(ioloop._handlers)
        counts['remaining'], counts['previous'] = remaining, counts['remaining']
        previous = counts['previous']
        # Wait until we only have only one IO handler remaining.  That
        # final handler will be our PeriodicCallback polling task.
        if remaining == 1:
            final_stop()
        if previous is None or remaining != previous:
            logging.info("Waiting on IO %d remaining handlers", remaining)

    if graceful:
        # Callback to check on remaining handlers.
        poller = PeriodicCallback(poll_stop, 250, io_loop=ioloop)
        poller.start()

        # Give up after 10 seconds of waiting.
        ioloop.add_timeout(time.time() + 10, final_stop)
    else:
        final_stop()
107326
def shutdown(self):
        """"""
        # Return early if this server has already exited.
        if not process.proc_alive(self.proc):
            return
        logger.info("Attempting to connect to %s", self.hostname)
        client = self.connection
        # Attempt the shutdown command twice, the first attempt might fail due
        # to an election.
        attempts = 2
        for i in range(attempts):
            logger.info("Attempting to send shutdown command to %s",
                        self.hostname)
            try:
                client.admin.command("shutdown", force=True)
            except ConnectionFailure:
                # A shutdown succeeds by closing the connection but a
                # connection error does not necessarily mean that the shutdown
                # has succeeded.
                pass
            # Wait for the server to exit otherwise rerun the shutdown command.
            try:
                return process.wait_mprocess(self.proc, 5)
            except TimeoutError as exc:
                logger.info("Timed out waiting on process: %s", exc)
                continue
        raise ServersError("Server %s failed to shutdown after %s attempts" %
                           (self.hostname, attempts))
171085
public synchronized void shutdown() {
        if (stopLock.get())
            return;


        // shutting down underlying transport
        transport.shutdown();

        // disposing INDArray flow
        disposable.dispose();

        updaterParamsSubscribers.clear();
        modelParamsSubsribers.clear();
        updatesSubscribers.clear();
        updatesQueue.clear();

        // state that we're done
        launchLock.set(false);

        stopLock.set(true);
    }
1183296
def shutdown(self):
        """"""
        self.socket.shutdown()

        if scoop:
            if scoop.DEBUG:
                from scoop import _debug
                _debug.writeWorkerDebug(
                    scoop._control.debug_stats,
                    scoop._control.QueueLength,
                )
158823
def shutdown(self):
        """"""
        self.stopped.set()

        if hasattr(self.api, "shutdown"):
            self.api.shutdown()

        for thread in self.thread.values():
            thread.join()