Handle slave disconnected

Typically called after slave has finished handling request
324426
public function slaveClosed()
    {
        $this->verboseTimer(function ($took) {
            return sprintf('<info>Worker %d took abnormal %.3f seconds for handling a connection</info>', $this->slave->getPort(), $took);
        });

        // Return a "502 Bad Gateway" response if the response was empty
        if ($this->lastOutgoingData == '') {
            $this->output->writeln('Script did not return a valid HTTP response. Maybe it has called exit() prematurely?');
            $this->incoming->write($this->createErrorResponse('502 Bad Gateway', 'Slave returned an invalid HTTP response. Maybe the script has called exit() prematurely?'));
        }
        $this->incoming->end();
        if ($this->maxExecutionTime > 0) {
            $this->loop->cancelTimer($this->maxExecutionTimer);
        }

        if ($this->slave->getStatus() === Slave::LOCKED) {
            // slave was locked, so mark as closed now.
            $this->slave->close();
            $this->output->writeln(sprintf('Marking locked worker #%d as closed', $this->slave->getPort()));
            $this->slave->getConnection()->close();
        } elseif ($this->slave->getStatus() !== Slave::CLOSED) {
            // if slave has already closed its connection to master,
            // it probably died and is already terminated

            // mark slave as available
            $this->slave->release();

            /** @var ConnectionInterface $connection */
            $connection = $this->slave->getConnection();

            $maxRequests = $this->slave->getMaxRequests();
            if ($this->slave->getHandledRequests() >= $maxRequests) {
                $this->slave->close();
                $this->output->writeln(sprintf('Restart worker #%d because it reached max requests of %d', $this->slave->getPort(), $maxRequests));
                $connection->close();
            }
            // Enforce memory limit
            $memoryLimit = $this->slave->getMemoryLimit();
            if ($memoryLimit > 0 && $this->slave->getUsedMemory() >= $memoryLimit) {
                $this->slave->close();
                $this->output->writeln(sprintf('Restart worker #%d because it reached memory limit of %d', $this->slave->getPort(), $memoryLimit));
                $connection->close();
            }
        }
    }
278251
def process_request_thread(self, request, client_address):
        
        try:
            self.finish_request(request, client_address)
            self.shutdown_request(request)
        except:
            self.handle_error(request, client_address)
            self.shutdown_request(request)
121895
def _disconnected(self, uri):
        """"""
        self.param_updater.close()
        self.is_updated = False
        # Clear all values from the previous Crazyflie
        self.toc = Toc()
        self.values = {}
645325
function handleControlConnection(connection) {
		connection.on('data', function (data) {
			console.log('Got command:', data.toString().trim());
			var request = data.toString().trim().split(' '),
				cmd = request[0],
				target = request[1],
				newline = '\r\n',
				response;
			console.log('Command is:', cmd);
			switch (cmd) {
				case 'start':
					console.log('got here');
					self.store.broadcast('worker:start', target);
					response = lib.format('Starting {0} servers.', (target || 'all'));
					break;
				case 'pause':
					self.store.broadcast('worker:pause', target);
					response = lib.format('Pausing {0} servers.', (target || 'all'));
					break;
				case 'stop':
					self.store.broadcast('worker:stop', target);
					response = lib.format('Stopping {0} servers.', (target || 'all'));
					break;
				case 'resume':
					self.store.broadcast('worker:resume', target);
					response = lib.format('Resuming {0} servers.', (target || 'all'));
					break;
				case 'heartbeat':
					var id = lib.guid();
					self.store.broadcast('worker:heartbeat', id);
					wait(id, function () {
						var args = Array.prototype.slice.call(arguments),
							response = {};
						lib.each(args, function (data) {
							var message = data[0],
								worker = data[1];
							response[worker] = message;
						});
						connection.write(JSON.stringify(response));
						connection.end(newline);
					});
					break;
				case 'stats':
					var id = lib.guid();
					self.store.broadcast('worker:stats', id);
					wait(id, function () {
						var args = Array.prototype.slice.call(arguments),
							response = {};
						lib.each(args, function (data) {
							var message = data[0],
								worker = data[1];
							response[worker] = message;
						});
						connection.write(JSON.stringify(response));
						connection.end(newline);
					});
					break;
				default:
					response = lib.format('Unknown command: {0}.', cmd);
					break;
			}
			if (response) {
				connection.write(response);
				connection.end(newline);
			}
		});
	}
275153
def clientdisconnect(self, event):
        

        try:
            if event.clientuuid == self.remote_controller:
                self.log("Remote controller disconnected!", lvl=critical)
                self.remote_controller = None
        except Exception as e:
            self.log("Strange thing while client disconnected", e, type(e))
