示例#1
0
    def __init__(self, clock: Clock, handler: "ReplicationCommandHandler"):
        self.clock = clock
        self.command_handler = handler

        self.last_received_command = self.clock.time_msec()
        self.last_sent_command = 0
        # When we requested the connection be closed
        self.time_we_closed = None  # type: Optional[int]

        self.received_ping = False  # Have we received 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
        self.pending_commands = []  # type: List[Command]

        # The LoopingCall for sending pings.
        self._send_ping_loop = None  # type: Optional[task.LoopingCall]

        # 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.
        self._logging_context = BackgroundProcessLoggingContext(
            "replication-conn", self.conn_id
        )
示例#2
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 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.
        self._logging_context = BackgroundProcessLoggingContext(
            "replication_command_handler")
示例#3
0
    def __init__(self, clock: Clock, handler: "ReplicationCommandHandler"):
        self.clock = clock
        self.command_handler = handler

        self.last_received_command = self.clock.time_msec()
        self.last_sent_command = 0
        # When we requested the connection be closed
        self.time_we_closed: Optional[int] = None

        self.received_ping = False  # Have we received 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
        self.pending_commands: List[Command] = []

        # The LoopingCall for sending pings.
        self._send_ping_loop: Optional[task.LoopingCall] = None

        # 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.
        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)
示例#4
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 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.
        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_command_handler")
