2017-03-27 16:40:37 +02:00
|
|
|
# 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.
|
|
|
|
|
2023-03-30 12:51:35 +02:00
|
|
|
An explanation of this protocol is available in docs/tcp_replication.md
|
2017-03-27 16:40:37 +02:00
|
|
|
"""
|
2018-07-09 08:09:20 +02:00
|
|
|
import fcntl
|
|
|
|
import logging
|
|
|
|
import struct
|
2020-07-27 19:54:43 +02:00
|
|
|
from inspect import isawaitable
|
2022-02-08 17:03:08 +01:00
|
|
|
from typing import TYPE_CHECKING, Any, Collection, List, Optional
|
2018-07-09 08:09:20 +02:00
|
|
|
|
|
|
|
from prometheus_client import Counter
|
2021-03-12 17:37:57 +01:00
|
|
|
from zope.interface import Interface, implementer
|
2018-07-09 08:09:20 +02:00
|
|
|
|
2020-10-01 14:09:18 +02:00
|
|
|
from twisted.internet import task
|
2021-03-15 16:14:39 +01:00
|
|
|
from twisted.internet.tcp import Connection
|
2017-03-27 16:40:37 +02:00
|
|
|
from twisted.protocols.basic import LineOnlyReceiver
|
2017-04-05 14:34:54 +02:00
|
|
|
from twisted.python.failure import Failure
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2020-07-22 01:40:42 +02:00
|
|
|
from synapse.logging.context import PreserveLoggingContext
|
2018-05-22 02:47:37 +02:00
|
|
|
from synapse.metrics import LaterGauge
|
2020-07-22 01:40:42 +02:00
|
|
|
from synapse.metrics.background_process_metrics import (
|
|
|
|
BackgroundProcessLoggingContext,
|
|
|
|
run_as_background_process,
|
|
|
|
)
|
2020-01-14 15:08:06 +01:00
|
|
|
from synapse.replication.tcp.commands import (
|
2018-07-09 08:09:20 +02:00
|
|
|
VALID_CLIENT_COMMANDS,
|
|
|
|
VALID_SERVER_COMMANDS,
|
2020-01-14 15:08:06 +01:00
|
|
|
Command,
|
2018-07-09 08:09:20 +02:00
|
|
|
ErrorCommand,
|
|
|
|
NameCommand,
|
|
|
|
PingCommand,
|
|
|
|
ReplicateCommand,
|
|
|
|
ServerCommand,
|
2020-04-22 14:07:41 +02:00
|
|
|
parse_command_from_line,
|
2018-07-09 08:09:20 +02:00
|
|
|
)
|
2020-01-14 15:08:06 +01:00
|
|
|
from synapse.util import Clock
|
|
|
|
from synapse.util.stringutils import random_string
|
|
|
|
|
2020-04-06 10:58:42 +02:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.replication.tcp.handler import ReplicationCommandHandler
|
2020-03-25 15:54:01 +01:00
|
|
|
from synapse.server import HomeServer
|
|
|
|
|
|
|
|
|
2018-05-22 02:47:37 +02:00
|
|
|
connection_close_counter = Counter(
|
2019-06-20 11:32:02 +02:00
|
|
|
"synapse_replication_tcp_protocol_close_reason", "", ["reason_type"]
|
|
|
|
)
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2020-04-22 17:26:19 +02:00
|
|
|
tcp_inbound_commands_counter = Counter(
|
|
|
|
"synapse_replication_tcp_protocol_inbound_commands",
|
|
|
|
"Number of commands received from replication, by command and name of process connected to",
|
|
|
|
["command", "name"],
|
|
|
|
)
|
|
|
|
|
|
|
|
tcp_outbound_commands_counter = Counter(
|
|
|
|
"synapse_replication_tcp_protocol_outbound_commands",
|
|
|
|
"Number of commands sent to replication, by command and name of process connected to",
|
|
|
|
["command", "name"],
|
|
|
|
)
|
|
|
|
|
2017-03-27 16:40:37 +02:00
|
|
|
# A list of all connected protocols. This allows us to send metrics about the
|
|
|
|
# connections.
|
2021-07-15 12:02:43 +02:00
|
|
|
connected_connections: "List[BaseReplicationStreamProtocol]" = []
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
PING_TIME = 5000
|
2017-04-10 12:32:05 +02:00
|
|
|
PING_TIMEOUT_MULTIPLIER = 5
|
|
|
|
PING_TIMEOUT_MS = PING_TIME * PING_TIMEOUT_MULTIPLIER
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
|
2020-09-04 12:54:56 +02:00
|
|
|
class ConnectionStates:
|
2017-03-27 16:40:37 +02:00
|
|
|
CONNECTING = "connecting"
|
|
|
|
ESTABLISHED = "established"
|
|
|
|
PAUSED = "paused"
|
|
|
|
CLOSED = "closed"
|
|
|
|
|
|
|
|
|
2021-03-12 17:37:57 +01:00
|
|
|
class IReplicationConnection(Interface):
|
|
|
|
"""An interface for replication connections."""
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def send_command(cmd: Command) -> None:
|
2021-03-12 17:37:57 +01:00
|
|
|
"""Send the command down the connection"""
|
|
|
|
|
|
|
|
|
|
|
|
@implementer(IReplicationConnection)
|
2017-03-27 16:40:37 +02:00
|
|
|
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
|
2020-04-07 11:51:07 +02:00
|
|
|
command before delegating to `ReplicationCommandHandler.on_<COMMAND_NAME>`.
|
2020-07-27 19:54:43 +02:00
|
|
|
`ReplicationCommandHandler.on_<COMMAND_NAME>` can optionally return a coroutine;
|
|
|
|
if so, that will get run as a background process.
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
It also sends `PING` periodically, and correctly times out remote connections
|
|
|
|
(if they send a `PING` command)
|
|
|
|
"""
|
2019-06-20 11:32:02 +02:00
|
|
|
|
2021-03-15 16:14:39 +01:00
|
|
|
# The transport is going to be an ITCPTransport, but that doesn't have the
|
|
|
|
# (un)registerProducer methods, those are only on the implementation.
|
2021-07-15 12:02:43 +02:00
|
|
|
transport: Connection
|
2021-03-15 16:14:39 +01:00
|
|
|
|
2019-06-20 11:32:02 +02:00
|
|
|
delimiter = b"\n"
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2020-01-14 15:08:06 +01:00
|
|
|
# Valid commands we expect to receive
|
2021-07-15 12:02:43 +02:00
|
|
|
VALID_INBOUND_COMMANDS: Collection[str] = []
|
2020-01-14 15:08:06 +01:00
|
|
|
|
|
|
|
# Valid commands we can send
|
2021-07-15 12:02:43 +02:00
|
|
|
VALID_OUTBOUND_COMMANDS: Collection[str] = []
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
max_line_buffer = 10000
|
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
def __init__(self, clock: Clock, handler: "ReplicationCommandHandler"):
|
2017-03-27 16:40:37 +02:00
|
|
|
self.clock = clock
|
2020-04-07 11:51:07 +02:00
|
|
|
self.command_handler = handler
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
self.last_received_command = self.clock.time_msec()
|
|
|
|
self.last_sent_command = 0
|
2020-10-01 14:09:18 +02:00
|
|
|
# When we requested the connection be closed
|
2021-07-15 12:02:43 +02:00
|
|
|
self.time_we_closed: Optional[int] = None
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2020-10-01 14:09:18 +02:00
|
|
|
self.received_ping = False # Have we received a ping from the other side
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
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
|
2021-07-15 12:02:43 +02:00
|
|
|
self.pending_commands: List[Command] = []
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
# The LoopingCall for sending pings.
|
2021-07-15 12:02:43 +02:00
|
|
|
self._send_ping_loop: Optional[task.LoopingCall] = None
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2020-07-22 01:40:42 +02:00
|
|
|
# a logcontext which we use for processing incoming commands. We declare it as a
|
|
|
|
# background process so that the CPU stats get reported to prometheus.
|
2021-10-15 14:10:58 +02:00
|
|
|
with PreserveLoggingContext():
|
|
|
|
# thanks to `PreserveLoggingContext()`, the new logcontext is guaranteed to
|
|
|
|
# capture the sentinel context as its containing context and won't prevent
|
|
|
|
# GC of / unintentionally reactivate what would be the current context.
|
|
|
|
self._logging_context = BackgroundProcessLoggingContext(
|
|
|
|
"replication-conn", self.conn_id
|
|
|
|
)
|
2020-07-22 01:40:42 +02:00
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def connectionMade(self) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
logger.info("[%s] Connection established", self.id())
|
|
|
|
|
|
|
|
self.state = ConnectionStates.ESTABLISHED
|
|
|
|
|
|
|
|
connected_connections.append(self) # Register connection for metrics
|
|
|
|
|
2021-03-15 16:14:39 +01:00
|
|
|
assert self.transport is not None
|
2017-03-27 16:40:37 +02:00
|
|
|
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.
|
2022-02-08 17:03:08 +01:00
|
|
|
self.send_command(PingCommand(str(self.clock.time_msec())))
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
self.command_handler.new_connection(self)
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def send_ping(self) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
"""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 12:32:05 +02:00
|
|
|
if now - self.time_we_closed > PING_TIMEOUT_MS:
|
2017-03-27 16:40:37 +02:00
|
|
|
logger.info(
|
|
|
|
"[%s] Failed to close connection gracefully, aborting", self.id()
|
|
|
|
)
|
2021-03-15 16:14:39 +01:00
|
|
|
assert self.transport is not None
|
2017-03-27 16:40:37 +02:00
|
|
|
self.transport.abortConnection()
|
|
|
|
else:
|
|
|
|
if now - self.last_sent_command >= PING_TIME:
|
2022-02-08 17:03:08 +01:00
|
|
|
self.send_command(PingCommand(str(now)))
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2019-06-20 11:32:02 +02:00
|
|
|
if (
|
|
|
|
self.received_ping
|
|
|
|
and now - self.last_received_command > PING_TIMEOUT_MS
|
|
|
|
):
|
2017-03-27 16:40:37 +02:00
|
|
|
logger.info(
|
|
|
|
"[%s] Connection hasn't received command in %r ms. Closing.",
|
2019-06-20 11:32:02 +02:00
|
|
|
self.id(),
|
|
|
|
now - self.last_received_command,
|
2017-03-27 16:40:37 +02:00
|
|
|
)
|
|
|
|
self.send_error("ping timeout")
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def lineReceived(self, line: bytes) -> None:
|
2021-02-16 23:32:34 +01:00
|
|
|
"""Called when we've received a line"""
|
2020-07-22 01:40:42 +02:00
|
|
|
with PreserveLoggingContext(self._logging_context):
|
|
|
|
self._parse_and_dispatch_line(line)
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def _parse_and_dispatch_line(self, line: bytes) -> None:
|
2022-11-17 17:09:56 +01:00
|
|
|
if line.strip() == b"":
|
2017-03-27 16:40:37 +02:00
|
|
|
# Ignore blank lines
|
|
|
|
return
|
|
|
|
|
2020-04-07 18:21:13 +02:00
|
|
|
linestr = line.decode("utf-8")
|
|
|
|
|
2020-04-22 14:07:41 +02:00
|
|
|
try:
|
|
|
|
cmd = parse_command_from_line(linestr)
|
|
|
|
except Exception as e:
|
|
|
|
logger.exception("[%s] failed to parse line: %r", self.id(), linestr)
|
|
|
|
self.send_error("failed to parse line: %r (%r):" % (e, linestr))
|
|
|
|
return
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2020-04-22 14:07:41 +02:00
|
|
|
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)
|
2017-03-27 16:40:37 +02:00
|
|
|
return
|
|
|
|
|
|
|
|
self.last_received_command = self.clock.time_msec()
|
|
|
|
|
2020-04-22 17:26:19 +02:00
|
|
|
tcp_inbound_commands_counter.labels(cmd.NAME, self.name).inc()
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2020-07-27 19:54:43 +02:00
|
|
|
self.handle_command(cmd)
|
2019-03-25 17:38:05 +01:00
|
|
|
|
2020-07-27 19:54:43 +02:00
|
|
|
def handle_command(self, cmd: Command) -> None:
|
2019-03-25 17:38:05 +01:00
|
|
|
"""Handle a command we have received over the replication stream.
|
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
First calls `self.on_<COMMAND>` if it exists, then calls
|
2020-07-27 19:54:43 +02:00
|
|
|
`self.command_handler.on_<COMMAND>` if it exists (which can optionally
|
|
|
|
return an Awaitable).
|
|
|
|
|
|
|
|
This allows for protocol level handling of commands (e.g. PINGs), before
|
|
|
|
delegating to the handler.
|
2019-03-25 17:38:05 +01:00
|
|
|
|
|
|
|
Args:
|
2020-01-16 10:16:12 +01:00
|
|
|
cmd: received command
|
2019-03-25 17:38:05 +01:00
|
|
|
"""
|
2020-04-07 11:51:07 +02:00
|
|
|
handled = False
|
|
|
|
|
|
|
|
# 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:
|
2020-07-27 19:54:43 +02:00
|
|
|
cmd_func(cmd)
|
2020-04-07 11:51:07 +02:00
|
|
|
handled = True
|
|
|
|
|
|
|
|
# Then call out to the handler.
|
|
|
|
cmd_func = getattr(self.command_handler, "on_%s" % (cmd.NAME,), None)
|
|
|
|
if cmd_func:
|
2020-07-27 19:54:43 +02:00
|
|
|
res = cmd_func(self, cmd)
|
|
|
|
|
|
|
|
# the handler might be a coroutine: fire it off as a background process
|
|
|
|
# if so.
|
|
|
|
|
|
|
|
if isawaitable(res):
|
|
|
|
run_as_background_process(
|
|
|
|
"replication-" + cmd.get_logcontext_id(), lambda: res
|
|
|
|
)
|
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
handled = True
|
|
|
|
|
|
|
|
if not handled:
|
|
|
|
logger.warning("Unhandled command: %r", cmd)
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def close(self) -> None:
|
2019-10-31 11:23:24 +01:00
|
|
|
logger.warning("[%s] Closing connection", self.id())
|
2017-03-27 16:40:37 +02:00
|
|
|
self.time_we_closed = self.clock.time_msec()
|
2021-03-15 16:14:39 +01:00
|
|
|
assert self.transport is not None
|
2017-03-27 16:40:37 +02:00
|
|
|
self.transport.loseConnection()
|
|
|
|
self.on_connection_closed()
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def send_error(self, error_string: str, *args: Any) -> None:
|
2021-02-16 23:32:34 +01:00
|
|
|
"""Send an error to remote and close the connection."""
|
2017-03-27 16:40:37 +02:00
|
|
|
self.send_command(ErrorCommand(error_string % args))
|
|
|
|
self.close()
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def send_command(self, cmd: Command, do_buffer: bool = True) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
"""Send a command if connection has been established.
|
|
|
|
|
|
|
|
Args:
|
2022-02-08 17:03:08 +01:00
|
|
|
cmd
|
|
|
|
do_buffer: Whether to buffer the message or always attempt
|
2017-03-27 16:40:37 +02:00
|
|
|
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 11:04:21 +02:00
|
|
|
logger.debug("[%s] Not sending, connection closed", self.id())
|
2017-03-27 16:40:37 +02:00
|
|
|
return
|
|
|
|
|
|
|
|
if do_buffer and self.state != ConnectionStates.ESTABLISHED:
|
|
|
|
self._queue_command(cmd)
|
|
|
|
return
|
|
|
|
|
2020-04-22 17:26:19 +02:00
|
|
|
tcp_outbound_commands_counter.labels(cmd.NAME, self.name).inc()
|
|
|
|
|
2019-06-20 11:32:02 +02:00
|
|
|
string = "%s %s" % (cmd.NAME, cmd.to_line())
|
2017-03-27 16:40:37 +02:00
|
|
|
if "\n" in string:
|
|
|
|
raise Exception("Unexpected newline in command: %r", string)
|
|
|
|
|
2019-02-27 11:28:37 +01:00
|
|
|
encoded_string = string.encode("utf-8")
|
|
|
|
|
|
|
|
if len(encoded_string) > self.MAX_LENGTH:
|
|
|
|
raise Exception(
|
2019-06-20 11:32:02 +02:00
|
|
|
"Failed to send command %s as too long (%d > %d)"
|
|
|
|
% (cmd.NAME, len(encoded_string), self.MAX_LENGTH)
|
2019-02-27 11:28:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
self.sendLine(encoded_string)
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
self.last_sent_command = self.clock.time_msec()
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def _queue_command(self, cmd: Command) -> None:
|
2021-02-16 23:32:34 +01:00
|
|
|
"""Queue the command until the connection is ready to write to again."""
|
2020-07-09 15:52:58 +02:00
|
|
|
logger.debug("[%s] Queueing as conn %r, cmd: %r", self.id(), self.state, cmd)
|
2017-03-27 16:40:37 +02: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()
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def _send_pending_commands(self) -> None:
|
2021-02-16 23:32:34 +01:00
|
|
|
"""Send any queued commandes"""
|
2017-03-27 16:40:37 +02:00
|
|
|
pending = self.pending_commands
|
|
|
|
self.pending_commands = []
|
|
|
|
for cmd in pending:
|
|
|
|
self.send_command(cmd)
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def on_PING(self, cmd: PingCommand) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
self.received_ping = True
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def on_ERROR(self, cmd: ErrorCommand) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
logger.error("[%s] Remote reported error: %r", self.id(), cmd.data)
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def pauseProducing(self) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
"""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
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def resumeProducing(self) -> None:
|
2021-02-16 23:32:34 +01:00
|
|
|
"""The remote has caught up after we started buffering!"""
|
2017-03-27 16:40:37 +02:00
|
|
|
logger.info("[%s] Resume producing", self.id())
|
|
|
|
self.state = ConnectionStates.ESTABLISHED
|
|
|
|
self._send_pending_commands()
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def stopProducing(self) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
"""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()
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def connectionLost(self, reason: Failure) -> None: # type: ignore[override]
|
2017-03-27 16:40:37 +02:00
|
|
|
logger.info("[%s] Replication connection closed: %r", self.id(), reason)
|
2017-04-05 14:34:54 +02:00
|
|
|
if isinstance(reason, Failure):
|
2021-03-15 16:14:39 +01:00
|
|
|
assert reason.type is not None
|
2018-05-22 02:47:37 +02:00
|
|
|
connection_close_counter.labels(reason.type.__name__).inc()
|
2017-04-05 14:34:54 +02:00
|
|
|
else:
|
2022-02-08 17:03:08 +01:00
|
|
|
connection_close_counter.labels(reason.__class__.__name__).inc() # type: ignore[unreachable]
|
2017-03-27 16:40:37 +02: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()
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def on_connection_closed(self) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
logger.info("[%s] Connection was closed", self.id())
|
|
|
|
|
|
|
|
self.state = ConnectionStates.CLOSED
|
|
|
|
self.pending_commands = []
|
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
self.command_handler.lost_connection(self)
|
|
|
|
|
2017-03-27 16:40:37 +02:00
|
|
|
if self.transport:
|
|
|
|
self.transport.unregisterProducer()
|
|
|
|
|
2021-10-15 14:10:58 +02:00
|
|
|
# mark the logging context as finished by triggering `__exit__()`
|
|
|
|
with PreserveLoggingContext():
|
|
|
|
with self._logging_context:
|
|
|
|
pass
|
|
|
|
# the sentinel context is now active, which may not be correct.
|
|
|
|
# PreserveLoggingContext() will restore the correct logging context.
|
2020-07-22 01:40:42 +02:00
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def __str__(self) -> str:
|
2019-03-25 17:41:51 +01:00
|
|
|
addr = None
|
|
|
|
if self.transport:
|
|
|
|
addr = str(self.transport.getPeer())
|
2017-03-27 16:40:37 +02:00
|
|
|
return "ReplicationConnection<name=%s,conn_id=%s,addr=%s>" % (
|
2019-06-20 11:32:02 +02:00
|
|
|
self.name,
|
|
|
|
self.conn_id,
|
|
|
|
addr,
|
2017-03-27 16:40:37 +02:00
|
|
|
)
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def id(self) -> str:
|
2017-03-27 16:40:37 +02:00
|
|
|
return "%s-%s" % (self.name, self.conn_id)
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def lineLengthExceeded(self, line: str) -> None:
|
2021-02-16 23:32:34 +01:00
|
|
|
"""Called when we receive a line that is above the maximum line length"""
|
2019-02-27 11:28:37 +01:00
|
|
|
self.send_error("Line length exceeded")
|
|
|
|
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
class ServerReplicationStreamProtocol(BaseReplicationStreamProtocol):
|
|
|
|
VALID_INBOUND_COMMANDS = VALID_CLIENT_COMMANDS
|
|
|
|
VALID_OUTBOUND_COMMANDS = VALID_SERVER_COMMANDS
|
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
def __init__(
|
|
|
|
self, server_name: str, clock: Clock, handler: "ReplicationCommandHandler"
|
|
|
|
):
|
|
|
|
super().__init__(clock, handler)
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
self.server_name = server_name
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def connectionMade(self) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
self.send_command(ServerCommand(self.server_name))
|
2020-04-07 11:51:07 +02:00
|
|
|
super().connectionMade()
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def on_NAME(self, cmd: NameCommand) -> None:
|
2017-04-04 15:14:03 +02:00
|
|
|
logger.info("[%s] Renamed to %r", self.id(), cmd.data)
|
2017-03-27 16:40:37 +02:00
|
|
|
self.name = cmd.data
|
|
|
|
|
|
|
|
|
|
|
|
class ClientReplicationStreamProtocol(BaseReplicationStreamProtocol):
|
|
|
|
VALID_INBOUND_COMMANDS = VALID_SERVER_COMMANDS
|
|
|
|
VALID_OUTBOUND_COMMANDS = VALID_CLIENT_COMMANDS
|
|
|
|
|
2019-11-04 13:40:18 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
2020-03-25 15:54:01 +01:00
|
|
|
hs: "HomeServer",
|
2019-11-04 13:40:18 +01:00
|
|
|
client_name: str,
|
|
|
|
server_name: str,
|
|
|
|
clock: Clock,
|
2020-04-06 10:58:42 +02:00
|
|
|
command_handler: "ReplicationCommandHandler",
|
2019-11-04 13:40:18 +01:00
|
|
|
):
|
2020-04-07 11:51:07 +02:00
|
|
|
super().__init__(clock, command_handler)
|
2020-03-30 17:37:24 +02:00
|
|
|
|
2017-03-27 16:40:37 +02:00
|
|
|
self.client_name = client_name
|
|
|
|
self.server_name = server_name
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def connectionMade(self) -> None:
|
2017-03-27 16:40:37 +02:00
|
|
|
self.send_command(NameCommand(self.client_name))
|
2020-04-07 11:51:07 +02:00
|
|
|
super().connectionMade()
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
# Once we've connected subscribe to the necessary streams
|
2020-03-25 15:54:01 +01:00
|
|
|
self.replicate()
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def on_SERVER(self, cmd: ServerCommand) -> None:
|
2020-04-06 10:58:42 +02:00
|
|
|
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 11:27:19 +01:00
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def replicate(self) -> None:
|
2021-02-16 23:32:34 +01:00
|
|
|
"""Send the subscription request to the server"""
|
2020-03-25 15:54:01 +01:00
|
|
|
logger.info("[%s] Subscribing to replication streams", self.id())
|
2019-02-27 11:22:52 +01:00
|
|
|
|
2020-03-25 15:54:01 +01:00
|
|
|
self.send_command(ReplicateCommand())
|
2017-03-27 16:40:37 +02:00
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
|
2017-03-27 16:40:37 +02:00
|
|
|
# The following simply registers metrics for the replication connections
|
|
|
|
|
2018-05-22 02:47:37 +02:00
|
|
|
pending_commands = LaterGauge(
|
2018-06-21 10:39:27 +02:00
|
|
|
"synapse_replication_tcp_protocol_pending_commands",
|
|
|
|
"",
|
2018-09-04 12:45:52 +02:00
|
|
|
["name"],
|
2019-06-20 11:32:02 +02:00
|
|
|
lambda: {(p.name,): len(p.pending_commands) for p in connected_connections},
|
2018-06-21 10:39:27 +02:00
|
|
|
)
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def transport_buffer_size(protocol: BaseReplicationStreamProtocol) -> int:
|
2017-03-27 16:40:37 +02:00
|
|
|
if protocol.transport:
|
|
|
|
size = len(protocol.transport.dataBuffer) + protocol.transport._tempDataLen
|
|
|
|
return size
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
2018-05-22 02:47:37 +02:00
|
|
|
transport_send_buffer = LaterGauge(
|
2018-06-21 10:39:27 +02:00
|
|
|
"synapse_replication_tcp_protocol_transport_send_buffer",
|
|
|
|
"",
|
2018-09-03 18:22:49 +02:00
|
|
|
["name"],
|
2019-06-20 11:32:02 +02:00
|
|
|
lambda: {(p.name,): transport_buffer_size(p) for p in connected_connections},
|
2018-06-21 10:39:27 +02:00
|
|
|
)
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
|
2022-02-08 17:03:08 +01:00
|
|
|
def transport_kernel_read_buffer_size(
|
|
|
|
protocol: BaseReplicationStreamProtocol, read: bool = True
|
|
|
|
) -> int:
|
2017-03-27 16:40:37 +02:00
|
|
|
SIOCINQ = 0x541B
|
|
|
|
SIOCOUTQ = 0x5411
|
|
|
|
|
|
|
|
if protocol.transport:
|
|
|
|
fileno = protocol.transport.getHandle().fileno()
|
|
|
|
if read:
|
|
|
|
op = SIOCINQ
|
|
|
|
else:
|
|
|
|
op = SIOCOUTQ
|
2020-01-14 15:08:06 +01:00
|
|
|
size = struct.unpack("I", fcntl.ioctl(fileno, op, b"\0\0\0\0"))[0]
|
2017-03-27 16:40:37 +02:00
|
|
|
return size
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
2018-05-22 02:47:37 +02:00
|
|
|
tcp_transport_kernel_send_buffer = LaterGauge(
|
2018-06-21 10:39:27 +02:00
|
|
|
"synapse_replication_tcp_protocol_transport_kernel_send_buffer",
|
|
|
|
"",
|
2018-09-03 18:22:49 +02:00
|
|
|
["name"],
|
2017-03-27 16:40:37 +02:00
|
|
|
lambda: {
|
2018-09-03 18:22:49 +02:00
|
|
|
(p.name,): transport_kernel_read_buffer_size(p, False)
|
2017-03-27 16:40:37 +02:00
|
|
|
for p in connected_connections
|
2018-06-21 10:39:27 +02:00
|
|
|
},
|
|
|
|
)
|
2017-03-27 16:40:37 +02:00
|
|
|
|
|
|
|
|
2018-05-22 02:47:37 +02:00
|
|
|
tcp_transport_kernel_read_buffer = LaterGauge(
|
2018-06-21 10:39:27 +02:00
|
|
|
"synapse_replication_tcp_protocol_transport_kernel_read_buffer",
|
|
|
|
"",
|
2018-09-03 18:22:49 +02:00
|
|
|
["name"],
|
2017-03-27 16:40:37 +02:00
|
|
|
lambda: {
|
2018-09-03 18:22:49 +02:00
|
|
|
(p.name,): transport_kernel_read_buffer_size(p, True)
|
2017-03-27 16:40:37 +02:00
|
|
|
for p in connected_connections
|
2018-06-21 10:39:27 +02:00
|
|
|
},
|
|
|
|
)
|