Actions to be performed on stopping the node.

        - Close the UDP socket of the nodestack
762686
def onStopping(self):
        
        # Log stats should happen before any kind of reset or clearing
        if self.config.STACK_COMPANION == 1:
            add_stop_time(self.ledger_dir, self.utc_epoch())

        self.logstats()
        self.reset()

        # Stop the ledgers
        for ledger in self.ledgers:
            try:
                ledger.stop()
            except Exception as ex:
                logger.exception('{} got exception while stopping ledger: {}'.format(self, ex))

        self.nodestack.stop()
        self.clientstack.stop()

        self.closeAllKVStores()

        self._info_tool.stop()
        self.mode = None
        self.execute_hook(NodeHooks.POST_NODE_STOPPED)
294379
def terminate(self, nodes=None):
        
        if not self.is_connected():
            return None

        nodes = nodes or self.nodes
        failed_kill = []

        result = self.gce.ex_destroy_multiple_nodes(nodes, poll_interval=1, ignore_errors=False)

        # Verify whether all instances have been terminated.
        for i, success in enumerate(result):
            if success:
                logging.info('Successfully destroyed: %s', nodes[i].name)
            else:
                logging.error('Failed to destroy: %s', nodes[i].name)
                failed_kill.append(nodes[i])

        return failed_kill
891156
def close(self):
        

        if not (yield from super().close()):
            return False

        nio = self._ethernet_adapter.get_nio(0)
        if isinstance(nio, NIOUDP):
            self.manager.port_manager.release_udp_port(nio.lport, self._project)

        if self._local_udp_tunnel:
            self.manager.port_manager.release_udp_port(self._local_udp_tunnel[0].lport, self._project)
            self.manager.port_manager.release_udp_port(self._local_udp_tunnel[1].lport, self._project)
            self._local_udp_tunnel = None

        yield from self._stop_ubridge()

        if self.is_running():
            self._terminate_process()

        return True
590192
async def disconnect(self):
        
        self._is_shutdown = True
        self.ready.clear()

        self.update_state(NodeState.DISCONNECTING)

        await self.player_manager.disconnect()

        if self._ws is not None and self._ws.open:
            await self._ws.close()

        if self._listener_task is not None and not self.loop.is_closed():
            self._listener_task.cancel()

        self._state_handlers = []

        _nodes.remove(self)
        log.debug("Shutdown Lavalink WS.")
521814
@Handler(priority = -1000)
    public void onStop(Stop event) {
        if (closing || !serverSocketChannel.isOpen()) {
            return;
        }
        newSyncEventPipeline().fire(new Close(), this);
    }
686564
public void close() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "close");
        }

        // Doing a channel.close() will actually put the keys associated with this
        // channel
        // into the associated selectors cancelledKey list, but they don't get
        // removed until the
        // next time the selector runs. In some cases, we need to make sure they are
        // really gone before we
        // we close the channel, because another thread may have requested another
        // operation
        // on the channel at the same time, which causes problems on some OS'es.
        // So, cancel them manually and wait for the selector to run once before
        // continuing

        // call super.close() to see if we are using Regular Sockets, and if so, let
        // the parent class handle closing the socket
        super.close();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.event(this, tc, "SocketChannel closing, local: " + socket.getLocalSocketAddress() + " remote: " + socket.getRemoteSocketAddress());
        }

        // synchronize on this SocketIOChannel to prevent duplicate closes from
        // being processed
        synchronized (this) {
            if (closed) {
                processClose = false;
            }
            closed = true;
        }

        if (processClose) {

            // checkCancel is only on if we need to manually cancel keys as
            // the socket close() is supposed to do that for us
            if (checkCancel) {
                // Remove socket from current selectors.
                if (channelSelectorRead != null) {
                    SelectionKey k = channelSelectorRead.getKey(channel);
                    if (k != null) {
                        CancelRequest cr = new CancelRequest(k);
                        synchronized (cr) {
                            channelSelectorRead.addCancelRequest(cr);
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(this, tc, "waiting for read key to be canceled, key is " + k);
                            }
                            try {
                                cr.wait();
                            } catch (InterruptedException e) {
                                // No FFDC code needed
                            }
                        } // end-sync
                    }
                }
                if (channelSelectorWrite != null) {
                    SelectionKey k = channelSelectorWrite.getKey(channel);
                    if (k != null) {
                        CancelRequest cr = new CancelRequest(k);
                        synchronized (cr) {
                            channelSelectorWrite.addCancelRequest(cr);
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(this, tc, "waiting for write key to be canceled, key is " + k);
                            }
                            try {
                                cr.wait();
                            } catch (InterruptedException e) {
                                // No FFDC code needed
                            }
                        } // end-sync
                    }
                }
            }

            try {
                if (channel != null) {
                    channel.close();
                }

                // need to make sure the keys get cancelled after the close call
                if (channelSelectorRead != null) {
                    channelSelectorRead.wakeup();
                    channelSelectorRead = null;
                }
                if (channelSelectorWrite != null) {
                    channelSelectorWrite.wakeup();
                    channelSelectorWrite = null;
                }

            } catch (Throwable t) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "Error closing channel: " + t);
                }
                // ignore all shutdown/close errors
            }
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "close");
        }
    }