示例#5
0
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 before delegating to `ReplicationCommandHandler.on_<COMMAND_NAME>`.
    `ReplicationCommandHandler.on_<COMMAND_NAME>` can optionally return a coroutine;
    if so, that will get run as a background process.

    It also sends `PING` periodically, and correctly times out remote connections
    (if they send a `PING` command)
    """

    # The transport is going to be an ITCPTransport, but that doesn't have the
    # (un)registerProducer methods, those are only on the implementation.
    transport = None  # type: Connection

    delimiter = b"\n"

    # Valid commands we expect to receive
    VALID_INBOUND_COMMANDS = []  # type: Collection[str]

    # Valid commands we can send
    VALID_OUTBOUND_COMMANDS = []  # type: Collection[str]

    max_line_buffer = 10000

    def __init__(self, clock: Clock, handler: "ReplicationCommandHandler"):
        self.clock = clock
        self.command_handler = handler

        self.last_received_command = self.clock.time_msec()
        self.last_sent_command = 0
        # When we requested the connection be closed
        self.time_we_closed = None  # type: Optional[int]

        self.received_ping = False  # Have we received 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
        self.pending_commands = []  # type: List[Command]

        # The LoopingCall for sending pings.
        self._send_ping_loop = None  # type: Optional[task.LoopingCall]

        # 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.
        self._logging_context = BackgroundProcessLoggingContext(
            "replication-conn", self.conn_id
        )

    def connectionMade(self):
        logger.info("[%s] Connection established", self.id())

        self.state = ConnectionStates.ESTABLISHED

        connected_connections.append(self)  # Register connection for metrics

        assert self.transport is not None
        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()))

        self.command_handler.new_connection(self)

    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:
            if now - self.time_we_closed > PING_TIMEOUT_MS:
                logger.info(
                    "[%s] Failed to close connection gracefully, aborting", self.id()
                )
                assert self.transport is not None
                self.transport.abortConnection()
        else:
            if now - self.last_sent_command >= PING_TIME:
                self.send_command(PingCommand(now))

            if (
                self.received_ping
                and now - self.last_received_command > PING_TIMEOUT_MS
            ):
                logger.info(
                    "[%s] Connection hasn't received command in %r ms. Closing.",
                    self.id(),
                    now - self.last_received_command,
                )
                self.send_error("ping timeout")

    def lineReceived(self, line: bytes):
        """Called when we've received a line"""
        with PreserveLoggingContext(self._logging_context):
            self._parse_and_dispatch_line(line)

    def _parse_and_dispatch_line(self, line: bytes):
        if line.strip() == "":
            # Ignore blank lines
            return

        linestr = line.decode("utf-8")

        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

        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()

        tcp_inbound_commands_counter.labels(cmd.NAME, self.name).inc()

        self.handle_command(cmd)

    def handle_command(self, cmd: Command) -> None:
        """Handle a command we have received over the replication stream.

        First calls `self.on_<COMMAND>` if it exists, then calls
        `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.

        Args:
            cmd: received command
        """
        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:
            cmd_func(cmd)
            handled = True

        # Then call out to the handler.
        cmd_func = getattr(self.command_handler, "on_%s" % (cmd.NAME,), None)
        if cmd_func:
            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
                )

            handled = True

        if not handled:
            logger.warning("Unhandled command: %r", cmd)

    def close(self):
        logger.warning("[%s] Closing connection", self.id())
        self.time_we_closed = self.clock.time_msec()
        assert self.transport is not None
        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:
            logger.debug("[%s] Not sending, connection closed", self.id())
            return

        if do_buffer and self.state != ConnectionStates.ESTABLISHED:
            self._queue_command(cmd)
            return

        tcp_outbound_commands_counter.labels(cmd.NAME, self.name).inc()

        string = "%s %s" % (cmd.NAME, cmd.to_line())
        if "\n" in string:
            raise Exception("Unexpected newline in command: %r", string)

        encoded_string = string.encode("utf-8")

        if len(encoded_string) > self.MAX_LENGTH:
            raise Exception(
                "Failed to send command %s as too long (%d > %d)"
                % (cmd.NAME, len(encoded_string), self.MAX_LENGTH)
            )

        self.sendLine(encoded_string)

        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."""
        logger.debug("[%s] Queueing as conn %r, cmd: %r", self.id(), self.state, cmd)
        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)

    def on_PING(self, line):
        self.received_ping = True

    def on_ERROR(self, cmd):
        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)
        if isinstance(reason, Failure):
            assert reason.type is not None
            connection_close_counter.labels(reason.type.__name__).inc()
        else:
            connection_close_counter.labels(reason.__class__.__name__).inc()

        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 = []

        self.command_handler.lost_connection(self)

        if self.transport:
            self.transport.unregisterProducer()

        # mark the logging context as finished
        self._logging_context.__exit__(None, None, None)

    def __str__(self):
        addr = None
        if self.transport:
            addr = str(self.transport.getPeer())
        return "ReplicationConnection<name=%s,conn_id=%s,addr=%s>" % (
            self.name,
            self.conn_id,
            addr,
        )

    def id(self):
        return "%s-%s" % (self.name, self.conn_id)

    def lineLengthExceeded(self, line):
        """Called when we receive a line that is above the maximum line length"""
        self.send_error("Line length exceeded")
示例#6
0
class RedisSubscriber(txredisapi.SubscriberProtocol):
    """Connection to redis subscribed to replication stream.

    This class fulfils two functions:

    (a) it implements the twisted Protocol API, where it handles the SUBSCRIBEd redis
    connection, parsing *incoming* messages into replication commands, and passing them
    to `ReplicationCommandHandler`

    (b) it implements the IReplicationConnection API, where it sends *outgoing* commands
    onto outbound_redis_connection.

    Due to the vagaries of `txredisapi` we don't want to have a custom
    constructor, so instead we expect the defined attributes below to be set
    immediately after initialisation.

    Attributes:
        synapse_handler: The command handler to handle incoming commands.
        synapse_stream_name: The *redis* stream name to subscribe to and publish
            from (not anything to do with Synapse replication streams).
        synapse_outbound_redis_connection: The connection to redis to use to send
            commands.
    """

    synapse_handler = None  # type: ReplicationCommandHandler
    synapse_stream_name = None  # type: str
    synapse_outbound_redis_connection = None  # type: txredisapi.RedisProtocol

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 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.
        self._logging_context = BackgroundProcessLoggingContext(
            "replication_command_handler")

    def connectionMade(self):
        logger.info("Connected to redis")
        super().connectionMade()
        run_as_background_process("subscribe-replication",
                                  self._send_subscribe)

    async def _send_subscribe(self):
        # it's important to make sure that we only send the REPLICATE command once we
        # have successfully subscribed to the stream - otherwise we might miss the
        # POSITION response sent back by the other end.
        logger.info("Sending redis SUBSCRIBE for %s", self.synapse_stream_name)
        await make_deferred_yieldable(self.subscribe(self.synapse_stream_name))
        logger.info(
            "Successfully subscribed to redis stream, sending REPLICATE command"
        )
        self.synapse_handler.new_connection(self)
        await self._async_send_command(ReplicateCommand())
        logger.info("REPLICATE successfully sent")

        # We send out our positions when there is a new connection in case the
        # other side missed updates. We do this for Redis connections as the
        # otherside won't know we've connected and so won't issue a REPLICATE.
        self.synapse_handler.send_positions_to_connection(self)

    def messageReceived(self, pattern: str, channel: str, message: str):
        """Received a message from redis."""
        with PreserveLoggingContext(self._logging_context):
            self._parse_and_dispatch_message(message)

    def _parse_and_dispatch_message(self, message: str):
        if message.strip() == "":
            # Ignore blank lines
            return

        try:
            cmd = parse_command_from_line(message)
        except Exception:
            logger.exception(
                "Failed to parse replication line: %r",
                message,
            )
            return

        # We use "redis" as the name here as we don't have 1:1 connections to
        # remote instances.
        tcp_inbound_commands_counter.labels(cmd.NAME, "redis").inc()

        self.handle_command(cmd)

    def handle_command(self, cmd: Command) -> None:
        """Handle a command we have received over the replication stream.

        Delegates to `self.handler.on_<COMMAND>` (which can optionally return an
        Awaitable).

        Args:
            cmd: received command
        """

        cmd_func = getattr(self.synapse_handler, "on_%s" % (cmd.NAME, ), None)
        if not cmd_func:
            logger.warning("Unhandled command: %r", cmd)
            return

        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)

    def connectionLost(self, reason):
        logger.info("Lost connection to redis")
        super().connectionLost(reason)
        self.synapse_handler.lost_connection(self)

        # mark the logging context as finished
        self._logging_context.__exit__(None, None, None)

    def send_command(self, cmd: Command):
        """Send a command if connection has been established.

        Args:
            cmd (Command)
        """
        run_as_background_process("send-cmd",
                                  self._async_send_command,
                                  cmd,
                                  bg_start_span=False)

    async def _async_send_command(self, cmd: Command):
        """Encode a replication command and send it over our outbound connection"""
        string = "%s %s" % (cmd.NAME, cmd.to_line())
        if "\n" in string:
            raise Exception("Unexpected newline in command: %r", string)

        encoded_string = string.encode("utf-8")

        # We use "redis" as the name here as we don't have 1:1 connections to
        # remote instances.
        tcp_outbound_commands_counter.labels(cmd.NAME, "redis").inc()

        await make_deferred_yieldable(
            self.synapse_outbound_redis_connection.publish(
                self.synapse_stream_name, encoded_string))