Handles the reception of a timeout signal indicating that a request has been processing for too long, as
        defined by the Harakiri settings.
964265
def harakiri(self, *_):
        
        if self.shutting_down:
            self.logger.warning('Graceful shutdown failed after {}s. Exiting now!'.format(
                self.settings['harakiri']['shutdown_grace']
            ))
            sys.exit(1)
        else:
            self.logger.warning('No activity during {}s, triggering harakiri with grace {}s'.format(
                self.settings['harakiri']['timeout'],
                self.settings['harakiri']['shutdown_grace'],
            ))
            self.shutting_down = True
            signal.alarm(self.settings['harakiri']['shutdown_grace'])
327413
public void processTimeout(TimeoutEvent timeoutEvent) {
        Transaction transaction = null;
        if(timeoutEvent.isServerTransaction()) {
            transaction = timeoutEvent.getServerTransaction();
            if(logger.isDebugEnabled()) {
                logger.debug("timeout => " + transaction.getRequest().toString());
            }
        } else {
            transaction = timeoutEvent.getClientTransaction();
            if(logger.isDebugEnabled()) {
                logger.debug("timeout => " + transaction.getRequest().toString());
            }
        }
        String callId = ((CallIdHeader)transaction.getRequest().getHeader(CallIdHeader.NAME)).getCallId();
        register.unStickSessionFromNode(callId);
    }
202203
def handle_request(self):
        
        # Support people who used socket.settimeout() to escape
        # handle_request before self.timeout was available.
        timeout = self.socket.gettimeout()
        if timeout is None:
            timeout = self.timeout
        elif self.timeout is not None:
            timeout = min(timeout, self.timeout)
        fd_sets = select.select([self], [], [], timeout)
        if not fd_sets[0]:
            self.handle_timeout()
            return
        self._handle_request_noblock()
40721
private void handleRequestFailure(long requestId, Throwable error, ThreadContext context) {
    ByteBuf buffer = channel.alloc().buffer(10)
      .writeByte(RESPONSE)
      .writeLong(requestId)
      .writeByte(FAILURE);

    try {
      writeError(buffer, error, context);
    } catch (SerializationException e) {
      return;
    }

    channel.writeAndFlush(buffer, channel.voidPromise());
  }
361172
def handle_signal(self, sig, frame):
        """"""
        if sig in [signal.SIGINT]:
            log.warning("Ctrl-C pressed, shutting down...")
        if sig in [signal.SIGTERM]:
            log.warning("SIGTERM received, shutting down...")
        self.cleanup()
        sys.exit(-sig)
1210765
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final Object data) {
        return requestTimeout(delay, unit, null, data);
    }
1068786
public void timeout(ServletTimer servletTimer) {
		SipSession sipSession = servletTimer.getApplicationSession().getSipSession((String)servletTimer.getInfo());
		if(!State.TERMINATED.equals(sipSession.getState())) {
			try {
				sipSession.createRequest("BYE").send();
			} catch (IOException e) {
				logger.error("An unexpected exception occured while sending the BYE", e);
			}				
		}
	}
393594
def _timeout(self, timeout, handler, *args, **kw):
        
        t = spawn_thread(target=handler, args=args, kw=kw)
        t.daemon = True
        t.start()
        t.join(timeout)

        if not t.is_alive():
            if t.exc_info:
                return t.exc_info
            return t.result
        else:
            try:
                msg = '[%s] Execution was forcefully terminated'
                raise RuntimeError(msg % t.name)
            except:
                return sys.exc_info()
1163917
def timeout(self, timeout):
        '''
        '''
        if self._timeout is None:
            self.event('connection_made').bind(self._add_timeout)
            self.event('connection_lost').bind(self._cancel_timeout)
        self._timeout = timeout or 0
        self._add_timeout(None)
