protocol.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Vector Creations 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. """This module contains the implementation of both the client and server
  16. protocols.
  17. The basic structure of the protocol is line based, where the initial word of
  18. each line specifies the command. The rest of the line is parsed based on the
  19. command. For example, the `RDATA` command is defined as::
  20. RDATA <stream_name> <token> <row_json>
  21. (Note that `<row_json>` may contains spaces, but cannot contain newlines.)
  22. Blank lines are ignored.
  23. # Example
  24. An example iteraction is shown below. Each line is prefixed with '>' or '<' to
  25. indicate which side is sending, these are *not* included on the wire::
  26. * connection established *
  27. > SERVER localhost:8823
  28. > PING 1490197665618
  29. < NAME synapse.app.appservice
  30. < PING 1490197665618
  31. < REPLICATE
  32. > POSITION events 1
  33. > POSITION backfill 1
  34. > POSITION caches 1
  35. > RDATA caches 2 ["get_user_by_id",["@01register-user:localhost:8823"],1490197670513]
  36. > RDATA events 14 ["ev", ["$149019767112vOHxz:localhost:8823",
  37. "!AFDCvgApUmpdfVjIXm:localhost:8823","m.room.guest_access","",null]]
  38. < PING 1490197675618
  39. > ERROR server stopping
  40. * connection closed by server *
  41. """
  42. import fcntl
  43. import logging
  44. import struct
  45. from inspect import isawaitable
  46. from typing import TYPE_CHECKING, List, Optional
  47. from prometheus_client import Counter
  48. from zope.interface import Interface, implementer
  49. from twisted.internet import task
  50. from twisted.internet.tcp import Connection
  51. from twisted.protocols.basic import LineOnlyReceiver
  52. from twisted.python.failure import Failure
  53. from synapse.logging.context import PreserveLoggingContext
  54. from synapse.metrics import LaterGauge
  55. from synapse.metrics.background_process_metrics import (
  56. BackgroundProcessLoggingContext,
  57. run_as_background_process,
  58. )
  59. from synapse.replication.tcp.commands import (
  60. VALID_CLIENT_COMMANDS,
  61. VALID_SERVER_COMMANDS,
  62. Command,
  63. ErrorCommand,
  64. NameCommand,
  65. PingCommand,
  66. ReplicateCommand,
  67. ServerCommand,
  68. parse_command_from_line,
  69. )
  70. from synapse.types import Collection
  71. from synapse.util import Clock
  72. from synapse.util.stringutils import random_string
  73. if TYPE_CHECKING:
  74. from synapse.replication.tcp.handler import ReplicationCommandHandler
  75. from synapse.server import HomeServer
  76. connection_close_counter = Counter(
  77. "synapse_replication_tcp_protocol_close_reason", "", ["reason_type"]
  78. )
  79. tcp_inbound_commands_counter = Counter(
  80. "synapse_replication_tcp_protocol_inbound_commands",
  81. "Number of commands received from replication, by command and name of process connected to",
  82. ["command", "name"],
  83. )
  84. tcp_outbound_commands_counter = Counter(
  85. "synapse_replication_tcp_protocol_outbound_commands",
  86. "Number of commands sent to replication, by command and name of process connected to",
  87. ["command", "name"],
  88. )
  89. # A list of all connected protocols. This allows us to send metrics about the
  90. # connections.
  91. connected_connections = [] # type: List[BaseReplicationStreamProtocol]
  92. logger = logging.getLogger(__name__)
  93. PING_TIME = 5000
  94. PING_TIMEOUT_MULTIPLIER = 5
  95. PING_TIMEOUT_MS = PING_TIME * PING_TIMEOUT_MULTIPLIER
  96. class ConnectionStates:
  97. CONNECTING = "connecting"
  98. ESTABLISHED = "established"
  99. PAUSED = "paused"
  100. CLOSED = "closed"
  101. class IReplicationConnection(Interface):
  102. """An interface for replication connections."""
  103. def send_command(cmd: Command):
  104. """Send the command down the connection"""
  105. @implementer(IReplicationConnection)
  106. class BaseReplicationStreamProtocol(LineOnlyReceiver):
  107. """Base replication protocol shared between client and server.
  108. Reads lines (ignoring blank ones) and parses them into command classes,
  109. asserting that they are valid for the given direction, i.e. server commands
  110. are only sent by the server.
  111. On receiving a new command it calls `on_<COMMAND_NAME>` with the parsed
  112. command before delegating to `ReplicationCommandHandler.on_<COMMAND_NAME>`.
  113. `ReplicationCommandHandler.on_<COMMAND_NAME>` can optionally return a coroutine;
  114. if so, that will get run as a background process.
  115. It also sends `PING` periodically, and correctly times out remote connections
  116. (if they send a `PING` command)
  117. """
  118. # The transport is going to be an ITCPTransport, but that doesn't have the
  119. # (un)registerProducer methods, those are only on the implementation.
  120. transport = None # type: Connection
  121. delimiter = b"\n"
  122. # Valid commands we expect to receive
  123. VALID_INBOUND_COMMANDS = [] # type: Collection[str]
  124. # Valid commands we can send
  125. VALID_OUTBOUND_COMMANDS = [] # type: Collection[str]
  126. max_line_buffer = 10000
  127. def __init__(self, clock: Clock, handler: "ReplicationCommandHandler"):
  128. self.clock = clock
  129. self.command_handler = handler
  130. self.last_received_command = self.clock.time_msec()
  131. self.last_sent_command = 0
  132. # When we requested the connection be closed
  133. self.time_we_closed = None # type: Optional[int]
  134. self.received_ping = False # Have we received a ping from the other side
  135. self.state = ConnectionStates.CONNECTING
  136. self.name = "anon" # The name sent by a client.
  137. self.conn_id = random_string(5) # To dedupe in case of name clashes.
  138. # List of pending commands to send once we've established the connection
  139. self.pending_commands = [] # type: List[Command]
  140. # The LoopingCall for sending pings.
  141. self._send_ping_loop = None # type: Optional[task.LoopingCall]
  142. # a logcontext which we use for processing incoming commands. We declare it as a
  143. # background process so that the CPU stats get reported to prometheus.
  144. self._logging_context = BackgroundProcessLoggingContext(
  145. "replication-conn-%s" % (self.conn_id,)
  146. )
  147. def connectionMade(self):
  148. logger.info("[%s] Connection established", self.id())
  149. self.state = ConnectionStates.ESTABLISHED
  150. connected_connections.append(self) # Register connection for metrics
  151. assert self.transport is not None
  152. self.transport.registerProducer(self, True) # For the *Producing callbacks
  153. self._send_pending_commands()
  154. # Starts sending pings
  155. self._send_ping_loop = self.clock.looping_call(self.send_ping, 5000)
  156. # Always send the initial PING so that the other side knows that they
  157. # can time us out.
  158. self.send_command(PingCommand(self.clock.time_msec()))
  159. self.command_handler.new_connection(self)
  160. def send_ping(self):
  161. """Periodically sends a ping and checks if we should close the connection
  162. due to the other side timing out.
  163. """
  164. now = self.clock.time_msec()
  165. if self.time_we_closed:
  166. if now - self.time_we_closed > PING_TIMEOUT_MS:
  167. logger.info(
  168. "[%s] Failed to close connection gracefully, aborting", self.id()
  169. )
  170. assert self.transport is not None
  171. self.transport.abortConnection()
  172. else:
  173. if now - self.last_sent_command >= PING_TIME:
  174. self.send_command(PingCommand(now))
  175. if (
  176. self.received_ping
  177. and now - self.last_received_command > PING_TIMEOUT_MS
  178. ):
  179. logger.info(
  180. "[%s] Connection hasn't received command in %r ms. Closing.",
  181. self.id(),
  182. now - self.last_received_command,
  183. )
  184. self.send_error("ping timeout")
  185. def lineReceived(self, line: bytes):
  186. """Called when we've received a line"""
  187. with PreserveLoggingContext(self._logging_context):
  188. self._parse_and_dispatch_line(line)
  189. def _parse_and_dispatch_line(self, line: bytes):
  190. if line.strip() == "":
  191. # Ignore blank lines
  192. return
  193. linestr = line.decode("utf-8")
  194. try:
  195. cmd = parse_command_from_line(linestr)
  196. except Exception as e:
  197. logger.exception("[%s] failed to parse line: %r", self.id(), linestr)
  198. self.send_error("failed to parse line: %r (%r):" % (e, linestr))
  199. return
  200. if cmd.NAME not in self.VALID_INBOUND_COMMANDS:
  201. logger.error("[%s] invalid command %s", self.id(), cmd.NAME)
  202. self.send_error("invalid command: %s", cmd.NAME)
  203. return
  204. self.last_received_command = self.clock.time_msec()
  205. tcp_inbound_commands_counter.labels(cmd.NAME, self.name).inc()
  206. self.handle_command(cmd)
  207. def handle_command(self, cmd: Command) -> None:
  208. """Handle a command we have received over the replication stream.
  209. First calls `self.on_<COMMAND>` if it exists, then calls
  210. `self.command_handler.on_<COMMAND>` if it exists (which can optionally
  211. return an Awaitable).
  212. This allows for protocol level handling of commands (e.g. PINGs), before
  213. delegating to the handler.
  214. Args:
  215. cmd: received command
  216. """
  217. handled = False
  218. # First call any command handlers on this instance. These are for TCP
  219. # specific handling.
  220. cmd_func = getattr(self, "on_%s" % (cmd.NAME,), None)
  221. if cmd_func:
  222. cmd_func(cmd)
  223. handled = True
  224. # Then call out to the handler.
  225. cmd_func = getattr(self.command_handler, "on_%s" % (cmd.NAME,), None)
  226. if cmd_func:
  227. res = cmd_func(self, cmd)
  228. # the handler might be a coroutine: fire it off as a background process
  229. # if so.
  230. if isawaitable(res):
  231. run_as_background_process(
  232. "replication-" + cmd.get_logcontext_id(), lambda: res
  233. )
  234. handled = True
  235. if not handled:
  236. logger.warning("Unhandled command: %r", cmd)
  237. def close(self):
  238. logger.warning("[%s] Closing connection", self.id())
  239. self.time_we_closed = self.clock.time_msec()
  240. assert self.transport is not None
  241. self.transport.loseConnection()
  242. self.on_connection_closed()
  243. def send_error(self, error_string, *args):
  244. """Send an error to remote and close the connection."""
  245. self.send_command(ErrorCommand(error_string % args))
  246. self.close()
  247. def send_command(self, cmd, do_buffer=True):
  248. """Send a command if connection has been established.
  249. Args:
  250. cmd (Command)
  251. do_buffer (bool): Whether to buffer the message or always attempt
  252. to send the command. This is mostly used to send an error
  253. message if we're about to close the connection due our buffers
  254. becoming full.
  255. """
  256. if self.state == ConnectionStates.CLOSED:
  257. logger.debug("[%s] Not sending, connection closed", self.id())
  258. return
  259. if do_buffer and self.state != ConnectionStates.ESTABLISHED:
  260. self._queue_command(cmd)
  261. return
  262. tcp_outbound_commands_counter.labels(cmd.NAME, self.name).inc()
  263. string = "%s %s" % (cmd.NAME, cmd.to_line())
  264. if "\n" in string:
  265. raise Exception("Unexpected newline in command: %r", string)
  266. encoded_string = string.encode("utf-8")
  267. if len(encoded_string) > self.MAX_LENGTH:
  268. raise Exception(
  269. "Failed to send command %s as too long (%d > %d)"
  270. % (cmd.NAME, len(encoded_string), self.MAX_LENGTH)
  271. )
  272. self.sendLine(encoded_string)
  273. self.last_sent_command = self.clock.time_msec()
  274. def _queue_command(self, cmd):
  275. """Queue the command until the connection is ready to write to again."""
  276. logger.debug("[%s] Queueing as conn %r, cmd: %r", self.id(), self.state, cmd)
  277. self.pending_commands.append(cmd)
  278. if len(self.pending_commands) > self.max_line_buffer:
  279. # The other side is failing to keep up and out buffers are becoming
  280. # full, so lets close the connection.
  281. # XXX: should we squawk more loudly?
  282. logger.error("[%s] Remote failed to keep up", self.id())
  283. self.send_command(ErrorCommand("Failed to keep up"), do_buffer=False)
  284. self.close()
  285. def _send_pending_commands(self):
  286. """Send any queued commandes"""
  287. pending = self.pending_commands
  288. self.pending_commands = []
  289. for cmd in pending:
  290. self.send_command(cmd)
  291. def on_PING(self, line):
  292. self.received_ping = True
  293. def on_ERROR(self, cmd):
  294. logger.error("[%s] Remote reported error: %r", self.id(), cmd.data)
  295. def pauseProducing(self):
  296. """This is called when both the kernel send buffer and the twisted
  297. tcp connection send buffers have become full.
  298. We don't actually have any control over those sizes, so we buffer some
  299. commands ourselves before knifing the connection due to the remote
  300. failing to keep up.
  301. """
  302. logger.info("[%s] Pause producing", self.id())
  303. self.state = ConnectionStates.PAUSED
  304. def resumeProducing(self):
  305. """The remote has caught up after we started buffering!"""
  306. logger.info("[%s] Resume producing", self.id())
  307. self.state = ConnectionStates.ESTABLISHED
  308. self._send_pending_commands()
  309. def stopProducing(self):
  310. """We're never going to send any more data (normally because either
  311. we or the remote has closed the connection)
  312. """
  313. logger.info("[%s] Stop producing", self.id())
  314. self.on_connection_closed()
  315. def connectionLost(self, reason):
  316. logger.info("[%s] Replication connection closed: %r", self.id(), reason)
  317. if isinstance(reason, Failure):
  318. assert reason.type is not None
  319. connection_close_counter.labels(reason.type.__name__).inc()
  320. else:
  321. connection_close_counter.labels(reason.__class__.__name__).inc()
  322. try:
  323. # Remove us from list of connections to be monitored
  324. connected_connections.remove(self)
  325. except ValueError:
  326. pass
  327. # Stop the looping call sending pings.
  328. if self._send_ping_loop and self._send_ping_loop.running:
  329. self._send_ping_loop.stop()
  330. self.on_connection_closed()
  331. def on_connection_closed(self):
  332. logger.info("[%s] Connection was closed", self.id())
  333. self.state = ConnectionStates.CLOSED
  334. self.pending_commands = []
  335. self.command_handler.lost_connection(self)
  336. if self.transport:
  337. self.transport.unregisterProducer()
  338. # mark the logging context as finished
  339. self._logging_context.__exit__(None, None, None)
  340. def __str__(self):
  341. addr = None
  342. if self.transport:
  343. addr = str(self.transport.getPeer())
  344. return "ReplicationConnection<name=%s,conn_id=%s,addr=%s>" % (
  345. self.name,
  346. self.conn_id,
  347. addr,
  348. )
  349. def id(self):
  350. return "%s-%s" % (self.name, self.conn_id)
  351. def lineLengthExceeded(self, line):
  352. """Called when we receive a line that is above the maximum line length"""
  353. self.send_error("Line length exceeded")
  354. class ServerReplicationStreamProtocol(BaseReplicationStreamProtocol):
  355. VALID_INBOUND_COMMANDS = VALID_CLIENT_COMMANDS
  356. VALID_OUTBOUND_COMMANDS = VALID_SERVER_COMMANDS
  357. def __init__(
  358. self, server_name: str, clock: Clock, handler: "ReplicationCommandHandler"
  359. ):
  360. super().__init__(clock, handler)
  361. self.server_name = server_name
  362. def connectionMade(self):
  363. self.send_command(ServerCommand(self.server_name))
  364. super().connectionMade()
  365. def on_NAME(self, cmd):
  366. logger.info("[%s] Renamed to %r", self.id(), cmd.data)
  367. self.name = cmd.data
  368. class ClientReplicationStreamProtocol(BaseReplicationStreamProtocol):
  369. VALID_INBOUND_COMMANDS = VALID_SERVER_COMMANDS
  370. VALID_OUTBOUND_COMMANDS = VALID_CLIENT_COMMANDS
  371. def __init__(
  372. self,
  373. hs: "HomeServer",
  374. client_name: str,
  375. server_name: str,
  376. clock: Clock,
  377. command_handler: "ReplicationCommandHandler",
  378. ):
  379. super().__init__(clock, command_handler)
  380. self.client_name = client_name
  381. self.server_name = server_name
  382. def connectionMade(self):
  383. self.send_command(NameCommand(self.client_name))
  384. super().connectionMade()
  385. # Once we've connected subscribe to the necessary streams
  386. self.replicate()
  387. def on_SERVER(self, cmd):
  388. if cmd.data != self.server_name:
  389. logger.error("[%s] Connected to wrong remote: %r", self.id(), cmd.data)
  390. self.send_error("Wrong remote")
  391. def replicate(self):
  392. """Send the subscription request to the server"""
  393. logger.info("[%s] Subscribing to replication streams", self.id())
  394. self.send_command(ReplicateCommand())
  395. # The following simply registers metrics for the replication connections
  396. pending_commands = LaterGauge(
  397. "synapse_replication_tcp_protocol_pending_commands",
  398. "",
  399. ["name"],
  400. lambda: {(p.name,): len(p.pending_commands) for p in connected_connections},
  401. )
  402. def transport_buffer_size(protocol):
  403. if protocol.transport:
  404. size = len(protocol.transport.dataBuffer) + protocol.transport._tempDataLen
  405. return size
  406. return 0
  407. transport_send_buffer = LaterGauge(
  408. "synapse_replication_tcp_protocol_transport_send_buffer",
  409. "",
  410. ["name"],
  411. lambda: {(p.name,): transport_buffer_size(p) for p in connected_connections},
  412. )
  413. def transport_kernel_read_buffer_size(protocol, read=True):
  414. SIOCINQ = 0x541B
  415. SIOCOUTQ = 0x5411
  416. if protocol.transport:
  417. fileno = protocol.transport.getHandle().fileno()
  418. if read:
  419. op = SIOCINQ
  420. else:
  421. op = SIOCOUTQ
  422. size = struct.unpack("I", fcntl.ioctl(fileno, op, b"\0\0\0\0"))[0]
  423. return size
  424. return 0
  425. tcp_transport_kernel_send_buffer = LaterGauge(
  426. "synapse_replication_tcp_protocol_transport_kernel_send_buffer",
  427. "",
  428. ["name"],
  429. lambda: {
  430. (p.name,): transport_kernel_read_buffer_size(p, False)
  431. for p in connected_connections
  432. },
  433. )
  434. tcp_transport_kernel_read_buffer = LaterGauge(
  435. "synapse_replication_tcp_protocol_transport_kernel_read_buffer",
  436. "",
  437. ["name"],
  438. lambda: {
  439. (p.name,): transport_kernel_read_buffer_size(p, True)
  440. for p in connected_connections
  441. },
  442. )