protocol.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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 events 1
  32. < REPLICATE backfill 1
  33. < REPLICATE caches 1
  34. > POSITION events 1
  35. > POSITION backfill 1
  36. > POSITION caches 1
  37. > RDATA caches 2 ["get_user_by_id",["@01register-user:localhost:8823"],1490197670513]
  38. > RDATA events 14 ["$149019767112vOHxz:localhost:8823",
  39. "!AFDCvgApUmpdfVjIXm:localhost:8823","m.room.guest_access","",null]
  40. < PING 1490197675618
  41. > ERROR server stopping
  42. * connection closed by server *
  43. """
  44. from twisted.internet import defer
  45. from twisted.protocols.basic import LineOnlyReceiver
  46. from twisted.python.failure import Failure
  47. from .commands import (
  48. COMMAND_MAP, VALID_CLIENT_COMMANDS, VALID_SERVER_COMMANDS,
  49. ErrorCommand, ServerCommand, RdataCommand, PositionCommand, PingCommand,
  50. NameCommand, ReplicateCommand, UserSyncCommand, SyncCommand,
  51. )
  52. from .streams import STREAMS_MAP
  53. from synapse.metrics import LaterGauge
  54. from synapse.util.stringutils import random_string
  55. from prometheus_client import Counter
  56. from collections import defaultdict
  57. from six import iterkeys, iteritems
  58. import logging
  59. import struct
  60. import fcntl
  61. connection_close_counter = Counter(
  62. "synapse_replication_tcp_protocol_close_reason", "", ["reason_type"])
  63. # A list of all connected protocols. This allows us to send metrics about the
  64. # connections.
  65. connected_connections = []
  66. logger = logging.getLogger(__name__)
  67. PING_TIME = 5000
  68. PING_TIMEOUT_MULTIPLIER = 5
  69. PING_TIMEOUT_MS = PING_TIME * PING_TIMEOUT_MULTIPLIER
  70. class ConnectionStates(object):
  71. CONNECTING = "connecting"
  72. ESTABLISHED = "established"
  73. PAUSED = "paused"
  74. CLOSED = "closed"
  75. class BaseReplicationStreamProtocol(LineOnlyReceiver):
  76. """Base replication protocol shared between client and server.
  77. Reads lines (ignoring blank ones) and parses them into command classes,
  78. asserting that they are valid for the given direction, i.e. server commands
  79. are only sent by the server.
  80. On receiving a new command it calls `on_<COMMAND_NAME>` with the parsed
  81. command.
  82. It also sends `PING` periodically, and correctly times out remote connections
  83. (if they send a `PING` command)
  84. """
  85. delimiter = b'\n'
  86. VALID_INBOUND_COMMANDS = [] # Valid commands we expect to receive
  87. VALID_OUTBOUND_COMMANDS = [] # Valid commans we can send
  88. max_line_buffer = 10000
  89. def __init__(self, clock):
  90. self.clock = clock
  91. self.last_received_command = self.clock.time_msec()
  92. self.last_sent_command = 0
  93. self.time_we_closed = None # When we requested the connection be closed
  94. self.received_ping = False # Have we reecived a ping from the other side
  95. self.state = ConnectionStates.CONNECTING
  96. self.name = "anon" # The name sent by a client.
  97. self.conn_id = random_string(5) # To dedupe in case of name clashes.
  98. # List of pending commands to send once we've established the connection
  99. self.pending_commands = []
  100. # The LoopingCall for sending pings.
  101. self._send_ping_loop = None
  102. self.inbound_commands_counter = defaultdict(int)
  103. self.outbound_commands_counter = defaultdict(int)
  104. def connectionMade(self):
  105. logger.info("[%s] Connection established", self.id())
  106. self.state = ConnectionStates.ESTABLISHED
  107. connected_connections.append(self) # Register connection for metrics
  108. self.transport.registerProducer(self, True) # For the *Producing callbacks
  109. self._send_pending_commands()
  110. # Starts sending pings
  111. self._send_ping_loop = self.clock.looping_call(self.send_ping, 5000)
  112. # Always send the initial PING so that the other side knows that they
  113. # can time us out.
  114. self.send_command(PingCommand(self.clock.time_msec()))
  115. def send_ping(self):
  116. """Periodically sends a ping and checks if we should close the connection
  117. due to the other side timing out.
  118. """
  119. now = self.clock.time_msec()
  120. if self.time_we_closed:
  121. if now - self.time_we_closed > PING_TIMEOUT_MS:
  122. logger.info(
  123. "[%s] Failed to close connection gracefully, aborting", self.id()
  124. )
  125. self.transport.abortConnection()
  126. else:
  127. if now - self.last_sent_command >= PING_TIME:
  128. self.send_command(PingCommand(now))
  129. if self.received_ping and now - self.last_received_command > PING_TIMEOUT_MS:
  130. logger.info(
  131. "[%s] Connection hasn't received command in %r ms. Closing.",
  132. self.id(), now - self.last_received_command
  133. )
  134. self.send_error("ping timeout")
  135. def lineReceived(self, line):
  136. """Called when we've received a line
  137. """
  138. if line.strip() == "":
  139. # Ignore blank lines
  140. return
  141. line = line.decode("utf-8")
  142. cmd_name, rest_of_line = line.split(" ", 1)
  143. if cmd_name not in self.VALID_INBOUND_COMMANDS:
  144. logger.error("[%s] invalid command %s", self.id(), cmd_name)
  145. self.send_error("invalid command: %s", cmd_name)
  146. return
  147. self.last_received_command = self.clock.time_msec()
  148. self.inbound_commands_counter[cmd_name] = (
  149. self.inbound_commands_counter[cmd_name] + 1)
  150. cmd_cls = COMMAND_MAP[cmd_name]
  151. try:
  152. cmd = cmd_cls.from_line(rest_of_line)
  153. except Exception as e:
  154. logger.exception(
  155. "[%s] failed to parse line %r: %r", self.id(), cmd_name, rest_of_line
  156. )
  157. self.send_error(
  158. "failed to parse line for %r: %r (%r):" % (cmd_name, e, rest_of_line)
  159. )
  160. return
  161. # Now lets try and call on_<CMD_NAME> function
  162. try:
  163. getattr(self, "on_%s" % (cmd_name,))(cmd)
  164. except Exception:
  165. logger.exception("[%s] Failed to handle line: %r", self.id(), line)
  166. def close(self):
  167. logger.warn("[%s] Closing connection", self.id())
  168. self.time_we_closed = self.clock.time_msec()
  169. self.transport.loseConnection()
  170. self.on_connection_closed()
  171. def send_error(self, error_string, *args):
  172. """Send an error to remote and close the connection.
  173. """
  174. self.send_command(ErrorCommand(error_string % args))
  175. self.close()
  176. def send_command(self, cmd, do_buffer=True):
  177. """Send a command if connection has been established.
  178. Args:
  179. cmd (Command)
  180. do_buffer (bool): Whether to buffer the message or always attempt
  181. to send the command. This is mostly used to send an error
  182. message if we're about to close the connection due our buffers
  183. becoming full.
  184. """
  185. if self.state == ConnectionStates.CLOSED:
  186. logger.debug("[%s] Not sending, connection closed", self.id())
  187. return
  188. if do_buffer and self.state != ConnectionStates.ESTABLISHED:
  189. self._queue_command(cmd)
  190. return
  191. self.outbound_commands_counter[cmd.NAME] = (
  192. self.outbound_commands_counter[cmd.NAME] + 1)
  193. string = "%s %s" % (cmd.NAME, cmd.to_line(),)
  194. if "\n" in string:
  195. raise Exception("Unexpected newline in command: %r", string)
  196. self.sendLine(string.encode("utf-8"))
  197. self.last_sent_command = self.clock.time_msec()
  198. def _queue_command(self, cmd):
  199. """Queue the command until the connection is ready to write to again.
  200. """
  201. logger.debug("[%s] Queing as conn %r, cmd: %r", self.id(), self.state, cmd)
  202. self.pending_commands.append(cmd)
  203. if len(self.pending_commands) > self.max_line_buffer:
  204. # The other side is failing to keep up and out buffers are becoming
  205. # full, so lets close the connection.
  206. # XXX: should we squawk more loudly?
  207. logger.error("[%s] Remote failed to keep up", self.id())
  208. self.send_command(ErrorCommand("Failed to keep up"), do_buffer=False)
  209. self.close()
  210. def _send_pending_commands(self):
  211. """Send any queued commandes
  212. """
  213. pending = self.pending_commands
  214. self.pending_commands = []
  215. for cmd in pending:
  216. self.send_command(cmd)
  217. def on_PING(self, line):
  218. self.received_ping = True
  219. def on_ERROR(self, cmd):
  220. logger.error("[%s] Remote reported error: %r", self.id(), cmd.data)
  221. def pauseProducing(self):
  222. """This is called when both the kernel send buffer and the twisted
  223. tcp connection send buffers have become full.
  224. We don't actually have any control over those sizes, so we buffer some
  225. commands ourselves before knifing the connection due to the remote
  226. failing to keep up.
  227. """
  228. logger.info("[%s] Pause producing", self.id())
  229. self.state = ConnectionStates.PAUSED
  230. def resumeProducing(self):
  231. """The remote has caught up after we started buffering!
  232. """
  233. logger.info("[%s] Resume producing", self.id())
  234. self.state = ConnectionStates.ESTABLISHED
  235. self._send_pending_commands()
  236. def stopProducing(self):
  237. """We're never going to send any more data (normally because either
  238. we or the remote has closed the connection)
  239. """
  240. logger.info("[%s] Stop producing", self.id())
  241. self.on_connection_closed()
  242. def connectionLost(self, reason):
  243. logger.info("[%s] Replication connection closed: %r", self.id(), reason)
  244. if isinstance(reason, Failure):
  245. connection_close_counter.labels(reason.type.__name__).inc()
  246. else:
  247. connection_close_counter.labels(reason.__class__.__name__).inc()
  248. try:
  249. # Remove us from list of connections to be monitored
  250. connected_connections.remove(self)
  251. except ValueError:
  252. pass
  253. # Stop the looping call sending pings.
  254. if self._send_ping_loop and self._send_ping_loop.running:
  255. self._send_ping_loop.stop()
  256. self.on_connection_closed()
  257. def on_connection_closed(self):
  258. logger.info("[%s] Connection was closed", self.id())
  259. self.state = ConnectionStates.CLOSED
  260. self.pending_commands = []
  261. if self.transport:
  262. self.transport.unregisterProducer()
  263. def __str__(self):
  264. return "ReplicationConnection<name=%s,conn_id=%s,addr=%s>" % (
  265. self.name, self.conn_id, self.addr,
  266. )
  267. def id(self):
  268. return "%s-%s" % (self.name, self.conn_id)
  269. class ServerReplicationStreamProtocol(BaseReplicationStreamProtocol):
  270. VALID_INBOUND_COMMANDS = VALID_CLIENT_COMMANDS
  271. VALID_OUTBOUND_COMMANDS = VALID_SERVER_COMMANDS
  272. def __init__(self, server_name, clock, streamer, addr):
  273. BaseReplicationStreamProtocol.__init__(self, clock) # Old style class
  274. self.server_name = server_name
  275. self.streamer = streamer
  276. self.addr = addr
  277. # The streams the client has subscribed to and is up to date with
  278. self.replication_streams = set()
  279. # The streams the client is currently subscribing to.
  280. self.connecting_streams = set()
  281. # Map from stream name to list of updates to send once we've finished
  282. # subscribing the client to the stream.
  283. self.pending_rdata = {}
  284. def connectionMade(self):
  285. self.send_command(ServerCommand(self.server_name))
  286. BaseReplicationStreamProtocol.connectionMade(self)
  287. self.streamer.new_connection(self)
  288. def on_NAME(self, cmd):
  289. logger.info("[%s] Renamed to %r", self.id(), cmd.data)
  290. self.name = cmd.data
  291. def on_USER_SYNC(self, cmd):
  292. self.streamer.on_user_sync(
  293. self.conn_id, cmd.user_id, cmd.is_syncing, cmd.last_sync_ms,
  294. )
  295. def on_REPLICATE(self, cmd):
  296. stream_name = cmd.stream_name
  297. token = cmd.token
  298. if stream_name == "ALL":
  299. # Subscribe to all streams we're publishing to.
  300. for stream in iterkeys(self.streamer.streams_by_name):
  301. self.subscribe_to_stream(stream, token)
  302. else:
  303. self.subscribe_to_stream(stream_name, token)
  304. def on_FEDERATION_ACK(self, cmd):
  305. self.streamer.federation_ack(cmd.token)
  306. def on_REMOVE_PUSHER(self, cmd):
  307. self.streamer.on_remove_pusher(cmd.app_id, cmd.push_key, cmd.user_id)
  308. def on_INVALIDATE_CACHE(self, cmd):
  309. self.streamer.on_invalidate_cache(cmd.cache_func, cmd.keys)
  310. def on_USER_IP(self, cmd):
  311. self.streamer.on_user_ip(
  312. cmd.user_id, cmd.access_token, cmd.ip, cmd.user_agent, cmd.device_id,
  313. cmd.last_seen,
  314. )
  315. @defer.inlineCallbacks
  316. def subscribe_to_stream(self, stream_name, token):
  317. """Subscribe the remote to a streams.
  318. This invloves checking if they've missed anything and sending those
  319. updates down if they have. During that time new updates for the stream
  320. are queued and sent once we've sent down any missed updates.
  321. """
  322. self.replication_streams.discard(stream_name)
  323. self.connecting_streams.add(stream_name)
  324. try:
  325. # Get missing updates
  326. updates, current_token = yield self.streamer.get_stream_updates(
  327. stream_name, token,
  328. )
  329. # Send all the missing updates
  330. for update in updates:
  331. token, row = update[0], update[1]
  332. self.send_command(RdataCommand(stream_name, token, row))
  333. # We send a POSITION command to ensure that they have an up to
  334. # date token (especially useful if we didn't send any updates
  335. # above)
  336. self.send_command(PositionCommand(stream_name, current_token))
  337. # Now we can send any updates that came in while we were subscribing
  338. pending_rdata = self.pending_rdata.pop(stream_name, [])
  339. for token, update in pending_rdata:
  340. # Only send updates newer than the current token
  341. if token > current_token:
  342. self.send_command(RdataCommand(stream_name, token, update))
  343. # They're now fully subscribed
  344. self.replication_streams.add(stream_name)
  345. except Exception as e:
  346. logger.exception("[%s] Failed to handle REPLICATE command", self.id())
  347. self.send_error("failed to handle replicate: %r", e)
  348. finally:
  349. self.connecting_streams.discard(stream_name)
  350. def stream_update(self, stream_name, token, data):
  351. """Called when a new update is available to stream to clients.
  352. We need to check if the client is interested in the stream or not
  353. """
  354. if stream_name in self.replication_streams:
  355. # The client is subscribed to the stream
  356. self.send_command(RdataCommand(stream_name, token, data))
  357. elif stream_name in self.connecting_streams:
  358. # The client is being subscribed to the stream
  359. logger.debug("[%s] Queuing RDATA %r %r", self.id(), stream_name, token)
  360. self.pending_rdata.setdefault(stream_name, []).append((token, data))
  361. else:
  362. # The client isn't subscribed
  363. logger.debug("[%s] Dropping RDATA %r %r", self.id(), stream_name, token)
  364. def send_sync(self, data):
  365. self.send_command(SyncCommand(data))
  366. def on_connection_closed(self):
  367. BaseReplicationStreamProtocol.on_connection_closed(self)
  368. self.streamer.lost_connection(self)
  369. class ClientReplicationStreamProtocol(BaseReplicationStreamProtocol):
  370. VALID_INBOUND_COMMANDS = VALID_SERVER_COMMANDS
  371. VALID_OUTBOUND_COMMANDS = VALID_CLIENT_COMMANDS
  372. def __init__(self, client_name, server_name, clock, handler):
  373. BaseReplicationStreamProtocol.__init__(self, clock)
  374. self.client_name = client_name
  375. self.server_name = server_name
  376. self.handler = handler
  377. # Map of stream to batched updates. See RdataCommand for info on how
  378. # batching works.
  379. self.pending_batches = {}
  380. def connectionMade(self):
  381. self.send_command(NameCommand(self.client_name))
  382. BaseReplicationStreamProtocol.connectionMade(self)
  383. # Once we've connected subscribe to the necessary streams
  384. for stream_name, token in iteritems(self.handler.get_streams_to_replicate()):
  385. self.replicate(stream_name, token)
  386. # Tell the server if we have any users currently syncing (should only
  387. # happen on synchrotrons)
  388. currently_syncing = self.handler.get_currently_syncing_users()
  389. now = self.clock.time_msec()
  390. for user_id in currently_syncing:
  391. self.send_command(UserSyncCommand(user_id, True, now))
  392. # We've now finished connecting to so inform the client handler
  393. self.handler.update_connection(self)
  394. def on_SERVER(self, cmd):
  395. if cmd.data != self.server_name:
  396. logger.error("[%s] Connected to wrong remote: %r", self.id(), cmd.data)
  397. self.send_error("Wrong remote")
  398. def on_RDATA(self, cmd):
  399. stream_name = cmd.stream_name
  400. inbound_rdata_count.labels(stream_name).inc()
  401. try:
  402. row = STREAMS_MAP[stream_name].ROW_TYPE(*cmd.row)
  403. except Exception:
  404. logger.exception(
  405. "[%s] Failed to parse RDATA: %r %r",
  406. self.id(), stream_name, cmd.row
  407. )
  408. raise
  409. if cmd.token is None:
  410. # I.e. this is part of a batch of updates for this stream. Batch
  411. # until we get an update for the stream with a non None token
  412. self.pending_batches.setdefault(stream_name, []).append(row)
  413. else:
  414. # Check if this is the last of a batch of updates
  415. rows = self.pending_batches.pop(stream_name, [])
  416. rows.append(row)
  417. self.handler.on_rdata(stream_name, cmd.token, rows)
  418. def on_POSITION(self, cmd):
  419. self.handler.on_position(cmd.stream_name, cmd.token)
  420. def on_SYNC(self, cmd):
  421. self.handler.on_sync(cmd.data)
  422. def replicate(self, stream_name, token):
  423. """Send the subscription request to the server
  424. """
  425. if stream_name not in STREAMS_MAP:
  426. raise Exception("Invalid stream name %r" % (stream_name,))
  427. logger.info(
  428. "[%s] Subscribing to replication stream: %r from %r",
  429. self.id(), stream_name, token
  430. )
  431. self.send_command(ReplicateCommand(stream_name, token))
  432. def on_connection_closed(self):
  433. BaseReplicationStreamProtocol.on_connection_closed(self)
  434. self.handler.update_connection(None)
  435. # The following simply registers metrics for the replication connections
  436. pending_commands = LaterGauge(
  437. "pending_commands", "", ["name", "conn_id"],
  438. lambda: {
  439. (p.name, p.conn_id): len(p.pending_commands)
  440. for p in connected_connections
  441. })
  442. def transport_buffer_size(protocol):
  443. if protocol.transport:
  444. size = len(protocol.transport.dataBuffer) + protocol.transport._tempDataLen
  445. return size
  446. return 0
  447. transport_send_buffer = LaterGauge(
  448. "synapse_replication_tcp_transport_send_buffer", "", ["name", "conn_id"],
  449. lambda: {
  450. (p.name, p.conn_id): transport_buffer_size(p)
  451. for p in connected_connections
  452. })
  453. def transport_kernel_read_buffer_size(protocol, read=True):
  454. SIOCINQ = 0x541B
  455. SIOCOUTQ = 0x5411
  456. if protocol.transport:
  457. fileno = protocol.transport.getHandle().fileno()
  458. if read:
  459. op = SIOCINQ
  460. else:
  461. op = SIOCOUTQ
  462. size = struct.unpack("I", fcntl.ioctl(fileno, op, '\0\0\0\0'))[0]
  463. return size
  464. return 0
  465. tcp_transport_kernel_send_buffer = LaterGauge(
  466. "synapse_replication_tcp_transport_kernel_send_buffer", "", ["name", "conn_id"],
  467. lambda: {
  468. (p.name, p.conn_id): transport_kernel_read_buffer_size(p, False)
  469. for p in connected_connections
  470. })
  471. tcp_transport_kernel_read_buffer = LaterGauge(
  472. "synapse_replication_tcp_transport_kernel_read_buffer", "", ["name", "conn_id"],
  473. lambda: {
  474. (p.name, p.conn_id): transport_kernel_read_buffer_size(p, True)
  475. for p in connected_connections
  476. })
  477. tcp_inbound_commands = LaterGauge(
  478. "synapse_replication_tcp_inbound_commands", "", ["command", "name", "conn_id"],
  479. lambda: {
  480. (k[0], p.name, p.conn_id): count
  481. for p in connected_connections
  482. for k, count in iteritems(p.inbound_commands_counter)
  483. })
  484. tcp_outbound_commands = LaterGauge(
  485. "synapse_replication_tcp_outbound_commands", "", ["command", "name", "conn_id"],
  486. lambda: {
  487. (k[0], p.name, p.conn_id): count
  488. for p in connected_connections
  489. for k, count in iteritems(p.outbound_commands_counter)
  490. })
  491. # number of updates received for each RDATA stream
  492. inbound_rdata_count = Counter("synapse_replication_tcp_inbound_rdata_count", "",
  493. ["stream_name"])