_base.py 9.6 KB

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