site.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. # Copyright 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import contextlib
  15. import logging
  16. import time
  17. from typing import Optional
  18. from twisted.python.failure import Failure
  19. from twisted.web.server import Request, Site
  20. from synapse.http import redact_uri
  21. from synapse.http.request_metrics import RequestMetrics, requests_counter
  22. from synapse.logging.context import LoggingContext, PreserveLoggingContext
  23. logger = logging.getLogger(__name__)
  24. _next_request_seq = 0
  25. class SynapseRequest(Request):
  26. """Class which encapsulates an HTTP request to synapse.
  27. All of the requests processed in synapse are of this type.
  28. It extends twisted's twisted.web.server.Request, and adds:
  29. * Unique request ID
  30. * A log context associated with the request
  31. * Redaction of access_token query-params in __repr__
  32. * Logging at start and end
  33. * Metrics to record CPU, wallclock and DB time by endpoint.
  34. It also provides a method `processing`, which returns a context manager. If this
  35. method is called, the request won't be logged until the context manager is closed;
  36. this is useful for asynchronous request handlers which may go on processing the
  37. request even after the client has disconnected.
  38. Attributes:
  39. logcontext: the log context for this request
  40. """
  41. def __init__(self, channel, *args, **kw):
  42. Request.__init__(self, channel, *args, **kw)
  43. self.site = channel.site
  44. self._channel = channel # this is used by the tests
  45. self.authenticated_entity = None
  46. self.start_time = 0.0
  47. # we can't yet create the logcontext, as we don't know the method.
  48. self.logcontext = None # type: Optional[LoggingContext]
  49. global _next_request_seq
  50. self.request_seq = _next_request_seq
  51. _next_request_seq += 1
  52. # whether an asynchronous request handler has called processing()
  53. self._is_processing = False
  54. # the time when the asynchronous request handler completed its processing
  55. self._processing_finished_time = None
  56. # what time we finished sending the response to the client (or the connection
  57. # dropped)
  58. self.finish_time = None
  59. def __repr__(self):
  60. # We overwrite this so that we don't log ``access_token``
  61. return "<%s at 0x%x method=%r uri=%r clientproto=%r site=%r>" % (
  62. self.__class__.__name__,
  63. id(self),
  64. self.get_method(),
  65. self.get_redacted_uri(),
  66. self.clientproto.decode("ascii", errors="replace"),
  67. self.site.site_tag,
  68. )
  69. def get_request_id(self):
  70. return "%s-%i" % (self.get_method(), self.request_seq)
  71. def get_redacted_uri(self):
  72. uri = self.uri
  73. if isinstance(uri, bytes):
  74. uri = self.uri.decode("ascii", errors="replace")
  75. return redact_uri(uri)
  76. def get_method(self):
  77. """Gets the method associated with the request (or placeholder if not
  78. method has yet been received).
  79. Note: This is necessary as the placeholder value in twisted is str
  80. rather than bytes, so we need to sanitise `self.method`.
  81. Returns:
  82. str
  83. """
  84. method = self.method
  85. if isinstance(method, bytes):
  86. method = self.method.decode("ascii")
  87. return method
  88. def get_user_agent(self):
  89. return self.requestHeaders.getRawHeaders(b"User-Agent", [None])[-1]
  90. def render(self, resrc):
  91. # this is called once a Resource has been found to serve the request; in our
  92. # case the Resource in question will normally be a JsonResource.
  93. # create a LogContext for this request
  94. request_id = self.get_request_id()
  95. logcontext = self.logcontext = LoggingContext(request_id)
  96. logcontext.request = request_id
  97. # override the Server header which is set by twisted
  98. self.setHeader("Server", self.site.server_version_string)
  99. with PreserveLoggingContext(self.logcontext):
  100. # we start the request metrics timer here with an initial stab
  101. # at the servlet name. For most requests that name will be
  102. # JsonResource (or a subclass), and JsonResource._async_render
  103. # will update it once it picks a servlet.
  104. servlet_name = resrc.__class__.__name__
  105. self._started_processing(servlet_name)
  106. Request.render(self, resrc)
  107. # record the arrival of the request *after*
  108. # dispatching to the handler, so that the handler
  109. # can update the servlet name in the request
  110. # metrics
  111. requests_counter.labels(self.get_method(), self.request_metrics.name).inc()
  112. @contextlib.contextmanager
  113. def processing(self):
  114. """Record the fact that we are processing this request.
  115. Returns a context manager; the correct way to use this is:
  116. @defer.inlineCallbacks
  117. def handle_request(request):
  118. with request.processing("FooServlet"):
  119. yield really_handle_the_request()
  120. Once the context manager is closed, the completion of the request will be logged,
  121. and the various metrics will be updated.
  122. """
  123. if self._is_processing:
  124. raise RuntimeError("Request is already processing")
  125. self._is_processing = True
  126. try:
  127. yield
  128. except Exception:
  129. # this should already have been caught, and sent back to the client as a 500.
  130. logger.exception("Asynchronous messge handler raised an uncaught exception")
  131. finally:
  132. # the request handler has finished its work and either sent the whole response
  133. # back, or handed over responsibility to a Producer.
  134. self._processing_finished_time = time.time()
  135. self._is_processing = False
  136. # if we've already sent the response, log it now; otherwise, we wait for the
  137. # response to be sent.
  138. if self.finish_time is not None:
  139. self._finished_processing()
  140. def finish(self):
  141. """Called when all response data has been written to this Request.
  142. Overrides twisted.web.server.Request.finish to record the finish time and do
  143. logging.
  144. """
  145. self.finish_time = time.time()
  146. Request.finish(self)
  147. if not self._is_processing:
  148. assert self.logcontext is not None
  149. with PreserveLoggingContext(self.logcontext):
  150. self._finished_processing()
  151. def connectionLost(self, reason):
  152. """Called when the client connection is closed before the response is written.
  153. Overrides twisted.web.server.Request.connectionLost to record the finish time and
  154. do logging.
  155. """
  156. # There is a bug in Twisted where reason is not wrapped in a Failure object
  157. # Detect this and wrap it manually as a workaround
  158. # More information: https://github.com/matrix-org/synapse/issues/7441
  159. if not isinstance(reason, Failure):
  160. reason = Failure(reason)
  161. self.finish_time = time.time()
  162. Request.connectionLost(self, reason)
  163. if self.logcontext is None:
  164. logger.info(
  165. "Connection from %s lost before request headers were read", self.client
  166. )
  167. return
  168. # we only get here if the connection to the client drops before we send
  169. # the response.
  170. #
  171. # It's useful to log it here so that we can get an idea of when
  172. # the client disconnects.
  173. with PreserveLoggingContext(self.logcontext):
  174. logger.warning(
  175. "Error processing request %r: %s %s", self, reason.type, reason.value
  176. )
  177. if not self._is_processing:
  178. self._finished_processing()
  179. def _started_processing(self, servlet_name):
  180. """Record the fact that we are processing this request.
  181. This will log the request's arrival. Once the request completes,
  182. be sure to call finished_processing.
  183. Args:
  184. servlet_name (str): the name of the servlet which will be
  185. processing this request. This is used in the metrics.
  186. It is possible to update this afterwards by updating
  187. self.request_metrics.name.
  188. """
  189. self.start_time = time.time()
  190. self.request_metrics = RequestMetrics()
  191. self.request_metrics.start(
  192. self.start_time, name=servlet_name, method=self.get_method()
  193. )
  194. self.site.access_logger.debug(
  195. "%s - %s - Received request: %s %s",
  196. self.getClientIP(),
  197. self.site.site_tag,
  198. self.get_method(),
  199. self.get_redacted_uri(),
  200. )
  201. def _finished_processing(self):
  202. """Log the completion of this request and update the metrics
  203. """
  204. assert self.logcontext is not None
  205. usage = self.logcontext.get_resource_usage()
  206. if self._processing_finished_time is None:
  207. # we completed the request without anything calling processing()
  208. self._processing_finished_time = time.time()
  209. # the time between receiving the request and the request handler finishing
  210. processing_time = self._processing_finished_time - self.start_time
  211. # the time between the request handler finishing and the response being sent
  212. # to the client (nb may be negative)
  213. response_send_time = self.finish_time - self._processing_finished_time
  214. # need to decode as it could be raw utf-8 bytes
  215. # from a IDN servname in an auth header
  216. authenticated_entity = self.authenticated_entity
  217. if authenticated_entity is not None and isinstance(authenticated_entity, bytes):
  218. authenticated_entity = authenticated_entity.decode("utf-8", "replace")
  219. # ...or could be raw utf-8 bytes in the User-Agent header.
  220. # N.B. if you don't do this, the logger explodes cryptically
  221. # with maximum recursion trying to log errors about
  222. # the charset problem.
  223. # c.f. https://github.com/matrix-org/synapse/issues/3471
  224. user_agent = self.get_user_agent()
  225. if user_agent is not None:
  226. user_agent = user_agent.decode("utf-8", "replace")
  227. else:
  228. user_agent = "-"
  229. code = str(self.code)
  230. if not self.finished:
  231. # we didn't send the full response before we gave up (presumably because
  232. # the connection dropped)
  233. code += "!"
  234. self.site.access_logger.info(
  235. "%s - %s - {%s}"
  236. " Processed request: %.3fsec/%.3fsec (%.3fsec, %.3fsec) (%.3fsec/%.3fsec/%d)"
  237. ' %sB %s "%s %s %s" "%s" [%d dbevts]',
  238. self.getClientIP(),
  239. self.site.site_tag,
  240. authenticated_entity,
  241. processing_time,
  242. response_send_time,
  243. usage.ru_utime,
  244. usage.ru_stime,
  245. usage.db_sched_duration_sec,
  246. usage.db_txn_duration_sec,
  247. int(usage.db_txn_count),
  248. self.sentLength,
  249. code,
  250. self.get_method(),
  251. self.get_redacted_uri(),
  252. self.clientproto.decode("ascii", errors="replace"),
  253. user_agent,
  254. usage.evt_db_fetch_count,
  255. )
  256. try:
  257. self.request_metrics.stop(self.finish_time, self.code, self.sentLength)
  258. except Exception as e:
  259. logger.warning("Failed to stop metrics: %r", e)
  260. class XForwardedForRequest(SynapseRequest):
  261. def __init__(self, *args, **kw):
  262. SynapseRequest.__init__(self, *args, **kw)
  263. """
  264. Add a layer on top of another request that only uses the value of an
  265. X-Forwarded-For header as the result of C{getClientIP}.
  266. """
  267. def getClientIP(self):
  268. """
  269. @return: The client address (the first address) in the value of the
  270. I{X-Forwarded-For header}. If the header is not present, return
  271. C{b"-"}.
  272. """
  273. return (
  274. self.requestHeaders.getRawHeaders(b"x-forwarded-for", [b"-"])[0]
  275. .split(b",")[0]
  276. .strip()
  277. .decode("ascii")
  278. )
  279. class SynapseSite(Site):
  280. """
  281. Subclass of a twisted http Site that does access logging with python's
  282. standard logging
  283. """
  284. def __init__(
  285. self,
  286. logger_name,
  287. site_tag,
  288. config,
  289. resource,
  290. server_version_string,
  291. *args,
  292. **kwargs
  293. ):
  294. Site.__init__(self, resource, *args, **kwargs)
  295. self.site_tag = site_tag
  296. proxied = config.get("x_forwarded", False)
  297. self.requestFactory = XForwardedForRequest if proxied else SynapseRequest
  298. self.access_logger = logging.getLogger(logger_name)
  299. self.server_version_string = server_version_string.encode("ascii")
  300. def log(self, request):
  301. pass