_base.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector 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. import abc
  16. import logging
  17. import re
  18. import urllib
  19. from inspect import signature
  20. from typing import Dict, List, Tuple
  21. from twisted.internet import defer
  22. from synapse.api.errors import (
  23. CodeMessageException,
  24. HttpResponseException,
  25. RequestSendFailed,
  26. SynapseError,
  27. )
  28. from synapse.logging.opentracing import (
  29. inject_active_span_byte_dict,
  30. trace,
  31. trace_servlet,
  32. )
  33. from synapse.util.caches.response_cache import ResponseCache
  34. from synapse.util.stringutils import random_string
  35. logger = logging.getLogger(__name__)
  36. class ReplicationEndpoint(object):
  37. """Helper base class for defining new replication HTTP endpoints.
  38. This creates an endpoint under `/_synapse/replication/:NAME/:PATH_ARGS..`
  39. (with a `/:txn_id` suffix for cached requests), where NAME is a name,
  40. PATH_ARGS are a tuple of parameters to be encoded in the URL.
  41. For example, if `NAME` is "send_event" and `PATH_ARGS` is `("event_id",)`,
  42. with `CACHE` set to true then this generates an endpoint:
  43. /_synapse/replication/send_event/:event_id/:txn_id
  44. For POST/PUT requests the payload is serialized to json and sent as the
  45. body, while for GET requests the payload is added as query parameters. See
  46. `_serialize_payload` for details.
  47. Incoming requests are handled by overriding `_handle_request`. Servers
  48. must call `register` to register the path with the HTTP server.
  49. Requests can be sent by calling the client returned by `make_client`.
  50. Requests are sent to master process by default, but can be sent to other
  51. named processes by specifying an `instance_name` keyword argument.
  52. Attributes:
  53. NAME (str): A name for the endpoint, added to the path as well as used
  54. in logging and metrics.
  55. PATH_ARGS (tuple[str]): A list of parameters to be added to the path.
  56. Adding parameters to the path (rather than payload) can make it
  57. easier to follow along in the log files.
  58. METHOD (str): The method of the HTTP request, defaults to POST. Can be
  59. one of POST, PUT or GET. If GET then the payload is sent as query
  60. parameters rather than a JSON body.
  61. CACHE (bool): Whether server should cache the result of the request/
  62. If true then transparently adds a txn_id to all requests, and
  63. `_handle_request` must return a Deferred.
  64. RETRY_ON_TIMEOUT(bool): Whether or not to retry the request when a 504
  65. is received.
  66. """
  67. __metaclass__ = abc.ABCMeta
  68. NAME = abc.abstractproperty() # type: str # type: ignore
  69. PATH_ARGS = abc.abstractproperty() # type: Tuple[str, ...] # type: ignore
  70. METHOD = "POST"
  71. CACHE = True
  72. RETRY_ON_TIMEOUT = True
  73. def __init__(self, hs):
  74. if self.CACHE:
  75. self.response_cache = ResponseCache(
  76. hs, "repl." + self.NAME, timeout_ms=30 * 60 * 1000
  77. )
  78. # We reserve `instance_name` as a parameter to sending requests, so we
  79. # assert here that sub classes don't try and use the name.
  80. assert (
  81. "instance_name" not in self.PATH_ARGS
  82. ), "`instance_name` is a reserved paramater name"
  83. assert (
  84. "instance_name"
  85. not in signature(self.__class__._serialize_payload).parameters
  86. ), "`instance_name` is a reserved paramater name"
  87. assert self.METHOD in ("PUT", "POST", "GET")
  88. @abc.abstractmethod
  89. def _serialize_payload(**kwargs):
  90. """Static method that is called when creating a request.
  91. Concrete implementations should have explicit parameters (rather than
  92. kwargs) so that an appropriate exception is raised if the client is
  93. called with unexpected parameters. All PATH_ARGS must appear in
  94. argument list.
  95. Returns:
  96. Deferred[dict]|dict: If POST/PUT request then dictionary must be
  97. JSON serialisable, otherwise must be appropriate for adding as
  98. query args.
  99. """
  100. return {}
  101. @abc.abstractmethod
  102. async def _handle_request(self, request, **kwargs):
  103. """Handle incoming request.
  104. This is called with the request object and PATH_ARGS.
  105. Returns:
  106. tuple[int, dict]: HTTP status code and a JSON serialisable dict
  107. to be used as response body of request.
  108. """
  109. pass
  110. @classmethod
  111. def make_client(cls, hs):
  112. """Create a client that makes requests.
  113. Returns a callable that accepts the same parameters as `_serialize_payload`.
  114. """
  115. clock = hs.get_clock()
  116. client = hs.get_simple_http_client()
  117. local_instance_name = hs.get_instance_name()
  118. master_host = hs.config.worker_replication_host
  119. master_port = hs.config.worker_replication_http_port
  120. instance_map = hs.config.worker.instance_map
  121. @trace(opname="outgoing_replication_request")
  122. @defer.inlineCallbacks
  123. def send_request(instance_name="master", **kwargs):
  124. if instance_name == local_instance_name:
  125. raise Exception("Trying to send HTTP request to self")
  126. if instance_name == "master":
  127. host = master_host
  128. port = master_port
  129. elif instance_name in instance_map:
  130. host = instance_map[instance_name].host
  131. port = instance_map[instance_name].port
  132. else:
  133. raise Exception(
  134. "Instance %r not in 'instance_map' config" % (instance_name,)
  135. )
  136. data = yield cls._serialize_payload(**kwargs)
  137. url_args = [
  138. urllib.parse.quote(kwargs[name], safe="") for name in cls.PATH_ARGS
  139. ]
  140. if cls.CACHE:
  141. txn_id = random_string(10)
  142. url_args.append(txn_id)
  143. if cls.METHOD == "POST":
  144. request_func = client.post_json_get_json
  145. elif cls.METHOD == "PUT":
  146. request_func = client.put_json
  147. elif cls.METHOD == "GET":
  148. request_func = client.get_json
  149. else:
  150. # We have already asserted in the constructor that a
  151. # compatible was picked, but lets be paranoid.
  152. raise Exception(
  153. "Unknown METHOD on %s replication endpoint" % (cls.NAME,)
  154. )
  155. uri = "http://%s:%s/_synapse/replication/%s/%s" % (
  156. host,
  157. port,
  158. cls.NAME,
  159. "/".join(url_args),
  160. )
  161. try:
  162. # We keep retrying the same request for timeouts. This is so that we
  163. # have a good idea that the request has either succeeded or failed on
  164. # the master, and so whether we should clean up or not.
  165. while True:
  166. headers = {} # type: Dict[bytes, List[bytes]]
  167. inject_active_span_byte_dict(headers, None, check_destination=False)
  168. try:
  169. result = yield request_func(uri, data, headers=headers)
  170. break
  171. except CodeMessageException as e:
  172. if e.code != 504 or not cls.RETRY_ON_TIMEOUT:
  173. raise
  174. logger.warning("%s request timed out", cls.NAME)
  175. # If we timed out we probably don't need to worry about backing
  176. # off too much, but lets just wait a little anyway.
  177. yield clock.sleep(1)
  178. except HttpResponseException as e:
  179. # We convert to SynapseError as we know that it was a SynapseError
  180. # on the master process that we should send to the client. (And
  181. # importantly, not stack traces everywhere)
  182. raise e.to_synapse_error()
  183. except RequestSendFailed as e:
  184. raise SynapseError(502, "Failed to talk to master") from e
  185. return result
  186. return send_request
  187. def register(self, http_server):
  188. """Called by the server to register this as a handler to the
  189. appropriate path.
  190. """
  191. url_args = list(self.PATH_ARGS)
  192. handler = self._handle_request
  193. method = self.METHOD
  194. if self.CACHE:
  195. handler = self._cached_handler # type: ignore
  196. url_args.append("txn_id")
  197. args = "/".join("(?P<%s>[^/]+)" % (arg,) for arg in url_args)
  198. pattern = re.compile("^/_synapse/replication/%s/%s$" % (self.NAME, args))
  199. handler = trace_servlet(self.__class__.__name__, extract_context=True)(handler)
  200. # We don't let register paths trace this servlet using the default tracing
  201. # options because we wish to extract the context explicitly.
  202. http_server.register_paths(
  203. method, [pattern], handler, self.__class__.__name__, trace=False
  204. )
  205. def _cached_handler(self, request, txn_id, **kwargs):
  206. """Called on new incoming requests when caching is enabled. Checks
  207. if there is a cached response for the request and returns that,
  208. otherwise calls `_handle_request` and caches its response.
  209. """
  210. # We just use the txn_id here, but we probably also want to use the
  211. # other PATH_ARGS as well.
  212. assert self.CACHE
  213. return self.response_cache.wrap(txn_id, self._handle_request, request, **kwargs)