2015-01-22 09:37:08 -07:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# Copyright 2014, 2015 OpenMarket 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.
|
|
|
|
|
|
|
|
|
|
|
|
from twisted.internet import defer
|
|
|
|
|
2015-01-26 03:45:24 -07:00
|
|
|
from .persistence import TransactionActions
|
2015-01-22 09:37:08 -07:00
|
|
|
from .units import Transaction
|
|
|
|
|
2015-02-04 09:28:12 -07:00
|
|
|
from synapse.api.errors import HttpResponseException
|
2015-01-22 09:37:08 -07:00
|
|
|
from synapse.util.logutils import log_function
|
|
|
|
from synapse.util.logcontext import PreserveLoggingContext
|
2015-02-17 10:20:56 -07:00
|
|
|
from synapse.util.retryutils import (
|
|
|
|
get_retry_limiter, NotRetryingDestination,
|
|
|
|
)
|
2015-03-04 11:15:34 -07:00
|
|
|
import synapse.metrics
|
2015-01-22 09:37:08 -07:00
|
|
|
|
|
|
|
import logging
|
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2015-03-04 11:15:34 -07:00
|
|
|
metrics = synapse.metrics.get_metrics_for(__name__)
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
|
|
|
|
class TransactionQueue(object):
|
|
|
|
"""This class makes sure we only have one transaction in flight at
|
|
|
|
a time for a given destination.
|
|
|
|
|
|
|
|
It batches pending PDUs into single transactions.
|
|
|
|
"""
|
|
|
|
|
2015-01-26 03:45:24 -07:00
|
|
|
def __init__(self, hs, transport_layer):
|
2015-01-22 09:37:08 -07:00
|
|
|
self.server_name = hs.hostname
|
2015-01-26 03:45:24 -07:00
|
|
|
|
|
|
|
self.store = hs.get_datastore()
|
|
|
|
self.transaction_actions = TransactionActions(self.store)
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
self.transport_layer = transport_layer
|
|
|
|
|
|
|
|
self._clock = hs.get_clock()
|
|
|
|
|
|
|
|
# Is a mapping from destinations -> deferreds. Used to keep track
|
|
|
|
# of which destinations have transactions in flight and when they are
|
|
|
|
# done
|
|
|
|
self.pending_transactions = {}
|
|
|
|
|
2015-03-12 10:24:38 -06:00
|
|
|
metrics.register_callback(
|
|
|
|
"pending_destinations",
|
2015-03-10 12:24:52 -06:00
|
|
|
lambda: len(self.pending_transactions),
|
|
|
|
)
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
# Is a mapping from destination -> list of
|
|
|
|
# tuple(pending pdus, deferred, order)
|
2015-03-04 11:15:34 -07:00
|
|
|
self.pending_pdus_by_dest = pdus = {}
|
2015-01-22 09:37:08 -07:00
|
|
|
# destination -> list of tuple(edu, deferred)
|
2015-03-04 11:15:34 -07:00
|
|
|
self.pending_edus_by_dest = edus = {}
|
2015-01-22 09:37:08 -07:00
|
|
|
|
2015-03-12 10:24:38 -06:00
|
|
|
metrics.register_callback(
|
|
|
|
"pending_pdus",
|
2015-03-10 12:24:52 -06:00
|
|
|
lambda: sum(map(len, pdus.values())),
|
|
|
|
)
|
2015-03-12 10:24:38 -06:00
|
|
|
metrics.register_callback(
|
|
|
|
"pending_edus",
|
2015-03-10 12:24:52 -06:00
|
|
|
lambda: sum(map(len, edus.values())),
|
|
|
|
)
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
# destination -> list of tuple(failure, deferred)
|
|
|
|
self.pending_failures_by_dest = {}
|
|
|
|
|
|
|
|
# HACK to get unique tx id
|
|
|
|
self._next_txn_id = int(self._clock.time_msec())
|
|
|
|
|
2015-02-18 04:51:00 -07:00
|
|
|
def can_send_to(self, destination):
|
|
|
|
"""Can we send messages to the given server?
|
|
|
|
|
|
|
|
We can't send messages to ourselves. If we are running on localhost
|
|
|
|
then we can only federation with other servers running on localhost.
|
|
|
|
Otherwise we only federate with servers on a public domain.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
destination(str): The server we are possibly trying to send to.
|
|
|
|
Returns:
|
|
|
|
bool: True if we can send to the server.
|
|
|
|
"""
|
|
|
|
|
|
|
|
if destination == self.server_name:
|
|
|
|
return False
|
|
|
|
if self.server_name.startswith("localhost"):
|
|
|
|
return destination.startswith("localhost")
|
|
|
|
else:
|
|
|
|
return not destination.startswith("localhost")
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
@defer.inlineCallbacks
|
|
|
|
def enqueue_pdu(self, pdu, destinations, order):
|
|
|
|
# We loop through all destinations to see whether we already have
|
|
|
|
# a transaction in progress. If we do, stick it in the pending_pdus
|
|
|
|
# table and we'll get back to it later.
|
|
|
|
|
|
|
|
destinations = set(destinations)
|
2015-02-18 04:51:00 -07:00
|
|
|
destinations = set(
|
|
|
|
dest for dest in destinations if self.can_send_to(dest)
|
|
|
|
)
|
2015-01-22 09:37:08 -07:00
|
|
|
|
|
|
|
logger.debug("Sending to: %s", str(destinations))
|
|
|
|
|
|
|
|
if not destinations:
|
|
|
|
return
|
|
|
|
|
|
|
|
deferreds = []
|
|
|
|
|
|
|
|
for destination in destinations:
|
|
|
|
deferred = defer.Deferred()
|
|
|
|
self.pending_pdus_by_dest.setdefault(destination, []).append(
|
|
|
|
(pdu, deferred, order)
|
|
|
|
)
|
|
|
|
|
2015-02-18 05:03:12 -07:00
|
|
|
def chain(failure):
|
2015-01-22 09:37:08 -07:00
|
|
|
if not deferred.called:
|
|
|
|
deferred.errback(failure)
|
2015-02-18 05:03:12 -07:00
|
|
|
|
2015-03-10 04:28:24 -06:00
|
|
|
def log_failure(f):
|
|
|
|
logger.warn("Failed to send pdu to %s: %s", destination, f.value)
|
2015-02-18 05:03:12 -07:00
|
|
|
|
|
|
|
deferred.addErrback(log_failure)
|
2015-01-22 09:37:08 -07:00
|
|
|
|
|
|
|
with PreserveLoggingContext():
|
2015-02-18 05:03:12 -07:00
|
|
|
self._attempt_new_transaction(destination).addErrback(chain)
|
2015-01-22 09:37:08 -07:00
|
|
|
|
|
|
|
deferreds.append(deferred)
|
|
|
|
|
2015-02-17 03:03:23 -07:00
|
|
|
yield defer.DeferredList(deferreds, consumeErrors=True)
|
2015-01-22 09:37:08 -07:00
|
|
|
|
|
|
|
# NO inlineCallbacks
|
|
|
|
def enqueue_edu(self, edu):
|
|
|
|
destination = edu.destination
|
|
|
|
|
2015-02-18 04:51:00 -07:00
|
|
|
if not self.can_send_to(destination):
|
2015-01-22 09:37:08 -07:00
|
|
|
return
|
|
|
|
|
|
|
|
deferred = defer.Deferred()
|
|
|
|
self.pending_edus_by_dest.setdefault(destination, []).append(
|
|
|
|
(edu, deferred)
|
|
|
|
)
|
|
|
|
|
2015-02-18 05:03:12 -07:00
|
|
|
def chain(failure):
|
2015-01-22 09:37:08 -07:00
|
|
|
if not deferred.called:
|
|
|
|
deferred.errback(failure)
|
2015-02-18 05:03:12 -07:00
|
|
|
|
2015-03-10 04:28:24 -06:00
|
|
|
def log_failure(f):
|
|
|
|
logger.warn("Failed to send edu to %s: %s", destination, f.value)
|
2015-02-18 05:03:12 -07:00
|
|
|
|
|
|
|
deferred.addErrback(log_failure)
|
2015-01-22 09:37:08 -07:00
|
|
|
|
|
|
|
with PreserveLoggingContext():
|
2015-02-18 05:03:12 -07:00
|
|
|
self._attempt_new_transaction(destination).addErrback(chain)
|
2015-01-22 09:37:08 -07:00
|
|
|
|
|
|
|
return deferred
|
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
|
|
|
def enqueue_failure(self, failure, destination):
|
2015-02-18 04:32:39 -07:00
|
|
|
if destination == self.server_name or destination == "localhost":
|
2015-02-18 04:30:37 -07:00
|
|
|
return
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
deferred = defer.Deferred()
|
|
|
|
|
2015-02-18 04:51:00 -07:00
|
|
|
if not self.can_send_to(destination):
|
|
|
|
return
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
self.pending_failures_by_dest.setdefault(
|
|
|
|
destination, []
|
|
|
|
).append(
|
|
|
|
(failure, deferred)
|
|
|
|
)
|
|
|
|
|
2015-02-18 05:03:12 -07:00
|
|
|
def chain(f):
|
2015-02-17 06:58:52 -07:00
|
|
|
if not deferred.called:
|
2015-02-18 05:03:12 -07:00
|
|
|
deferred.errback(f)
|
|
|
|
|
|
|
|
def log_failure(f):
|
2015-03-10 04:28:24 -06:00
|
|
|
logger.warn("Failed to send failure to %s: %s", destination, f.value)
|
2015-02-18 05:03:12 -07:00
|
|
|
|
|
|
|
deferred.addErrback(log_failure)
|
2015-02-17 06:58:52 -07:00
|
|
|
|
|
|
|
with PreserveLoggingContext():
|
2015-02-18 05:03:12 -07:00
|
|
|
self._attempt_new_transaction(destination).addErrback(chain)
|
2015-02-17 06:58:52 -07:00
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
yield deferred
|
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
|
|
|
@log_function
|
|
|
|
def _attempt_new_transaction(self, destination):
|
|
|
|
if destination in self.pending_transactions:
|
|
|
|
# XXX: pending_transactions can get stuck on by a never-ending
|
|
|
|
# request at which point pending_pdus_by_dest just keeps growing.
|
|
|
|
# we need application-layer timeouts of some flavour of these
|
|
|
|
# requests
|
2015-02-10 10:30:46 -07:00
|
|
|
logger.info(
|
|
|
|
"TX [%s] Transaction already in progress",
|
|
|
|
destination
|
|
|
|
)
|
2015-01-22 09:37:08 -07:00
|
|
|
return
|
|
|
|
|
2015-02-10 10:30:46 -07:00
|
|
|
logger.info("TX [%s] _attempt_new_transaction", destination)
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
# list of (pending_pdu, deferred, order)
|
|
|
|
pending_pdus = self.pending_pdus_by_dest.pop(destination, [])
|
|
|
|
pending_edus = self.pending_edus_by_dest.pop(destination, [])
|
|
|
|
pending_failures = self.pending_failures_by_dest.pop(destination, [])
|
|
|
|
|
|
|
|
if pending_pdus:
|
|
|
|
logger.info("TX [%s] len(pending_pdus_by_dest[dest]) = %d",
|
|
|
|
destination, len(pending_pdus))
|
|
|
|
|
|
|
|
if not pending_pdus and not pending_edus and not pending_failures:
|
2015-02-10 10:30:46 -07:00
|
|
|
logger.info("TX [%s] Nothing to send", destination)
|
2015-01-22 09:37:08 -07:00
|
|
|
return
|
|
|
|
|
|
|
|
# Sort based on the order field
|
|
|
|
pending_pdus.sort(key=lambda t: t[2])
|
|
|
|
|
|
|
|
pdus = [x[0] for x in pending_pdus]
|
|
|
|
edus = [x[0] for x in pending_edus]
|
|
|
|
failures = [x[0].get_dict() for x in pending_failures]
|
|
|
|
deferreds = [
|
|
|
|
x[1]
|
|
|
|
for x in pending_pdus + pending_edus + pending_failures
|
|
|
|
]
|
|
|
|
|
|
|
|
try:
|
2015-02-26 08:47:35 -07:00
|
|
|
self.pending_transactions[destination] = 1
|
|
|
|
|
2015-02-17 10:20:56 -07:00
|
|
|
limiter = yield get_retry_limiter(
|
|
|
|
destination,
|
|
|
|
self._clock,
|
|
|
|
self.store,
|
2015-01-22 09:37:08 -07:00
|
|
|
)
|
|
|
|
|
2015-02-17 11:13:34 -07:00
|
|
|
logger.debug(
|
|
|
|
"TX [%s] Attempting new transaction"
|
|
|
|
" (pdus: %d, edus: %d, failures: %d)",
|
|
|
|
destination,
|
|
|
|
len(pending_pdus),
|
|
|
|
len(pending_edus),
|
|
|
|
len(pending_failures)
|
|
|
|
)
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
logger.debug("TX [%s] Persisting transaction...", destination)
|
|
|
|
|
|
|
|
transaction = Transaction.create_new(
|
|
|
|
origin_server_ts=int(self._clock.time_msec()),
|
|
|
|
transaction_id=str(self._next_txn_id),
|
|
|
|
origin=self.server_name,
|
|
|
|
destination=destination,
|
|
|
|
pdus=pdus,
|
|
|
|
edus=edus,
|
|
|
|
pdu_failures=failures,
|
|
|
|
)
|
|
|
|
|
|
|
|
self._next_txn_id += 1
|
|
|
|
|
|
|
|
yield self.transaction_actions.prepare_to_send(transaction)
|
|
|
|
|
|
|
|
logger.debug("TX [%s] Persisted transaction", destination)
|
|
|
|
logger.info(
|
|
|
|
"TX [%s] Sending transaction [%s]",
|
|
|
|
destination,
|
|
|
|
transaction.transaction_id,
|
|
|
|
)
|
|
|
|
|
2015-02-17 11:13:34 -07:00
|
|
|
with limiter:
|
2015-02-17 10:20:56 -07:00
|
|
|
# Actually send the transaction
|
|
|
|
|
|
|
|
# FIXME (erikj): This is a bit of a hack to make the Pdu age
|
|
|
|
# keys work
|
|
|
|
def json_data_cb():
|
|
|
|
data = transaction.get_dict()
|
|
|
|
now = int(self._clock.time_msec())
|
|
|
|
if "pdus" in data:
|
|
|
|
for p in data["pdus"]:
|
|
|
|
if "age_ts" in p:
|
|
|
|
unsigned = p.setdefault("unsigned", {})
|
|
|
|
unsigned["age"] = now - int(p["age_ts"])
|
|
|
|
del p["age_ts"]
|
|
|
|
return data
|
|
|
|
|
|
|
|
try:
|
|
|
|
response = yield self.transport_layer.send_transaction(
|
|
|
|
transaction, json_data_cb
|
|
|
|
)
|
|
|
|
code = 200
|
2015-02-18 03:34:40 -07:00
|
|
|
|
|
|
|
if response:
|
2015-02-23 06:58:02 -07:00
|
|
|
for e_id, r in response.get("pdus", {}).items():
|
2015-02-18 03:34:40 -07:00
|
|
|
if "error" in r:
|
|
|
|
logger.warn(
|
|
|
|
"Transaction returned error for %s: %s",
|
|
|
|
e_id, r,
|
|
|
|
)
|
2015-02-17 10:20:56 -07:00
|
|
|
except HttpResponseException as e:
|
|
|
|
code = e.code
|
|
|
|
response = e.response
|
2015-01-22 09:37:08 -07:00
|
|
|
|
2015-02-17 10:20:56 -07:00
|
|
|
logger.info("TX [%s] got %d response", destination, code)
|
2015-01-22 09:37:08 -07:00
|
|
|
|
2015-02-17 10:20:56 -07:00
|
|
|
logger.debug("TX [%s] Sent transaction", destination)
|
|
|
|
logger.debug("TX [%s] Marking as delivered...", destination)
|
|
|
|
|
2015-01-22 09:37:08 -07:00
|
|
|
yield self.transaction_actions.delivered(
|
|
|
|
transaction, code, response
|
|
|
|
)
|
|
|
|
|
|
|
|
logger.debug("TX [%s] Marked as delivered", destination)
|
|
|
|
|
|
|
|
logger.debug("TX [%s] Yielding to callbacks...", destination)
|
|
|
|
|
|
|
|
for deferred in deferreds:
|
|
|
|
if code == 200:
|
|
|
|
deferred.callback(None)
|
|
|
|
else:
|
|
|
|
deferred.errback(RuntimeError("Got status %d" % code))
|
|
|
|
|
|
|
|
# Ensures we don't continue until all callbacks on that
|
|
|
|
# deferred have fired
|
|
|
|
try:
|
|
|
|
yield deferred
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
|
|
|
logger.debug("TX [%s] Yielded to callbacks", destination)
|
2015-02-17 10:20:56 -07:00
|
|
|
except NotRetryingDestination:
|
|
|
|
logger.info(
|
|
|
|
"TX [%s] not ready for retry yet - "
|
|
|
|
"dropping transaction for now",
|
|
|
|
destination,
|
|
|
|
)
|
2015-02-04 09:28:12 -07:00
|
|
|
except RuntimeError as e:
|
2015-01-22 09:37:08 -07:00
|
|
|
# We capture this here as there as nothing actually listens
|
|
|
|
# for this finishing functions deferred.
|
|
|
|
logger.warn(
|
|
|
|
"TX [%s] Problem in _attempt_transaction: %s",
|
|
|
|
destination,
|
|
|
|
e,
|
|
|
|
)
|
2015-02-04 09:28:12 -07:00
|
|
|
except Exception as e:
|
|
|
|
# We capture this here as there as nothing actually listens
|
|
|
|
# for this finishing functions deferred.
|
2015-02-18 05:03:12 -07:00
|
|
|
logger.warn(
|
2015-02-04 09:28:12 -07:00
|
|
|
"TX [%s] Problem in _attempt_transaction: %s",
|
|
|
|
destination,
|
|
|
|
e,
|
|
|
|
)
|
2015-01-22 09:37:08 -07:00
|
|
|
|
|
|
|
for deferred in deferreds:
|
|
|
|
if not deferred.called:
|
|
|
|
deferred.errback(e)
|
|
|
|
|
|
|
|
finally:
|
|
|
|
# We want to be *very* sure we delete this after we stop processing
|
|
|
|
self.pending_transactions.pop(destination, None)
|
|
|
|
|
|
|
|
# Check to see if there is anything else to send.
|
|
|
|
self._attempt_new_transaction(destination)
|