1196671
@Override
  public void close() {

    LOG.log(Level.FINE, "Closing netty transport socket address: {0}", this.localAddress);

    final ChannelGroupFuture clientChannelGroupFuture = this.clientChannelGroup.close();
    final ChannelGroupFuture serverChannelGroupFuture = this.serverChannelGroup.close();
    final ChannelFuture acceptorFuture = this.acceptor.close();

    final ArrayList<Future> eventLoopGroupFutures = new ArrayList<>(3);
    eventLoopGroupFutures.add(this.clientWorkerGroup.shutdownGracefully());
    eventLoopGroupFutures.add(this.serverBossGroup.shutdownGracefully());
    eventLoopGroupFutures.add(this.serverWorkerGroup.shutdownGracefully());

    clientChannelGroupFuture.awaitUninterruptibly();
    serverChannelGroupFuture.awaitUninterruptibly();

    try {
      acceptorFuture.sync();
    } catch (final Exception ex) {
      LOG.log(Level.SEVERE, "Error closing the acceptor channel for " + this.localAddress, ex);
    }

    for (final Future eventLoopGroupFuture : eventLoopGroupFutures) {
      eventLoopGroupFuture.awaitUninterruptibly();
    }

    LOG.log(Level.FINE, "Closing netty transport socket address: {0} done", this.localAddress);
  }
929416
function onSocketClose() {
        self.resetAll(errors.SocketClosedError({
            reason: 'remote closed',
            socketRemoteAddr: self.socketRemoteAddr,
            direction: self.direction,
            remoteName: self.remoteName
        }));

        if (self.ephemeral) {
            var peer = self.channel.peers.get(self.socketRemoteAddr);
            if (peer) {
                peer.close(noop);
            }
            self.channel.peers.delete(self.socketRemoteAddr);
        }
    }
1046911
def kill(self):
        

        self._socket.shutdown(socket.SHUT_RDWR)
        self._socket.close()
1234067
private void closeOutgoingSockets() throws ClientException {

        SocketOperator op = new SocketOperator() {
                public void operate(SocketBox sb) throws Exception {
                    if (((ManagedSocketBox) sb).isReusable()) {
                        Socket s = sb.getSocket();
                        if (s != null) {
                            // write the closing Eblock and close the socket
                            EBlockImageDCWriter.close(
                                  new DataOutputStream(s.getOutputStream()));
                        }
                    }
                }
       };

        try {
            socketPool.applyToAll(op);
        } catch (IOException e) {
            // ignore - sometimes server might close the socket
        } catch (Exception e) {
            ClientException ce =
                new ClientException(ClientException.SOCKET_OP_FAILED);
            ce.setRootCause(e);
            throw ce;
        }
    }
120701
def close(self):
        
        log.debug("Closing socket connection for %s:%d" % (self.host, self.port))
        if self._sock:
            # Call shutdown to be a good TCP client
            # But expect an error if the socket has already been
            # closed by the server
            try:
                self._sock.shutdown(socket.SHUT_RDWR)
            except socket.error:
                pass

            # Closing the socket should always succeed
            self._sock.close()
            self._sock = None
        else:
            log.debug("No socket found to close!")
76295
private void closeServerSocket() {
       getLogger().debug("{} closing server socket", getName());

       try {
         if (serverSocket != null) {
           serverSocket.close();
         }
       } catch (Exception e) {
         // ignore for now
       }

       serverSocket = null;
     }
963866
def close(self):
        
        log.debug('%r: close() proto=%r connector=%r', self, self.proto, self.connector)
        assert self._dDown is None
        self._dDown = Deferred()

        if self.proto is not None:
            self.proto.transport.loseConnection()
        elif self.connector is not None:
            def connectingFailed(reason):
                """
                Handle the failure resulting from cancellation.

                :reason: a `Failure`, most likely a cancellation error (but
                    that's not guaranteed).
                :returns: `None` to handle the failure
                """
                log.debug('%r: connection attempt has been cancelled: %r', self, reason)
                self._dDown.callback(None)

            self.connector.addErrback(connectingFailed)
            self.connector.cancel()
        else:
            # Fake a cleanly closing connection
            self._dDown.callback(None)

        try:
            raise CancelledError(message="Broker client for node_id={} {}:{} was closed".format(
                self.node_id, self.host, self.port))
        except Exception:
            reason = Failure()
        # Cancel any requests
        for correlation_id in list(self.requests.keys()):  # must copy, may del
            self.cancelRequest(correlation_id, reason)
        return self._dDown
1120059
def stop(self, nodes=None):
        
        if not self.is_connected():
            return None

        nodes = nodes or self.nodes
        result = []

        for node in nodes:
            if node.state == 'stopped':
                logging.warning('Node %s is already "stopped".', node.name)
                continue
            try:
                status = self.gce.ex_stop_node(node)
                if status:
                    result.append(node)
            except InvalidRequestError as err:
                raise ComputeEngineManagerException(err)

        return result
552911
public void close() {
        LOG.info("Begin to shutdown NettyServer");
        if (allChannels != null) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        // await(5, TimeUnit.SECONDS)
                        // sometimes allChannels.close() will block the exit thread
                        allChannels.close().await(1, TimeUnit.SECONDS);
                        LOG.info("Successfully close all channel");
                        factory.releaseExternalResources();
                    } catch (Exception ignored) {
                    }
                    allChannels = null;
                }
            }).start();

            JStormUtils.sleepMs(1000);
        }
        LOG.info("Successfully shutdown NettyServer");
    }
1075804
def stop(self):
        """"""
        self.logger.warning("Stop executed")
        try:
            self._socket.close()
        except Exception:
            self.logger.error("Error while closing socket")
            raise VelbusException("Error while closing socket")
        time.sleep(1)
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)