Gracefully shutdown a server that is serving forever.
422931
def stop(self):
        """"""
        self.ready = False
        if self._start_time is not None:
            self._run_time += (time.time() - self._start_time)
        self._start_time = None

        sock = getattr(self, 'socket', None)
        if sock:
            if not isinstance(self.bind_addr, six.string_types):
                # Touch our own socket to make accept() return immediately.
                try:
                    host, port = sock.getsockname()[:2]
                except socket.error as ex:
                    if ex.args[0] not in errors.socket_errors_to_ignore:
                        # Changed to use error code and not message
                        # See
                        # https://github.com/cherrypy/cherrypy/issues/860.
                        raise
                else:
                    # Note that we're explicitly NOT using AI_PASSIVE,
                    # here, because we want an actual IP to touch.
                    # localhost won't work if we've bound to a public IP,
                    # but it will if we bound to '0.0.0.0' (INADDR_ANY).
                    for res in socket.getaddrinfo(
                        host, port, socket.AF_UNSPEC,
                        socket.SOCK_STREAM,
                    ):
                        af, socktype, proto, canonname, sa = res
                        s = None
                        try:
                            s = socket.socket(af, socktype, proto)
                            # See
                            # https://groups.google.com/group/cherrypy-users/
                            #     browse_frm/thread/bbfe5eb39c904fe0
                            s.settimeout(1.0)
                            s.connect((host, port))
                            s.close()
                        except socket.error:
                            if s:
                                s.close()
            if hasattr(sock, 'close'):
                sock.close()
            self.socket = None

        self.requests.stop(self.shutdown_timeout)
811146
def stop(self, timeout_s=None):
    """"""
    self._live = False
    try:
      self._sock.shutdown(socket.SHUT_RDWR)
      self._sock.close()
    except socket.error:
      pass
    self.join(timeout_s)
202618
def server_off(self):
        '''  '''
        if (self.server.is_server_running() == 'yes' or
                self.server.is_server_running() == 'maybe'):
            self.server.shutdown()
            print 'Please wait. This could take a few seconds.'
            time.sleep(0.5)
918862
static public void shutdown() {

        // need to unregister the service
        if (getServerConfig().enableRegistry && registry != null && serviceUrls != null) {
            for(URL serviceUrl: serviceUrls) {
                registry.unregister(serviceUrl);
                // Please don't remove the following line. When server is killed, the logback won't work anymore.
                // Even debugger won't reach this point; however, the logic is executed successfully here.
                System.out.println("unregister serviceUrl " + serviceUrl);
                if (logger.isInfoEnabled())
                    logger.info("unregister serviceUrl " + serviceUrl);
            }
        }

        if (gracefulShutdownHandler != null) {
            logger.info("Starting graceful shutdown.");
            gracefulShutdownHandler.shutdown();
            try {
                gracefulShutdownHandler.awaitShutdown(60 * 1000);
            } catch (InterruptedException e) {
                logger.error("Error occurred while waiting for pending requests to complete.", e);
            }
            logger.info("Graceful shutdown complete.");
        }

        ShutdownHookProvider[] shutdownHookProviders = SingletonServiceFactory.getBeans(ShutdownHookProvider.class);
        if (shutdownHookProviders != null)
            Arrays.stream(shutdownHookProviders).forEach(s -> s.onShutdown());

        stop();
        logger.info("Cleaning up before server shutdown");
    }
1374217
def shutdown(self):
        """"""
        if self.sock:
            self.sock.close()
            self.sock = None
            self.connected = False
71945
@Override
    public void shutdown() {
        final WireMockServer server = this;
        Thread shutdownThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // We have to sleep briefly to finish serving the shutdown request before stopping the server, as
                    // there's no support in Jetty for shutting down after the current request.
                    // See http://stackoverflow.com/questions/4650713
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                server.stop();
            }
        });
        shutdownThread.start();
    }
1113473
def stop(self, terminate=False):
        

        if not self.__online:
            raise foundations.exceptions.ServerOperationError(
                "{0} | '{1}' TCP Server is not online!".format(self.__class__.__name__, self))

        if not terminate:
            self.__server.shutdown()
        else:
            self.__server._BaseServer__shutdown_request = True

        self.__server = None
        self.__worker = None
        self.__online = False

        LOGGER.info("{0} | TCP Server successfully stopped!".format(self.__class__.__name__))
        return True
1259292
def __serve_forever(self):
        """"""
        # No need to update the server list
        # It's done by the GlancesAutoDiscoverListener class (autodiscover.py)
        # Or define staticaly in the configuration file (module static_list.py)
        # For each server in the list, grab elementary stats (CPU, LOAD, MEM, OS...)
        thread_list = {}
        while self.screen.is_end == False:
            logger.debug("Iter through the following server list: {}".format(self.get_servers_list()))
            for v in self.get_servers_list():
                key = v["key"]
                thread = thread_list.get(key, None)
                if thread is None or thread.is_alive() == False:
                    thread = threading.Thread(target=self.__update_stats, args=[v])
                    thread_list[key] = thread
                    thread.start()

            # Update the screen (list or Glances client)
            if self.screen.active_server is None:
                #  Display the Glances browser
                self.screen.update(self.get_servers_list())
            else:
                # Display the active server
                self.__display_server(self.get_servers_list()[self.screen.active_server])

        # exit key pressed
        for thread in thread_list.values():
            thread.join()
1117543
public void stop() {
        CompletableFuture.runAsync(() -> {
            try {
                bootstrap.getInjector().getInstance(Server.class).stop();
            } catch (Exception ignore) {
                // Ignore NPE. At this point the server REALLY should be possible to find
            }
            bootstrap.shutdown();
        });
    }
721883
def stop_serving(self):
        
        if self.container:
            self.container.down()
            self.container.join()
            self._cleanup()
        # for serving we can delete everything in the container root.
        _delete_tree(self.container_root)
57472
def shutdown(self):
        ''''''
        if self._proxy:
            os.sync()
            self._proxy(*self._args)
1253499
def on_server_shutdown(self):
        """"""
        if not self._container:
            return
        self._container.stop()
        self._container.remove(v=True, force=True)
481355
def stop_server(self):
        
        if self.rpc_server is not None:
            try:
                self.rpc_server.socket.shutdown(socket.SHUT_RDWR)
            except:
                log.warning("Failed to shut down server socket")

            self.rpc_server.shutdown()
847093
async def terminate(self) -> None:
        """"""
        await asyncio.sleep(config.shutdown_wait)
        # stop server and close loop if no more connection exists
        if not is_connected():
            stop_server(self.application.server)
            self.application.loop.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))
1169131
async def close(self) -> None:
        
        self.stream.close()
        # Block until the serving loop is done, but ignore any exceptions
        # (start_serving is already responsible for logging them).
        assert self._serving_future is not None
        try:
            await self._serving_future
        except Exception:
            pass
1053293
public void shutdown() {
	accept = false;
	try {
	    _server.close();
	} catch(Exception e) {}
	// this is a hack to ensue the server socket is
	// unblocked from accpet()
	// but this is not guaranteed to work still
        SocketFactory factory = SocketFactory.getDefault();
	Socket s = null;
	try {
	    s = factory.createSocket(InetAddress.getLocalHost(), getPort());
	    s.getInputStream();
	} catch (Exception e) {
	    // can be ignored
	} finally {
	    if (s != null) {
		try { s.close(); } catch (Exception e) {}
	    }
	}

	// reset everything
        serverThread = null;
        _server = null;
    }