2017-03-27 16:42:07 +02: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.
|
|
|
|
"""The server side of the replication stream.
|
|
|
|
"""
|
|
|
|
|
2018-07-09 08:09:20 +02:00
|
|
|
import logging
|
2019-03-20 17:04:35 +01:00
|
|
|
import random
|
2018-07-09 08:09:20 +02:00
|
|
|
|
|
|
|
from prometheus_client import Counter
|
|
|
|
|
2017-03-27 16:42:07 +02:00
|
|
|
from twisted.internet.protocol import Factory
|
|
|
|
|
2018-07-25 10:41:12 +02:00
|
|
|
from synapse.metrics.background_process_metrics import run_as_background_process
|
2020-04-07 11:51:07 +02:00
|
|
|
from synapse.replication.tcp.protocol import ServerReplicationStreamProtocol
|
|
|
|
from synapse.util.metrics import Measure
|
2017-03-27 16:42:07 +02:00
|
|
|
|
2019-06-20 11:32:02 +02:00
|
|
|
stream_updates_counter = Counter(
|
|
|
|
"synapse_replication_tcp_resource_stream_updates", "", ["stream_name"]
|
|
|
|
)
|
2017-03-27 16:42:07 +02:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class ReplicationStreamProtocolFactory(Factory):
|
|
|
|
"""Factory for new replication connections.
|
|
|
|
"""
|
2019-06-20 11:32:02 +02:00
|
|
|
|
2017-03-27 16:42:07 +02:00
|
|
|
def __init__(self, hs):
|
2020-04-07 11:51:07 +02:00
|
|
|
self.command_handler = hs.get_tcp_replication()
|
2017-03-27 16:42:07 +02:00
|
|
|
self.clock = hs.get_clock()
|
|
|
|
self.server_name = hs.config.server_name
|
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
# If we've created a `ReplicationStreamProtocolFactory` then we're
|
|
|
|
# almost certainly registering a replication listener, so let's ensure
|
|
|
|
# that we've started a `ReplicationStreamer` instance to actually push
|
|
|
|
# data.
|
|
|
|
#
|
|
|
|
# (This is a bit of a weird place to do this, but the alternatives such
|
|
|
|
# as putting this in `HomeServer.setup()`, requires either passing the
|
|
|
|
# listener config again or always starting a `ReplicationStreamer`.)
|
|
|
|
hs.get_replication_streamer()
|
|
|
|
|
2017-03-27 16:42:07 +02:00
|
|
|
def buildProtocol(self, addr):
|
|
|
|
return ServerReplicationStreamProtocol(
|
2020-04-07 11:51:07 +02:00
|
|
|
self.server_name, self.clock, self.command_handler
|
2017-03-27 16:42:07 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-09-04 12:54:56 +02:00
|
|
|
class ReplicationStreamer:
|
2017-03-27 16:42:07 +02:00
|
|
|
"""Handles replication connections.
|
|
|
|
|
|
|
|
This needs to be poked when new replication data may be available. When new
|
|
|
|
data is available it will propagate to all connected clients.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, hs):
|
|
|
|
self.store = hs.get_datastore()
|
|
|
|
self.clock = hs.get_clock()
|
2017-06-09 12:24:41 +02:00
|
|
|
self.notifier = hs.get_notifier()
|
2020-05-07 14:51:08 +02:00
|
|
|
self._instance_name = hs.get_instance_name()
|
2017-03-27 16:42:07 +02:00
|
|
|
|
2019-03-20 17:04:35 +01:00
|
|
|
self._replication_torture_level = hs.config.replication_torture_level
|
|
|
|
|
2020-05-13 11:27:02 +02:00
|
|
|
self.notifier.add_replication_callback(self.on_notifier_poke)
|
2017-03-27 16:42:07 +02:00
|
|
|
|
|
|
|
# Keeps track of whether we are currently checking for updates
|
|
|
|
self.is_looping = False
|
|
|
|
self.pending_updates = False
|
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
self.command_handler = hs.get_tcp_replication()
|
2017-03-27 16:42:07 +02:00
|
|
|
|
2020-05-13 11:27:02 +02:00
|
|
|
# Set of streams to replicate.
|
|
|
|
self.streams = self.command_handler.get_streams_to_replicate()
|
2020-03-25 15:54:01 +01:00
|
|
|
|
2017-03-27 16:42:07 +02:00
|
|
|
def on_notifier_poke(self):
|
|
|
|
"""Checks if there is actually any new data and sends it to the
|
|
|
|
connections if there are.
|
|
|
|
|
|
|
|
This should get called each time new data is available, even if it
|
|
|
|
is currently being executed, so that nothing gets missed
|
|
|
|
"""
|
2020-04-07 11:51:07 +02:00
|
|
|
if not self.command_handler.connected():
|
2017-04-03 16:22:56 +02:00
|
|
|
# Don't bother if nothing is listening. We still need to advance
|
2020-09-14 17:46:58 +02:00
|
|
|
# the stream tokens otherwise they'll fall behind forever
|
2017-04-03 16:22:56 +02:00
|
|
|
for stream in self.streams:
|
2017-04-04 14:19:26 +02:00
|
|
|
stream.discard_updates_and_advance()
|
2017-03-27 16:42:07 +02:00
|
|
|
return
|
|
|
|
|
2018-07-25 10:41:12 +02:00
|
|
|
self.pending_updates = True
|
|
|
|
|
2017-03-27 16:42:07 +02:00
|
|
|
if self.is_looping:
|
2018-07-25 10:41:12 +02:00
|
|
|
logger.debug("Notifier poke loop already running")
|
2017-03-27 16:42:07 +02:00
|
|
|
return
|
|
|
|
|
2018-07-25 10:41:12 +02:00
|
|
|
run_as_background_process("replication_notifier", self._run_notifier_loop)
|
|
|
|
|
2020-01-16 10:16:12 +01:00
|
|
|
async def _run_notifier_loop(self):
|
2017-03-27 16:42:07 +02:00
|
|
|
self.is_looping = True
|
|
|
|
|
|
|
|
try:
|
|
|
|
# Keep looping while there have been pokes about potential updates.
|
|
|
|
# This protects against the race where a stream we already checked
|
|
|
|
# gets an update while we're handling other streams.
|
|
|
|
while self.pending_updates:
|
|
|
|
self.pending_updates = False
|
|
|
|
|
|
|
|
with Measure(self.clock, "repl.stream.get_updates"):
|
2019-03-20 17:04:35 +01:00
|
|
|
all_streams = self.streams
|
|
|
|
|
|
|
|
if self._replication_torture_level is not None:
|
|
|
|
# there is no guarantee about ordering between the streams,
|
|
|
|
# so let's shuffle them around a bit when we are in torture mode.
|
|
|
|
all_streams = list(all_streams)
|
|
|
|
random.shuffle(all_streams)
|
|
|
|
|
|
|
|
for stream in all_streams:
|
2020-05-07 14:51:08 +02:00
|
|
|
if stream.last_token == stream.current_token(
|
|
|
|
self._instance_name
|
|
|
|
):
|
2017-03-27 16:42:07 +02:00
|
|
|
continue
|
|
|
|
|
2019-03-20 17:04:35 +01:00
|
|
|
if self._replication_torture_level:
|
2020-01-16 10:16:12 +01:00
|
|
|
await self.clock.sleep(
|
2019-03-20 17:04:35 +01:00
|
|
|
self._replication_torture_level / 1000.0
|
|
|
|
)
|
|
|
|
|
2017-03-27 16:42:07 +02:00
|
|
|
logger.debug(
|
|
|
|
"Getting stream: %s: %s -> %s",
|
2019-06-20 11:32:02 +02:00
|
|
|
stream.NAME,
|
|
|
|
stream.last_token,
|
2020-05-07 14:51:08 +02:00
|
|
|
stream.current_token(self._instance_name),
|
2017-03-27 16:42:07 +02:00
|
|
|
)
|
2017-10-12 12:50:44 +02:00
|
|
|
try:
|
2020-03-25 15:54:01 +01:00
|
|
|
updates, current_token, limited = await stream.get_updates()
|
|
|
|
self.pending_updates |= limited
|
2017-10-23 16:52:32 +02:00
|
|
|
except Exception:
|
2017-10-12 12:50:44 +02:00
|
|
|
logger.info("Failed to handle stream %s", stream.NAME)
|
|
|
|
raise
|
2017-03-27 16:42:07 +02:00
|
|
|
|
|
|
|
logger.debug(
|
2020-04-07 11:51:07 +02:00
|
|
|
"Sending %d updates", len(updates),
|
2017-03-27 16:42:07 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
if updates:
|
|
|
|
logger.info(
|
|
|
|
"Streaming: %s -> %s", stream.NAME, updates[-1][0]
|
|
|
|
)
|
2018-05-22 02:48:57 +02:00
|
|
|
stream_updates_counter.labels(stream.NAME).inc(len(updates))
|
2017-03-27 16:42:07 +02:00
|
|
|
|
|
|
|
# Some streams return multiple rows with the same stream IDs,
|
|
|
|
# we need to make sure they get sent out in batches. We do
|
|
|
|
# this by setting the current token to all but the last of
|
|
|
|
# a series of updates with the same token to have a None
|
|
|
|
# token. See RdataCommand for more details.
|
|
|
|
batched_updates = _batch_updates(updates)
|
|
|
|
|
2020-04-07 11:51:07 +02:00
|
|
|
for token, row in batched_updates:
|
|
|
|
try:
|
|
|
|
self.command_handler.stream_update(
|
|
|
|
stream.NAME, token, row
|
|
|
|
)
|
|
|
|
except Exception:
|
|
|
|
logger.exception("Failed to replicate")
|
2017-03-27 16:42:07 +02:00
|
|
|
|
|
|
|
logger.debug("No more pending updates, breaking poke loop")
|
|
|
|
finally:
|
|
|
|
self.pending_updates = False
|
|
|
|
self.is_looping = False
|
|
|
|
|
|
|
|
|
|
|
|
def _batch_updates(updates):
|
|
|
|
"""Takes a list of updates of form [(token, row)] and sets the token to
|
|
|
|
None for all rows where the next row has the same token. This is used to
|
|
|
|
implement batching.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
[(1, _), (1, _), (2, _), (3, _), (3, _)]
|
|
|
|
|
|
|
|
becomes:
|
|
|
|
|
|
|
|
[(None, _), (1, _), (2, _), (None, _), (3, _)]
|
|
|
|
"""
|
|
|
|
if not updates:
|
|
|
|
return []
|
|
|
|
|
|
|
|
new_updates = []
|
|
|
|
for i, update in enumerate(updates[:-1]):
|
|
|
|
if update[0] == updates[i + 1][0]:
|
|
|
|
new_updates.append((None, update[1]))
|
|
|
|
else:
|
|
|
|
new_updates.append(update)
|
|
|
|
|
|
|
|
new_updates.append(updates[-1])
|
|
|
|
return new_updates
|