1374554
def execute_request_handler(self):
        
        self._response_timeout_handler = self.loop.call_later(
            self.response_timeout, self.response_timeout_callback
        )
        self._last_request_time = time()
        self._request_handler_task = self.loop.create_task(
            self.request_handler(
                self.request, self.write_response, self.stream_response
            )
        )
1329886
def requestTimedOut(self, reply):
        """"""
        # adapt http_call_result basing on receiving qgs timer timout signal
        self.exception_class = RequestsExceptionTimeout
        self.http_call_result.exception = RequestsExceptionTimeout("Timeout error")
127735
public void waitForBuffer(long timeoutMilli) {
        //assert(callerProcessing.booleanValue() == false);

        synchronized(buffer) {
            if( dirtyBuffer )
                return;
            if( !foundEOF() ) {
                logger.trace("Waiting for things to come in, or until timeout");
                try {
                    if( timeoutMilli > 0 )
                        buffer.wait(timeoutMilli);
                    else
                        buffer.wait();
                } catch(InterruptedException ie) {
                    logger.trace("Woken up, while waiting for buffer");
                }
                // this might went early, but running the processing again isn't a big deal
                logger.trace("Waited");
            }
        }
    }
759668
def timeout_deferred(deferred, timeout, error_message="Timeout occured"):
    
    
    timeout_occured = [False]
    
    def got_result(result):
        if not timeout_occured[0]:
            # Deferred called back before the timeout.
            delayedCall.cancel()
            return result
        else:
            if isinstance(result, failure.Failure) and result.check(defer.CancelledError):
                # Got a `CancelledError` after we called  `cancel()`.
                # Replace it with a `TimeoutError`.
                raise TimeoutError(error_message)
            else:
                # Apparently the given deferred has something else to tell us.
                # It might be that it completed before the `cancel()` had an effect
                # (or as a result thereof). It might also be that it triggered an
                # error. In either case, we want this to be visible down-stream.
                return result
    
    def time_is_up():
        timeout_occured[0] = True
        deferred.cancel()
    delayedCall = reactor.callLater(timeout, time_is_up)

    deferred.addBoth(got_result)
    return deferred
