handle keep-alive timeout gracefully

This commit is contained in:
zyguan 2017-07-24 01:37:36 +08:00
parent e8a9b4743b
commit f50dc83829

View File

@ -139,8 +139,10 @@ class HttpProtocol(asyncio.Protocol):
self._request_stream_task.cancel() self._request_stream_task.cancel()
if self._request_handler_task: if self._request_handler_task:
self._request_handler_task.cancel() self._request_handler_task.cancel()
exception = RequestTimeout('Request Timeout') try:
self.write_error(exception) raise RequestTimeout('Request Timeout')
except RequestTimeout as exception:
self.write_error(exception)
# -------------------------------------------- # # -------------------------------------------- #
# Parsing # Parsing
@ -317,6 +319,7 @@ class HttpProtocol(asyncio.Protocol):
self.cleanup() self.cleanup()
def write_error(self, exception): def write_error(self, exception):
response = None
try: try:
response = self.error_handler.response(self.request, exception) response = self.error_handler.response(self.request, exception)
version = self.request.version if self.request else '1.1' version = self.request.version if self.request else '1.1'
@ -331,20 +334,23 @@ class HttpProtocol(asyncio.Protocol):
from_error=True) from_error=True)
finally: finally:
if self.has_log: if self.has_log:
extra = { extra = dict()
'status': response.status, if isinstance(response, HTTPResponse):
'host': '', extra['status'] = response.status
'request': str(self.request) + str(self.url)
}
if response and isinstance(response, HTTPResponse):
extra['byte'] = len(response.body) extra['byte'] = len(response.body)
else: else:
extra['status'] = 0
extra['byte'] = -1 extra['byte'] = -1
if self.request: if self.request:
extra['host'] = '%s:%d' % self.request.ip, extra['host'] = '%s:%d' % self.request.ip,
extra['request'] = '%s %s' % (self.request.method, extra['request'] = '%s %s' % (self.request.method,
self.url) self.url)
netlog.info('', extra=extra) else:
extra['host'] = 'UNKNOWN'
extra['request'] = 'nil'
if self.parser and not (self.keep_alive
and extra['status'] == 408):
netlog.info('', extra=extra)
self.transport.close() self.transport.close()
def bail_out(self, message, from_error=False): def bail_out(self, message, from_error=False):