server.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. import synapse.metrics
  21. import synapse.events
  22. from canonicaljson import (
  23. encode_canonical_json, encode_pretty_printed_json
  24. )
  25. from twisted.internet import defer
  26. from twisted.web import server, resource
  27. from twisted.web.server import NOT_DONE_YET
  28. from twisted.web.util import redirectTo
  29. import collections
  30. import logging
  31. import urllib
  32. import ujson
  33. logger = logging.getLogger(__name__)
  34. metrics = synapse.metrics.get_metrics_for(__name__)
  35. incoming_requests_counter = metrics.register_counter(
  36. "requests",
  37. labels=["method", "servlet", "tag"],
  38. )
  39. outgoing_responses_counter = metrics.register_counter(
  40. "responses",
  41. labels=["method", "code"],
  42. )
  43. response_timer = metrics.register_distribution(
  44. "response_time",
  45. labels=["method", "servlet", "tag"]
  46. )
  47. response_ru_utime = metrics.register_distribution(
  48. "response_ru_utime", labels=["method", "servlet", "tag"]
  49. )
  50. response_ru_stime = metrics.register_distribution(
  51. "response_ru_stime", labels=["method", "servlet", "tag"]
  52. )
  53. response_db_txn_count = metrics.register_distribution(
  54. "response_db_txn_count", labels=["method", "servlet", "tag"]
  55. )
  56. response_db_txn_duration = metrics.register_distribution(
  57. "response_db_txn_duration", labels=["method", "servlet", "tag"]
  58. )
  59. _next_request_id = 0
  60. def request_handler(report_metrics=True):
  61. """Decorator for ``wrap_request_handler``"""
  62. return lambda request_handler: wrap_request_handler(request_handler, report_metrics)
  63. def wrap_request_handler(request_handler, report_metrics):
  64. """Wraps a method that acts as a request handler with the necessary logging
  65. and exception handling.
  66. The method must have a signature of "handle_foo(self, request)". The
  67. argument "self" must have "version_string" and "clock" attributes. The
  68. argument "request" must be a twisted HTTP request.
  69. The method must return a deferred. If the deferred succeeds we assume that
  70. a response has been sent. If the deferred fails with a SynapseError we use
  71. it to send a JSON response with the appropriate HTTP reponse code. If the
  72. deferred fails with any other type of error we send a 500 reponse.
  73. We insert a unique request-id into the logging context for this request and
  74. log the response and duration for this request.
  75. """
  76. @defer.inlineCallbacks
  77. def wrapped_request_handler(self, request):
  78. global _next_request_id
  79. request_id = "%s-%s" % (request.method, _next_request_id)
  80. _next_request_id += 1
  81. with LoggingContext(request_id) as request_context:
  82. if report_metrics:
  83. request_metrics = RequestMetrics()
  84. request_metrics.start(self.clock)
  85. request_context.request = request_id
  86. with request.processing():
  87. try:
  88. with PreserveLoggingContext(request_context):
  89. yield request_handler(self, request)
  90. except CodeMessageException as e:
  91. code = e.code
  92. if isinstance(e, SynapseError):
  93. logger.info(
  94. "%s SynapseError: %s - %s", request, code, e.msg
  95. )
  96. else:
  97. logger.exception(e)
  98. outgoing_responses_counter.inc(request.method, str(code))
  99. respond_with_json(
  100. request, code, cs_exception(e), send_cors=True,
  101. pretty_print=_request_user_agent_is_curl(request),
  102. version_string=self.version_string,
  103. )
  104. except:
  105. logger.exception(
  106. "Failed handle request %s.%s on %r: %r",
  107. request_handler.__module__,
  108. request_handler.__name__,
  109. self,
  110. request
  111. )
  112. respond_with_json(
  113. request,
  114. 500,
  115. {
  116. "error": "Internal server error",
  117. "errcode": Codes.UNKNOWN,
  118. },
  119. send_cors=True
  120. )
  121. finally:
  122. try:
  123. if report_metrics:
  124. request_metrics.stop(
  125. self.clock, request, self.__class__.__name__
  126. )
  127. except:
  128. pass
  129. return wrapped_request_handler
  130. class HttpServer(object):
  131. """ Interface for registering callbacks on a HTTP server
  132. """
  133. def register_paths(self, method, path_patterns, callback):
  134. """ Register a callback that gets fired if we receive a http request
  135. with the given method for a path that matches the given regex.
  136. If the regex contains groups these gets passed to the calback via
  137. an unpacked tuple.
  138. Args:
  139. method (str): The method to listen to.
  140. path_patterns (list<SRE_Pattern>): The regex used to match requests.
  141. callback (function): The function to fire if we receive a matched
  142. request. The first argument will be the request object and
  143. subsequent arguments will be any matched groups from the regex.
  144. This should return a tuple of (code, response).
  145. """
  146. pass
  147. class JsonResource(HttpServer, resource.Resource):
  148. """ This implements the HttpServer interface and provides JSON support for
  149. Resources.
  150. Register callbacks via register_path()
  151. Callbacks can return a tuple of status code and a dict in which case the
  152. the dict will automatically be sent to the client as a JSON object.
  153. The JsonResource is primarily intended for returning JSON, but callbacks
  154. may send something other than JSON, they may do so by using the methods
  155. on the request object and instead returning None.
  156. """
  157. isLeaf = True
  158. _PathEntry = collections.namedtuple("_PathEntry", ["pattern", "callback"])
  159. def __init__(self, hs, canonical_json=True):
  160. resource.Resource.__init__(self)
  161. self.canonical_json = canonical_json
  162. self.clock = hs.get_clock()
  163. self.path_regexs = {}
  164. self.version_string = hs.version_string
  165. self.hs = hs
  166. def register_paths(self, method, path_patterns, callback):
  167. for path_pattern in path_patterns:
  168. self.path_regexs.setdefault(method, []).append(
  169. self._PathEntry(path_pattern, callback)
  170. )
  171. def render(self, request):
  172. """ This gets called by twisted every time someone sends us a request.
  173. """
  174. self._async_render(request)
  175. return server.NOT_DONE_YET
  176. # Disable metric reporting because _async_render does its own metrics.
  177. # It does its own metric reporting because _async_render dispatches to
  178. # a callback and it's the class name of that callback we want to report
  179. # against rather than the JsonResource itself.
  180. @request_handler(report_metrics=False)
  181. @defer.inlineCallbacks
  182. def _async_render(self, request):
  183. """ This gets called from render() every time someone sends us a request.
  184. This checks if anyone has registered a callback for that method and
  185. path.
  186. """
  187. if request.method == "OPTIONS":
  188. self._send_response(request, 200, {})
  189. return
  190. request_metrics = RequestMetrics()
  191. request_metrics.start(self.clock)
  192. # Loop through all the registered callbacks to check if the method
  193. # and path regex match
  194. for path_entry in self.path_regexs.get(request.method, []):
  195. m = path_entry.pattern.match(request.path)
  196. if not m:
  197. continue
  198. # We found a match! Trigger callback and then return the
  199. # returned response. We pass both the request and any
  200. # matched groups from the regex to the callback.
  201. callback = path_entry.callback
  202. servlet_instance = getattr(callback, "__self__", None)
  203. if servlet_instance is not None:
  204. servlet_classname = servlet_instance.__class__.__name__
  205. else:
  206. servlet_classname = "%r" % callback
  207. kwargs = intern_dict({
  208. name: urllib.unquote(value).decode("UTF-8") if value else value
  209. for name, value in m.groupdict().items()
  210. })
  211. callback_return = yield callback(request, **kwargs)
  212. if callback_return is not None:
  213. code, response = callback_return
  214. self._send_response(request, code, response)
  215. try:
  216. request_metrics.stop(self.clock, request, servlet_classname)
  217. except:
  218. pass
  219. return
  220. # Huh. No one wanted to handle that? Fiiiiiine. Send 400.
  221. raise UnrecognizedRequestError()
  222. def _send_response(self, request, code, response_json_object,
  223. response_code_message=None):
  224. # could alternatively use request.notifyFinish() and flip a flag when
  225. # the Deferred fires, but since the flag is RIGHT THERE it seems like
  226. # a waste.
  227. if request._disconnected:
  228. logger.warn(
  229. "Not sending response to request %s, already disconnected.",
  230. request)
  231. return
  232. outgoing_responses_counter.inc(request.method, str(code))
  233. # TODO: Only enable CORS for the requests that need it.
  234. respond_with_json(
  235. request, code, response_json_object,
  236. send_cors=True,
  237. response_code_message=response_code_message,
  238. pretty_print=_request_user_agent_is_curl(request),
  239. version_string=self.version_string,
  240. canonical_json=self.canonical_json,
  241. )
  242. class RequestMetrics(object):
  243. def start(self, clock):
  244. self.start = clock.time_msec()
  245. self.start_context = LoggingContext.current_context()
  246. def stop(self, clock, request, servlet_classname):
  247. context = LoggingContext.current_context()
  248. tag = ""
  249. if context:
  250. tag = context.tag
  251. if context != self.start_context:
  252. logger.warn(
  253. "Context have unexpectedly changed %r, %r",
  254. context, self.start_context
  255. )
  256. return
  257. incoming_requests_counter.inc(request.method, servlet_classname, tag)
  258. response_timer.inc_by(
  259. clock.time_msec() - self.start, request.method,
  260. servlet_classname, tag
  261. )
  262. ru_utime, ru_stime = context.get_resource_usage()
  263. response_ru_utime.inc_by(
  264. ru_utime, request.method, servlet_classname, tag
  265. )
  266. response_ru_stime.inc_by(
  267. ru_stime, request.method, servlet_classname, tag
  268. )
  269. response_db_txn_count.inc_by(
  270. context.db_txn_count, request.method, servlet_classname, tag
  271. )
  272. response_db_txn_duration.inc_by(
  273. context.db_txn_duration, request.method, servlet_classname, tag
  274. )
  275. class RootRedirect(resource.Resource):
  276. """Redirects the root '/' path to another path."""
  277. def __init__(self, path):
  278. resource.Resource.__init__(self)
  279. self.url = path
  280. def render_GET(self, request):
  281. return redirectTo(self.url, request)
  282. def getChild(self, name, request):
  283. if len(name) == 0:
  284. return self # select ourselves as the child to render
  285. return resource.Resource.getChild(self, name, request)
  286. def respond_with_json(request, code, json_object, send_cors=False,
  287. response_code_message=None, pretty_print=False,
  288. version_string="", canonical_json=True):
  289. if pretty_print:
  290. json_bytes = encode_pretty_printed_json(json_object) + "\n"
  291. else:
  292. if canonical_json or synapse.events.USE_FROZEN_DICTS:
  293. json_bytes = encode_canonical_json(json_object)
  294. else:
  295. # ujson doesn't like frozen_dicts.
  296. json_bytes = ujson.dumps(json_object, ensure_ascii=False)
  297. return respond_with_json_bytes(
  298. request, code, json_bytes,
  299. send_cors=send_cors,
  300. response_code_message=response_code_message,
  301. version_string=version_string
  302. )
  303. def respond_with_json_bytes(request, code, json_bytes, send_cors=False,
  304. version_string="", response_code_message=None):
  305. """Sends encoded JSON in response to the given request.
  306. Args:
  307. request (twisted.web.http.Request): The http request to respond to.
  308. code (int): The HTTP response code.
  309. json_bytes (bytes): The json bytes to use as the response body.
  310. send_cors (bool): Whether to send Cross-Origin Resource Sharing headers
  311. http://www.w3.org/TR/cors/
  312. Returns:
  313. twisted.web.server.NOT_DONE_YET"""
  314. request.setResponseCode(code, message=response_code_message)
  315. request.setHeader(b"Content-Type", b"application/json")
  316. request.setHeader(b"Server", version_string)
  317. request.setHeader(b"Content-Length", b"%d" % (len(json_bytes),))
  318. if send_cors:
  319. request.setHeader("Access-Control-Allow-Origin", "*")
  320. request.setHeader("Access-Control-Allow-Methods",
  321. "GET, POST, PUT, DELETE, OPTIONS")
  322. request.setHeader("Access-Control-Allow-Headers",
  323. "Origin, X-Requested-With, Content-Type, Accept")
  324. request.write(json_bytes)
  325. finish_request(request)
  326. return NOT_DONE_YET
  327. def finish_request(request):
  328. """ Finish writing the response to the request.
  329. Twisted throws a RuntimeException if the connection closed before the
  330. response was written but doesn't provide a convenient or reliable way to
  331. determine if the connection was closed. So we catch and log the RuntimeException
  332. You might think that ``request.notifyFinish`` could be used to tell if the
  333. request was finished. However the deferred it returns won't fire if the
  334. connection was already closed, meaning we'd have to have called the method
  335. right at the start of the request. By the time we want to write the response
  336. it will already be too late.
  337. """
  338. try:
  339. request.finish()
  340. except RuntimeError as e:
  341. logger.info("Connection disconnected before response was written: %r", e)
  342. def _request_user_agent_is_curl(request):
  343. user_agents = request.requestHeaders.getRawHeaders(
  344. "User-Agent", default=[]
  345. )
  346. for user_agent in user_agents:
  347. if "curl" in user_agent:
  348. return True
  349. return False