##// END OF EJS Templates
Moving base ZMQ handlers to base/zmqhandlers.py.
Brian E. Granger -
Show More
@@ -0,0 +1,114 b''
1 """Tornado handlers for WebSocket <-> ZMQ sockets.
2
3 Authors:
4
5 * Brian Granger
6 """
7
8 #-----------------------------------------------------------------------------
9 # Copyright (C) 2008-2011 The IPython Development Team
10 #
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
14
15 #-----------------------------------------------------------------------------
16 # Imports
17 #-----------------------------------------------------------------------------
18
19 import Cookie
20 import logging
21 from tornado import web
22 from tornado import websocket
23
24 from zmq.utils import jsonapi
25
26 from IPython.kernel.zmq.session import Session
27 from IPython.utils.jsonutil import date_default
28 from IPython.utils.py3compat import PY3
29
30 from ..base.handlers import IPythonHandler
31
32 #-----------------------------------------------------------------------------
33 # ZMQ handlers
34 #-----------------------------------------------------------------------------
35
36 class ZMQStreamHandler(websocket.WebSocketHandler):
37
38 def clear_cookie(self, *args, **kwargs):
39 """meaningless for websockets"""
40 pass
41
42 def _reserialize_reply(self, msg_list):
43 """Reserialize a reply message using JSON.
44
45 This takes the msg list from the ZMQ socket, unserializes it using
46 self.session and then serializes the result using JSON. This method
47 should be used by self._on_zmq_reply to build messages that can
48 be sent back to the browser.
49 """
50 idents, msg_list = self.session.feed_identities(msg_list)
51 msg = self.session.unserialize(msg_list)
52 try:
53 msg['header'].pop('date')
54 except KeyError:
55 pass
56 try:
57 msg['parent_header'].pop('date')
58 except KeyError:
59 pass
60 msg.pop('buffers')
61 return jsonapi.dumps(msg, default=date_default)
62
63 def _on_zmq_reply(self, msg_list):
64 # Sometimes this gets triggered when the on_close method is scheduled in the
65 # eventloop but hasn't been called.
66 if self.stream.closed(): return
67 try:
68 msg = self._reserialize_reply(msg_list)
69 except Exception:
70 self.log.critical("Malformed message: %r" % msg_list, exc_info=True)
71 else:
72 self.write_message(msg)
73
74 def allow_draft76(self):
75 """Allow draft 76, until browsers such as Safari update to RFC 6455.
76
77 This has been disabled by default in tornado in release 2.2.0, and
78 support will be removed in later versions.
79 """
80 return True
81
82
83 class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
84
85 def open(self, kernel_id):
86 self.kernel_id = kernel_id.decode('ascii')
87 self.session = Session(config=self.config)
88 self.save_on_message = self.on_message
89 self.on_message = self.on_first_message
90
91 def _inject_cookie_message(self, msg):
92 """Inject the first message, which is the document cookie,
93 for authentication."""
94 if not PY3 and isinstance(msg, unicode):
95 # Cookie constructor doesn't accept unicode strings
96 # under Python 2.x for some reason
97 msg = msg.encode('utf8', 'replace')
98 try:
99 identity, msg = msg.split(':', 1)
100 self.session.session = identity.decode('ascii')
101 except Exception:
102 logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg)
103
104 try:
105 self.request._cookies = Cookie.SimpleCookie(msg)
106 except:
107 self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True)
108
109 def on_first_message(self, msg):
110 self._inject_cookie_message(msg)
111 if self.get_current_user() is None:
112 self.log.warn("Couldn't authenticate WebSocket connection")
113 raise web.HTTPError(403)
114 self.on_message = self.save_on_message No newline at end of file
@@ -16,18 +16,15 b' Authors:'
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import Cookie
20 import logging
19 import logging
21 from tornado import web
20 from tornado import web
22 from tornado import websocket
23
21
24 from zmq.utils import jsonapi
22 from zmq.utils import jsonapi
25
23
26 from IPython.kernel.zmq.session import Session
27 from IPython.utils.jsonutil import date_default
24 from IPython.utils.jsonutil import date_default
28 from IPython.utils.py3compat import PY3
29
25
30 from ..base.handlers import IPythonHandler
26 from ..base.handlers import IPythonHandler
27 from ..base.zmqhandlers import AuthenticatedZMQStreamHandler
31
28
32 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
33 # Kernel handlers
30 # Kernel handlers
@@ -80,87 +77,6 b' class KernelActionHandler(IPythonHandler):'
80 self.finish()
77 self.finish()
81
78
82
79
83 class ZMQStreamHandler(websocket.WebSocketHandler):
84
85 def clear_cookie(self, *args, **kwargs):
86 """meaningless for websockets"""
87 pass
88
89 def _reserialize_reply(self, msg_list):
90 """Reserialize a reply message using JSON.
91
92 This takes the msg list from the ZMQ socket, unserializes it using
93 self.session and then serializes the result using JSON. This method
94 should be used by self._on_zmq_reply to build messages that can
95 be sent back to the browser.
96 """
97 idents, msg_list = self.session.feed_identities(msg_list)
98 msg = self.session.unserialize(msg_list)
99 try:
100 msg['header'].pop('date')
101 except KeyError:
102 pass
103 try:
104 msg['parent_header'].pop('date')
105 except KeyError:
106 pass
107 msg.pop('buffers')
108 return jsonapi.dumps(msg, default=date_default)
109
110 def _on_zmq_reply(self, msg_list):
111 # Sometimes this gets triggered when the on_close method is scheduled in the
112 # eventloop but hasn't been called.
113 if self.stream.closed(): return
114 try:
115 msg = self._reserialize_reply(msg_list)
116 except Exception:
117 self.log.critical("Malformed message: %r" % msg_list, exc_info=True)
118 else:
119 self.write_message(msg)
120
121 def allow_draft76(self):
122 """Allow draft 76, until browsers such as Safari update to RFC 6455.
123
124 This has been disabled by default in tornado in release 2.2.0, and
125 support will be removed in later versions.
126 """
127 return True
128
129
130 class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler):
131
132 def open(self, kernel_id):
133 self.kernel_id = kernel_id.decode('ascii')
134 self.session = Session(config=self.config)
135 self.save_on_message = self.on_message
136 self.on_message = self.on_first_message
137
138 def _inject_cookie_message(self, msg):
139 """Inject the first message, which is the document cookie,
140 for authentication."""
141 if not PY3 and isinstance(msg, unicode):
142 # Cookie constructor doesn't accept unicode strings
143 # under Python 2.x for some reason
144 msg = msg.encode('utf8', 'replace')
145 try:
146 identity, msg = msg.split(':', 1)
147 self.session.session = identity.decode('ascii')
148 except Exception:
149 logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg)
150
151 try:
152 self.request._cookies = Cookie.SimpleCookie(msg)
153 except:
154 self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True)
155
156 def on_first_message(self, msg):
157 self._inject_cookie_message(msg)
158 if self.get_current_user() is None:
159 self.log.warn("Couldn't authenticate WebSocket connection")
160 raise web.HTTPError(403)
161 self.on_message = self.save_on_message
162
163
164 class ZMQChannelHandler(AuthenticatedZMQStreamHandler):
80 class ZMQChannelHandler(AuthenticatedZMQStreamHandler):
165
81
166 @property
82 @property
General Comments 0
You need to be logged in to leave comments. Login now