// StopInbounds is the first step in shutdown. It stops all inbounds
// configured on the dispatcher, which stops routing RPCs to all registered
// procedures. It's safe to call concurrently, but all calls after the first
// return an error.
172088
func (s *PhasedStopper) StopInbounds() error {
	if s.inboundsStopInitiated.Swap(true) {
		return errors.New("already began stopping inbounds")
	}
	defer s.inboundsStopped.Store(true)
	s.log.Debug("stopping inbounds")
	wait := errorsync.ErrorWaiter{}
	for _, ib := range s.dispatcher.inbounds {
		wait.Submit(ib.Stop)
	}
	if errs := wait.Wait(); len(errs) > 0 {
		return multierr.Combine(errs...)
	}
	s.log.Debug("stopped inbounds")
	return nil
}
1153207
func Shutdown() {
	lock.Lock()
	defer lock.Unlock()
	for _, v := range instances {
		v.Shutdown()
	}
}
180070
func (s *GracefulServer) BlockingClose() bool {
	result := s.Close()
	<-s.shutdownFinished
	return result
}
264449
func (dp *DaemonPen) Shutdown(sig os.Signal) {
	dp.Lock()
	defer dp.Unlock()
	if dp.daemons != nil {
		for _, d := range dp.daemons {
			d.Shutdown(sig)
		}
	}
}
702638
func (i *Inbound) shutdown(ctx context.Context) error {
	return i.once.Stop(func() error {
		if i.server == nil {
			return nil
		}

		return i.server.Shutdown(ctx)
	})
}
667003
func (s *PhasedStopper) StopTransports() error {
	if !s.inboundsStopped.Load() || !s.outboundsStopped.Load() {
		return errors.New("must stop inbounds and outbounds first")
	}
	if s.transportsStopInitiated.Swap(true) {
		return errors.New("already began stopping transports")
	}
	s.log.Debug("stopping transports")
	wait := errorsync.ErrorWaiter{}
	for _, t := range s.dispatcher.transports {
		wait.Submit(t.Stop)
	}
	if errs := wait.Wait(); len(errs) > 0 {
		return multierr.Combine(errs...)
	}
	s.log.Debug("stopped transports")

	s.log.Debug("stopping metrics push loop, if any")
	s.dispatcher.stopMeter()
	s.log.Debug("stopped metrics push loop, if any")

	return nil
}
1318113
func (t *Transport) NewInbound(addr string, opts ...InboundOption) *Inbound {
	i := &Inbound{
		once:              lifecycle.NewOnce(),
		addr:              addr,
		shutdownTimeout:   defaultShutdownTimeout,
		tracer:            t.tracer,
		logger:            t.logger,
		transport:         t,
		grabHeaders:       make(map[string]struct{}),
		bothResponseError: true,
	}
	for _, opt := range opts {
		opt(i)
	}
	return i
}
440422
func (c *RPCClient) Stop() {
	c.quitMtx.Lock()
	select {
	case <-c.quit:
	default:
		close(c.quit)
		c.Client.Shutdown()

		if !c.started {
			close(c.dequeueNotification)
		}
	}
	c.quitMtx.Unlock()
}
102393
func (c *RPCClient) Close() error {
	c.shutdownLock.Lock()
	defer c.shutdownLock.Unlock()

	if !c.shutdown {
		c.shutdown = true
		close(c.shutdownCh)
		c.deregisterAll()
		return c.conn.Close()
	}
	return nil
}
1294974
func (e *Environ) StopInstances(ctx envcontext.ProviderCallContext, ids ...instance.Id) error {
	ociInstances, err := e.getOciInstances(ctx, ids...)
	if err == environs.ErrNoInstances {
		return nil
	} else if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return err
	}

	logger.Debugf("terminating instances %v", ids)
	if err := e.terminateInstances(ctx, ociInstances...); err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return err
	}

	return nil
}
1168275
func (m *MockZonedEnviron) StopInstances(arg0 context.ProviderCallContext, arg1 ...instance.Id) error {
	varargs := []interface{}{arg0}
	for _, a := range arg1 {
		varargs = append(varargs, a)
	}
	ret := m.ctrl.Call(m, "StopInstances", varargs...)
	ret0, _ := ret[0].(error)
	return ret0
}
542251
func (ep *endpoint) Shutdown(flags tcpip.ShutdownFlags) *tcpip.Error {
	ep.mu.Lock()
	defer ep.mu.Unlock()

	if !ep.connected {
		return tcpip.ErrNotConnected
	}

	ep.shutdownFlags |= flags

	if flags&tcpip.ShutdownRead != 0 {
		ep.rcvMu.Lock()
		wasClosed := ep.rcvClosed
		ep.rcvClosed = true
		ep.rcvMu.Unlock()

		if !wasClosed {
			ep.waiterQueue.Notify(waiter.EventIn)
		}
	}

	return nil
}
932226
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
	// Exit early if we have already been instructed to shutdown, this
	// prevents any delayed callbacks from accidentally registering peers.
	if s.Stopped() {
		return
	}

	nodePub := conn.(*brontide.Conn).RemotePub()
	pubStr := string(nodePub.SerializeCompressed())

	s.mu.Lock()
	defer s.mu.Unlock()

	// If we already have an inbound connection to this peer, then ignore
	// this new connection.
	if _, ok := s.inboundPeers[pubStr]; ok {
		srvrLog.Debugf("Already have inbound connection for %x, "+
			"ignoring outbound connection",
			nodePub.SerializeCompressed())

		if connReq != nil {
			s.connMgr.Remove(connReq.ID())
		}
		conn.Close()
		return
	}
	if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
		srvrLog.Debugf("Ignoring cancelled outbound connection")
		s.connMgr.Remove(connReq.ID())
		conn.Close()
		return
	}

	// If we already have a valid connection that is scheduled to take
	// precedence once the prior peer has finished disconnecting, we'll
	// ignore this connection.
	if _, ok := s.scheduledPeerConnection[pubStr]; ok {
		srvrLog.Debugf("Ignoring connection, peer already scheduled")

		if connReq != nil {
			s.connMgr.Remove(connReq.ID())
		}

		conn.Close()
		return
	}

	srvrLog.Infof("Established connection to: %x@%v", pubStr,
		conn.RemoteAddr())

	if connReq != nil {
		// A successful connection was returned by the connmgr.
		// Immediately cancel all pending requests, excluding the
		// outbound connection we just established.
		ignore := connReq.ID()
		s.cancelConnReqs(pubStr, &ignore)
	} else {
		// This was a successful connection made by some other
		// subsystem. Remove all requests being managed by the connmgr.
		s.cancelConnReqs(pubStr, nil)
	}

	// If we already have a connection with this peer, decide whether or not
	// we need to drop the stale connection. We forgo adding a default case
	// as we expect these to be the only error values returned from
	// findPeerByPubStr.
	connectedPeer, err := s.findPeerByPubStr(pubStr)
	switch err {
	case ErrPeerNotConnected:
		// We were unable to locate an existing connection with the
		// target peer, proceed to connect.
		s.peerConnected(conn, connReq, false)

	case nil:
		// We already have a connection with the incoming peer. If the
		// connection we've already established should be kept and is
		// not of the same type of the new connection (outbound), then
		// we'll close out the new connection s.t there's only a single
		// connection between us.
		localPub := s.identityPriv.PubKey()
		if connectedPeer.inbound &&
			shouldDropLocalConnection(localPub, nodePub) {

			srvrLog.Warnf("Established outbound connection to "+
				"peer %v, but already have inbound "+
				"connection, dropping conn", connectedPeer)
			if connReq != nil {
				s.connMgr.Remove(connReq.ID())
			}
			conn.Close()
			return
		}

		// Otherwise, _their_ connection should be dropped. So we'll
		// disconnect the peer and send the now obsolete peer to the
		// server for garbage collection.
		srvrLog.Debugf("Disconnecting stale connection to %v",
			connectedPeer)

		// Remove the current peer from the server's internal state and
		// signal that the peer termination watcher does not need to
		// execute for this peer.
		s.removePeer(connectedPeer)
		s.ignorePeerTermination[connectedPeer] = struct{}{}
		s.scheduledPeerConnection[pubStr] = func() {
			s.peerConnected(conn, connReq, false)
		}
	}
}
78347
func (p *Plan) Stop() {
	p.stopLock.Lock()
	defer p.stopLock.Unlock()
	if p.stop {
		return
	}
	p.stop = true
	if p.cancelFunc != nil {
		p.cancelFunc()
	}
	close(p.stopCh)
}
203921
func (net *Network) Stop(id enode.ID) error {
	// IMPORTANT: node.Stop() must NOT be called under net.lock as
	// node.Reachable() closure has a reference to the network and
	// calls net.InitConn() what also locks the network. => DEADLOCK
	// That holds until the following ticket is not resolved:

	var err error

	node, err := func() (*Node, error) {
		net.lock.Lock()
		defer net.lock.Unlock()

		node := net.getNode(id)
		if node == nil {
			return nil, fmt.Errorf("node %v does not exist", id)
		}
		if !node.Up() {
			return nil, fmt.Errorf("node %v already down", id)
		}
		node.SetUp(false)
		return node, nil
	}()
	if err != nil {
		return err
	}

	err = node.Stop() // must be called without net.lock

	net.lock.Lock()
	defer net.lock.Unlock()

	if err != nil {
		node.SetUp(true)
		return err
	}
	log.Info("Stopped node", "id", id, "err", err)
	ev := ControlEvent(node)
	net.events.Send(ev)
	return nil
}
1284705
func (p *blockPrefetcher) Shutdown() <-chan struct{} {
	p.shutdownOnce.Do(func() {
		close(p.shutdownCh)
	})
	return p.doneCh
}
206883
func (rf *requestForwardingHandler) Stop() error {
	// Give some time for existing RPCs to drain.
	time.Sleep(cluster.ListenerAcceptDeadline)
	close(rf.stopCh)
	rf.fwRPCServer.Stop()
	return nil
}