_base.py 7.8 KB

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