699900
public void processTimeout(final TimeoutEvent timeoutEvent) {
		Transaction eventTransaction = null;
		if(timeoutEvent.isServerTransaction()) {
			eventTransaction = timeoutEvent.getServerTransaction();
		} else {
			eventTransaction = timeoutEvent.getClientTransaction();
		}
		final Transaction transaction = eventTransaction;
		if(logger.isDebugEnabled()) {
			logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString());
		}

		final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData();
		if(tad != null && tad.getSipServletMessage() != null) {
			// https://github.com/RestComm/sip-servlets/issues/107 guard against NPEon concurrent cleanup
			final SipServletMessageImpl sipServletMessage = tad.getSipServletMessage();
			final MobicentsSipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey();
			final MobicentsSipSession sipSession = sipServletMessage.getSipSession();
			getAsynchronousExecutor().execute(new Runnable() {
				public void run() {
					try {
						if(logger.isDebugEnabled()) {
							logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString());
						}
						boolean appNotifiedOfPrackNotReceived = false;
						// session can be null if a message was sent outside of the container by the container itself during Initial request dispatching
						// but the external host doesn't send any response so we call out to the application only if the session is not null
						if(logger.isDebugEnabled()) {
                            logger.debug("time out happened on sipSession " + sipSession);
                        }
						if(sipSession != null) {
							SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName());
							//the context can be null if the server is being shutdown
							if(sipContext != null) {
								MobicentsSipApplicationSession sipApplicationSession = sipSession.getSipApplicationSession();
								try {
									sipContext.enterSipApp(sipApplicationSession, sipSession, false, true);
									MobicentsB2BUAHelper b2buaHelperImpl = sipSession.getB2buaHelper();

									if(b2buaHelperImpl != null && tad.getSipServletMessage() instanceof SipServletRequestImpl) {
										b2buaHelperImpl.unlinkRequestInternal((SipServletRequestImpl)tad.getSipServletMessage(), false);
									}
									// naoki : Fix for Issue 1618 http://code.google.com/p/mobicents/issues/detail?id=1618 on Timeout don't do the 408 processing for Server Transactions
									if(logger.isDebugEnabled()) {
			                            logger.debug("time out happened on server tx ? " + timeoutEvent.isServerTransaction() + " and message " + sipServletMessage);
			                        }
									if(sipServletMessage instanceof SipServletRequestImpl && !timeoutEvent.isServerTransaction()) {
										try {
											ProxyBranchImpl proxyBranchImpl = tad.getProxyBranch();
											if(proxyBranchImpl != null) {
												ProxyImpl proxy = (ProxyImpl) proxyBranchImpl.getProxy();
												if(proxy.getFinalBranchForSubsequentRequests() != null) {
													tad.cleanUp();
													transaction.setApplicationData(null);
													return;
												}
											}
											SipServletRequestImpl sipServletRequestImpl = (SipServletRequestImpl) sipServletMessage;
											if(sipServletRequestImpl.visitNextHop()) {
												return;
											}
											sipServletMessage.setTransaction(transaction);
											SipServletResponseImpl response = (SipServletResponseImpl) sipServletRequestImpl.createResponse(408, null, false, true);
											// Fix for Issue 1734
											sipServletRequestImpl.setResponse(response);
											MessageDispatcher.callServlet(response);
											if(tad.getProxyBranch() != null) {
												tad.getProxyBranch().setResponse(response);
												tad.getProxyBranch().onResponse(response, response.getStatus());
											}
											sipSession.updateStateOnResponse(response, true);
										} catch (Throwable t) {
											logger.error("Failed to deliver 408 response on transaction timeout" + transaction, t);
										}
									}
									// Guard only invite tx should check that, otherwise proxy might become null http://code.google.com/p/mobicents/issues/detail?id=2350
									// Should check only Server Tx for ack or prack not received http://code.google.com/p/mobicents/issues/detail?id=2525
									if(Request.INVITE.equals(sipServletMessage.getMethod()) && timeoutEvent.isServerTransaction()) {
										checkForAckNotReceived(sipServletMessage);
										appNotifiedOfPrackNotReceived = checkForPrackNotReceived(sipServletMessage);
									}
								} finally {
									sipSession.removeOngoingTransaction(transaction);
									sipSession.setRequestsPending(0);
									sipContext.exitSipApp(sipApplicationSession, sipSession);
								}
								// don't invalidate here because if the application sends a final response on the noPrack received
								// the ACK to this final response won't be able to get routed since the sip session would have been invalidated
								if(!appNotifiedOfPrackNotReceived) {
									tryToInvalidateSession(sipSessionKey, false);
								}
							}
						}
						// don't clean up for the same reason we don't invalidate the sip session right above
						tad.cleanUp();
						transaction.setApplicationData(null);
					} catch (Exception e) {
						logger.error("Problem handling timeout", e);
					}
				}
			});
		}
	}
1123781
private void checkTimeout() throws ParserException {
	if (timeout > 0) {
	    if (System.currentTimeMillis() - startTime > timeout * 1000) {
		throw new ParserException("Timeout after " + timeout + " seconds near '"
			+ getTokenStream().getCodeSample(maxPosition) + "'!");
	    }
	}
    }
318153
void terminateRequest() {
        int oldVal = state;
        if (allAreSet(oldVal, FLAG_REQUEST_TERMINATED)) {
            // idempotent
            return;
        }
        if (requestChannel != null) {
            requestChannel.requestDone();
        }
        this.state = oldVal | FLAG_REQUEST_TERMINATED;
        if (anyAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) {
            invokeExchangeCompleteListeners();
        }
    }
1069592
private void handleResponseFailure(long requestId, Throwable t) {
    ContextualFuture future = responseFutures.remove(requestId);
    if (future != null) {
      future.context.executor().execute(() -> future.completeExceptionally(t));
    }
  }