2013-04-23 18:51:17 +02:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2013-01-09 22:45:23 +01:00
|
|
|
from django.conf import settings
|
|
|
|
settings.RUNNING_INSIDE_TORNADO = True
|
2013-07-29 23:03:31 +02:00
|
|
|
# We must call zerver.lib.tornado_ioloop_logging.instrument_tornado_ioloop
|
2013-03-28 19:01:04 +01:00
|
|
|
# before we import anything else from our project in order for our
|
|
|
|
# Tornado load logging to work; otherwise we might accidentally import
|
2013-07-29 23:03:31 +02:00
|
|
|
# zerver.lib.queue (which will instantiate the Tornado ioloop) before
|
2013-03-28 19:01:04 +01:00
|
|
|
# this.
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.lib.tornado_ioloop_logging import instrument_tornado_ioloop
|
2013-03-28 19:01:04 +01:00
|
|
|
instrument_tornado_ioloop()
|
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
|
|
|
from optparse import make_option
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import tornado.web
|
2012-09-07 19:48:23 +02:00
|
|
|
import logging
|
2013-01-09 23:34:19 +01:00
|
|
|
from tornado import ioloop
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.lib.debug import interactive_debug_listen
|
|
|
|
from zerver.lib.response import json_response
|
|
|
|
from zerver import tornado_callbacks
|
|
|
|
from zerver.lib.event_queue import setup_event_queue, add_client_gc_hook
|
|
|
|
from zerver.lib.queue import setup_tornado_rabbitmq
|
2013-09-07 00:27:10 +02:00
|
|
|
from zerver.lib.socket import get_sockjs_router, respond_send_message
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.middleware import async_request_stop
|
2013-01-09 23:34:19 +01:00
|
|
|
|
2013-03-25 20:37:00 +01:00
|
|
|
if settings.USING_RABBITMQ:
|
2013-10-23 22:33:59 +02:00
|
|
|
from zerver.lib.queue import get_queue_client
|
2013-03-25 20:37:00 +01:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
class Command(BaseCommand):
|
|
|
|
option_list = BaseCommand.option_list + (
|
|
|
|
make_option('--nokeepalive', action='store_true',
|
|
|
|
dest='no_keep_alive', default=False,
|
|
|
|
help="Tells Tornado to NOT keep alive http connections."),
|
|
|
|
make_option('--noxheaders', action='store_false',
|
|
|
|
dest='xheaders', default=True,
|
|
|
|
help="Tells Tornado to NOT override remote IP with X-Real-IP."),
|
|
|
|
)
|
|
|
|
help = "Starts a Tornado Web server wrapping Django."
|
|
|
|
args = '[optional port number or ipaddr:port]\n (use multiple ports to start multiple servers)'
|
|
|
|
|
2012-10-30 21:37:19 +01:00
|
|
|
def handle(self, addrport, **options):
|
2012-08-28 22:56:21 +02:00
|
|
|
# setup unbuffered I/O
|
|
|
|
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
|
|
|
|
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)
|
2013-03-06 19:28:41 +01:00
|
|
|
interactive_debug_listen()
|
2012-09-05 17:23:58 +02:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
import django
|
2013-06-27 20:03:51 +02:00
|
|
|
from tornado import httpserver, web
|
2012-08-28 22:56:21 +02:00
|
|
|
|
2012-10-30 21:37:19 +01:00
|
|
|
try:
|
|
|
|
addr, port = addrport.split(':')
|
|
|
|
except ValueError:
|
|
|
|
addr, port = '', addrport
|
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
if not addr:
|
|
|
|
addr = '127.0.0.1'
|
2012-09-05 17:23:58 +02:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
if not port.isdigit():
|
|
|
|
raise CommandError("%r is not a valid port number." % port)
|
2012-09-05 17:23:58 +02:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
xheaders = options.get('xheaders', True)
|
|
|
|
no_keep_alive = options.get('no_keep_alive', False)
|
|
|
|
quit_command = 'CTRL-C'
|
|
|
|
|
|
|
|
if settings.DEBUG:
|
2012-09-05 19:20:32 +02:00
|
|
|
logging.basicConfig(level=logging.INFO,
|
|
|
|
format='%(asctime)s %(levelname)-8s %(message)s')
|
2012-09-05 17:23:58 +02:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
def inner_run():
|
|
|
|
from django.conf import settings
|
|
|
|
from django.utils import translation
|
|
|
|
translation.activate(settings.LANGUAGE_CODE)
|
|
|
|
|
|
|
|
print "Validating Django models.py..."
|
|
|
|
self.validate(display_num_errors=True)
|
|
|
|
print "\nDjango version %s" % (django.get_version())
|
|
|
|
print "Tornado server is running at http://%s:%s/" % (addr, port)
|
2013-06-27 20:15:19 +02:00
|
|
|
print "Quit the server with %s." % (quit_command,)
|
2012-09-05 17:23:58 +02:00
|
|
|
|
2013-01-18 23:16:53 +01:00
|
|
|
if settings.USING_RABBITMQ:
|
2013-10-23 22:33:59 +02:00
|
|
|
queue_client = get_queue_client()
|
2013-03-22 20:55:40 +01:00
|
|
|
# Process notifications received via RabbitMQ
|
2013-10-30 22:03:50 +01:00
|
|
|
queue_client.register_json_consumer('notify_tornado', tornado_callbacks.process_notification)
|
2013-09-07 00:27:10 +02:00
|
|
|
queue_client.register_json_consumer('tornado_return', respond_send_message)
|
2013-01-18 23:16:53 +01:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
try:
|
2013-11-05 17:02:34 +01:00
|
|
|
urls = (r"/notify_tornado",
|
2013-03-26 18:06:52 +01:00
|
|
|
r"/json/get_events",
|
2013-11-19 23:11:30 +01:00
|
|
|
r"/json/events",
|
2013-03-26 18:06:52 +01:00
|
|
|
r"/api/v1/events",
|
2013-03-22 18:31:34 +01:00
|
|
|
)
|
2013-09-07 00:27:10 +02:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
# Application is an instance of Django's standard wsgi handler.
|
2013-09-07 00:27:10 +02:00
|
|
|
application = web.Application([(url, AsyncDjangoHandler) for url in urls]
|
|
|
|
+ get_sockjs_router().urls,
|
2013-03-22 18:31:34 +01:00
|
|
|
debug=django.conf.settings.DEBUG,
|
2013-03-14 22:33:13 +01:00
|
|
|
# Disable Tornado's own request logging, since we have our own
|
|
|
|
log_function=lambda x: None)
|
2012-08-28 22:56:21 +02:00
|
|
|
|
|
|
|
# start tornado web server in single-threaded mode
|
|
|
|
http_server = httpserver.HTTPServer(application,
|
|
|
|
xheaders=xheaders,
|
|
|
|
no_keep_alive=no_keep_alive)
|
|
|
|
http_server.listen(int(port), address=addr)
|
|
|
|
|
2012-09-18 19:42:27 +02:00
|
|
|
if django.conf.settings.DEBUG:
|
|
|
|
ioloop.IOLoop.instance().set_blocking_log_threshold(5)
|
|
|
|
|
2013-03-22 23:24:28 +01:00
|
|
|
setup_event_queue()
|
2013-05-22 23:49:02 +02:00
|
|
|
add_client_gc_hook(tornado_callbacks.missedmessage_hook)
|
2013-04-16 17:49:03 +02:00
|
|
|
setup_tornado_rabbitmq()
|
2012-08-28 22:56:21 +02:00
|
|
|
ioloop.IOLoop.instance().start()
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
sys.exit(0)
|
2012-09-05 17:23:58 +02:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
inner_run()
|
|
|
|
|
|
|
|
#
|
|
|
|
# Modify the base Tornado handler for Django
|
|
|
|
#
|
|
|
|
from threading import Lock
|
|
|
|
from django.core.handlers import base
|
|
|
|
from django.core.urlresolvers import set_script_prefix
|
|
|
|
from django.core import signals
|
|
|
|
|
|
|
|
class AsyncDjangoHandler(tornado.web.RequestHandler, base.BaseHandler):
|
|
|
|
initLock = Lock()
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(AsyncDjangoHandler, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
# Set up middleware if needed. We couldn't do this earlier, because
|
|
|
|
# settings weren't available.
|
|
|
|
self._request_middleware = None
|
|
|
|
self.initLock.acquire()
|
|
|
|
# Check that middleware is still uninitialised.
|
|
|
|
if self._request_middleware is None:
|
|
|
|
self.load_middleware()
|
|
|
|
self.initLock.release()
|
|
|
|
self._auto_finish = False
|
|
|
|
|
|
|
|
def get(self):
|
2012-09-07 19:36:41 +02:00
|
|
|
from tornado.wsgi import WSGIContainer
|
2012-09-07 19:51:57 +02:00
|
|
|
from django.core.handlers.wsgi import WSGIRequest
|
2012-08-28 22:56:21 +02:00
|
|
|
import urllib
|
|
|
|
|
|
|
|
environ = WSGIContainer.environ(self.request)
|
|
|
|
environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO'])
|
|
|
|
request = WSGIRequest(environ)
|
|
|
|
request._tornado_handler = self
|
|
|
|
|
|
|
|
set_script_prefix(base.get_script_name(environ))
|
|
|
|
signals.request_started.send(sender=self.__class__)
|
|
|
|
try:
|
|
|
|
response = self.get_response(request)
|
|
|
|
|
|
|
|
if not response:
|
2012-09-05 17:23:58 +02:00
|
|
|
return
|
2012-08-28 22:56:21 +02:00
|
|
|
finally:
|
|
|
|
signals.request_finished.send(sender=self.__class__)
|
|
|
|
|
|
|
|
self.set_status(response.status_code)
|
|
|
|
for h in response.items():
|
|
|
|
self.set_header(h[0], h[1])
|
|
|
|
|
|
|
|
if not hasattr(self, "_new_cookies"):
|
|
|
|
self._new_cookies = []
|
|
|
|
self._new_cookies.append(response.cookies)
|
|
|
|
|
|
|
|
self.write(response.content)
|
|
|
|
self.finish()
|
2012-09-05 17:23:58 +02:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
|
|
|
|
def head(self):
|
|
|
|
self.get()
|
|
|
|
|
|
|
|
def post(self):
|
|
|
|
self.get()
|
|
|
|
|
2013-11-19 23:11:30 +01:00
|
|
|
def delete(self):
|
|
|
|
self.get()
|
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
# Based on django.core.handlers.base: get_response
|
|
|
|
def get_response(self, request):
|
|
|
|
"Returns an HttpResponse object for the given HttpRequest"
|
|
|
|
from django import http
|
|
|
|
from django.core import exceptions, urlresolvers
|
|
|
|
from django.conf import settings
|
|
|
|
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
# Setup default url resolver for this thread.
|
|
|
|
urlconf = settings.ROOT_URLCONF
|
|
|
|
urlresolvers.set_urlconf(urlconf)
|
|
|
|
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
|
|
|
|
|
2012-10-27 23:28:07 +02:00
|
|
|
response = None
|
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
# Apply request middleware
|
|
|
|
for middleware_method in self._request_middleware:
|
|
|
|
response = middleware_method(request)
|
|
|
|
if response:
|
|
|
|
break
|
|
|
|
|
|
|
|
if hasattr(request, "urlconf"):
|
|
|
|
# Reset url resolver with a custom urlconf.
|
|
|
|
urlconf = request.urlconf
|
|
|
|
urlresolvers.set_urlconf(urlconf)
|
|
|
|
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
|
|
|
|
|
2013-08-06 22:30:41 +02:00
|
|
|
### ADDED BY ZULIP
|
2013-03-14 21:21:30 +01:00
|
|
|
request._resolver = resolver
|
2013-08-06 22:30:41 +02:00
|
|
|
### END ADDED BY ZULIP
|
2013-03-14 21:21:30 +01:00
|
|
|
|
2012-08-28 22:56:21 +02:00
|
|
|
callback, callback_args, callback_kwargs = resolver.resolve(
|
|
|
|
request.path_info)
|
|
|
|
|
|
|
|
# Apply view middleware
|
2012-10-27 23:28:07 +02:00
|
|
|
if response is None:
|
|
|
|
for middleware_method in self._view_middleware:
|
|
|
|
response = middleware_method(request, callback, callback_args, callback_kwargs)
|
2012-08-28 22:56:21 +02:00
|
|
|
if response:
|
|
|
|
break
|
2012-10-27 23:28:07 +02:00
|
|
|
|
2013-08-06 22:30:41 +02:00
|
|
|
### THIS BLOCK MODIFIED BY ZULIP
|
2012-10-27 23:28:07 +02:00
|
|
|
if response is None:
|
2012-11-28 06:16:28 +01:00
|
|
|
from ...decorator import RespondAsynchronously
|
2012-10-27 23:28:07 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
response = callback(request, *callback_args, **callback_kwargs)
|
2012-11-28 06:16:28 +01:00
|
|
|
if response is RespondAsynchronously:
|
2013-04-23 19:36:50 +02:00
|
|
|
async_request_stop(request)
|
2012-11-28 06:16:28 +01:00
|
|
|
return
|
2012-10-27 23:28:07 +02:00
|
|
|
except Exception, e:
|
|
|
|
# If the view raised an exception, run it through exception
|
|
|
|
# middleware, and if the exception middleware returns a
|
|
|
|
# response, use that. Otherwise, reraise the exception.
|
|
|
|
for middleware_method in self._exception_middleware:
|
|
|
|
response = middleware_method(request, e)
|
|
|
|
if response:
|
|
|
|
break
|
|
|
|
if response is None:
|
|
|
|
raise
|
2012-08-28 22:56:21 +02:00
|
|
|
|
|
|
|
if response is None:
|
|
|
|
try:
|
|
|
|
view_name = callback.func_name
|
|
|
|
except AttributeError:
|
|
|
|
view_name = callback.__class__.__name__ + '.__call__'
|
2012-09-05 17:23:58 +02:00
|
|
|
raise ValueError("The view %s.%s returned None." %
|
2012-08-28 22:56:21 +02:00
|
|
|
(callback.__module__, view_name))
|
|
|
|
|
2012-09-05 17:23:58 +02:00
|
|
|
# If the response supports deferred rendering, apply template
|
|
|
|
# response middleware and the render the response
|
2012-08-28 22:56:21 +02:00
|
|
|
if hasattr(response, 'render') and callable(response.render):
|
|
|
|
for middleware_method in self._template_response_middleware:
|
|
|
|
response = middleware_method(request, response)
|
|
|
|
response = response.render()
|
|
|
|
|
|
|
|
|
|
|
|
except http.Http404, e:
|
|
|
|
if settings.DEBUG:
|
|
|
|
from django.views import debug
|
|
|
|
response = debug.technical_404_response(request, e)
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
callback, param_dict = resolver.resolve404()
|
|
|
|
response = callback(request, **param_dict)
|
|
|
|
except:
|
|
|
|
try:
|
|
|
|
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
|
|
|
|
finally:
|
2012-09-07 19:51:57 +02:00
|
|
|
signals.got_request_exception.send(sender=self.__class__, request=request)
|
2012-08-28 22:56:21 +02:00
|
|
|
except exceptions.PermissionDenied:
|
2012-09-07 19:48:23 +02:00
|
|
|
logging.warning(
|
2012-08-28 22:56:21 +02:00
|
|
|
'Forbidden (Permission denied): %s', request.path,
|
|
|
|
extra={
|
|
|
|
'status_code': 403,
|
|
|
|
'request': request
|
|
|
|
})
|
|
|
|
try:
|
|
|
|
callback, param_dict = resolver.resolve403()
|
|
|
|
response = callback(request, **param_dict)
|
|
|
|
except:
|
|
|
|
try:
|
|
|
|
response = self.handle_uncaught_exception(request,
|
|
|
|
resolver, sys.exc_info())
|
|
|
|
finally:
|
|
|
|
signals.got_request_exception.send(
|
|
|
|
sender=self.__class__, request=request)
|
|
|
|
except SystemExit:
|
|
|
|
# See https://code.djangoproject.com/ticket/4701
|
|
|
|
raise
|
|
|
|
except Exception, e:
|
|
|
|
exc_info = sys.exc_info()
|
2012-09-07 19:51:57 +02:00
|
|
|
signals.got_request_exception.send(sender=self.__class__, request=request)
|
2012-08-28 22:56:21 +02:00
|
|
|
return self.handle_uncaught_exception(request, resolver, exc_info)
|
|
|
|
finally:
|
|
|
|
# Reset urlconf on the way out for isolation
|
|
|
|
urlresolvers.set_urlconf(None)
|
|
|
|
|
2013-08-06 22:30:41 +02:00
|
|
|
### ZULIP CHANGE: The remainder of this function was moved
|
2013-03-14 21:21:30 +01:00
|
|
|
### into its own function, just below, so we can call it from
|
|
|
|
### finish().
|
|
|
|
response = self.apply_response_middleware(request, response, resolver)
|
|
|
|
|
|
|
|
return response
|
|
|
|
|
|
|
|
### Copied from get_response (above in this file)
|
|
|
|
def apply_response_middleware(self, request, response, resolver):
|
2012-08-28 22:56:21 +02:00
|
|
|
try:
|
2012-09-05 17:23:58 +02:00
|
|
|
# Apply response middleware, regardless of the response
|
2012-08-28 22:56:21 +02:00
|
|
|
for middleware_method in self._response_middleware:
|
|
|
|
response = middleware_method(request, response)
|
|
|
|
response = self.apply_response_fixes(request, response)
|
2012-09-05 17:23:58 +02:00
|
|
|
except: # Any exception should be gathered and handled
|
2012-08-28 22:56:21 +02:00
|
|
|
signals.got_request_exception.send(sender=self.__class__, request=request)
|
|
|
|
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
|
|
|
|
|
|
|
|
return response
|
2013-03-13 21:02:00 +01:00
|
|
|
|
2013-08-06 22:21:12 +02:00
|
|
|
def zulip_finish(self, response, request, apply_markdown):
|
2013-03-13 21:02:00 +01:00
|
|
|
# Make sure that Markdown rendering really happened, if requested.
|
|
|
|
# This is a security issue because it's where we escape HTML.
|
|
|
|
# c.f. ticket #64
|
|
|
|
#
|
|
|
|
# apply_markdown=True is the fail-safe default.
|
|
|
|
if response['result'] == 'success' and 'messages' in response and apply_markdown:
|
|
|
|
for msg in response['messages']:
|
|
|
|
if msg['content_type'] != 'text/html':
|
|
|
|
self.set_status(500)
|
2013-03-15 17:28:03 +01:00
|
|
|
return self.finish('Internal error: bad message format')
|
2013-03-13 21:02:00 +01:00
|
|
|
if response['result'] == 'error':
|
|
|
|
self.set_status(400)
|
2013-03-14 21:43:04 +01:00
|
|
|
|
2013-03-14 21:21:30 +01:00
|
|
|
# Call the Django response middleware on our object so that
|
|
|
|
# e.g. our own logging code can run; but don't actually use
|
|
|
|
# the headers from that since sending those to Tornado seems
|
|
|
|
# tricky; instead just send the (already json-rendered)
|
|
|
|
# content on to Tornado
|
|
|
|
django_response = json_response(res_type=response['result'],
|
|
|
|
data=response, status=self.get_status())
|
|
|
|
django_response = self.apply_response_middleware(request, django_response,
|
|
|
|
request._resolver)
|
2013-07-02 17:33:59 +02:00
|
|
|
# Pass through the content-type from Django, as json content should be
|
|
|
|
# served as application/json
|
|
|
|
self.set_header("Content-Type", django_response['Content-Type'])
|
2013-03-15 17:28:03 +01:00
|
|
|
return self.finish(django_response.content)
|