_base.py 9.9 KB

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