server.py 16 KB

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