2013-04-23 18:51:17 +02:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2013-01-11 21:16:42 +01:00
|
|
|
from django.conf import settings
|
|
|
|
import pika
|
2016-07-03 15:58:27 +02:00
|
|
|
from pika.adapters.blocking_connection import BlockingChannel
|
|
|
|
from pika.spec import Basic
|
2013-01-18 19:16:34 +01:00
|
|
|
import logging
|
2013-06-18 23:55:55 +02:00
|
|
|
import ujson
|
2013-02-15 17:01:28 +01:00
|
|
|
import random
|
2013-03-11 19:53:41 +01:00
|
|
|
import time
|
2013-03-25 20:37:00 +01:00
|
|
|
import threading
|
2013-04-16 17:49:03 +02:00
|
|
|
import atexit
|
2013-03-11 19:53:41 +01:00
|
|
|
from collections import defaultdict
|
2013-01-11 21:16:42 +01:00
|
|
|
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.lib.utils import statsd
|
2017-03-03 19:01:52 +01:00
|
|
|
from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Union
|
2016-07-03 15:58:27 +02:00
|
|
|
|
|
|
|
Consumer = Callable[[BlockingChannel, Basic.Deliver, pika.BasicProperties, str], None]
|
2013-04-16 22:58:21 +02:00
|
|
|
|
2013-01-11 21:16:42 +01:00
|
|
|
# This simple queuing library doesn't expose much of the power of
|
|
|
|
# rabbitmq/pika's queuing system; its purpose is to just provide an
|
|
|
|
# interface for external files to put things into queues and take them
|
|
|
|
# out from bots without having to import pika code all over our codebase.
|
2013-01-18 19:01:20 +01:00
|
|
|
class SimpleQueueClient(object):
|
2013-01-11 21:16:42 +01:00
|
|
|
def __init__(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-08-06 22:51:47 +02:00
|
|
|
self.log = logging.getLogger('zulip.queue')
|
2017-05-07 17:09:07 +02:00
|
|
|
self.queues = set() # type: Set[str]
|
|
|
|
self.channel = None # type: Optional[BlockingChannel]
|
|
|
|
self.consumers = defaultdict(set) # type: Dict[str, Set[Consumer]]
|
2016-05-08 00:50:43 +02:00
|
|
|
# Disable RabbitMQ heartbeats since BlockingConnection can't process them
|
|
|
|
self.rabbitmq_heartbeat = 0
|
2013-01-18 19:15:09 +01:00
|
|
|
self._connect()
|
2013-01-11 21:16:42 +01:00
|
|
|
|
2013-01-18 19:15:09 +01:00
|
|
|
def _connect(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-09-30 19:40:24 +02:00
|
|
|
start = time.time()
|
2013-01-18 19:15:09 +01:00
|
|
|
self.connection = pika.BlockingConnection(self._get_parameters())
|
|
|
|
self.channel = self.connection.channel()
|
2013-09-30 19:40:24 +02:00
|
|
|
self.log.info('SimpleQueueClient connected (connecting took %.3fs)' % (time.time() - start,))
|
2013-01-18 19:15:09 +01:00
|
|
|
|
2013-03-11 19:53:41 +01:00
|
|
|
def _reconnect(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-03-11 19:53:41 +01:00
|
|
|
self.connection = None
|
|
|
|
self.channel = None
|
|
|
|
self.queues = set()
|
|
|
|
self._connect()
|
|
|
|
|
2013-01-18 19:15:09 +01:00
|
|
|
def _get_parameters(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> pika.ConnectionParameters
|
2016-05-08 00:50:43 +02:00
|
|
|
# We explicitly disable the RabbitMQ heartbeat feature, since
|
|
|
|
# it doesn't make sense with BlockingConnection
|
2016-05-08 00:50:15 +02:00
|
|
|
credentials = pika.PlainCredentials(settings.RABBITMQ_USERNAME,
|
|
|
|
settings.RABBITMQ_PASSWORD)
|
2016-01-21 12:52:24 +01:00
|
|
|
return pika.ConnectionParameters(settings.RABBITMQ_HOST,
|
2016-05-08 00:50:43 +02:00
|
|
|
heartbeat_interval=self.rabbitmq_heartbeat,
|
2016-05-08 00:50:15 +02:00
|
|
|
credentials=credentials)
|
2013-01-17 23:15:40 +01:00
|
|
|
|
2013-02-15 17:01:28 +01:00
|
|
|
def _generate_ctag(self, queue_name):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str) -> str
|
2013-02-15 17:01:28 +01:00
|
|
|
return "%s_%s" % (queue_name, str(random.getrandbits(16)))
|
|
|
|
|
2013-09-09 20:13:40 +02:00
|
|
|
def _reconnect_consumer_callback(self, queue, consumer):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, Consumer) -> None
|
2013-09-09 20:13:40 +02:00
|
|
|
self.log.info("Queue reconnecting saved consumer %s to queue %s" % (consumer, queue))
|
|
|
|
self.ensure_queue(queue, lambda: self.channel.basic_consume(consumer,
|
|
|
|
queue=queue,
|
|
|
|
consumer_tag=self._generate_ctag(queue)))
|
|
|
|
|
2013-04-17 18:11:28 +02:00
|
|
|
def _reconnect_consumer_callbacks(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-03-11 19:53:41 +01:00
|
|
|
for queue, consumers in self.consumers.items():
|
|
|
|
for consumer in consumers:
|
2013-09-09 20:13:40 +02:00
|
|
|
self._reconnect_consumer_callback(queue, consumer)
|
2013-03-11 19:53:41 +01:00
|
|
|
|
2013-04-16 17:49:03 +02:00
|
|
|
def close(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-04-16 17:49:03 +02:00
|
|
|
if self.connection:
|
|
|
|
self.connection.close()
|
|
|
|
|
2013-01-18 19:15:09 +01:00
|
|
|
def ready(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> bool
|
2013-01-18 19:15:09 +01:00
|
|
|
return self.channel is not None
|
|
|
|
|
2013-01-29 00:00:02 +01:00
|
|
|
def ensure_queue(self, queue_name, callback):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, Callable[[], None]) -> None
|
2013-01-29 00:00:02 +01:00
|
|
|
'''Ensure that a given queue has been declared, and then call
|
|
|
|
the callback with no arguments.'''
|
2013-03-11 19:53:41 +01:00
|
|
|
if not self.connection.is_open:
|
|
|
|
self._connect()
|
|
|
|
|
2013-01-29 00:00:02 +01:00
|
|
|
if queue_name not in self.queues:
|
|
|
|
self.channel.queue_declare(queue=queue_name, durable=True)
|
|
|
|
self.queues.add(queue_name)
|
|
|
|
callback()
|
2013-01-11 21:16:42 +01:00
|
|
|
|
|
|
|
def publish(self, queue_name, body):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, str) -> None
|
2013-04-16 22:58:21 +02:00
|
|
|
def do_publish():
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-04-16 22:58:21 +02:00
|
|
|
self.channel.basic_publish(
|
2017-01-24 07:06:13 +01:00
|
|
|
exchange='',
|
|
|
|
routing_key=queue_name,
|
|
|
|
properties=pika.BasicProperties(delivery_mode=2),
|
|
|
|
body=body)
|
2013-04-16 22:58:21 +02:00
|
|
|
|
|
|
|
statsd.incr("rabbitmq.publish.%s" % (queue_name,))
|
|
|
|
|
|
|
|
self.ensure_queue(queue_name, do_publish)
|
2013-01-11 21:16:42 +01:00
|
|
|
|
|
|
|
def json_publish(self, queue_name, body):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, Union[Mapping[str, Any], str]) -> None
|
|
|
|
# Union because of zerver.middleware.write_log_line uses a str
|
2013-03-11 19:53:41 +01:00
|
|
|
try:
|
2016-06-05 21:32:00 +02:00
|
|
|
self.publish(queue_name, ujson.dumps(body))
|
2013-03-11 19:53:41 +01:00
|
|
|
except (AttributeError, pika.exceptions.AMQPConnectionError):
|
|
|
|
self.log.warning("Failed to send to rabbitmq, trying to reconnect and send again")
|
|
|
|
self._reconnect()
|
|
|
|
|
2016-06-05 21:32:00 +02:00
|
|
|
self.publish(queue_name, ujson.dumps(body))
|
2013-01-11 21:16:42 +01:00
|
|
|
|
2013-01-29 00:00:02 +01:00
|
|
|
def register_consumer(self, queue_name, consumer):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, Consumer) -> None
|
2013-01-29 00:00:02 +01:00
|
|
|
def wrapped_consumer(ch, method, properties, body):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (BlockingChannel, Basic.Deliver, pika.BasicProperties, str) -> None
|
2013-10-17 22:52:45 +02:00
|
|
|
try:
|
|
|
|
consumer(ch, method, properties, body)
|
|
|
|
ch.basic_ack(delivery_tag=method.delivery_tag)
|
2015-11-01 17:08:33 +01:00
|
|
|
except Exception as e:
|
2013-10-17 22:52:45 +02:00
|
|
|
ch.basic_nack(delivery_tag=method.delivery_tag)
|
|
|
|
raise e
|
2013-01-11 21:16:42 +01:00
|
|
|
|
2013-03-11 19:53:41 +01:00
|
|
|
self.consumers[queue_name].add(wrapped_consumer)
|
2013-01-29 00:00:02 +01:00
|
|
|
self.ensure_queue(queue_name,
|
2016-12-03 00:04:17 +01:00
|
|
|
lambda: self.channel.basic_consume(wrapped_consumer, queue=queue_name,
|
|
|
|
consumer_tag=self._generate_ctag(queue_name)))
|
2013-01-11 21:16:42 +01:00
|
|
|
|
|
|
|
def register_json_consumer(self, queue_name, callback):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, Callable[[Mapping[str, Any]], None]) -> None
|
2013-01-11 21:16:42 +01:00
|
|
|
def wrapped_callback(ch, method, properties, body):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (BlockingChannel, Basic.Deliver, pika.BasicProperties, str) -> None
|
|
|
|
callback(ujson.loads(body))
|
|
|
|
self.register_consumer(queue_name, wrapped_callback)
|
2013-01-11 21:16:42 +01:00
|
|
|
|
2013-05-03 20:15:29 +02:00
|
|
|
def drain_queue(self, queue_name, json=False):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, bool) -> List[Dict[str, Any]]
|
2013-05-03 20:15:29 +02:00
|
|
|
"Returns all messages in the desired queue"
|
2016-04-20 20:36:09 +02:00
|
|
|
messages = []
|
2016-11-29 07:22:02 +01:00
|
|
|
|
2013-05-03 20:15:29 +02:00
|
|
|
def opened():
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-05-03 20:15:29 +02:00
|
|
|
while True:
|
|
|
|
(meta, _, message) = self.channel.basic_get(queue_name)
|
|
|
|
|
|
|
|
if not message:
|
2016-11-09 13:44:29 +01:00
|
|
|
break
|
2013-05-03 20:15:29 +02:00
|
|
|
|
|
|
|
self.channel.basic_ack(meta.delivery_tag)
|
|
|
|
if json:
|
2013-06-18 23:55:55 +02:00
|
|
|
message = ujson.loads(message)
|
2013-05-03 20:15:29 +02:00
|
|
|
messages.append(message)
|
|
|
|
|
|
|
|
self.ensure_queue(queue_name, opened)
|
|
|
|
return messages
|
|
|
|
|
2013-01-11 21:16:42 +01:00
|
|
|
def start_consuming(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-01-11 21:16:42 +01:00
|
|
|
self.channel.start_consuming()
|
2013-02-15 17:03:28 +01:00
|
|
|
|
|
|
|
def stop_consuming(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-02-15 17:03:28 +01:00
|
|
|
self.channel.stop_consuming()
|
2013-01-18 23:15:23 +01:00
|
|
|
|
2013-04-17 16:11:43 +02:00
|
|
|
# Patch pika.adapters.TornadoConnection so that a socket error doesn't
|
|
|
|
# throw an exception and disconnect the tornado process from the rabbitmq
|
|
|
|
# queue. Instead, just re-connect as usual
|
|
|
|
class ExceptionFreeTornadoConnection(pika.adapters.TornadoConnection):
|
|
|
|
def _adapter_disconnect(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-04-17 16:11:43 +02:00
|
|
|
try:
|
|
|
|
super(ExceptionFreeTornadoConnection, self)._adapter_disconnect()
|
|
|
|
except (pika.exceptions.ProbableAuthenticationError,
|
2013-04-18 21:40:37 +02:00
|
|
|
pika.exceptions.ProbableAccessDeniedError,
|
|
|
|
pika.exceptions.IncompatibleProtocolError) as e:
|
2013-04-17 16:11:43 +02:00
|
|
|
logging.warning("Caught exception '%r' in ExceptionFreeTornadoConnection when \
|
|
|
|
calling _adapter_disconnect, ignoring" % (e,))
|
|
|
|
|
|
|
|
|
2013-01-18 23:15:23 +01:00
|
|
|
class TornadoQueueClient(SimpleQueueClient):
|
|
|
|
# Based on:
|
2016-04-30 01:00:06 +02:00
|
|
|
# https://pika.readthedocs.io/en/0.9.8/examples/asynchronous_consumer_example.html
|
2013-04-17 18:11:28 +02:00
|
|
|
def __init__(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-04-17 18:11:28 +02:00
|
|
|
super(TornadoQueueClient, self).__init__()
|
2016-05-08 00:50:43 +02:00
|
|
|
# Enable rabbitmq heartbeat since TornadoConection can process them
|
|
|
|
self.rabbitmq_heartbeat = None
|
2017-05-07 17:09:07 +02:00
|
|
|
self._on_open_cbs = [] # type: List[Callable[[], None]]
|
2013-01-18 23:15:23 +01:00
|
|
|
|
2013-03-11 19:53:41 +01:00
|
|
|
def _connect(self, on_open_cb = None):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (Optional[Callable[[], None]]) -> None
|
2013-03-11 19:53:41 +01:00
|
|
|
self.log.info("Beginning TornadoQueueClient connection")
|
2016-07-03 15:58:27 +02:00
|
|
|
if on_open_cb is not None:
|
2013-03-19 19:29:22 +01:00
|
|
|
self._on_open_cbs.append(on_open_cb)
|
2013-04-17 16:11:43 +02:00
|
|
|
self.connection = ExceptionFreeTornadoConnection(
|
2013-01-18 23:15:23 +01:00
|
|
|
self._get_parameters(),
|
2013-01-29 00:00:24 +01:00
|
|
|
on_open_callback = self._on_open,
|
|
|
|
stop_ioloop_on_close = False)
|
2013-04-17 17:16:23 +02:00
|
|
|
self.connection.add_on_close_callback(self._on_connection_closed)
|
2013-01-18 23:15:23 +01:00
|
|
|
|
2013-04-17 18:11:28 +02:00
|
|
|
def _reconnect(self):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-03-11 19:53:41 +01:00
|
|
|
self.connection = None
|
|
|
|
self.channel = None
|
|
|
|
self.queues = set()
|
2013-04-17 18:11:28 +02:00
|
|
|
self._connect()
|
2013-03-11 19:53:41 +01:00
|
|
|
|
2013-01-18 23:15:23 +01:00
|
|
|
def _on_open(self, connection):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (pika.Connection) -> None
|
2013-01-18 23:15:23 +01:00
|
|
|
self.connection.channel(
|
|
|
|
on_open_callback = self._on_channel_open)
|
|
|
|
|
|
|
|
def _on_channel_open(self, channel):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (BlockingChannel) -> None
|
2013-01-18 23:15:23 +01:00
|
|
|
self.channel = channel
|
2013-03-19 19:29:22 +01:00
|
|
|
for callback in self._on_open_cbs:
|
|
|
|
callback()
|
2013-04-17 18:11:28 +02:00
|
|
|
self._reconnect_consumer_callbacks()
|
2013-01-18 23:15:23 +01:00
|
|
|
self.log.info('TornadoQueueClient connected')
|
2013-01-29 00:00:02 +01:00
|
|
|
|
2013-10-09 00:35:58 +02:00
|
|
|
def _on_connection_closed(self, connection, reply_code, reply_text):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (pika.Connection, int, str) -> None
|
2013-03-11 19:53:41 +01:00
|
|
|
self.log.warning("TornadoQueueClient lost connection to RabbitMQ, reconnecting...")
|
|
|
|
from tornado import ioloop
|
|
|
|
|
|
|
|
# Try to reconnect in two seconds
|
|
|
|
retry_seconds = 2
|
2016-11-29 07:22:02 +01:00
|
|
|
|
2013-03-11 19:53:41 +01:00
|
|
|
def on_timeout():
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-03-11 19:53:41 +01:00
|
|
|
try:
|
2013-04-17 18:11:28 +02:00
|
|
|
self._reconnect()
|
2013-03-11 19:53:41 +01:00
|
|
|
except pika.exceptions.AMQPConnectionError:
|
|
|
|
self.log.critical("Failed to reconnect to RabbitMQ, retrying...")
|
|
|
|
ioloop.IOLoop.instance().add_timeout(time.time() + retry_seconds, on_timeout)
|
|
|
|
|
|
|
|
ioloop.IOLoop.instance().add_timeout(time.time() + retry_seconds, on_timeout)
|
|
|
|
|
2013-01-29 00:00:02 +01:00
|
|
|
def ensure_queue(self, queue_name, callback):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, Callable[[], None]) -> None
|
2013-01-29 00:00:02 +01:00
|
|
|
def finish(frame):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (Any) -> None
|
2013-01-29 00:00:02 +01:00
|
|
|
self.queues.add(queue_name)
|
|
|
|
callback()
|
|
|
|
|
|
|
|
if queue_name not in self.queues:
|
2013-04-16 16:01:18 +02:00
|
|
|
# If we're not connected yet, send this message
|
|
|
|
# once we have created the channel
|
|
|
|
if not self.ready():
|
|
|
|
self._on_open_cbs.append(lambda: self.ensure_queue(queue_name, callback))
|
|
|
|
return
|
|
|
|
|
|
|
|
self.channel.queue_declare(queue=queue_name, durable=True, callback=finish)
|
2013-01-29 00:00:02 +01:00
|
|
|
else:
|
|
|
|
callback()
|
2013-03-19 19:29:22 +01:00
|
|
|
|
|
|
|
def register_consumer(self, queue_name, consumer):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, Consumer) -> None
|
2013-03-19 19:29:22 +01:00
|
|
|
def wrapped_consumer(ch, method, properties, body):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (BlockingChannel, Basic.Deliver, pika.BasicProperties, str) -> None
|
2013-03-19 19:29:22 +01:00
|
|
|
consumer(ch, method, properties, body)
|
|
|
|
ch.basic_ack(delivery_tag=method.delivery_tag)
|
|
|
|
|
|
|
|
if not self.ready():
|
2013-04-17 18:11:28 +02:00
|
|
|
self.consumers[queue_name].add(wrapped_consumer)
|
2013-03-19 19:29:22 +01:00
|
|
|
return
|
|
|
|
|
|
|
|
self.consumers[queue_name].add(wrapped_consumer)
|
|
|
|
self.ensure_queue(queue_name,
|
2016-12-03 00:04:17 +01:00
|
|
|
lambda: self.channel.basic_consume(wrapped_consumer, queue=queue_name,
|
|
|
|
consumer_tag=self._generate_ctag(queue_name)))
|
2013-03-25 20:37:00 +01:00
|
|
|
|
2017-05-07 17:09:07 +02:00
|
|
|
queue_client = None # type: Optional[SimpleQueueClient]
|
2013-10-23 22:33:59 +02:00
|
|
|
def get_queue_client():
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> SimpleQueueClient
|
2013-10-23 22:33:59 +02:00
|
|
|
global queue_client
|
|
|
|
if queue_client is None:
|
|
|
|
if settings.RUNNING_INSIDE_TORNADO and settings.USING_RABBITMQ:
|
|
|
|
queue_client = TornadoQueueClient()
|
|
|
|
elif settings.USING_RABBITMQ:
|
|
|
|
queue_client = SimpleQueueClient()
|
|
|
|
|
|
|
|
return queue_client
|
2013-03-25 20:37:00 +01:00
|
|
|
|
2013-04-16 17:49:03 +02:00
|
|
|
def setup_tornado_rabbitmq():
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: () -> None
|
2013-04-16 17:49:03 +02:00
|
|
|
# When tornado is shut down, disconnect cleanly from rabbitmq
|
2013-05-08 00:32:33 +02:00
|
|
|
if settings.USING_RABBITMQ:
|
|
|
|
atexit.register(lambda: queue_client.close())
|
2013-04-16 17:49:03 +02:00
|
|
|
|
2013-03-25 20:37:00 +01:00
|
|
|
# We using a simple lock to prevent multiple RabbitMQ messages being
|
|
|
|
# sent to the SimpleQueueClient at the same time; this is a workaround
|
|
|
|
# for an issue with the pika BlockingConnection where using
|
|
|
|
# BlockingConnection for multiple queues causes the channel to
|
|
|
|
# randomly close.
|
|
|
|
queue_lock = threading.RLock()
|
|
|
|
|
|
|
|
def queue_json_publish(queue_name, event, processor):
|
2016-07-03 15:58:27 +02:00
|
|
|
# type: (str, Union[Mapping[str, Any], str], Callable[[Any], None]) -> None
|
|
|
|
# most events are dicts, but zerver.middleware.write_log_line uses a str
|
2013-03-25 20:37:00 +01:00
|
|
|
with queue_lock:
|
|
|
|
if settings.USING_RABBITMQ:
|
2013-10-23 22:33:59 +02:00
|
|
|
get_queue_client().json_publish(queue_name, event)
|
2013-03-25 20:37:00 +01:00
|
|
|
else:
|
|
|
|
processor(event)
|