2017-03-27 10:40:37 -04:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# Copyright 2017 Vector Creations Ltd
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
"""This module contains the implementation of both the client and server
|
|
|
|
protocols.
|
|
|
|
|
|
|
|
The basic structure of the protocol is line based, where the initial word of
|
|
|
|
each line specifies the command. The rest of the line is parsed based on the
|
|
|
|
command. For example, the `RDATA` command is defined as::
|
|
|
|
|
|
|
|
RDATA <stream_name> <token> <row_json>
|
|
|
|
|
|
|
|
(Note that `<row_json>` may contains spaces, but cannot contain newlines.)
|
|
|
|
|
|
|
|
Blank lines are ignored.
|
|
|
|
|
|
|
|
# Example
|
|
|
|
|
|
|
|
An example iteraction is shown below. Each line is prefixed with '>' or '<' to
|
|
|
|
indicate which side is sending, these are *not* included on the wire::
|
|
|
|
|
|
|
|
* connection established *
|
|
|
|
> SERVER localhost:8823
|
|
|
|
> PING 1490197665618
|
|
|
|
< NAME synapse.app.appservice
|
|
|
|
< PING 1490197665618
|
2020-03-25 10:54:01 -04:00
|
|
|
< REPLICATE
|
2017-03-27 10:40:37 -04:00
|
|
|
> POSITION events 1
|
|
|
|
> POSITION backfill 1
|
|
|
|
> POSITION caches 1
|
|
|
|
> RDATA caches 2 ["get_user_by_id",["@01register-user:localhost:8823"],1490197670513]
|
2019-03-27 11:18:28 -04:00
|
|
|
> RDATA events 14 ["ev", ["$149019767112vOHxz:localhost:8823",
|
|
|
|
"!AFDCvgApUmpdfVjIXm:localhost:8823","m.room.guest_access","",null]]
|
2017-03-27 10:40:37 -04:00
|
|
|
< PING 1490197675618
|
|
|
|
> ERROR server stopping
|
|
|
|
* connection closed by server *
|
|
|
|
"""
|
2018-07-09 02:09:20 -04:00
|
|
|
import fcntl
|
|
|
|
import logging
|
|
|
|
import struct
|
|
|
|
from collections import defaultdict
|
2020-04-06 04:58:42 -04:00
|
|
|
from typing import TYPE_CHECKING, DefaultDict, List
|
2018-07-09 02:09:20 -04:00
|
|
|
|
2020-03-25 10:54:01 -04:00
|
|
|
from six import iteritems
|
2018-07-09 02:09:20 -04:00
|
|
|
|
|
|
|
from prometheus_client import Counter
|
|
|
|
|
2017-03-27 10:40:37 -04:00
|
|
|
from twisted.protocols.basic import LineOnlyReceiver
|
2017-04-05 08:34:54 -04:00
|
|
|
from twisted.python.failure import Failure
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
from synapse.metrics import LaterGauge
|
2018-08-16 19:43:43 -04:00
|
|
|
from synapse.metrics.background_process_metrics import run_as_background_process
|
2020-01-14 09:08:06 -05:00
|
|
|
from synapse.replication.tcp.commands import (
|
2018-07-09 02:09:20 -04:00
|
|
|
COMMAND_MAP,
|
|
|
|
VALID_CLIENT_COMMANDS,
|
|
|
|
VALID_SERVER_COMMANDS,
|
2020-01-14 09:08:06 -05:00
|
|
|
Command,
|
2018-07-09 02:09:20 -04:00
|
|
|
ErrorCommand,
|
|
|
|
NameCommand,
|
|
|
|
PingCommand,
|
|
|
|
PositionCommand,
|
|
|
|
RdataCommand,
|
2020-01-17 05:27:19 -05:00
|
|
|
RemoteServerUpCommand,
|
2018-07-09 02:09:20 -04:00
|
|
|
ReplicateCommand,
|
|
|
|
ServerCommand,
|
|
|
|
SyncCommand,
|
|
|
|
UserSyncCommand,
|
|
|
|
)
|
2020-01-14 09:08:06 -05:00
|
|
|
from synapse.types import Collection
|
|
|
|
from synapse.util import Clock
|
|
|
|
from synapse.util.stringutils import random_string
|
|
|
|
|
2020-04-06 04:58:42 -04:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.replication.tcp.handler import ReplicationCommandHandler
|
2020-03-25 10:54:01 -04:00
|
|
|
from synapse.server import HomeServer
|
|
|
|
|
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
connection_close_counter = Counter(
|
2019-06-20 05:32:02 -04:00
|
|
|
"synapse_replication_tcp_protocol_close_reason", "", ["reason_type"]
|
|
|
|
)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
# A list of all connected protocols. This allows us to send metrics about the
|
|
|
|
# connections.
|
|
|
|
connected_connections = []
|
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
PING_TIME = 5000
|
2017-04-10 06:32:05 -04:00
|
|
|
PING_TIMEOUT_MULTIPLIER = 5
|
|
|
|
PING_TIMEOUT_MS = PING_TIME * PING_TIMEOUT_MULTIPLIER
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
|
|
|
|
class ConnectionStates(object):
|
|
|
|
CONNECTING = "connecting"
|
|
|
|
ESTABLISHED = "established"
|
|
|
|
PAUSED = "paused"
|
|
|
|
CLOSED = "closed"
|
|
|
|
|
|
|
|
|
|
|
|
class BaseReplicationStreamProtocol(LineOnlyReceiver):
|
|
|
|
"""Base replication protocol shared between client and server.
|
|
|
|
|
|
|
|
Reads lines (ignoring blank ones) and parses them into command classes,
|
|
|
|
asserting that they are valid for the given direction, i.e. server commands
|
|
|
|
are only sent by the server.
|
|
|
|
|
|
|
|
On receiving a new command it calls `on_<COMMAND_NAME>` with the parsed
|
|
|
|
command.
|
|
|
|
|
|
|
|
It also sends `PING` periodically, and correctly times out remote connections
|
|
|
|
(if they send a `PING` command)
|
|
|
|
"""
|
2019-06-20 05:32:02 -04:00
|
|
|
|
|
|
|
delimiter = b"\n"
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2020-01-14 09:08:06 -05:00
|
|
|
# Valid commands we expect to receive
|
|
|
|
VALID_INBOUND_COMMANDS = [] # type: Collection[str]
|
|
|
|
|
|
|
|
# Valid commands we can send
|
|
|
|
VALID_OUTBOUND_COMMANDS = [] # type: Collection[str]
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
max_line_buffer = 10000
|
|
|
|
|
|
|
|
def __init__(self, clock):
|
|
|
|
self.clock = clock
|
|
|
|
|
|
|
|
self.last_received_command = self.clock.time_msec()
|
|
|
|
self.last_sent_command = 0
|
|
|
|
self.time_we_closed = None # When we requested the connection be closed
|
|
|
|
|
|
|
|
self.received_ping = False # Have we reecived a ping from the other side
|
|
|
|
|
|
|
|
self.state = ConnectionStates.CONNECTING
|
|
|
|
|
|
|
|
self.name = "anon" # The name sent by a client.
|
|
|
|
self.conn_id = random_string(5) # To dedupe in case of name clashes.
|
|
|
|
|
|
|
|
# List of pending commands to send once we've established the connection
|
2020-01-14 09:08:06 -05:00
|
|
|
self.pending_commands = [] # type: List[Command]
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
# The LoopingCall for sending pings.
|
|
|
|
self._send_ping_loop = None
|
|
|
|
|
2020-01-14 09:08:06 -05:00
|
|
|
self.inbound_commands_counter = defaultdict(int) # type: DefaultDict[str, int]
|
|
|
|
self.outbound_commands_counter = defaultdict(int) # type: DefaultDict[str, int]
|
2017-04-05 09:15:09 -04:00
|
|
|
|
2017-03-27 10:40:37 -04:00
|
|
|
def connectionMade(self):
|
|
|
|
logger.info("[%s] Connection established", self.id())
|
|
|
|
|
|
|
|
self.state = ConnectionStates.ESTABLISHED
|
|
|
|
|
|
|
|
connected_connections.append(self) # Register connection for metrics
|
|
|
|
|
|
|
|
self.transport.registerProducer(self, True) # For the *Producing callbacks
|
|
|
|
|
|
|
|
self._send_pending_commands()
|
|
|
|
|
|
|
|
# Starts sending pings
|
|
|
|
self._send_ping_loop = self.clock.looping_call(self.send_ping, 5000)
|
|
|
|
|
|
|
|
# Always send the initial PING so that the other side knows that they
|
|
|
|
# can time us out.
|
|
|
|
self.send_command(PingCommand(self.clock.time_msec()))
|
|
|
|
|
|
|
|
def send_ping(self):
|
|
|
|
"""Periodically sends a ping and checks if we should close the connection
|
|
|
|
due to the other side timing out.
|
|
|
|
"""
|
|
|
|
now = self.clock.time_msec()
|
|
|
|
|
|
|
|
if self.time_we_closed:
|
2017-04-10 06:32:05 -04:00
|
|
|
if now - self.time_we_closed > PING_TIMEOUT_MS:
|
2017-03-27 10:40:37 -04:00
|
|
|
logger.info(
|
|
|
|
"[%s] Failed to close connection gracefully, aborting", self.id()
|
|
|
|
)
|
|
|
|
self.transport.abortConnection()
|
|
|
|
else:
|
|
|
|
if now - self.last_sent_command >= PING_TIME:
|
|
|
|
self.send_command(PingCommand(now))
|
|
|
|
|
2019-06-20 05:32:02 -04:00
|
|
|
if (
|
|
|
|
self.received_ping
|
|
|
|
and now - self.last_received_command > PING_TIMEOUT_MS
|
|
|
|
):
|
2017-03-27 10:40:37 -04:00
|
|
|
logger.info(
|
|
|
|
"[%s] Connection hasn't received command in %r ms. Closing.",
|
2019-06-20 05:32:02 -04:00
|
|
|
self.id(),
|
|
|
|
now - self.last_received_command,
|
2017-03-27 10:40:37 -04:00
|
|
|
)
|
|
|
|
self.send_error("ping timeout")
|
|
|
|
|
|
|
|
def lineReceived(self, line):
|
|
|
|
"""Called when we've received a line
|
|
|
|
"""
|
|
|
|
if line.strip() == "":
|
|
|
|
# Ignore blank lines
|
|
|
|
return
|
|
|
|
|
|
|
|
line = line.decode("utf-8")
|
|
|
|
cmd_name, rest_of_line = line.split(" ", 1)
|
|
|
|
|
|
|
|
if cmd_name not in self.VALID_INBOUND_COMMANDS:
|
|
|
|
logger.error("[%s] invalid command %s", self.id(), cmd_name)
|
|
|
|
self.send_error("invalid command: %s", cmd_name)
|
|
|
|
return
|
|
|
|
|
|
|
|
self.last_received_command = self.clock.time_msec()
|
|
|
|
|
2018-05-22 18:36:20 -04:00
|
|
|
self.inbound_commands_counter[cmd_name] = (
|
2019-06-20 05:32:02 -04:00
|
|
|
self.inbound_commands_counter[cmd_name] + 1
|
|
|
|
)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
cmd_cls = COMMAND_MAP[cmd_name]
|
|
|
|
try:
|
|
|
|
cmd = cmd_cls.from_line(rest_of_line)
|
|
|
|
except Exception as e:
|
|
|
|
logger.exception(
|
|
|
|
"[%s] failed to parse line %r: %r", self.id(), cmd_name, rest_of_line
|
|
|
|
)
|
|
|
|
self.send_error(
|
|
|
|
"failed to parse line for %r: %r (%r):" % (cmd_name, e, rest_of_line)
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
|
|
|
# Now lets try and call on_<CMD_NAME> function
|
2019-03-25 12:38:05 -04:00
|
|
|
run_as_background_process(
|
2019-06-20 05:32:02 -04:00
|
|
|
"replication-" + cmd.get_logcontext_id(), self.handle_command, cmd
|
2019-03-25 12:38:05 -04:00
|
|
|
)
|
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def handle_command(self, cmd: Command):
|
2019-03-25 12:38:05 -04:00
|
|
|
"""Handle a command we have received over the replication stream.
|
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
By default delegates to on_<COMMAND>, which should return an awaitable.
|
2019-03-25 12:38:05 -04:00
|
|
|
|
|
|
|
Args:
|
2020-01-16 04:16:12 -05:00
|
|
|
cmd: received command
|
2019-03-25 12:38:05 -04:00
|
|
|
"""
|
|
|
|
handler = getattr(self, "on_%s" % (cmd.NAME,))
|
2020-01-16 04:16:12 -05:00
|
|
|
await handler(cmd)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
def close(self):
|
2019-10-31 06:23:24 -04:00
|
|
|
logger.warning("[%s] Closing connection", self.id())
|
2017-03-27 10:40:37 -04:00
|
|
|
self.time_we_closed = self.clock.time_msec()
|
|
|
|
self.transport.loseConnection()
|
|
|
|
self.on_connection_closed()
|
|
|
|
|
|
|
|
def send_error(self, error_string, *args):
|
|
|
|
"""Send an error to remote and close the connection.
|
|
|
|
"""
|
|
|
|
self.send_command(ErrorCommand(error_string % args))
|
|
|
|
self.close()
|
|
|
|
|
|
|
|
def send_command(self, cmd, do_buffer=True):
|
|
|
|
"""Send a command if connection has been established.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
cmd (Command)
|
|
|
|
do_buffer (bool): Whether to buffer the message or always attempt
|
|
|
|
to send the command. This is mostly used to send an error
|
|
|
|
message if we're about to close the connection due our buffers
|
|
|
|
becoming full.
|
|
|
|
"""
|
|
|
|
if self.state == ConnectionStates.CLOSED:
|
2017-07-11 05:04:21 -04:00
|
|
|
logger.debug("[%s] Not sending, connection closed", self.id())
|
2017-03-27 10:40:37 -04:00
|
|
|
return
|
|
|
|
|
|
|
|
if do_buffer and self.state != ConnectionStates.ESTABLISHED:
|
|
|
|
self._queue_command(cmd)
|
|
|
|
return
|
|
|
|
|
2018-05-22 18:36:20 -04:00
|
|
|
self.outbound_commands_counter[cmd.NAME] = (
|
2019-06-20 05:32:02 -04:00
|
|
|
self.outbound_commands_counter[cmd.NAME] + 1
|
|
|
|
)
|
|
|
|
string = "%s %s" % (cmd.NAME, cmd.to_line())
|
2017-03-27 10:40:37 -04:00
|
|
|
if "\n" in string:
|
|
|
|
raise Exception("Unexpected newline in command: %r", string)
|
|
|
|
|
2019-02-27 05:28:37 -05:00
|
|
|
encoded_string = string.encode("utf-8")
|
|
|
|
|
|
|
|
if len(encoded_string) > self.MAX_LENGTH:
|
|
|
|
raise Exception(
|
2019-06-20 05:32:02 -04:00
|
|
|
"Failed to send command %s as too long (%d > %d)"
|
|
|
|
% (cmd.NAME, len(encoded_string), self.MAX_LENGTH)
|
2019-02-27 05:28:37 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
self.sendLine(encoded_string)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
self.last_sent_command = self.clock.time_msec()
|
|
|
|
|
|
|
|
def _queue_command(self, cmd):
|
|
|
|
"""Queue the command until the connection is ready to write to again.
|
|
|
|
"""
|
2017-07-11 05:04:21 -04:00
|
|
|
logger.debug("[%s] Queing as conn %r, cmd: %r", self.id(), self.state, cmd)
|
2017-03-27 10:40:37 -04:00
|
|
|
self.pending_commands.append(cmd)
|
|
|
|
|
|
|
|
if len(self.pending_commands) > self.max_line_buffer:
|
|
|
|
# The other side is failing to keep up and out buffers are becoming
|
|
|
|
# full, so lets close the connection.
|
|
|
|
# XXX: should we squawk more loudly?
|
|
|
|
logger.error("[%s] Remote failed to keep up", self.id())
|
|
|
|
self.send_command(ErrorCommand("Failed to keep up"), do_buffer=False)
|
|
|
|
self.close()
|
|
|
|
|
|
|
|
def _send_pending_commands(self):
|
|
|
|
"""Send any queued commandes
|
|
|
|
"""
|
|
|
|
pending = self.pending_commands
|
|
|
|
self.pending_commands = []
|
|
|
|
for cmd in pending:
|
|
|
|
self.send_command(cmd)
|
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def on_PING(self, line):
|
2017-03-27 10:40:37 -04:00
|
|
|
self.received_ping = True
|
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def on_ERROR(self, cmd):
|
2017-03-27 10:40:37 -04:00
|
|
|
logger.error("[%s] Remote reported error: %r", self.id(), cmd.data)
|
|
|
|
|
|
|
|
def pauseProducing(self):
|
|
|
|
"""This is called when both the kernel send buffer and the twisted
|
|
|
|
tcp connection send buffers have become full.
|
|
|
|
|
|
|
|
We don't actually have any control over those sizes, so we buffer some
|
|
|
|
commands ourselves before knifing the connection due to the remote
|
|
|
|
failing to keep up.
|
|
|
|
"""
|
|
|
|
logger.info("[%s] Pause producing", self.id())
|
|
|
|
self.state = ConnectionStates.PAUSED
|
|
|
|
|
|
|
|
def resumeProducing(self):
|
|
|
|
"""The remote has caught up after we started buffering!
|
|
|
|
"""
|
|
|
|
logger.info("[%s] Resume producing", self.id())
|
|
|
|
self.state = ConnectionStates.ESTABLISHED
|
|
|
|
self._send_pending_commands()
|
|
|
|
|
|
|
|
def stopProducing(self):
|
|
|
|
"""We're never going to send any more data (normally because either
|
|
|
|
we or the remote has closed the connection)
|
|
|
|
"""
|
|
|
|
logger.info("[%s] Stop producing", self.id())
|
|
|
|
self.on_connection_closed()
|
|
|
|
|
|
|
|
def connectionLost(self, reason):
|
|
|
|
logger.info("[%s] Replication connection closed: %r", self.id(), reason)
|
2017-04-05 08:34:54 -04:00
|
|
|
if isinstance(reason, Failure):
|
2018-05-21 20:47:37 -04:00
|
|
|
connection_close_counter.labels(reason.type.__name__).inc()
|
2017-04-05 08:34:54 -04:00
|
|
|
else:
|
2018-05-21 20:47:37 -04:00
|
|
|
connection_close_counter.labels(reason.__class__.__name__).inc()
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
try:
|
|
|
|
# Remove us from list of connections to be monitored
|
|
|
|
connected_connections.remove(self)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
# Stop the looping call sending pings.
|
|
|
|
if self._send_ping_loop and self._send_ping_loop.running:
|
|
|
|
self._send_ping_loop.stop()
|
|
|
|
|
|
|
|
self.on_connection_closed()
|
|
|
|
|
|
|
|
def on_connection_closed(self):
|
|
|
|
logger.info("[%s] Connection was closed", self.id())
|
|
|
|
|
|
|
|
self.state = ConnectionStates.CLOSED
|
|
|
|
self.pending_commands = []
|
|
|
|
|
|
|
|
if self.transport:
|
|
|
|
self.transport.unregisterProducer()
|
|
|
|
|
|
|
|
def __str__(self):
|
2019-03-25 12:41:51 -04:00
|
|
|
addr = None
|
|
|
|
if self.transport:
|
|
|
|
addr = str(self.transport.getPeer())
|
2017-03-27 10:40:37 -04:00
|
|
|
return "ReplicationConnection<name=%s,conn_id=%s,addr=%s>" % (
|
2019-06-20 05:32:02 -04:00
|
|
|
self.name,
|
|
|
|
self.conn_id,
|
|
|
|
addr,
|
2017-03-27 10:40:37 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
def id(self):
|
|
|
|
return "%s-%s" % (self.name, self.conn_id)
|
|
|
|
|
2019-02-27 05:28:37 -05:00
|
|
|
def lineLengthExceeded(self, line):
|
|
|
|
"""Called when we receive a line that is above the maximum line length
|
|
|
|
"""
|
|
|
|
self.send_error("Line length exceeded")
|
|
|
|
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
class ServerReplicationStreamProtocol(BaseReplicationStreamProtocol):
|
|
|
|
VALID_INBOUND_COMMANDS = VALID_CLIENT_COMMANDS
|
|
|
|
VALID_OUTBOUND_COMMANDS = VALID_SERVER_COMMANDS
|
|
|
|
|
2019-03-25 12:41:51 -04:00
|
|
|
def __init__(self, server_name, clock, streamer):
|
2017-03-27 10:40:37 -04:00
|
|
|
BaseReplicationStreamProtocol.__init__(self, clock) # Old style class
|
|
|
|
|
|
|
|
self.server_name = server_name
|
|
|
|
self.streamer = streamer
|
|
|
|
|
|
|
|
def connectionMade(self):
|
|
|
|
self.send_command(ServerCommand(self.server_name))
|
|
|
|
BaseReplicationStreamProtocol.connectionMade(self)
|
|
|
|
self.streamer.new_connection(self)
|
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def on_NAME(self, cmd):
|
2017-04-04 09:14:03 -04:00
|
|
|
logger.info("[%s] Renamed to %r", self.id(), cmd.data)
|
2017-03-27 10:40:37 -04:00
|
|
|
self.name = cmd.data
|
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def on_USER_SYNC(self, cmd):
|
|
|
|
await self.streamer.on_user_sync(
|
2020-03-30 11:37:24 -04:00
|
|
|
cmd.instance_id, cmd.user_id, cmd.is_syncing, cmd.last_sync_ms
|
2017-03-31 06:46:20 -04:00
|
|
|
)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2020-03-30 11:37:24 -04:00
|
|
|
async def on_CLEAR_USER_SYNC(self, cmd):
|
|
|
|
await self.streamer.on_clear_user_syncs(cmd.instance_id)
|
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def on_REPLICATE(self, cmd):
|
2020-03-25 10:54:01 -04:00
|
|
|
# Subscribe to all streams we're publishing to.
|
|
|
|
for stream_name in self.streamer.streams_by_name:
|
|
|
|
current_token = self.streamer.get_stream_token(stream_name)
|
|
|
|
self.send_command(PositionCommand(stream_name, current_token))
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def on_FEDERATION_ACK(self, cmd):
|
|
|
|
self.streamer.federation_ack(cmd.token)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def on_REMOVE_PUSHER(self, cmd):
|
|
|
|
await self.streamer.on_remove_pusher(cmd.app_id, cmd.push_key, cmd.user_id)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def on_INVALIDATE_CACHE(self, cmd):
|
2020-01-27 08:47:50 -05:00
|
|
|
await self.streamer.on_invalidate_cache(cmd.cache_func, cmd.keys)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2020-01-17 05:27:19 -05:00
|
|
|
async def on_REMOTE_SERVER_UP(self, cmd: RemoteServerUpCommand):
|
|
|
|
self.streamer.on_remote_server_up(cmd.data)
|
|
|
|
|
2020-01-16 04:16:12 -05:00
|
|
|
async def on_USER_IP(self, cmd):
|
|
|
|
self.streamer.on_user_ip(
|
2019-06-20 05:32:02 -04:00
|
|
|
cmd.user_id,
|
|
|
|
cmd.access_token,
|
|
|
|
cmd.ip,
|
|
|
|
cmd.user_agent,
|
|
|
|
cmd.device_id,
|
2017-06-27 09:58:10 -04:00
|
|
|
cmd.last_seen,
|
|
|
|
)
|
|
|
|
|
2017-03-27 10:40:37 -04:00
|
|
|
def stream_update(self, stream_name, token, data):
|
|
|
|
"""Called when a new update is available to stream to clients.
|
|
|
|
|
|
|
|
We need to check if the client is interested in the stream or not
|
|
|
|
"""
|
2020-03-25 10:54:01 -04:00
|
|
|
self.send_command(RdataCommand(stream_name, token, data))
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
def send_sync(self, data):
|
|
|
|
self.send_command(SyncCommand(data))
|
|
|
|
|
2020-01-17 05:27:19 -05:00
|
|
|
def send_remote_server_up(self, server: str):
|
|
|
|
self.send_command(RemoteServerUpCommand(server))
|
|
|
|
|
2017-03-27 10:40:37 -04:00
|
|
|
def on_connection_closed(self):
|
|
|
|
BaseReplicationStreamProtocol.on_connection_closed(self)
|
|
|
|
self.streamer.lost_connection(self)
|
|
|
|
|
|
|
|
|
|
|
|
class ClientReplicationStreamProtocol(BaseReplicationStreamProtocol):
|
|
|
|
VALID_INBOUND_COMMANDS = VALID_SERVER_COMMANDS
|
|
|
|
VALID_OUTBOUND_COMMANDS = VALID_CLIENT_COMMANDS
|
|
|
|
|
2019-11-04 07:40:18 -05:00
|
|
|
def __init__(
|
|
|
|
self,
|
2020-03-25 10:54:01 -04:00
|
|
|
hs: "HomeServer",
|
2019-11-04 07:40:18 -05:00
|
|
|
client_name: str,
|
|
|
|
server_name: str,
|
|
|
|
clock: Clock,
|
2020-04-06 04:58:42 -04:00
|
|
|
command_handler: "ReplicationCommandHandler",
|
2019-11-04 07:40:18 -05:00
|
|
|
):
|
2017-03-27 10:40:37 -04:00
|
|
|
BaseReplicationStreamProtocol.__init__(self, clock)
|
|
|
|
|
2020-03-30 11:37:24 -04:00
|
|
|
self.instance_id = hs.get_instance_id()
|
|
|
|
|
2017-03-27 10:40:37 -04:00
|
|
|
self.client_name = client_name
|
|
|
|
self.server_name = server_name
|
2020-04-06 04:58:42 -04:00
|
|
|
self.handler = command_handler
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
def connectionMade(self):
|
|
|
|
self.send_command(NameCommand(self.client_name))
|
|
|
|
BaseReplicationStreamProtocol.connectionMade(self)
|
|
|
|
|
|
|
|
# Once we've connected subscribe to the necessary streams
|
2020-03-25 10:54:01 -04:00
|
|
|
self.replicate()
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
# Tell the server if we have any users currently syncing (should only
|
|
|
|
# happen on synchrotrons)
|
|
|
|
currently_syncing = self.handler.get_currently_syncing_users()
|
2017-03-31 06:46:20 -04:00
|
|
|
now = self.clock.time_msec()
|
2017-03-27 10:40:37 -04:00
|
|
|
for user_id in currently_syncing:
|
2020-03-30 11:37:24 -04:00
|
|
|
self.send_command(UserSyncCommand(self.instance_id, user_id, True, now))
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
# We've now finished connecting to so inform the client handler
|
|
|
|
self.handler.update_connection(self)
|
2020-04-06 04:58:42 -04:00
|
|
|
self.handler.finished_connecting()
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2020-04-06 04:58:42 -04:00
|
|
|
async def handle_command(self, cmd: Command):
|
|
|
|
"""Handle a command we have received over the replication stream.
|
2020-03-25 10:54:01 -04:00
|
|
|
|
2020-04-06 04:58:42 -04:00
|
|
|
Delegates to `command_handler.on_<COMMAND>`, which must return an
|
|
|
|
awaitable.
|
2020-03-25 10:54:01 -04:00
|
|
|
|
2020-04-06 04:58:42 -04:00
|
|
|
Args:
|
|
|
|
cmd: received command
|
|
|
|
"""
|
|
|
|
handled = False
|
2019-02-27 05:22:52 -05:00
|
|
|
|
2020-04-06 04:58:42 -04:00
|
|
|
# First call any command handlers on this instance. These are for TCP
|
|
|
|
# specific handling.
|
|
|
|
cmd_func = getattr(self, "on_%s" % (cmd.NAME,), None)
|
|
|
|
if cmd_func:
|
|
|
|
await cmd_func(cmd)
|
|
|
|
handled = True
|
2020-03-25 10:54:01 -04:00
|
|
|
|
2020-04-06 04:58:42 -04:00
|
|
|
# Then call out to the handler.
|
|
|
|
cmd_func = getattr(self.handler, "on_%s" % (cmd.NAME,), None)
|
|
|
|
if cmd_func:
|
|
|
|
await cmd_func(cmd)
|
|
|
|
handled = True
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2020-04-06 04:58:42 -04:00
|
|
|
if not handled:
|
|
|
|
logger.warning("Unhandled command: %r", cmd)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
2020-04-06 04:58:42 -04:00
|
|
|
async def on_SERVER(self, cmd):
|
|
|
|
if cmd.data != self.server_name:
|
|
|
|
logger.error("[%s] Connected to wrong remote: %r", self.id(), cmd.data)
|
|
|
|
self.send_error("Wrong remote")
|
2020-01-17 05:27:19 -05:00
|
|
|
|
2020-03-25 10:54:01 -04:00
|
|
|
def replicate(self):
|
2017-03-27 10:40:37 -04:00
|
|
|
"""Send the subscription request to the server
|
|
|
|
"""
|
2020-03-25 10:54:01 -04:00
|
|
|
logger.info("[%s] Subscribing to replication streams", self.id())
|
2019-02-27 05:22:52 -05:00
|
|
|
|
2020-03-25 10:54:01 -04:00
|
|
|
self.send_command(ReplicateCommand())
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
def on_connection_closed(self):
|
|
|
|
BaseReplicationStreamProtocol.on_connection_closed(self)
|
|
|
|
self.handler.update_connection(None)
|
|
|
|
|
|
|
|
|
|
|
|
# The following simply registers metrics for the replication connections
|
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
pending_commands = LaterGauge(
|
2018-06-21 04:39:27 -04:00
|
|
|
"synapse_replication_tcp_protocol_pending_commands",
|
|
|
|
"",
|
2018-09-04 06:45:52 -04:00
|
|
|
["name"],
|
2019-06-20 05:32:02 -04:00
|
|
|
lambda: {(p.name,): len(p.pending_commands) for p in connected_connections},
|
2018-06-21 04:39:27 -04:00
|
|
|
)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
|
|
|
|
def transport_buffer_size(protocol):
|
|
|
|
if protocol.transport:
|
|
|
|
size = len(protocol.transport.dataBuffer) + protocol.transport._tempDataLen
|
|
|
|
return size
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
transport_send_buffer = LaterGauge(
|
2018-06-21 04:39:27 -04:00
|
|
|
"synapse_replication_tcp_protocol_transport_send_buffer",
|
|
|
|
"",
|
2018-09-03 12:22:49 -04:00
|
|
|
["name"],
|
2019-06-20 05:32:02 -04:00
|
|
|
lambda: {(p.name,): transport_buffer_size(p) for p in connected_connections},
|
2018-06-21 04:39:27 -04:00
|
|
|
)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
|
|
|
|
def transport_kernel_read_buffer_size(protocol, read=True):
|
|
|
|
SIOCINQ = 0x541B
|
|
|
|
SIOCOUTQ = 0x5411
|
|
|
|
|
|
|
|
if protocol.transport:
|
|
|
|
fileno = protocol.transport.getHandle().fileno()
|
|
|
|
if read:
|
|
|
|
op = SIOCINQ
|
|
|
|
else:
|
|
|
|
op = SIOCOUTQ
|
2020-01-14 09:08:06 -05:00
|
|
|
size = struct.unpack("I", fcntl.ioctl(fileno, op, b"\0\0\0\0"))[0]
|
2017-03-27 10:40:37 -04:00
|
|
|
return size
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
tcp_transport_kernel_send_buffer = LaterGauge(
|
2018-06-21 04:39:27 -04:00
|
|
|
"synapse_replication_tcp_protocol_transport_kernel_send_buffer",
|
|
|
|
"",
|
2018-09-03 12:22:49 -04:00
|
|
|
["name"],
|
2017-03-27 10:40:37 -04:00
|
|
|
lambda: {
|
2018-09-03 12:22:49 -04:00
|
|
|
(p.name,): transport_kernel_read_buffer_size(p, False)
|
2017-03-27 10:40:37 -04:00
|
|
|
for p in connected_connections
|
2018-06-21 04:39:27 -04:00
|
|
|
},
|
|
|
|
)
|
2017-03-27 10:40:37 -04:00
|
|
|
|
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
tcp_transport_kernel_read_buffer = LaterGauge(
|
2018-06-21 04:39:27 -04:00
|
|
|
"synapse_replication_tcp_protocol_transport_kernel_read_buffer",
|
|
|
|
"",
|
2018-09-03 12:22:49 -04:00
|
|
|
["name"],
|
2017-03-27 10:40:37 -04:00
|
|
|
lambda: {
|
2018-09-03 12:22:49 -04:00
|
|
|
(p.name,): transport_kernel_read_buffer_size(p, True)
|
2017-03-27 10:40:37 -04:00
|
|
|
for p in connected_connections
|
2018-06-21 04:39:27 -04:00
|
|
|
},
|
|
|
|
)
|
2017-04-05 09:15:09 -04:00
|
|
|
|
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
tcp_inbound_commands = LaterGauge(
|
2018-06-21 04:39:27 -04:00
|
|
|
"synapse_replication_tcp_protocol_inbound_commands",
|
|
|
|
"",
|
2018-09-03 12:22:49 -04:00
|
|
|
["command", "name"],
|
2017-04-05 09:15:09 -04:00
|
|
|
lambda: {
|
2019-06-20 05:32:02 -04:00
|
|
|
(k, p.name): count
|
2017-04-05 09:15:09 -04:00
|
|
|
for p in connected_connections
|
2018-06-04 11:23:05 -04:00
|
|
|
for k, count in iteritems(p.inbound_commands_counter)
|
2018-06-21 04:39:27 -04:00
|
|
|
},
|
|
|
|
)
|
2017-04-05 09:15:09 -04:00
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
tcp_outbound_commands = LaterGauge(
|
2018-06-21 04:39:27 -04:00
|
|
|
"synapse_replication_tcp_protocol_outbound_commands",
|
|
|
|
"",
|
2018-09-03 12:22:49 -04:00
|
|
|
["command", "name"],
|
2017-04-05 09:15:09 -04:00
|
|
|
lambda: {
|
2019-06-20 05:32:02 -04:00
|
|
|
(k, p.name): count
|
2017-04-05 09:15:09 -04:00
|
|
|
for p in connected_connections
|
2018-06-04 11:23:05 -04:00
|
|
|
for k, count in iteritems(p.outbound_commands_counter)
|
2018-06-21 04:39:27 -04:00
|
|
|
},
|
|
|
|
)
|