server.py 18 KB

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