412231
def ucs_manager_disconnect(self, handle, ucsm_ip):
        
        try:
            handle.Logout()
        except Exception as e:
            # Raise a Neutron exception. Include a description of
            # the original  exception.
            raise cexc.UcsmDisconnectFailed(ucsm_ip=ucsm_ip, exc=e)
1080710
void handleDisconnected() throws IOException {
		synchronized (this.asyncMutex) {
			if (socket != null) {
				socket.close();
			}
			this.socket = new Socket(server, port);
			this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			this.out = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
			
			this.listenThread = new SocketThread(this.in, this, this.resultParser, this.daemon);
			this.listenThread.start();
			if (lastWatch != null) { // restore watch if we had one.
				this.syncCommand(lastWatch, WatchObject.class);
			}
		}
		
	}
41840
def _disconnect(self, handle):
        

        payload = struct.pack('<B', handle)
        response = self._send_command(3, 0, payload)

        conn_handle, result = unpack("<BH", response.payload)
        if result != 0:
            self._logger.info("Disconnection failed result=%d", result)
            return False, None

        assert conn_handle == handle

        def disconnect_succeeded(event):
            if event.command_class == 3 and event.command == 4:
                event_handle, = unpack("B", event.payload[0:1])
                return event_handle == handle

            return False

        #FIXME Hardcoded timeout
        events = self._wait_process_events(3.0, lambda x: False, disconnect_succeeded)
        if len(events) != 1:
            return False, None

        return True, {'handle': handle}
687788
def process_request(self, request, client_address):
        

        self.finish_request(request, client_address)
        self.shutdown_request(request)
279795
def wait(self):
        
        if self.error:
            raise self.error
        if not self.running:
            raise ValueError("Unable to send until client has been started.")
        try:
            self._handler.wait()
        except (errors.TokenExpired, errors.AuthenticationException):
            log.info("Sender disconnected due to token error. Attempting reconnect.")
            self.reconnect()
        except (errors.LinkDetach, errors.ConnectionClose) as shutdown:
            if shutdown.action.retry and self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except errors.MessageHandlerError as shutdown:
            if self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except Exception as e:
            log.info("Unexpected error occurred (%r).", e)
            raise EventHubError("Send failed: {}".format(e))
94196
function (done) {
      if (called) return;

      called = true;

      // wait for req events to fire
      process.nextTick(function() {
        if (waitend && req.readable) {
          // dump rest of request
          req.resume();
          req.once('end', done);
          return;
        }

        done();
      });
    }
998386
private function cleanupSlaveConnections()
    {
        foreach ($this->config['database']['connections'] as $name => $connection) {
            if (count($connection['slaves']) <= 0) {
                unset($this->config['database']['connections'][$name]['slaves']);
            }
        }
    }
727575
def process_request_thread(self, request, client_address):
        

        try:
            self.finish_request(request, client_address)
            self.shutdown_request(request)
        except Exception as e:
            self.logger.error(e)
            self.handle_error(request, client_address)
            self.shutdown_request(request)
201946
def _raise_error_if_disconnected(self) -> None:
        
        if (
            self.transport is None
            or self.protocol is None
            or self.transport.is_closing()
        ):
            self.close()
            raise SMTPServerDisconnected("Disconnected from SMTP server")
213259
def serve(self):
        """"""
        while self.ready:
            try:
                self.tick()
            except (KeyboardInterrupt, SystemExit):
                raise
            except Exception:
                self.error_log(
                    'Error in HTTPServer.tick', level=logging.ERROR,
                    traceback=True,
                )

            if self.interrupt:
                while self.interrupt is True:
                    # Wait for self.stop() to complete. See _set_interrupt.
                    time.sleep(0.1)
                if self.interrupt:
                    raise self.interrupt
1062916
public function disconnect()
    {
        $this->connection = null;

        foreach ($this->getSlaves() as $slave) {
            $slave->disconnect();
        }
    }
1218526
def disconnect(self):
        '''
        
        '''
        self.log("Disconnecting broker %r.", self)
        d = defer.succeed(None)
        if self.is_master():
            if self.listener is not None:
                d.addCallback(defer.drop_param, self.listener.stopListening)
                d.addCallback(defer.drop_param, self.factory.disconnect)
        elif self.is_slave():
            d = defer.maybeDeferred(self.factory.disconnect)
        elif self._cmp_state(BrokerRole.disconnected):
            return defer.succeed(None)
        d.addCallback(defer.drop_param, self.become_disconnected)
        return d