server.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from synapse.api.errors import (
  17. cs_exception, SynapseError, CodeMessageException, UnrecognizedRequestError, Codes
  18. )
  19. from synapse.util.logcontext import LoggingContext, PreserveLoggingContext
  20. from synapse.util.caches import intern_dict
  21. from synapse.util.metrics import Measure
  22. import synapse.metrics
  23. import synapse.events
  24. from canonicaljson import (
  25. encode_canonical_json, encode_pretty_printed_json
  26. )
  27. from twisted.internet import defer
  28. from twisted.python import failure
  29. from twisted.web import server, resource
  30. from twisted.web.server import NOT_DONE_YET
  31. from twisted.web.util import redirectTo
  32. import collections
  33. import logging
  34. import urllib
  35. import simplejson
  36. logger = logging.getLogger(__name__)
  37. metrics = synapse.metrics.get_metrics_for(__name__)
  38. # total number of responses served, split by method/servlet/tag
  39. response_count = metrics.register_counter(
  40. "response_count",
  41. labels=["method", "servlet", "tag"],
  42. alternative_names=(
  43. # the following are all deprecated aliases for the same metric
  44. metrics.name_prefix + x for x in (
  45. "_requests",
  46. "_response_time:count",
  47. "_response_ru_utime:count",
  48. "_response_ru_stime:count",
  49. "_response_db_txn_count:count",
  50. "_response_db_txn_duration:count",
  51. )
  52. )
  53. )
  54. requests_counter = metrics.register_counter(
  55. "requests_received",
  56. labels=["method", "servlet", ],
  57. )
  58. outgoing_responses_counter = metrics.register_counter(
  59. "responses",
  60. labels=["method", "code"],
  61. )
  62. response_timer = metrics.register_counter(
  63. "response_time_seconds",
  64. labels=["method", "servlet", "tag"],
  65. alternative_names=(
  66. metrics.name_prefix + "_response_time:total",
  67. ),
  68. )
  69. response_ru_utime = metrics.register_counter(
  70. "response_ru_utime_seconds", labels=["method", "servlet", "tag"],
  71. alternative_names=(
  72. metrics.name_prefix + "_response_ru_utime:total",
  73. ),
  74. )
  75. response_ru_stime = metrics.register_counter(
  76. "response_ru_stime_seconds", labels=["method", "servlet", "tag"],
  77. alternative_names=(
  78. metrics.name_prefix + "_response_ru_stime:total",
  79. ),
  80. )
  81. response_db_txn_count = metrics.register_counter(
  82. "response_db_txn_count", labels=["method", "servlet", "tag"],
  83. alternative_names=(
  84. metrics.name_prefix + "_response_db_txn_count:total",
  85. ),
  86. )
  87. # seconds spent waiting for db txns, excluding scheduling time, when processing
  88. # this request
  89. response_db_txn_duration = metrics.register_counter(
  90. "response_db_txn_duration_seconds", labels=["method", "servlet", "tag"],
  91. alternative_names=(
  92. metrics.name_prefix + "_response_db_txn_duration:total",
  93. ),
  94. )
  95. # seconds spent waiting for a db connection, when processing this request
  96. response_db_sched_duration = metrics.register_counter(
  97. "response_db_sched_duration_seconds", labels=["method", "servlet", "tag"]
  98. )
  99. _next_request_id = 0
  100. def request_handler(include_metrics=False):
  101. """Decorator for ``wrap_request_handler``"""
  102. return lambda request_handler: wrap_request_handler(request_handler, include_metrics)
  103. def wrap_request_handler(request_handler, include_metrics=False):
  104. """Wraps a method that acts as a request handler with the necessary logging
  105. and exception handling.
  106. The method must have a signature of "handle_foo(self, request)". The
  107. argument "self" must have "version_string" and "clock" attributes. The
  108. argument "request" must be a twisted HTTP request.
  109. The method must return a deferred. If the deferred succeeds we assume that
  110. a response has been sent. If the deferred fails with a SynapseError we use
  111. it to send a JSON response with the appropriate HTTP reponse code. If the
  112. deferred fails with any other type of error we send a 500 reponse.
  113. We insert a unique request-id into the logging context for this request and
  114. log the response and duration for this request.
  115. """
  116. @defer.inlineCallbacks
  117. def wrapped_request_handler(self, request):
  118. global _next_request_id
  119. request_id = "%s-%s" % (request.method, _next_request_id)
  120. _next_request_id += 1
  121. with LoggingContext(request_id) as request_context:
  122. with Measure(self.clock, "wrapped_request_handler"):
  123. request_metrics = RequestMetrics()
  124. # we start the request metrics timer here with an initial stab
  125. # at the servlet name. For most requests that name will be
  126. # JsonResource (or a subclass), and JsonResource._async_render
  127. # will update it once it picks a servlet.
  128. servlet_name = self.__class__.__name__
  129. request_metrics.start(self.clock, name=servlet_name)
  130. request_context.request = request_id
  131. with request.processing():
  132. try:
  133. with PreserveLoggingContext(request_context):
  134. if include_metrics:
  135. yield request_handler(self, request, request_metrics)
  136. else:
  137. requests_counter.inc(request.method, servlet_name)
  138. yield request_handler(self, request)
  139. except CodeMessageException as e:
  140. code = e.code
  141. if isinstance(e, SynapseError):
  142. logger.info(
  143. "%s SynapseError: %s - %s", request, code, e.msg
  144. )
  145. else:
  146. logger.exception(e)
  147. outgoing_responses_counter.inc(request.method, str(code))
  148. respond_with_json(
  149. request, code, cs_exception(e), send_cors=True,
  150. pretty_print=_request_user_agent_is_curl(request),
  151. version_string=self.version_string,
  152. )
  153. except Exception:
  154. # failure.Failure() fishes the original Failure out
  155. # of our stack, and thus gives us a sensible stack
  156. # trace.
  157. f = failure.Failure()
  158. logger.error(
  159. "Failed handle request %s.%s on %r: %r: %s",
  160. request_handler.__module__,
  161. request_handler.__name__,
  162. self,
  163. request,
  164. f.getTraceback().rstrip(),
  165. )
  166. respond_with_json(
  167. request,
  168. 500,
  169. {
  170. "error": "Internal server error",
  171. "errcode": Codes.UNKNOWN,
  172. },
  173. send_cors=True,
  174. pretty_print=_request_user_agent_is_curl(request),
  175. version_string=self.version_string,
  176. )
  177. finally:
  178. try:
  179. request_metrics.stop(
  180. self.clock, request
  181. )
  182. except Exception as e:
  183. logger.warn("Failed to stop metrics: %r", e)
  184. return wrapped_request_handler
  185. class HttpServer(object):
  186. """ Interface for registering callbacks on a HTTP server
  187. """
  188. def register_paths(self, method, path_patterns, callback):
  189. """ Register a callback that gets fired if we receive a http request
  190. with the given method for a path that matches the given regex.
  191. If the regex contains groups these gets passed to the calback via
  192. an unpacked tuple.
  193. Args:
  194. method (str): The method to listen to.
  195. path_patterns (list<SRE_Pattern>): The regex used to match requests.
  196. callback (function): The function to fire if we receive a matched
  197. request. The first argument will be the request object and
  198. subsequent arguments will be any matched groups from the regex.
  199. This should return a tuple of (code, response).
  200. """
  201. pass
  202. class JsonResource(HttpServer, resource.Resource):
  203. """ This implements the HttpServer interface and provides JSON support for
  204. Resources.
  205. Register callbacks via register_paths()
  206. Callbacks can return a tuple of status code and a dict in which case the
  207. the dict will automatically be sent to the client as a JSON object.
  208. The JsonResource is primarily intended for returning JSON, but callbacks
  209. may send something other than JSON, they may do so by using the methods
  210. on the request object and instead returning None.
  211. """
  212. isLeaf = True
  213. _PathEntry = collections.namedtuple("_PathEntry", ["pattern", "callback"])
  214. def __init__(self, hs, canonical_json=True):
  215. resource.Resource.__init__(self)
  216. self.canonical_json = canonical_json
  217. self.clock = hs.get_clock()
  218. self.path_regexs = {}
  219. self.version_string = hs.version_string
  220. self.hs = hs
  221. def register_paths(self, method, path_patterns, callback):
  222. for path_pattern in path_patterns:
  223. logger.debug("Registering for %s %s", method, path_pattern.pattern)
  224. self.path_regexs.setdefault(method, []).append(
  225. self._PathEntry(path_pattern, callback)
  226. )
  227. def render(self, request):
  228. """ This gets called by twisted every time someone sends us a request.
  229. """
  230. self._async_render(request)
  231. return server.NOT_DONE_YET
  232. # Disable metric reporting because _async_render does its own metrics.
  233. # It does its own metric reporting because _async_render dispatches to
  234. # a callback and it's the class name of that callback we want to report
  235. # against rather than the JsonResource itself.
  236. @request_handler(include_metrics=True)
  237. @defer.inlineCallbacks
  238. def _async_render(self, request, request_metrics):
  239. """ This gets called from render() every time someone sends us a request.
  240. This checks if anyone has registered a callback for that method and
  241. path.
  242. """
  243. callback, group_dict = self._get_handler_for_request(request)
  244. servlet_instance = getattr(callback, "__self__", None)
  245. if servlet_instance is not None:
  246. servlet_classname = servlet_instance.__class__.__name__
  247. else:
  248. servlet_classname = "%r" % callback
  249. request_metrics.name = servlet_classname
  250. requests_counter.inc(request.method, servlet_classname)
  251. # Now trigger the callback. If it returns a response, we send it
  252. # here. If it throws an exception, that is handled by the wrapper
  253. # installed by @request_handler.
  254. kwargs = intern_dict({
  255. name: urllib.unquote(value).decode("UTF-8") if value else value
  256. for name, value in group_dict.items()
  257. })
  258. callback_return = yield callback(request, **kwargs)
  259. if callback_return is not None:
  260. code, response = callback_return
  261. self._send_response(request, code, response)
  262. def _get_handler_for_request(self, request):
  263. """Finds a callback method to handle the given request
  264. Args:
  265. request (twisted.web.http.Request):
  266. Returns:
  267. Tuple[Callable, dict[str, str]]: callback method, and the dict
  268. mapping keys to path components as specified in the handler's
  269. path match regexp.
  270. The callback will normally be a method registered via
  271. register_paths, so will return (possibly via Deferred) either
  272. None, or a tuple of (http code, response body).
  273. """
  274. if request.method == "OPTIONS":
  275. return _options_handler, {}
  276. # Loop through all the registered callbacks to check if the method
  277. # and path regex match
  278. for path_entry in self.path_regexs.get(request.method, []):
  279. m = path_entry.pattern.match(request.path)
  280. if m:
  281. # We found a match!
  282. return path_entry.callback, m.groupdict()
  283. # Huh. No one wanted to handle that? Fiiiiiine. Send 400.
  284. return _unrecognised_request_handler, {}
  285. def _send_response(self, request, code, response_json_object,
  286. response_code_message=None):
  287. outgoing_responses_counter.inc(request.method, str(code))
  288. # TODO: Only enable CORS for the requests that need it.
  289. respond_with_json(
  290. request, code, response_json_object,
  291. send_cors=True,
  292. response_code_message=response_code_message,
  293. pretty_print=_request_user_agent_is_curl(request),
  294. version_string=self.version_string,
  295. canonical_json=self.canonical_json,
  296. )
  297. def _options_handler(request):
  298. """Request handler for OPTIONS requests
  299. This is a request handler suitable for return from
  300. _get_handler_for_request. It returns a 200 and an empty body.
  301. Args:
  302. request (twisted.web.http.Request):
  303. Returns:
  304. Tuple[int, dict]: http code, response body.
  305. """
  306. return 200, {}
  307. def _unrecognised_request_handler(request):
  308. """Request handler for unrecognised requests
  309. This is a request handler suitable for return from
  310. _get_handler_for_request. It actually just raises an
  311. UnrecognizedRequestError.
  312. Args:
  313. request (twisted.web.http.Request):
  314. """
  315. raise UnrecognizedRequestError()
  316. class RequestMetrics(object):
  317. def start(self, clock, name):
  318. self.start = clock.time_msec()
  319. self.start_context = LoggingContext.current_context()
  320. self.name = name
  321. def stop(self, clock, request):
  322. context = LoggingContext.current_context()
  323. tag = ""
  324. if context:
  325. tag = context.tag
  326. if context != self.start_context:
  327. logger.warn(
  328. "Context have unexpectedly changed %r, %r",
  329. context, self.start_context
  330. )
  331. return
  332. response_count.inc(request.method, self.name, tag)
  333. response_timer.inc_by(
  334. clock.time_msec() - self.start, request.method,
  335. self.name, tag
  336. )
  337. ru_utime, ru_stime = context.get_resource_usage()
  338. response_ru_utime.inc_by(
  339. ru_utime, request.method, self.name, tag
  340. )
  341. response_ru_stime.inc_by(
  342. ru_stime, request.method, self.name, tag
  343. )
  344. response_db_txn_count.inc_by(
  345. context.db_txn_count, request.method, self.name, tag
  346. )
  347. response_db_txn_duration.inc_by(
  348. context.db_txn_duration_ms / 1000., request.method, self.name, tag
  349. )
  350. response_db_sched_duration.inc_by(
  351. context.db_sched_duration_ms / 1000., request.method, self.name, tag
  352. )
  353. class RootRedirect(resource.Resource):
  354. """Redirects the root '/' path to another path."""
  355. def __init__(self, path):
  356. resource.Resource.__init__(self)
  357. self.url = path
  358. def render_GET(self, request):
  359. return redirectTo(self.url, request)
  360. def getChild(self, name, request):
  361. if len(name) == 0:
  362. return self # select ourselves as the child to render
  363. return resource.Resource.getChild(self, name, request)
  364. def respond_with_json(request, code, json_object, send_cors=False,
  365. response_code_message=None, pretty_print=False,
  366. version_string="", canonical_json=True):
  367. # could alternatively use request.notifyFinish() and flip a flag when
  368. # the Deferred fires, but since the flag is RIGHT THERE it seems like
  369. # a waste.
  370. if request._disconnected:
  371. logger.warn(
  372. "Not sending response to request %s, already disconnected.",
  373. request)
  374. return
  375. if pretty_print:
  376. json_bytes = encode_pretty_printed_json(json_object) + "\n"
  377. else:
  378. if canonical_json or synapse.events.USE_FROZEN_DICTS:
  379. json_bytes = encode_canonical_json(json_object)
  380. else:
  381. json_bytes = simplejson.dumps(json_object)
  382. return respond_with_json_bytes(
  383. request, code, json_bytes,
  384. send_cors=send_cors,
  385. response_code_message=response_code_message,
  386. version_string=version_string
  387. )
  388. def respond_with_json_bytes(request, code, json_bytes, send_cors=False,
  389. version_string="", response_code_message=None):
  390. """Sends encoded JSON in response to the given request.
  391. Args:
  392. request (twisted.web.http.Request): The http request to respond to.
  393. code (int): The HTTP response code.
  394. json_bytes (bytes): The json bytes to use as the response body.
  395. send_cors (bool): Whether to send Cross-Origin Resource Sharing headers
  396. http://www.w3.org/TR/cors/
  397. Returns:
  398. twisted.web.server.NOT_DONE_YET"""
  399. request.setResponseCode(code, message=response_code_message)
  400. request.setHeader(b"Content-Type", b"application/json")
  401. request.setHeader(b"Server", version_string)
  402. request.setHeader(b"Content-Length", b"%d" % (len(json_bytes),))
  403. request.setHeader(b"Cache-Control", b"no-cache, no-store, must-revalidate")
  404. if send_cors:
  405. set_cors_headers(request)
  406. request.write(json_bytes)
  407. finish_request(request)
  408. return NOT_DONE_YET
  409. def set_cors_headers(request):
  410. """Set the CORs headers so that javascript running in a web browsers can
  411. use this API
  412. Args:
  413. request (twisted.web.http.Request): The http request to add CORs to.
  414. """
  415. request.setHeader("Access-Control-Allow-Origin", "*")
  416. request.setHeader(
  417. "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"
  418. )
  419. request.setHeader(
  420. "Access-Control-Allow-Headers",
  421. "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  422. )
  423. def finish_request(request):
  424. """ Finish writing the response to the request.
  425. Twisted throws a RuntimeException if the connection closed before the
  426. response was written but doesn't provide a convenient or reliable way to
  427. determine if the connection was closed. So we catch and log the RuntimeException
  428. You might think that ``request.notifyFinish`` could be used to tell if the
  429. request was finished. However the deferred it returns won't fire if the
  430. connection was already closed, meaning we'd have to have called the method
  431. right at the start of the request. By the time we want to write the response
  432. it will already be too late.
  433. """
  434. try:
  435. request.finish()
  436. except RuntimeError as e:
  437. logger.info("Connection disconnected before response was written: %r", e)
  438. def _request_user_agent_is_curl(request):
  439. user_agents = request.requestHeaders.getRawHeaders(
  440. "User-Agent", default=[]
  441. )
  442. for user_agent in user_agents:
  443. if "curl" in user_agent:
  444. return True
  445. return False