2013-04-23 18:51:17 +02:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2013-03-26 18:06:00 +01:00
|
|
|
from django.conf import settings
|
|
|
|
from collections import deque
|
2013-03-20 23:03:41 +01:00
|
|
|
import os
|
2013-03-26 18:06:00 +01:00
|
|
|
import time
|
|
|
|
import socket
|
|
|
|
import logging
|
2013-06-18 23:55:55 +02:00
|
|
|
import ujson
|
2013-03-14 23:21:53 +01:00
|
|
|
import requests
|
2013-03-20 23:03:41 +01:00
|
|
|
import cPickle as pickle
|
|
|
|
import atexit
|
|
|
|
import sys
|
|
|
|
import signal
|
2013-03-22 23:24:28 +01:00
|
|
|
import tornado
|
2013-03-22 23:25:37 +01:00
|
|
|
import random
|
2013-11-07 00:34:50 +01:00
|
|
|
import traceback
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.lib.utils import statsd
|
|
|
|
from zerver.middleware import async_request_restart
|
2013-11-19 23:51:32 +01:00
|
|
|
from zerver.models import get_client
|
2013-11-22 20:30:32 +01:00
|
|
|
import copy
|
2013-03-26 18:06:00 +01:00
|
|
|
|
2013-04-18 22:17:48 +02:00
|
|
|
# The idle timeout used to be a week, but we found that in that
|
|
|
|
# situation, queues from dead browser sessions would grow quite large
|
|
|
|
# due to the accumulation of message data in those queues.
|
|
|
|
IDLE_EVENT_QUEUE_TIMEOUT_SECS = 60 * 10
|
|
|
|
EVENT_QUEUE_GC_FREQ_MSECS = 1000 * 60 * 5
|
2013-08-05 22:09:12 +02:00
|
|
|
|
|
|
|
# Capped limit for how long a client can request an event queue
|
|
|
|
# to live
|
|
|
|
MAX_QUEUE_TIMEOUT_SECS = 7 * 24 * 60 * 60
|
|
|
|
|
2013-03-28 22:39:43 +01:00
|
|
|
# The heartbeats effectively act as a server-side timeout for
|
|
|
|
# get_events(). The actual timeout value is randomized for each
|
|
|
|
# client connection based on the below value. We ensure that the
|
|
|
|
# maximum timeout value is 55 seconds, to deal with crappy home
|
|
|
|
# wireless routers that kill "inactive" http connections.
|
|
|
|
HEARTBEAT_MIN_FREQ_SECS = 45
|
2013-03-26 18:06:00 +01:00
|
|
|
|
|
|
|
class ClientDescriptor(object):
|
2013-11-19 23:11:53 +01:00
|
|
|
def __init__(self, user_profile_id, realm_id, event_queue, event_types, client_type,
|
2013-10-17 23:51:25 +02:00
|
|
|
apply_markdown=True, all_public_streams=False, lifespan_secs=0):
|
2013-11-19 23:51:32 +01:00
|
|
|
# These objects are serialized on shutdown and restored on restart.
|
2013-10-17 23:51:25 +02:00
|
|
|
# If fields are added or semantics are changed, temporary code must be
|
2013-11-19 23:51:32 +01:00
|
|
|
# added to load_event_queues() to update the restored objects.
|
|
|
|
# Additionally, the to_dict and from_dict methods must be updated
|
2013-03-26 18:06:00 +01:00
|
|
|
self.user_profile_id = user_profile_id
|
2013-10-17 23:51:25 +02:00
|
|
|
self.realm_id = realm_id
|
2013-03-26 18:06:00 +01:00
|
|
|
self.current_handler = None
|
2013-11-19 23:11:53 +01:00
|
|
|
self.event_queue = event_queue
|
2013-08-05 22:09:12 +02:00
|
|
|
self.queue_timeout = lifespan_secs
|
2013-03-22 22:43:49 +01:00
|
|
|
self.event_types = event_types
|
2013-03-26 18:06:00 +01:00
|
|
|
self.last_connection_time = time.time()
|
|
|
|
self.apply_markdown = apply_markdown
|
2013-10-17 23:51:25 +02:00
|
|
|
self.all_public_streams = all_public_streams
|
2013-05-03 17:17:08 +02:00
|
|
|
self.client_type = client_type
|
2013-03-22 23:25:37 +01:00
|
|
|
self._timeout_handle = None
|
|
|
|
|
2013-08-05 22:09:12 +02:00
|
|
|
# Clamp queue_timeout to between minimum and maximum timeouts
|
|
|
|
self.queue_timeout = max(IDLE_EVENT_QUEUE_TIMEOUT_SECS, min(self.queue_timeout, MAX_QUEUE_TIMEOUT_SECS))
|
|
|
|
|
2013-11-19 23:51:32 +01:00
|
|
|
def to_dict(self):
|
2013-11-22 20:30:32 +01:00
|
|
|
# If you add a new key to this dict, make sure you add appropriate
|
|
|
|
# migration code in from_dict or load_event_queues to account for
|
|
|
|
# loading event queues that lack that key.
|
2013-11-19 23:51:32 +01:00
|
|
|
return dict(user_profile_id=self.user_profile_id,
|
|
|
|
realm_id=self.realm_id,
|
|
|
|
event_queue=self.event_queue.to_dict(),
|
|
|
|
queue_timeout=self.queue_timeout,
|
|
|
|
event_types=self.event_types,
|
|
|
|
last_connection_time=self.last_connection_time,
|
|
|
|
apply_markdown=self.apply_markdown,
|
|
|
|
all_public_streams=self.all_public_streams,
|
|
|
|
client_type=self.client_type.name)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_dict(cls, d):
|
|
|
|
ret = cls(d['user_profile_id'], d['realm_id'],
|
|
|
|
EventQueue.from_dict(d['event_queue']), d['event_types'],
|
|
|
|
get_client(d['client_type']), d['apply_markdown'], d['all_public_streams'],
|
|
|
|
d['queue_timeout'])
|
|
|
|
ret.last_connection_time = d['last_connection_time']
|
|
|
|
return ret
|
|
|
|
|
2013-03-22 23:25:37 +01:00
|
|
|
def prepare_for_pickling(self):
|
|
|
|
self.current_handler = None
|
|
|
|
self._timeout_handle = None
|
2013-03-26 18:06:00 +01:00
|
|
|
|
|
|
|
def add_event(self, event):
|
|
|
|
if self.current_handler is not None:
|
2013-04-23 19:36:50 +02:00
|
|
|
async_request_restart(self.current_handler._request)
|
2013-03-26 18:06:00 +01:00
|
|
|
|
|
|
|
self.event_queue.push(event)
|
2013-12-12 18:59:02 +01:00
|
|
|
self.finish_current_handler()
|
|
|
|
|
|
|
|
def finish_current_handler(self):
|
2013-03-26 18:06:00 +01:00
|
|
|
if self.current_handler is not None:
|
|
|
|
try:
|
2013-12-12 18:59:02 +01:00
|
|
|
# We call async_request_restart here in case we are
|
|
|
|
# being finished without any events (because another
|
|
|
|
# get_events request has supplanted this request)
|
|
|
|
async_request_restart(self.current_handler._request)
|
2013-11-08 20:18:02 +01:00
|
|
|
self.current_handler._request._log_data['extra'] = "[%s/1]" % (self.event_queue.id,)
|
2013-08-06 22:21:12 +02:00
|
|
|
self.current_handler.zulip_finish(dict(result='success', msg='',
|
2013-12-02 21:31:17 +01:00
|
|
|
events=self.event_queue.contents(),
|
2013-08-06 22:21:12 +02:00
|
|
|
queue_id=self.event_queue.id),
|
|
|
|
self.current_handler._request,
|
|
|
|
apply_markdown=self.apply_markdown)
|
2013-12-10 23:40:30 +01:00
|
|
|
except Exception:
|
2013-12-12 18:59:02 +01:00
|
|
|
logging.exception("Got error finishing handler for queue %s" % (self.event_queue.id))
|
2013-12-10 23:44:35 +01:00
|
|
|
finally:
|
|
|
|
self.disconnect_handler()
|
2013-12-12 18:59:02 +01:00
|
|
|
return True
|
|
|
|
return False
|
2013-03-26 18:06:00 +01:00
|
|
|
|
2013-03-22 22:43:49 +01:00
|
|
|
def accepts_event_type(self, type):
|
|
|
|
if self.event_types is None:
|
|
|
|
return True
|
|
|
|
return type in self.event_types
|
|
|
|
|
2013-03-26 18:06:00 +01:00
|
|
|
def idle(self, now):
|
2013-08-05 22:09:12 +02:00
|
|
|
if not hasattr(self, 'queue_timeout'):
|
|
|
|
self.queue_timeout = IDLE_EVENT_QUEUE_TIMEOUT_SECS
|
|
|
|
|
2013-03-26 18:06:00 +01:00
|
|
|
return (self.current_handler is None
|
2013-08-05 22:09:12 +02:00
|
|
|
and now - self.last_connection_time >= self.queue_timeout)
|
2013-03-26 18:06:00 +01:00
|
|
|
|
|
|
|
def connect_handler(self, handler):
|
|
|
|
self.current_handler = handler
|
|
|
|
self.last_connection_time = time.time()
|
2013-11-21 18:52:32 +01:00
|
|
|
def timeout_callback():
|
|
|
|
self._timeout_handle = None
|
|
|
|
# All clients get heartbeat events
|
|
|
|
self.add_event(dict(type='heartbeat'))
|
|
|
|
ioloop = tornado.ioloop.IOLoop.instance()
|
|
|
|
heartbeat_time = time.time() + HEARTBEAT_MIN_FREQ_SECS + random.randint(0, 10)
|
2013-11-27 16:30:28 +01:00
|
|
|
if self.client_type.name != 'API: heartbeat test':
|
|
|
|
self._timeout_handle = ioloop.add_timeout(heartbeat_time, timeout_callback)
|
2013-03-26 18:06:00 +01:00
|
|
|
|
|
|
|
def disconnect_handler(self):
|
|
|
|
self.current_handler = None
|
2013-03-22 23:25:37 +01:00
|
|
|
if self._timeout_handle is not None:
|
|
|
|
ioloop = tornado.ioloop.IOLoop.instance()
|
|
|
|
ioloop.remove_timeout(self._timeout_handle)
|
|
|
|
self._timeout_handle = None
|
2013-03-26 18:06:00 +01:00
|
|
|
|
2013-11-19 23:11:30 +01:00
|
|
|
def cleanup(self):
|
|
|
|
do_gc_event_queues([self.event_queue.id], [self.user_profile_id],
|
|
|
|
[self.realm_id])
|
|
|
|
|
2013-11-22 20:30:32 +01:00
|
|
|
def compute_full_event_type(event):
|
|
|
|
if event["type"] == "update_message_flags":
|
|
|
|
if event["all"]:
|
|
|
|
# Put the "all" case in its own category
|
2013-11-22 21:04:41 +01:00
|
|
|
return "all_flags/%s/%s" % (event["flag"], event["operation"])
|
|
|
|
return "flags/%s/%s" % (event["operation"], event["flag"])
|
2013-11-22 20:30:32 +01:00
|
|
|
return event["type"]
|
|
|
|
|
2013-03-26 18:06:00 +01:00
|
|
|
class EventQueue(object):
|
|
|
|
def __init__(self, id):
|
|
|
|
self.queue = deque()
|
|
|
|
self.next_event_id = 0
|
|
|
|
self.id = id
|
2013-11-22 20:30:32 +01:00
|
|
|
self.virtual_events = {}
|
2013-03-26 18:06:00 +01:00
|
|
|
|
2013-11-19 23:51:32 +01:00
|
|
|
def to_dict(self):
|
2013-11-22 20:30:32 +01:00
|
|
|
# If you add a new key to this dict, make sure you add appropriate
|
|
|
|
# migration code in from_dict or load_event_queues to account for
|
|
|
|
# loading event queues that lack that key.
|
|
|
|
return dict(id=self.id,
|
|
|
|
next_event_id=self.next_event_id,
|
|
|
|
queue=list(self.queue),
|
|
|
|
virtual_events=self.virtual_events)
|
2013-11-19 23:51:32 +01:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_dict(cls, d):
|
|
|
|
ret = cls(d['id'])
|
|
|
|
ret.next_event_id = d['next_event_id']
|
|
|
|
ret.queue = deque(d['queue'])
|
2013-11-22 20:30:32 +01:00
|
|
|
ret.virtual_events = d.get("virtual_events", {})
|
2013-11-19 23:51:32 +01:00
|
|
|
return ret
|
|
|
|
|
2013-03-26 18:06:00 +01:00
|
|
|
def push(self, event):
|
|
|
|
event['id'] = self.next_event_id
|
|
|
|
self.next_event_id += 1
|
2013-11-22 20:30:32 +01:00
|
|
|
full_event_type = compute_full_event_type(event)
|
2013-11-22 21:04:41 +01:00
|
|
|
if (full_event_type in ["pointer", "restart"] or
|
|
|
|
full_event_type.startswith("flags/")):
|
2013-11-22 20:30:32 +01:00
|
|
|
if full_event_type not in self.virtual_events:
|
|
|
|
self.virtual_events[full_event_type] = copy.deepcopy(event)
|
|
|
|
return
|
|
|
|
# Update the virtual event with the values from the event
|
|
|
|
virtual_event = self.virtual_events[full_event_type]
|
|
|
|
virtual_event["id"] = event["id"]
|
|
|
|
if "timestamp" in event:
|
|
|
|
virtual_event["timestamp"] = event["timestamp"]
|
|
|
|
if full_event_type == "pointer":
|
|
|
|
virtual_event["pointer"] = event["pointer"]
|
2013-11-22 20:53:59 +01:00
|
|
|
elif full_event_type == "restart":
|
|
|
|
virtual_event["server_generation"] = event["server_generation"]
|
2013-11-22 21:04:41 +01:00
|
|
|
elif full_event_type.startswith("flags/"):
|
|
|
|
virtual_event["messages"] += event["messages"]
|
2013-11-22 20:30:32 +01:00
|
|
|
else:
|
|
|
|
self.queue.append(event)
|
2013-03-26 18:06:00 +01:00
|
|
|
|
2013-12-11 23:09:59 +01:00
|
|
|
# Note that pop ignores virtual events. This is fine in our
|
|
|
|
# current usage since virtual events should always be resolved to
|
|
|
|
# a real event before being given to users.
|
2013-03-26 18:06:00 +01:00
|
|
|
def pop(self):
|
|
|
|
return self.queue.popleft()
|
|
|
|
|
|
|
|
def empty(self):
|
2013-12-11 22:58:12 +01:00
|
|
|
return len(self.queue) == 0 and len(self.virtual_events) == 0
|
2013-03-26 18:06:00 +01:00
|
|
|
|
2013-12-11 23:09:59 +01:00
|
|
|
# See the comment on pop; that applies here as well
|
2013-03-26 18:06:00 +01:00
|
|
|
def prune(self, through_id):
|
2013-12-11 23:09:59 +01:00
|
|
|
while len(self.queue) != 0 and self.queue[0]['id'] <= through_id:
|
2013-03-26 18:06:00 +01:00
|
|
|
self.pop()
|
|
|
|
|
|
|
|
def contents(self):
|
2013-11-22 20:30:32 +01:00
|
|
|
contents = []
|
|
|
|
virtual_id_map = {}
|
|
|
|
for event_type in self.virtual_events:
|
|
|
|
virtual_id_map[self.virtual_events[event_type]["id"]] = self.virtual_events[event_type]
|
|
|
|
virtual_ids = sorted(list(virtual_id_map.keys()))
|
|
|
|
|
|
|
|
# Merge the virtual events into their final place in the queue
|
|
|
|
index = 0
|
|
|
|
length = len(virtual_ids)
|
|
|
|
for event in self.queue:
|
|
|
|
while index < length and virtual_ids[index] < event["id"]:
|
|
|
|
contents.append(virtual_id_map[virtual_ids[index]])
|
|
|
|
index += 1
|
|
|
|
contents.append(event)
|
|
|
|
while index < length:
|
|
|
|
contents.append(virtual_id_map[virtual_ids[index]])
|
|
|
|
index += 1
|
|
|
|
|
|
|
|
self.virtual_events = {}
|
|
|
|
self.queue = deque(contents)
|
|
|
|
return contents
|
2013-03-26 18:06:00 +01:00
|
|
|
|
|
|
|
# maps queue ids to client descriptors
|
|
|
|
clients = {}
|
|
|
|
# maps user id to list of client descriptors
|
|
|
|
user_clients = {}
|
2013-10-17 23:51:25 +02:00
|
|
|
# maps realm id to list of client descriptors with all_public_streams=True
|
|
|
|
realm_clients_all_streams = {}
|
2013-03-26 18:06:00 +01:00
|
|
|
|
2013-05-22 23:49:02 +02:00
|
|
|
# list of registered gc hooks.
|
|
|
|
# each one will be called with a user profile id, queue, and bool
|
|
|
|
# last_for_client that is true if this is the last queue pertaining
|
|
|
|
# to this user_profile_id
|
|
|
|
# that is about to be deleted
|
|
|
|
gc_hooks = []
|
|
|
|
|
2013-03-26 18:06:00 +01:00
|
|
|
next_queue_id = 0
|
|
|
|
|
2013-05-22 23:49:02 +02:00
|
|
|
def add_client_gc_hook(hook):
|
|
|
|
gc_hooks.append(hook)
|
|
|
|
|
2013-03-27 22:19:24 +01:00
|
|
|
def get_client_descriptor(queue_id):
|
|
|
|
return clients.get(queue_id)
|
|
|
|
|
|
|
|
def get_client_descriptors_for_user(user_profile_id):
|
|
|
|
return user_clients.get(user_profile_id, [])
|
|
|
|
|
2013-10-17 23:51:25 +02:00
|
|
|
def get_client_descriptors_for_realm_all_streams(realm_id):
|
|
|
|
return realm_clients_all_streams.get(realm_id, [])
|
|
|
|
|
|
|
|
def allocate_client_descriptor(user_profile_id, realm_id, event_types, client_type,
|
|
|
|
apply_markdown, all_public_streams, lifespan_secs):
|
2013-03-26 18:06:00 +01:00
|
|
|
global next_queue_id
|
|
|
|
id = str(settings.SERVER_GENERATION) + ':' + str(next_queue_id)
|
|
|
|
next_queue_id += 1
|
2013-11-19 23:11:53 +01:00
|
|
|
client = ClientDescriptor(user_profile_id, realm_id, EventQueue(id), event_types, client_type,
|
2013-10-17 23:51:25 +02:00
|
|
|
apply_markdown, all_public_streams, lifespan_secs)
|
2013-03-26 18:06:00 +01:00
|
|
|
clients[id] = client
|
|
|
|
user_clients.setdefault(user_profile_id, []).append(client)
|
2013-10-17 23:51:25 +02:00
|
|
|
if all_public_streams:
|
|
|
|
realm_clients_all_streams.setdefault(realm_id, []).append(client)
|
2013-03-26 18:06:00 +01:00
|
|
|
return client
|
|
|
|
|
2013-11-19 23:11:30 +01:00
|
|
|
def do_gc_event_queues(to_remove, affected_users, affected_realms):
|
2013-10-17 23:51:25 +02:00
|
|
|
def filter_client_dict(client_dict, key):
|
|
|
|
if key not in client_dict:
|
|
|
|
return
|
2013-03-26 18:06:00 +01:00
|
|
|
|
|
|
|
new_client_list = filter(lambda c: c.event_queue.id not in to_remove,
|
2013-10-17 23:51:25 +02:00
|
|
|
client_dict[key])
|
2013-04-09 19:24:55 +02:00
|
|
|
if len(new_client_list) == 0:
|
2013-10-17 23:51:25 +02:00
|
|
|
del client_dict[key]
|
2013-04-09 19:24:55 +02:00
|
|
|
else:
|
2013-10-17 23:51:25 +02:00
|
|
|
client_dict[key] = new_client_list
|
|
|
|
|
|
|
|
for user_id in affected_users:
|
|
|
|
filter_client_dict(user_clients, user_id)
|
|
|
|
|
|
|
|
for realm_id in affected_realms:
|
|
|
|
filter_client_dict(realm_clients_all_streams, realm_id)
|
2013-03-26 18:06:00 +01:00
|
|
|
|
2013-05-22 23:49:02 +02:00
|
|
|
for id in to_remove:
|
|
|
|
for cb in gc_hooks:
|
|
|
|
cb(clients[id].user_profile_id, clients[id], clients[id].user_profile_id not in user_clients)
|
|
|
|
del clients[id]
|
|
|
|
|
2013-11-19 23:11:30 +01:00
|
|
|
def gc_event_queues():
|
|
|
|
start = time.time()
|
|
|
|
to_remove = set()
|
|
|
|
affected_users = set()
|
|
|
|
affected_realms = set()
|
|
|
|
for (id, client) in clients.iteritems():
|
|
|
|
if client.idle(start):
|
|
|
|
to_remove.add(id)
|
|
|
|
affected_users.add(client.user_profile_id)
|
|
|
|
affected_realms.add(client.realm_id)
|
|
|
|
|
|
|
|
do_gc_event_queues(to_remove, affected_users, affected_realms)
|
|
|
|
|
2013-03-26 18:06:00 +01:00
|
|
|
logging.info(('Tornado removed %d idle event queues owned by %d users in %.3fs.'
|
|
|
|
+ ' Now %d active queues')
|
|
|
|
% (len(to_remove), len(affected_users), time.time() - start,
|
|
|
|
len(clients)))
|
2013-05-24 23:27:19 +02:00
|
|
|
statsd.gauge('tornado.active_queues', len(clients))
|
|
|
|
statsd.gauge('tornado.active_users', len(user_clients))
|
2013-03-26 18:06:00 +01:00
|
|
|
|
2013-03-20 23:03:41 +01:00
|
|
|
def dump_event_queues():
|
|
|
|
start = time.time()
|
|
|
|
|
2013-11-19 23:51:32 +01:00
|
|
|
with file(settings.JSON_PERSISTENT_QUEUE_FILENAME, "w") as stored_queues:
|
|
|
|
ujson.dump([(qid, client.to_dict()) for (qid, client) in clients.iteritems()],
|
|
|
|
stored_queues)
|
2013-03-20 23:03:41 +01:00
|
|
|
|
|
|
|
logging.info('Tornado dumped %d event queues in %.3fs'
|
|
|
|
% (len(clients), time.time() - start))
|
|
|
|
|
2013-03-20 23:53:46 +01:00
|
|
|
def load_event_queues():
|
2013-03-20 23:03:41 +01:00
|
|
|
global clients
|
|
|
|
start = time.time()
|
2013-11-19 23:51:32 +01:00
|
|
|
|
|
|
|
if os.path.exists(settings.PERSISTENT_QUEUE_FILENAME):
|
|
|
|
try:
|
|
|
|
with file(settings.PERSISTENT_QUEUE_FILENAME, "r") as stored_queues:
|
|
|
|
clients = pickle.load(stored_queues)
|
|
|
|
except (IOError, EOFError):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
# ujson chokes on bad input pretty easily. We separate out the actual
|
|
|
|
# file reading from the loading so that we don't silently fail if we get
|
|
|
|
# bad input.
|
|
|
|
try:
|
|
|
|
with file(settings.JSON_PERSISTENT_QUEUE_FILENAME, "r") as stored_queues:
|
|
|
|
json_data = stored_queues.read()
|
|
|
|
try:
|
|
|
|
clients = dict((qid, ClientDescriptor.from_dict(client))
|
|
|
|
for (qid, client) in ujson.loads(json_data))
|
|
|
|
except Exception:
|
|
|
|
logging.exception("Could not deserialize event queues")
|
|
|
|
except (IOError, EOFError):
|
|
|
|
pass
|
2013-03-20 23:03:41 +01:00
|
|
|
|
|
|
|
for client in clients.itervalues():
|
2013-11-19 23:25:59 +01:00
|
|
|
# Put code for migrations due to event queue data format changes here
|
2013-10-17 23:51:25 +02:00
|
|
|
|
2013-03-20 23:03:41 +01:00
|
|
|
user_clients.setdefault(client.user_profile_id, []).append(client)
|
2013-10-17 23:51:25 +02:00
|
|
|
if client.all_public_streams:
|
|
|
|
realm_clients_all_streams.setdefault(client.realm_id, []).append(client)
|
2013-03-20 23:03:41 +01:00
|
|
|
|
|
|
|
logging.info('Tornado loaded %d event queues in %.3fs'
|
|
|
|
% (len(clients), time.time() - start))
|
|
|
|
|
2013-03-20 23:53:46 +01:00
|
|
|
def send_restart_events():
|
2013-03-22 22:43:49 +01:00
|
|
|
event = dict(type='restart', server_generation=settings.SERVER_GENERATION)
|
2013-03-20 23:53:46 +01:00
|
|
|
for client in clients.itervalues():
|
2013-11-18 17:24:49 +01:00
|
|
|
if not client.accepts_event_type('restart'):
|
|
|
|
continue
|
2013-03-22 22:43:49 +01:00
|
|
|
client.add_event(event.copy())
|
2013-03-20 23:53:46 +01:00
|
|
|
|
2013-03-22 23:24:28 +01:00
|
|
|
def setup_event_queue():
|
2013-03-20 23:53:46 +01:00
|
|
|
load_event_queues()
|
2013-03-20 23:03:41 +01:00
|
|
|
atexit.register(dump_event_queues)
|
|
|
|
# Make sure we dump event queues even if we exit via signal
|
|
|
|
signal.signal(signal.SIGTERM, lambda signum, stack: sys.exit(1))
|
|
|
|
|
|
|
|
try:
|
2013-11-19 21:02:36 +01:00
|
|
|
os.rename(settings.PERSISTENT_QUEUE_FILENAME, "/var/tmp/event_queues.pickle.last")
|
2013-03-20 23:03:41 +01:00
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
|
2013-11-19 23:51:32 +01:00
|
|
|
try:
|
|
|
|
os.rename(settings.JSON_PERSISTENT_QUEUE_FILENAME, "/var/tmp/event_queues.json.last")
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
|
2013-03-20 23:03:41 +01:00
|
|
|
# Set up event queue garbage collection
|
2013-03-22 23:24:28 +01:00
|
|
|
ioloop = tornado.ioloop.IOLoop.instance()
|
|
|
|
pc = tornado.ioloop.PeriodicCallback(gc_event_queues,
|
|
|
|
EVENT_QUEUE_GC_FREQ_MSECS, ioloop)
|
2013-03-26 18:06:00 +01:00
|
|
|
pc.start()
|
2013-03-14 23:21:53 +01:00
|
|
|
|
2013-03-20 23:53:46 +01:00
|
|
|
send_restart_events()
|
|
|
|
|
2013-03-22 18:21:50 +01:00
|
|
|
# The following functions are called from Django
|
|
|
|
|
2013-03-29 16:08:24 +01:00
|
|
|
# Workaround to support the Python-requests 1.0 transition of .json
|
|
|
|
# from a property to a function
|
|
|
|
requests_json_is_function = callable(requests.Response.json)
|
|
|
|
def extract_json_response(resp):
|
|
|
|
if requests_json_is_function:
|
|
|
|
return resp.json()
|
|
|
|
else:
|
|
|
|
return resp.json
|
|
|
|
|
2013-05-07 17:25:25 +02:00
|
|
|
def request_event_queue(user_profile, user_client, apply_markdown,
|
2013-10-17 23:51:25 +02:00
|
|
|
queue_lifespan_secs, event_types=None, all_public_streams=False):
|
2013-03-14 23:21:53 +01:00
|
|
|
if settings.TORNADO_SERVER:
|
|
|
|
req = {'dont_block' : 'true',
|
2013-06-18 23:55:55 +02:00
|
|
|
'apply_markdown': ujson.dumps(apply_markdown),
|
2013-10-17 23:51:25 +02:00
|
|
|
'all_public_streams': ujson.dumps(all_public_streams),
|
2013-05-07 17:25:25 +02:00
|
|
|
'client' : 'internal',
|
2013-08-05 22:09:12 +02:00
|
|
|
'user_client' : user_client.name,
|
|
|
|
'lifespan_secs' : queue_lifespan_secs}
|
2013-03-22 22:43:49 +01:00
|
|
|
if event_types is not None:
|
2013-06-18 23:55:55 +02:00
|
|
|
req['event_types'] = ujson.dumps(event_types)
|
2013-03-14 23:21:53 +01:00
|
|
|
resp = requests.get(settings.TORNADO_SERVER + '/api/v1/events',
|
2013-07-30 23:59:31 +02:00
|
|
|
auth=requests.auth.HTTPBasicAuth(user_profile.email,
|
|
|
|
user_profile.api_key),
|
2013-03-14 23:21:53 +01:00
|
|
|
params=req)
|
|
|
|
|
|
|
|
resp.raise_for_status()
|
|
|
|
|
2013-03-29 16:08:24 +01:00
|
|
|
return extract_json_response(resp)['queue_id']
|
2013-03-14 23:21:53 +01:00
|
|
|
|
|
|
|
return None
|
2013-03-22 18:21:50 +01:00
|
|
|
|
|
|
|
def get_user_events(user_profile, queue_id, last_event_id):
|
|
|
|
if settings.TORNADO_SERVER:
|
|
|
|
resp = requests.get(settings.TORNADO_SERVER + '/api/v1/events',
|
2013-03-28 20:43:34 +01:00
|
|
|
auth=requests.auth.HTTPBasicAuth(user_profile.email,
|
2013-03-22 18:21:50 +01:00
|
|
|
user_profile.api_key),
|
|
|
|
params={'queue_id' : queue_id,
|
|
|
|
'last_event_id': last_event_id,
|
2013-03-22 22:43:49 +01:00
|
|
|
'dont_block' : 'true',
|
2013-03-22 18:21:50 +01:00
|
|
|
'client' : 'internal'})
|
|
|
|
|
|
|
|
resp.raise_for_status()
|
|
|
|
|
2013-03-29 16:08:24 +01:00
|
|
|
return extract_json_response(resp)['events']
|