Show More
@@ -1,1000 +1,1012 | |||||
1 | """Base classes to manage the interaction with a running kernel. |
|
1 | """Base classes to manage the interaction with a running kernel. | |
2 |
|
2 | |||
3 | TODO |
|
3 | TODO | |
4 | * Create logger to handle debugging and console messages. |
|
4 | * Create logger to handle debugging and console messages. | |
5 | """ |
|
5 | """ | |
6 |
|
6 | |||
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | # Copyright (C) 2008-2011 The IPython Development Team | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | # Standard library imports. |
|
18 | # Standard library imports. | |
19 | import atexit |
|
19 | import atexit | |
20 | import errno |
|
20 | import errno | |
21 | import json |
|
21 | import json | |
22 | from subprocess import Popen |
|
22 | from subprocess import Popen | |
23 | import os |
|
23 | import os | |
24 | import signal |
|
24 | import signal | |
25 | import sys |
|
25 | import sys | |
26 | from threading import Thread |
|
26 | from threading import Thread | |
27 | import time |
|
27 | import time | |
28 |
|
28 | |||
29 | # System library imports. |
|
29 | # System library imports. | |
30 | import zmq |
|
30 | import zmq | |
31 | # import ZMQError in top-level namespace, to avoid ugly attribute-error messages |
|
31 | # import ZMQError in top-level namespace, to avoid ugly attribute-error messages | |
32 | # during garbage collection of threads at exit: |
|
32 | # during garbage collection of threads at exit: | |
33 | from zmq import ZMQError |
|
33 | from zmq import ZMQError | |
34 | from zmq.eventloop import ioloop, zmqstream |
|
34 | from zmq.eventloop import ioloop, zmqstream | |
35 |
|
35 | |||
36 | # Local imports. |
|
36 | # Local imports. | |
37 | from IPython.config.loader import Config |
|
37 | from IPython.config.loader import Config | |
38 | from IPython.utils.localinterfaces import LOCALHOST, LOCAL_IPS |
|
38 | from IPython.utils.localinterfaces import LOCALHOST, LOCAL_IPS | |
39 | from IPython.utils.traitlets import ( |
|
39 | from IPython.utils.traitlets import ( | |
40 | HasTraits, Any, Instance, Type, Unicode, Integer, Bool |
|
40 | HasTraits, Any, Instance, Type, Unicode, Integer, Bool | |
41 | ) |
|
41 | ) | |
42 | from IPython.utils.py3compat import str_to_bytes |
|
42 | from IPython.utils.py3compat import str_to_bytes | |
43 | from IPython.zmq.entry_point import write_connection_file |
|
43 | from IPython.zmq.entry_point import write_connection_file | |
44 | from session import Session |
|
44 | from session import Session | |
45 |
|
45 | |||
46 | #----------------------------------------------------------------------------- |
|
46 | #----------------------------------------------------------------------------- | |
47 | # Constants and exceptions |
|
47 | # Constants and exceptions | |
48 | #----------------------------------------------------------------------------- |
|
48 | #----------------------------------------------------------------------------- | |
49 |
|
49 | |||
50 | class InvalidPortNumber(Exception): |
|
50 | class InvalidPortNumber(Exception): | |
51 | pass |
|
51 | pass | |
52 |
|
52 | |||
53 | #----------------------------------------------------------------------------- |
|
53 | #----------------------------------------------------------------------------- | |
54 | # Utility functions |
|
54 | # Utility functions | |
55 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
56 |
|
56 | |||
57 | # some utilities to validate message structure, these might get moved elsewhere |
|
57 | # some utilities to validate message structure, these might get moved elsewhere | |
58 | # if they prove to have more generic utility |
|
58 | # if they prove to have more generic utility | |
59 |
|
59 | |||
60 | def validate_string_list(lst): |
|
60 | def validate_string_list(lst): | |
61 | """Validate that the input is a list of strings. |
|
61 | """Validate that the input is a list of strings. | |
62 |
|
62 | |||
63 | Raises ValueError if not.""" |
|
63 | Raises ValueError if not.""" | |
64 | if not isinstance(lst, list): |
|
64 | if not isinstance(lst, list): | |
65 | raise ValueError('input %r must be a list' % lst) |
|
65 | raise ValueError('input %r must be a list' % lst) | |
66 | for x in lst: |
|
66 | for x in lst: | |
67 | if not isinstance(x, basestring): |
|
67 | if not isinstance(x, basestring): | |
68 | raise ValueError('element %r in list must be a string' % x) |
|
68 | raise ValueError('element %r in list must be a string' % x) | |
69 |
|
69 | |||
70 |
|
70 | |||
71 | def validate_string_dict(dct): |
|
71 | def validate_string_dict(dct): | |
72 | """Validate that the input is a dict with string keys and values. |
|
72 | """Validate that the input is a dict with string keys and values. | |
73 |
|
73 | |||
74 | Raises ValueError if not.""" |
|
74 | Raises ValueError if not.""" | |
75 | for k,v in dct.iteritems(): |
|
75 | for k,v in dct.iteritems(): | |
76 | if not isinstance(k, basestring): |
|
76 | if not isinstance(k, basestring): | |
77 | raise ValueError('key %r in dict must be a string' % k) |
|
77 | raise ValueError('key %r in dict must be a string' % k) | |
78 | if not isinstance(v, basestring): |
|
78 | if not isinstance(v, basestring): | |
79 | raise ValueError('value %r in dict must be a string' % v) |
|
79 | raise ValueError('value %r in dict must be a string' % v) | |
80 |
|
80 | |||
81 |
|
81 | |||
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 | # ZMQ Socket Channel classes |
|
83 | # ZMQ Socket Channel classes | |
84 | #----------------------------------------------------------------------------- |
|
84 | #----------------------------------------------------------------------------- | |
85 |
|
85 | |||
86 | class ZMQSocketChannel(Thread): |
|
86 | class ZMQSocketChannel(Thread): | |
87 | """The base class for the channels that use ZMQ sockets. |
|
87 | """The base class for the channels that use ZMQ sockets. | |
88 | """ |
|
88 | """ | |
89 | context = None |
|
89 | context = None | |
90 | session = None |
|
90 | session = None | |
91 | socket = None |
|
91 | socket = None | |
92 | ioloop = None |
|
92 | ioloop = None | |
93 | stream = None |
|
93 | stream = None | |
94 | _address = None |
|
94 | _address = None | |
95 | _exiting = False |
|
95 | _exiting = False | |
96 |
|
96 | |||
97 | def __init__(self, context, session, address): |
|
97 | def __init__(self, context, session, address): | |
98 | """Create a channel |
|
98 | """Create a channel | |
99 |
|
99 | |||
100 | Parameters |
|
100 | Parameters | |
101 | ---------- |
|
101 | ---------- | |
102 | context : :class:`zmq.Context` |
|
102 | context : :class:`zmq.Context` | |
103 | The ZMQ context to use. |
|
103 | The ZMQ context to use. | |
104 | session : :class:`session.Session` |
|
104 | session : :class:`session.Session` | |
105 | The session to use. |
|
105 | The session to use. | |
106 | address : tuple |
|
106 | address : tuple | |
107 | Standard (ip, port) tuple that the kernel is listening on. |
|
107 | Standard (ip, port) tuple that the kernel is listening on. | |
108 | """ |
|
108 | """ | |
109 | super(ZMQSocketChannel, self).__init__() |
|
109 | super(ZMQSocketChannel, self).__init__() | |
110 | self.daemon = True |
|
110 | self.daemon = True | |
111 |
|
111 | |||
112 | self.context = context |
|
112 | self.context = context | |
113 | self.session = session |
|
113 | self.session = session | |
114 | if address[1] == 0: |
|
114 | if address[1] == 0: | |
115 | message = 'The port number for a channel cannot be 0.' |
|
115 | message = 'The port number for a channel cannot be 0.' | |
116 | raise InvalidPortNumber(message) |
|
116 | raise InvalidPortNumber(message) | |
117 | self._address = address |
|
117 | self._address = address | |
118 | atexit.register(self._notice_exit) |
|
118 | atexit.register(self._notice_exit) | |
119 |
|
119 | |||
120 | def _notice_exit(self): |
|
120 | def _notice_exit(self): | |
121 | self._exiting = True |
|
121 | self._exiting = True | |
122 |
|
122 | |||
123 | def _run_loop(self): |
|
123 | def _run_loop(self): | |
124 | """Run my loop, ignoring EINTR events in the poller""" |
|
124 | """Run my loop, ignoring EINTR events in the poller""" | |
125 | while True: |
|
125 | while True: | |
126 | try: |
|
126 | try: | |
127 | self.ioloop.start() |
|
127 | self.ioloop.start() | |
128 | except ZMQError as e: |
|
128 | except ZMQError as e: | |
129 | if e.errno == errno.EINTR: |
|
129 | if e.errno == errno.EINTR: | |
130 | continue |
|
130 | continue | |
131 | else: |
|
131 | else: | |
132 | raise |
|
132 | raise | |
133 | except Exception: |
|
133 | except Exception: | |
134 | if self._exiting: |
|
134 | if self._exiting: | |
135 | break |
|
135 | break | |
136 | else: |
|
136 | else: | |
137 | raise |
|
137 | raise | |
138 | else: |
|
138 | else: | |
139 | break |
|
139 | break | |
140 |
|
140 | |||
141 | def stop(self): |
|
141 | def stop(self): | |
142 | """Stop the channel's activity. |
|
142 | """Stop the channel's activity. | |
143 |
|
143 | |||
144 | This calls :method:`Thread.join` and returns when the thread |
|
144 | This calls :method:`Thread.join` and returns when the thread | |
145 | terminates. :class:`RuntimeError` will be raised if |
|
145 | terminates. :class:`RuntimeError` will be raised if | |
146 | :method:`self.start` is called again. |
|
146 | :method:`self.start` is called again. | |
147 | """ |
|
147 | """ | |
148 | self.join() |
|
148 | self.join() | |
149 |
|
149 | |||
150 | @property |
|
150 | @property | |
151 | def address(self): |
|
151 | def address(self): | |
152 | """Get the channel's address as an (ip, port) tuple. |
|
152 | """Get the channel's address as an (ip, port) tuple. | |
153 |
|
153 | |||
154 | By the default, the address is (localhost, 0), where 0 means a random |
|
154 | By the default, the address is (localhost, 0), where 0 means a random | |
155 | port. |
|
155 | port. | |
156 | """ |
|
156 | """ | |
157 | return self._address |
|
157 | return self._address | |
158 |
|
158 | |||
159 | def _queue_send(self, msg): |
|
159 | def _queue_send(self, msg): | |
160 | """Queue a message to be sent from the IOLoop's thread. |
|
160 | """Queue a message to be sent from the IOLoop's thread. | |
161 |
|
161 | |||
162 | Parameters |
|
162 | Parameters | |
163 | ---------- |
|
163 | ---------- | |
164 | msg : message to send |
|
164 | msg : message to send | |
165 |
|
165 | |||
166 | This is threadsafe, as it uses IOLoop.add_callback to give the loop's |
|
166 | This is threadsafe, as it uses IOLoop.add_callback to give the loop's | |
167 | thread control of the action. |
|
167 | thread control of the action. | |
168 | """ |
|
168 | """ | |
169 | def thread_send(): |
|
169 | def thread_send(): | |
170 | self.session.send(self.stream, msg) |
|
170 | self.session.send(self.stream, msg) | |
171 | self.ioloop.add_callback(thread_send) |
|
171 | self.ioloop.add_callback(thread_send) | |
172 |
|
172 | |||
173 | def _handle_recv(self, msg): |
|
173 | def _handle_recv(self, msg): | |
174 | """callback for stream.on_recv |
|
174 | """callback for stream.on_recv | |
175 |
|
175 | |||
176 | unpacks message, and calls handlers with it. |
|
176 | unpacks message, and calls handlers with it. | |
177 | """ |
|
177 | """ | |
178 | ident,smsg = self.session.feed_identities(msg) |
|
178 | ident,smsg = self.session.feed_identities(msg) | |
179 | self.call_handlers(self.session.unserialize(smsg)) |
|
179 | self.call_handlers(self.session.unserialize(smsg)) | |
180 |
|
180 | |||
181 |
|
181 | |||
182 |
|
182 | |||
183 | class ShellSocketChannel(ZMQSocketChannel): |
|
183 | class ShellSocketChannel(ZMQSocketChannel): | |
184 | """The DEALER channel for issues request/replies to the kernel. |
|
184 | """The DEALER channel for issues request/replies to the kernel. | |
185 | """ |
|
185 | """ | |
186 |
|
186 | |||
187 | command_queue = None |
|
187 | command_queue = None | |
188 | # flag for whether execute requests should be allowed to call raw_input: |
|
188 | # flag for whether execute requests should be allowed to call raw_input: | |
189 | allow_stdin = True |
|
189 | allow_stdin = True | |
190 |
|
190 | |||
191 | def __init__(self, context, session, address): |
|
191 | def __init__(self, context, session, address): | |
192 | super(ShellSocketChannel, self).__init__(context, session, address) |
|
192 | super(ShellSocketChannel, self).__init__(context, session, address) | |
193 | self.ioloop = ioloop.IOLoop() |
|
193 | self.ioloop = ioloop.IOLoop() | |
194 |
|
194 | |||
195 | def run(self): |
|
195 | def run(self): | |
196 | """The thread's main activity. Call start() instead.""" |
|
196 | """The thread's main activity. Call start() instead.""" | |
197 | self.socket = self.context.socket(zmq.DEALER) |
|
197 | self.socket = self.context.socket(zmq.DEALER) | |
198 | self.socket.setsockopt(zmq.IDENTITY, self.session.bsession) |
|
198 | self.socket.setsockopt(zmq.IDENTITY, self.session.bsession) | |
199 | self.socket.connect('tcp://%s:%i' % self.address) |
|
199 | self.socket.connect('tcp://%s:%i' % self.address) | |
200 | self.stream = zmqstream.ZMQStream(self.socket, self.ioloop) |
|
200 | self.stream = zmqstream.ZMQStream(self.socket, self.ioloop) | |
201 | self.stream.on_recv(self._handle_recv) |
|
201 | self.stream.on_recv(self._handle_recv) | |
202 | self._run_loop() |
|
202 | self._run_loop() | |
203 | try: |
|
203 | try: | |
204 | self.socket.close() |
|
204 | self.socket.close() | |
205 | except: |
|
205 | except: | |
206 | pass |
|
206 | pass | |
207 |
|
207 | |||
208 | def stop(self): |
|
208 | def stop(self): | |
209 | self.ioloop.stop() |
|
209 | self.ioloop.stop() | |
210 | super(ShellSocketChannel, self).stop() |
|
210 | super(ShellSocketChannel, self).stop() | |
211 |
|
211 | |||
212 | def call_handlers(self, msg): |
|
212 | def call_handlers(self, msg): | |
213 | """This method is called in the ioloop thread when a message arrives. |
|
213 | """This method is called in the ioloop thread when a message arrives. | |
214 |
|
214 | |||
215 | Subclasses should override this method to handle incoming messages. |
|
215 | Subclasses should override this method to handle incoming messages. | |
216 | It is important to remember that this method is called in the thread |
|
216 | It is important to remember that this method is called in the thread | |
217 | so that some logic must be done to ensure that the application leve |
|
217 | so that some logic must be done to ensure that the application leve | |
218 | handlers are called in the application thread. |
|
218 | handlers are called in the application thread. | |
219 | """ |
|
219 | """ | |
220 | raise NotImplementedError('call_handlers must be defined in a subclass.') |
|
220 | raise NotImplementedError('call_handlers must be defined in a subclass.') | |
221 |
|
221 | |||
222 | def execute(self, code, silent=False, store_history=True, |
|
222 | def execute(self, code, silent=False, store_history=True, | |
223 | user_variables=None, user_expressions=None, allow_stdin=None): |
|
223 | user_variables=None, user_expressions=None, allow_stdin=None): | |
224 | """Execute code in the kernel. |
|
224 | """Execute code in the kernel. | |
225 |
|
225 | |||
226 | Parameters |
|
226 | Parameters | |
227 | ---------- |
|
227 | ---------- | |
228 | code : str |
|
228 | code : str | |
229 | A string of Python code. |
|
229 | A string of Python code. | |
230 |
|
230 | |||
231 | silent : bool, optional (default False) |
|
231 | silent : bool, optional (default False) | |
232 | If set, the kernel will execute the code as quietly possible, and |
|
232 | If set, the kernel will execute the code as quietly possible, and | |
233 | will force store_history to be False. |
|
233 | will force store_history to be False. | |
234 |
|
234 | |||
235 | store_history : bool, optional (default True) |
|
235 | store_history : bool, optional (default True) | |
236 | If set, the kernel will store command history. This is forced |
|
236 | If set, the kernel will store command history. This is forced | |
237 | to be False if silent is True. |
|
237 | to be False if silent is True. | |
238 |
|
238 | |||
239 | user_variables : list, optional |
|
239 | user_variables : list, optional | |
240 | A list of variable names to pull from the user's namespace. They |
|
240 | A list of variable names to pull from the user's namespace. They | |
241 | will come back as a dict with these names as keys and their |
|
241 | will come back as a dict with these names as keys and their | |
242 | :func:`repr` as values. |
|
242 | :func:`repr` as values. | |
243 |
|
243 | |||
244 | user_expressions : dict, optional |
|
244 | user_expressions : dict, optional | |
245 | A dict mapping names to expressions to be evaluated in the user's |
|
245 | A dict mapping names to expressions to be evaluated in the user's | |
246 | dict. The expression values are returned as strings formatted using |
|
246 | dict. The expression values are returned as strings formatted using | |
247 | :func:`repr`. |
|
247 | :func:`repr`. | |
248 |
|
248 | |||
249 | allow_stdin : bool, optional (default self.allow_stdin) |
|
249 | allow_stdin : bool, optional (default self.allow_stdin) | |
250 | Flag for whether the kernel can send stdin requests to frontends. |
|
250 | Flag for whether the kernel can send stdin requests to frontends. | |
251 |
|
251 | |||
252 | Some frontends (e.g. the Notebook) do not support stdin requests. |
|
252 | Some frontends (e.g. the Notebook) do not support stdin requests. | |
253 | If raw_input is called from code executed from such a frontend, a |
|
253 | If raw_input is called from code executed from such a frontend, a | |
254 | StdinNotImplementedError will be raised. |
|
254 | StdinNotImplementedError will be raised. | |
255 |
|
255 | |||
256 | Returns |
|
256 | Returns | |
257 | ------- |
|
257 | ------- | |
258 | The msg_id of the message sent. |
|
258 | The msg_id of the message sent. | |
259 | """ |
|
259 | """ | |
260 | if user_variables is None: |
|
260 | if user_variables is None: | |
261 | user_variables = [] |
|
261 | user_variables = [] | |
262 | if user_expressions is None: |
|
262 | if user_expressions is None: | |
263 | user_expressions = {} |
|
263 | user_expressions = {} | |
264 | if allow_stdin is None: |
|
264 | if allow_stdin is None: | |
265 | allow_stdin = self.allow_stdin |
|
265 | allow_stdin = self.allow_stdin | |
266 |
|
266 | |||
267 |
|
267 | |||
268 | # Don't waste network traffic if inputs are invalid |
|
268 | # Don't waste network traffic if inputs are invalid | |
269 | if not isinstance(code, basestring): |
|
269 | if not isinstance(code, basestring): | |
270 | raise ValueError('code %r must be a string' % code) |
|
270 | raise ValueError('code %r must be a string' % code) | |
271 | validate_string_list(user_variables) |
|
271 | validate_string_list(user_variables) | |
272 | validate_string_dict(user_expressions) |
|
272 | validate_string_dict(user_expressions) | |
273 |
|
273 | |||
274 | # Create class for content/msg creation. Related to, but possibly |
|
274 | # Create class for content/msg creation. Related to, but possibly | |
275 | # not in Session. |
|
275 | # not in Session. | |
276 | content = dict(code=code, silent=silent, store_history=store_history, |
|
276 | content = dict(code=code, silent=silent, store_history=store_history, | |
277 | user_variables=user_variables, |
|
277 | user_variables=user_variables, | |
278 | user_expressions=user_expressions, |
|
278 | user_expressions=user_expressions, | |
279 | allow_stdin=allow_stdin, |
|
279 | allow_stdin=allow_stdin, | |
280 | ) |
|
280 | ) | |
281 | msg = self.session.msg('execute_request', content) |
|
281 | msg = self.session.msg('execute_request', content) | |
282 | self._queue_send(msg) |
|
282 | self._queue_send(msg) | |
283 | return msg['header']['msg_id'] |
|
283 | return msg['header']['msg_id'] | |
284 |
|
284 | |||
285 | def complete(self, text, line, cursor_pos, block=None): |
|
285 | def complete(self, text, line, cursor_pos, block=None): | |
286 | """Tab complete text in the kernel's namespace. |
|
286 | """Tab complete text in the kernel's namespace. | |
287 |
|
287 | |||
288 | Parameters |
|
288 | Parameters | |
289 | ---------- |
|
289 | ---------- | |
290 | text : str |
|
290 | text : str | |
291 | The text to complete. |
|
291 | The text to complete. | |
292 | line : str |
|
292 | line : str | |
293 | The full line of text that is the surrounding context for the |
|
293 | The full line of text that is the surrounding context for the | |
294 | text to complete. |
|
294 | text to complete. | |
295 | cursor_pos : int |
|
295 | cursor_pos : int | |
296 | The position of the cursor in the line where the completion was |
|
296 | The position of the cursor in the line where the completion was | |
297 | requested. |
|
297 | requested. | |
298 | block : str, optional |
|
298 | block : str, optional | |
299 | The full block of code in which the completion is being requested. |
|
299 | The full block of code in which the completion is being requested. | |
300 |
|
300 | |||
301 | Returns |
|
301 | Returns | |
302 | ------- |
|
302 | ------- | |
303 | The msg_id of the message sent. |
|
303 | The msg_id of the message sent. | |
304 | """ |
|
304 | """ | |
305 | content = dict(text=text, line=line, block=block, cursor_pos=cursor_pos) |
|
305 | content = dict(text=text, line=line, block=block, cursor_pos=cursor_pos) | |
306 | msg = self.session.msg('complete_request', content) |
|
306 | msg = self.session.msg('complete_request', content) | |
307 | self._queue_send(msg) |
|
307 | self._queue_send(msg) | |
308 | return msg['header']['msg_id'] |
|
308 | return msg['header']['msg_id'] | |
309 |
|
309 | |||
310 | def object_info(self, oname, detail_level=0): |
|
310 | def object_info(self, oname, detail_level=0): | |
311 | """Get metadata information about an object. |
|
311 | """Get metadata information about an object. | |
312 |
|
312 | |||
313 | Parameters |
|
313 | Parameters | |
314 | ---------- |
|
314 | ---------- | |
315 | oname : str |
|
315 | oname : str | |
316 | A string specifying the object name. |
|
316 | A string specifying the object name. | |
317 | detail_level : int, optional |
|
317 | detail_level : int, optional | |
318 | The level of detail for the introspection (0-2) |
|
318 | The level of detail for the introspection (0-2) | |
319 |
|
319 | |||
320 | Returns |
|
320 | Returns | |
321 | ------- |
|
321 | ------- | |
322 | The msg_id of the message sent. |
|
322 | The msg_id of the message sent. | |
323 | """ |
|
323 | """ | |
324 | content = dict(oname=oname, detail_level=detail_level) |
|
324 | content = dict(oname=oname, detail_level=detail_level) | |
325 | msg = self.session.msg('object_info_request', content) |
|
325 | msg = self.session.msg('object_info_request', content) | |
326 | self._queue_send(msg) |
|
326 | self._queue_send(msg) | |
327 | return msg['header']['msg_id'] |
|
327 | return msg['header']['msg_id'] | |
328 |
|
328 | |||
329 | def history(self, raw=True, output=False, hist_access_type='range', **kwargs): |
|
329 | def history(self, raw=True, output=False, hist_access_type='range', **kwargs): | |
330 | """Get entries from the history list. |
|
330 | """Get entries from the history list. | |
331 |
|
331 | |||
332 | Parameters |
|
332 | Parameters | |
333 | ---------- |
|
333 | ---------- | |
334 | raw : bool |
|
334 | raw : bool | |
335 | If True, return the raw input. |
|
335 | If True, return the raw input. | |
336 | output : bool |
|
336 | output : bool | |
337 | If True, then return the output as well. |
|
337 | If True, then return the output as well. | |
338 | hist_access_type : str |
|
338 | hist_access_type : str | |
339 | 'range' (fill in session, start and stop params), 'tail' (fill in n) |
|
339 | 'range' (fill in session, start and stop params), 'tail' (fill in n) | |
340 | or 'search' (fill in pattern param). |
|
340 | or 'search' (fill in pattern param). | |
341 |
|
341 | |||
342 | session : int |
|
342 | session : int | |
343 | For a range request, the session from which to get lines. Session |
|
343 | For a range request, the session from which to get lines. Session | |
344 | numbers are positive integers; negative ones count back from the |
|
344 | numbers are positive integers; negative ones count back from the | |
345 | current session. |
|
345 | current session. | |
346 | start : int |
|
346 | start : int | |
347 | The first line number of a history range. |
|
347 | The first line number of a history range. | |
348 | stop : int |
|
348 | stop : int | |
349 | The final (excluded) line number of a history range. |
|
349 | The final (excluded) line number of a history range. | |
350 |
|
350 | |||
351 | n : int |
|
351 | n : int | |
352 | The number of lines of history to get for a tail request. |
|
352 | The number of lines of history to get for a tail request. | |
353 |
|
353 | |||
354 | pattern : str |
|
354 | pattern : str | |
355 | The glob-syntax pattern for a search request. |
|
355 | The glob-syntax pattern for a search request. | |
356 |
|
356 | |||
357 | Returns |
|
357 | Returns | |
358 | ------- |
|
358 | ------- | |
359 | The msg_id of the message sent. |
|
359 | The msg_id of the message sent. | |
360 | """ |
|
360 | """ | |
361 | content = dict(raw=raw, output=output, hist_access_type=hist_access_type, |
|
361 | content = dict(raw=raw, output=output, hist_access_type=hist_access_type, | |
362 | **kwargs) |
|
362 | **kwargs) | |
363 | msg = self.session.msg('history_request', content) |
|
363 | msg = self.session.msg('history_request', content) | |
364 | self._queue_send(msg) |
|
364 | self._queue_send(msg) | |
365 | return msg['header']['msg_id'] |
|
365 | return msg['header']['msg_id'] | |
366 |
|
366 | |||
367 | def shutdown(self, restart=False): |
|
367 | def shutdown(self, restart=False): | |
368 | """Request an immediate kernel shutdown. |
|
368 | """Request an immediate kernel shutdown. | |
369 |
|
369 | |||
370 | Upon receipt of the (empty) reply, client code can safely assume that |
|
370 | Upon receipt of the (empty) reply, client code can safely assume that | |
371 | the kernel has shut down and it's safe to forcefully terminate it if |
|
371 | the kernel has shut down and it's safe to forcefully terminate it if | |
372 | it's still alive. |
|
372 | it's still alive. | |
373 |
|
373 | |||
374 | The kernel will send the reply via a function registered with Python's |
|
374 | The kernel will send the reply via a function registered with Python's | |
375 | atexit module, ensuring it's truly done as the kernel is done with all |
|
375 | atexit module, ensuring it's truly done as the kernel is done with all | |
376 | normal operation. |
|
376 | normal operation. | |
377 | """ |
|
377 | """ | |
378 | # Send quit message to kernel. Once we implement kernel-side setattr, |
|
378 | # Send quit message to kernel. Once we implement kernel-side setattr, | |
379 | # this should probably be done that way, but for now this will do. |
|
379 | # this should probably be done that way, but for now this will do. | |
380 | msg = self.session.msg('shutdown_request', {'restart':restart}) |
|
380 | msg = self.session.msg('shutdown_request', {'restart':restart}) | |
381 | self._queue_send(msg) |
|
381 | self._queue_send(msg) | |
382 | return msg['header']['msg_id'] |
|
382 | return msg['header']['msg_id'] | |
383 |
|
383 | |||
384 |
|
384 | |||
385 |
|
385 | |||
386 | class SubSocketChannel(ZMQSocketChannel): |
|
386 | class SubSocketChannel(ZMQSocketChannel): | |
387 | """The SUB channel which listens for messages that the kernel publishes. |
|
387 | """The SUB channel which listens for messages that the kernel publishes. | |
388 | """ |
|
388 | """ | |
389 |
|
389 | |||
390 | def __init__(self, context, session, address): |
|
390 | def __init__(self, context, session, address): | |
391 | super(SubSocketChannel, self).__init__(context, session, address) |
|
391 | super(SubSocketChannel, self).__init__(context, session, address) | |
392 | self.ioloop = ioloop.IOLoop() |
|
392 | self.ioloop = ioloop.IOLoop() | |
393 |
|
393 | |||
394 | def run(self): |
|
394 | def run(self): | |
395 | """The thread's main activity. Call start() instead.""" |
|
395 | """The thread's main activity. Call start() instead.""" | |
396 | self.socket = self.context.socket(zmq.SUB) |
|
396 | self.socket = self.context.socket(zmq.SUB) | |
397 | self.socket.setsockopt(zmq.SUBSCRIBE,b'') |
|
397 | self.socket.setsockopt(zmq.SUBSCRIBE,b'') | |
398 | self.socket.setsockopt(zmq.IDENTITY, self.session.bsession) |
|
398 | self.socket.setsockopt(zmq.IDENTITY, self.session.bsession) | |
399 | self.socket.connect('tcp://%s:%i' % self.address) |
|
399 | self.socket.connect('tcp://%s:%i' % self.address) | |
400 | self.stream = zmqstream.ZMQStream(self.socket, self.ioloop) |
|
400 | self.stream = zmqstream.ZMQStream(self.socket, self.ioloop) | |
401 | self.stream.on_recv(self._handle_recv) |
|
401 | self.stream.on_recv(self._handle_recv) | |
402 | self._run_loop() |
|
402 | self._run_loop() | |
403 | try: |
|
403 | try: | |
404 | self.socket.close() |
|
404 | self.socket.close() | |
405 | except: |
|
405 | except: | |
406 | pass |
|
406 | pass | |
407 |
|
407 | |||
408 | def stop(self): |
|
408 | def stop(self): | |
409 | self.ioloop.stop() |
|
409 | self.ioloop.stop() | |
410 | super(SubSocketChannel, self).stop() |
|
410 | super(SubSocketChannel, self).stop() | |
411 |
|
411 | |||
412 | def call_handlers(self, msg): |
|
412 | def call_handlers(self, msg): | |
413 | """This method is called in the ioloop thread when a message arrives. |
|
413 | """This method is called in the ioloop thread when a message arrives. | |
414 |
|
414 | |||
415 | Subclasses should override this method to handle incoming messages. |
|
415 | Subclasses should override this method to handle incoming messages. | |
416 | It is important to remember that this method is called in the thread |
|
416 | It is important to remember that this method is called in the thread | |
417 | so that some logic must be done to ensure that the application leve |
|
417 | so that some logic must be done to ensure that the application leve | |
418 | handlers are called in the application thread. |
|
418 | handlers are called in the application thread. | |
419 | """ |
|
419 | """ | |
420 | raise NotImplementedError('call_handlers must be defined in a subclass.') |
|
420 | raise NotImplementedError('call_handlers must be defined in a subclass.') | |
421 |
|
421 | |||
422 | def flush(self, timeout=1.0): |
|
422 | def flush(self, timeout=1.0): | |
423 | """Immediately processes all pending messages on the SUB channel. |
|
423 | """Immediately processes all pending messages on the SUB channel. | |
424 |
|
424 | |||
425 | Callers should use this method to ensure that :method:`call_handlers` |
|
425 | Callers should use this method to ensure that :method:`call_handlers` | |
426 | has been called for all messages that have been received on the |
|
426 | has been called for all messages that have been received on the | |
427 | 0MQ SUB socket of this channel. |
|
427 | 0MQ SUB socket of this channel. | |
428 |
|
428 | |||
429 | This method is thread safe. |
|
429 | This method is thread safe. | |
430 |
|
430 | |||
431 | Parameters |
|
431 | Parameters | |
432 | ---------- |
|
432 | ---------- | |
433 | timeout : float, optional |
|
433 | timeout : float, optional | |
434 | The maximum amount of time to spend flushing, in seconds. The |
|
434 | The maximum amount of time to spend flushing, in seconds. The | |
435 | default is one second. |
|
435 | default is one second. | |
436 | """ |
|
436 | """ | |
437 | # We do the IOLoop callback process twice to ensure that the IOLoop |
|
437 | # We do the IOLoop callback process twice to ensure that the IOLoop | |
438 | # gets to perform at least one full poll. |
|
438 | # gets to perform at least one full poll. | |
439 | stop_time = time.time() + timeout |
|
439 | stop_time = time.time() + timeout | |
440 | for i in xrange(2): |
|
440 | for i in xrange(2): | |
441 | self._flushed = False |
|
441 | self._flushed = False | |
442 | self.ioloop.add_callback(self._flush) |
|
442 | self.ioloop.add_callback(self._flush) | |
443 | while not self._flushed and time.time() < stop_time: |
|
443 | while not self._flushed and time.time() < stop_time: | |
444 | time.sleep(0.01) |
|
444 | time.sleep(0.01) | |
445 |
|
445 | |||
446 | def _flush(self): |
|
446 | def _flush(self): | |
447 | """Callback for :method:`self.flush`.""" |
|
447 | """Callback for :method:`self.flush`.""" | |
448 | self.stream.flush() |
|
448 | self.stream.flush() | |
449 | self._flushed = True |
|
449 | self._flushed = True | |
450 |
|
450 | |||
451 |
|
451 | |||
452 | class StdInSocketChannel(ZMQSocketChannel): |
|
452 | class StdInSocketChannel(ZMQSocketChannel): | |
453 | """A reply channel to handle raw_input requests that the kernel makes.""" |
|
453 | """A reply channel to handle raw_input requests that the kernel makes.""" | |
454 |
|
454 | |||
455 | msg_queue = None |
|
455 | msg_queue = None | |
456 |
|
456 | |||
457 | def __init__(self, context, session, address): |
|
457 | def __init__(self, context, session, address): | |
458 | super(StdInSocketChannel, self).__init__(context, session, address) |
|
458 | super(StdInSocketChannel, self).__init__(context, session, address) | |
459 | self.ioloop = ioloop.IOLoop() |
|
459 | self.ioloop = ioloop.IOLoop() | |
460 |
|
460 | |||
461 | def run(self): |
|
461 | def run(self): | |
462 | """The thread's main activity. Call start() instead.""" |
|
462 | """The thread's main activity. Call start() instead.""" | |
463 | self.socket = self.context.socket(zmq.DEALER) |
|
463 | self.socket = self.context.socket(zmq.DEALER) | |
464 | self.socket.setsockopt(zmq.IDENTITY, self.session.bsession) |
|
464 | self.socket.setsockopt(zmq.IDENTITY, self.session.bsession) | |
465 | self.socket.connect('tcp://%s:%i' % self.address) |
|
465 | self.socket.connect('tcp://%s:%i' % self.address) | |
466 | self.stream = zmqstream.ZMQStream(self.socket, self.ioloop) |
|
466 | self.stream = zmqstream.ZMQStream(self.socket, self.ioloop) | |
467 | self.stream.on_recv(self._handle_recv) |
|
467 | self.stream.on_recv(self._handle_recv) | |
468 | self._run_loop() |
|
468 | self._run_loop() | |
469 | try: |
|
469 | try: | |
470 | self.socket.close() |
|
470 | self.socket.close() | |
471 | except: |
|
471 | except: | |
472 | pass |
|
472 | pass | |
473 |
|
473 | |||
474 |
|
474 | |||
475 | def stop(self): |
|
475 | def stop(self): | |
476 | self.ioloop.stop() |
|
476 | self.ioloop.stop() | |
477 | super(StdInSocketChannel, self).stop() |
|
477 | super(StdInSocketChannel, self).stop() | |
478 |
|
478 | |||
479 | def call_handlers(self, msg): |
|
479 | def call_handlers(self, msg): | |
480 | """This method is called in the ioloop thread when a message arrives. |
|
480 | """This method is called in the ioloop thread when a message arrives. | |
481 |
|
481 | |||
482 | Subclasses should override this method to handle incoming messages. |
|
482 | Subclasses should override this method to handle incoming messages. | |
483 | It is important to remember that this method is called in the thread |
|
483 | It is important to remember that this method is called in the thread | |
484 | so that some logic must be done to ensure that the application leve |
|
484 | so that some logic must be done to ensure that the application leve | |
485 | handlers are called in the application thread. |
|
485 | handlers are called in the application thread. | |
486 | """ |
|
486 | """ | |
487 | raise NotImplementedError('call_handlers must be defined in a subclass.') |
|
487 | raise NotImplementedError('call_handlers must be defined in a subclass.') | |
488 |
|
488 | |||
489 | def input(self, string): |
|
489 | def input(self, string): | |
490 | """Send a string of raw input to the kernel.""" |
|
490 | """Send a string of raw input to the kernel.""" | |
491 | content = dict(value=string) |
|
491 | content = dict(value=string) | |
492 | msg = self.session.msg('input_reply', content) |
|
492 | msg = self.session.msg('input_reply', content) | |
493 | self._queue_send(msg) |
|
493 | self._queue_send(msg) | |
494 |
|
494 | |||
495 |
|
495 | |||
496 | class HBSocketChannel(ZMQSocketChannel): |
|
496 | class HBSocketChannel(ZMQSocketChannel): | |
497 | """The heartbeat channel which monitors the kernel heartbeat. |
|
497 | """The heartbeat channel which monitors the kernel heartbeat. | |
498 |
|
498 | |||
499 | Note that the heartbeat channel is paused by default. As long as you start |
|
499 | Note that the heartbeat channel is paused by default. As long as you start | |
500 | this channel, the kernel manager will ensure that it is paused and un-paused |
|
500 | this channel, the kernel manager will ensure that it is paused and un-paused | |
501 | as appropriate. |
|
501 | as appropriate. | |
502 | """ |
|
502 | """ | |
503 |
|
503 | |||
504 | time_to_dead = 3.0 |
|
504 | time_to_dead = 3.0 | |
505 | socket = None |
|
505 | socket = None | |
506 | poller = None |
|
506 | poller = None | |
507 | _running = None |
|
507 | _running = None | |
508 | _pause = None |
|
508 | _pause = None | |
509 | _beating = None |
|
509 | _beating = None | |
510 |
|
510 | |||
511 | def __init__(self, context, session, address): |
|
511 | def __init__(self, context, session, address): | |
512 | super(HBSocketChannel, self).__init__(context, session, address) |
|
512 | super(HBSocketChannel, self).__init__(context, session, address) | |
513 | self._running = False |
|
513 | self._running = False | |
514 | self._pause =True |
|
514 | self._pause =True | |
515 | self.poller = zmq.Poller() |
|
515 | self.poller = zmq.Poller() | |
516 |
|
516 | |||
517 | def _create_socket(self): |
|
517 | def _create_socket(self): | |
518 | if self.socket is not None: |
|
518 | if self.socket is not None: | |
519 | # close previous socket, before opening a new one |
|
519 | # close previous socket, before opening a new one | |
520 | self.poller.unregister(self.socket) |
|
520 | self.poller.unregister(self.socket) | |
521 | self.socket.close() |
|
521 | self.socket.close() | |
522 | self.socket = self.context.socket(zmq.REQ) |
|
522 | self.socket = self.context.socket(zmq.REQ) | |
523 | self.socket.setsockopt(zmq.LINGER, 0) |
|
523 | self.socket.setsockopt(zmq.LINGER, 0) | |
524 | self.socket.connect('tcp://%s:%i' % self.address) |
|
524 | self.socket.connect('tcp://%s:%i' % self.address) | |
525 |
|
525 | |||
526 | self.poller.register(self.socket, zmq.POLLIN) |
|
526 | self.poller.register(self.socket, zmq.POLLIN) | |
527 |
|
527 | |||
528 | def _poll(self, start_time): |
|
528 | def _poll(self, start_time): | |
529 | """poll for heartbeat replies until we reach self.time_to_dead |
|
529 | """poll for heartbeat replies until we reach self.time_to_dead | |
530 |
|
530 | |||
531 | Ignores interrupts, and returns the result of poll(), which |
|
531 | Ignores interrupts, and returns the result of poll(), which | |
532 | will be an empty list if no messages arrived before the timeout, |
|
532 | will be an empty list if no messages arrived before the timeout, | |
533 | or the event tuple if there is a message to receive. |
|
533 | or the event tuple if there is a message to receive. | |
534 | """ |
|
534 | """ | |
535 |
|
535 | |||
536 | until_dead = self.time_to_dead - (time.time() - start_time) |
|
536 | until_dead = self.time_to_dead - (time.time() - start_time) | |
537 | # ensure poll at least once |
|
537 | # ensure poll at least once | |
538 | until_dead = max(until_dead, 1e-3) |
|
538 | until_dead = max(until_dead, 1e-3) | |
539 | events = [] |
|
539 | events = [] | |
540 | while True: |
|
540 | while True: | |
541 | try: |
|
541 | try: | |
542 | events = self.poller.poll(1000 * until_dead) |
|
542 | events = self.poller.poll(1000 * until_dead) | |
543 | except ZMQError as e: |
|
543 | except ZMQError as e: | |
544 | if e.errno == errno.EINTR: |
|
544 | if e.errno == errno.EINTR: | |
545 | # ignore interrupts during heartbeat |
|
545 | # ignore interrupts during heartbeat | |
546 | # this may never actually happen |
|
546 | # this may never actually happen | |
547 | until_dead = self.time_to_dead - (time.time() - start_time) |
|
547 | until_dead = self.time_to_dead - (time.time() - start_time) | |
548 | until_dead = max(until_dead, 1e-3) |
|
548 | until_dead = max(until_dead, 1e-3) | |
549 | pass |
|
549 | pass | |
550 | else: |
|
550 | else: | |
551 | raise |
|
551 | raise | |
552 | except Exception: |
|
552 | except Exception: | |
553 | if self._exiting: |
|
553 | if self._exiting: | |
554 | break |
|
554 | break | |
555 | else: |
|
555 | else: | |
556 | raise |
|
556 | raise | |
557 | else: |
|
557 | else: | |
558 | break |
|
558 | break | |
559 | return events |
|
559 | return events | |
560 |
|
560 | |||
561 | def run(self): |
|
561 | def run(self): | |
562 | """The thread's main activity. Call start() instead.""" |
|
562 | """The thread's main activity. Call start() instead.""" | |
563 | self._create_socket() |
|
563 | self._create_socket() | |
564 | self._running = True |
|
564 | self._running = True | |
565 | self._beating = True |
|
565 | self._beating = True | |
566 |
|
566 | |||
567 | while self._running: |
|
567 | while self._running: | |
568 | if self._pause: |
|
568 | if self._pause: | |
569 | # just sleep, and skip the rest of the loop |
|
569 | # just sleep, and skip the rest of the loop | |
570 | time.sleep(self.time_to_dead) |
|
570 | time.sleep(self.time_to_dead) | |
571 | continue |
|
571 | continue | |
572 |
|
572 | |||
573 | since_last_heartbeat = 0.0 |
|
573 | since_last_heartbeat = 0.0 | |
574 | # io.rprint('Ping from HB channel') # dbg |
|
574 | # io.rprint('Ping from HB channel') # dbg | |
575 | # no need to catch EFSM here, because the previous event was |
|
575 | # no need to catch EFSM here, because the previous event was | |
576 | # either a recv or connect, which cannot be followed by EFSM |
|
576 | # either a recv or connect, which cannot be followed by EFSM | |
577 | self.socket.send(b'ping') |
|
577 | self.socket.send(b'ping') | |
578 | request_time = time.time() |
|
578 | request_time = time.time() | |
579 | ready = self._poll(request_time) |
|
579 | ready = self._poll(request_time) | |
580 | if ready: |
|
580 | if ready: | |
581 | self._beating = True |
|
581 | self._beating = True | |
582 | # the poll above guarantees we have something to recv |
|
582 | # the poll above guarantees we have something to recv | |
583 | self.socket.recv() |
|
583 | self.socket.recv() | |
584 | # sleep the remainder of the cycle |
|
584 | # sleep the remainder of the cycle | |
585 | remainder = self.time_to_dead - (time.time() - request_time) |
|
585 | remainder = self.time_to_dead - (time.time() - request_time) | |
586 | if remainder > 0: |
|
586 | if remainder > 0: | |
587 | time.sleep(remainder) |
|
587 | time.sleep(remainder) | |
588 | continue |
|
588 | continue | |
589 | else: |
|
589 | else: | |
590 | # nothing was received within the time limit, signal heart failure |
|
590 | # nothing was received within the time limit, signal heart failure | |
591 | self._beating = False |
|
591 | self._beating = False | |
592 | since_last_heartbeat = time.time() - request_time |
|
592 | since_last_heartbeat = time.time() - request_time | |
593 | self.call_handlers(since_last_heartbeat) |
|
593 | self.call_handlers(since_last_heartbeat) | |
594 | # and close/reopen the socket, because the REQ/REP cycle has been broken |
|
594 | # and close/reopen the socket, because the REQ/REP cycle has been broken | |
595 | self._create_socket() |
|
595 | self._create_socket() | |
596 | continue |
|
596 | continue | |
597 | try: |
|
597 | try: | |
598 | self.socket.close() |
|
598 | self.socket.close() | |
599 | except: |
|
599 | except: | |
600 | pass |
|
600 | pass | |
601 |
|
601 | |||
602 | def pause(self): |
|
602 | def pause(self): | |
603 | """Pause the heartbeat.""" |
|
603 | """Pause the heartbeat.""" | |
604 | self._pause = True |
|
604 | self._pause = True | |
605 |
|
605 | |||
606 | def unpause(self): |
|
606 | def unpause(self): | |
607 | """Unpause the heartbeat.""" |
|
607 | """Unpause the heartbeat.""" | |
608 | self._pause = False |
|
608 | self._pause = False | |
609 |
|
609 | |||
610 | def is_beating(self): |
|
610 | def is_beating(self): | |
611 | """Is the heartbeat running and responsive (and not paused).""" |
|
611 | """Is the heartbeat running and responsive (and not paused).""" | |
612 | if self.is_alive() and not self._pause and self._beating: |
|
612 | if self.is_alive() and not self._pause and self._beating: | |
613 | return True |
|
613 | return True | |
614 | else: |
|
614 | else: | |
615 | return False |
|
615 | return False | |
616 |
|
616 | |||
617 | def stop(self): |
|
617 | def stop(self): | |
618 | self._running = False |
|
618 | self._running = False | |
619 | super(HBSocketChannel, self).stop() |
|
619 | super(HBSocketChannel, self).stop() | |
620 |
|
620 | |||
621 | def call_handlers(self, since_last_heartbeat): |
|
621 | def call_handlers(self, since_last_heartbeat): | |
622 | """This method is called in the ioloop thread when a message arrives. |
|
622 | """This method is called in the ioloop thread when a message arrives. | |
623 |
|
623 | |||
624 | Subclasses should override this method to handle incoming messages. |
|
624 | Subclasses should override this method to handle incoming messages. | |
625 | It is important to remember that this method is called in the thread |
|
625 | It is important to remember that this method is called in the thread | |
626 | so that some logic must be done to ensure that the application level |
|
626 | so that some logic must be done to ensure that the application level | |
627 | handlers are called in the application thread. |
|
627 | handlers are called in the application thread. | |
628 | """ |
|
628 | """ | |
629 | raise NotImplementedError('call_handlers must be defined in a subclass.') |
|
629 | raise NotImplementedError('call_handlers must be defined in a subclass.') | |
630 |
|
630 | |||
631 |
|
631 | |||
632 | #----------------------------------------------------------------------------- |
|
632 | #----------------------------------------------------------------------------- | |
633 | # Main kernel manager class |
|
633 | # Main kernel manager class | |
634 | #----------------------------------------------------------------------------- |
|
634 | #----------------------------------------------------------------------------- | |
635 |
|
635 | |||
636 | class KernelManager(HasTraits): |
|
636 | class KernelManager(HasTraits): | |
637 | """ Manages a kernel for a frontend. |
|
637 | """ Manages a kernel for a frontend. | |
638 |
|
638 | |||
639 | The SUB channel is for the frontend to receive messages published by the |
|
639 | The SUB channel is for the frontend to receive messages published by the | |
640 | kernel. |
|
640 | kernel. | |
641 |
|
641 | |||
642 | The REQ channel is for the frontend to make requests of the kernel. |
|
642 | The REQ channel is for the frontend to make requests of the kernel. | |
643 |
|
643 | |||
644 | The REP channel is for the kernel to request stdin (raw_input) from the |
|
644 | The REP channel is for the kernel to request stdin (raw_input) from the | |
645 | frontend. |
|
645 | frontend. | |
646 | """ |
|
646 | """ | |
647 | # config object for passing to child configurables |
|
647 | # config object for passing to child configurables | |
648 | config = Instance(Config) |
|
648 | config = Instance(Config) | |
649 |
|
649 | |||
650 | # The PyZMQ Context to use for communication with the kernel. |
|
650 | # The PyZMQ Context to use for communication with the kernel. | |
651 | context = Instance(zmq.Context) |
|
651 | context = Instance(zmq.Context) | |
652 | def _context_default(self): |
|
652 | def _context_default(self): | |
653 | return zmq.Context.instance() |
|
653 | return zmq.Context.instance() | |
654 |
|
654 | |||
655 | # The Session to use for communication with the kernel. |
|
655 | # The Session to use for communication with the kernel. | |
656 | session = Instance(Session) |
|
656 | session = Instance(Session) | |
657 |
|
657 | |||
658 | # The kernel process with which the KernelManager is communicating. |
|
658 | # The kernel process with which the KernelManager is communicating. | |
659 | kernel = Instance(Popen) |
|
659 | kernel = Instance(Popen) | |
660 |
|
660 | |||
661 | # The addresses for the communication channels. |
|
661 | # The addresses for the communication channels. | |
662 | connection_file = Unicode('') |
|
662 | connection_file = Unicode('') | |
663 | ip = Unicode(LOCALHOST) |
|
663 | ip = Unicode(LOCALHOST) | |
664 | def _ip_changed(self, name, old, new): |
|
664 | def _ip_changed(self, name, old, new): | |
665 | if new == '*': |
|
665 | if new == '*': | |
666 | self.ip = '0.0.0.0' |
|
666 | self.ip = '0.0.0.0' | |
667 | shell_port = Integer(0) |
|
667 | shell_port = Integer(0) | |
668 | iopub_port = Integer(0) |
|
668 | iopub_port = Integer(0) | |
669 | stdin_port = Integer(0) |
|
669 | stdin_port = Integer(0) | |
670 | hb_port = Integer(0) |
|
670 | hb_port = Integer(0) | |
671 |
|
671 | |||
672 | # The classes to use for the various channels. |
|
672 | # The classes to use for the various channels. | |
673 | shell_channel_class = Type(ShellSocketChannel) |
|
673 | shell_channel_class = Type(ShellSocketChannel) | |
674 | sub_channel_class = Type(SubSocketChannel) |
|
674 | sub_channel_class = Type(SubSocketChannel) | |
675 | stdin_channel_class = Type(StdInSocketChannel) |
|
675 | stdin_channel_class = Type(StdInSocketChannel) | |
676 | hb_channel_class = Type(HBSocketChannel) |
|
676 | hb_channel_class = Type(HBSocketChannel) | |
677 |
|
677 | |||
678 | # Protected traits. |
|
678 | # Protected traits. | |
679 | _launch_args = Any |
|
679 | _launch_args = Any | |
680 | _shell_channel = Any |
|
680 | _shell_channel = Any | |
681 | _sub_channel = Any |
|
681 | _sub_channel = Any | |
682 | _stdin_channel = Any |
|
682 | _stdin_channel = Any | |
683 | _hb_channel = Any |
|
683 | _hb_channel = Any | |
684 | _connection_file_written=Bool(False) |
|
684 | _connection_file_written=Bool(False) | |
685 |
|
685 | |||
686 | def __init__(self, **kwargs): |
|
686 | def __init__(self, **kwargs): | |
687 | super(KernelManager, self).__init__(**kwargs) |
|
687 | super(KernelManager, self).__init__(**kwargs) | |
688 | if self.session is None: |
|
688 | if self.session is None: | |
689 | self.session = Session(config=self.config) |
|
689 | self.session = Session(config=self.config) | |
690 |
|
690 | |||
691 | def __del__(self): |
|
691 | def __del__(self): | |
692 | self.cleanup_connection_file() |
|
692 | self.cleanup_connection_file() | |
693 |
|
693 | |||
694 |
|
694 | |||
695 | #-------------------------------------------------------------------------- |
|
695 | #-------------------------------------------------------------------------- | |
696 | # Channel management methods: |
|
696 | # Channel management methods: | |
697 | #-------------------------------------------------------------------------- |
|
697 | #-------------------------------------------------------------------------- | |
698 |
|
698 | |||
699 | def start_channels(self, shell=True, sub=True, stdin=True, hb=True): |
|
699 | def start_channels(self, shell=True, sub=True, stdin=True, hb=True): | |
700 | """Starts the channels for this kernel. |
|
700 | """Starts the channels for this kernel. | |
701 |
|
701 | |||
702 | This will create the channels if they do not exist and then start |
|
702 | This will create the channels if they do not exist and then start | |
703 | them. If port numbers of 0 are being used (random ports) then you |
|
703 | them. If port numbers of 0 are being used (random ports) then you | |
704 | must first call :method:`start_kernel`. If the channels have been |
|
704 | must first call :method:`start_kernel`. If the channels have been | |
705 | stopped and you call this, :class:`RuntimeError` will be raised. |
|
705 | stopped and you call this, :class:`RuntimeError` will be raised. | |
706 | """ |
|
706 | """ | |
707 | if shell: |
|
707 | if shell: | |
708 | self.shell_channel.start() |
|
708 | self.shell_channel.start() | |
709 | if sub: |
|
709 | if sub: | |
710 | self.sub_channel.start() |
|
710 | self.sub_channel.start() | |
711 | if stdin: |
|
711 | if stdin: | |
712 | self.stdin_channel.start() |
|
712 | self.stdin_channel.start() | |
713 | self.shell_channel.allow_stdin = True |
|
713 | self.shell_channel.allow_stdin = True | |
714 | else: |
|
714 | else: | |
715 | self.shell_channel.allow_stdin = False |
|
715 | self.shell_channel.allow_stdin = False | |
716 | if hb: |
|
716 | if hb: | |
717 | self.hb_channel.start() |
|
717 | self.hb_channel.start() | |
718 |
|
718 | |||
719 | def stop_channels(self): |
|
719 | def stop_channels(self): | |
720 | """Stops all the running channels for this kernel. |
|
720 | """Stops all the running channels for this kernel. | |
721 | """ |
|
721 | """ | |
722 | if self.shell_channel.is_alive(): |
|
722 | if self.shell_channel.is_alive(): | |
723 | self.shell_channel.stop() |
|
723 | self.shell_channel.stop() | |
724 | if self.sub_channel.is_alive(): |
|
724 | if self.sub_channel.is_alive(): | |
725 | self.sub_channel.stop() |
|
725 | self.sub_channel.stop() | |
726 | if self.stdin_channel.is_alive(): |
|
726 | if self.stdin_channel.is_alive(): | |
727 | self.stdin_channel.stop() |
|
727 | self.stdin_channel.stop() | |
728 | if self.hb_channel.is_alive(): |
|
728 | if self.hb_channel.is_alive(): | |
729 | self.hb_channel.stop() |
|
729 | self.hb_channel.stop() | |
730 |
|
730 | |||
731 | @property |
|
731 | @property | |
732 | def channels_running(self): |
|
732 | def channels_running(self): | |
733 | """Are any of the channels created and running?""" |
|
733 | """Are any of the channels created and running?""" | |
734 | return (self.shell_channel.is_alive() or self.sub_channel.is_alive() or |
|
734 | return (self.shell_channel.is_alive() or self.sub_channel.is_alive() or | |
735 | self.stdin_channel.is_alive() or self.hb_channel.is_alive()) |
|
735 | self.stdin_channel.is_alive() or self.hb_channel.is_alive()) | |
736 |
|
736 | |||
737 | #-------------------------------------------------------------------------- |
|
737 | #-------------------------------------------------------------------------- | |
738 | # Kernel process management methods: |
|
738 | # Kernel process management methods: | |
739 | #-------------------------------------------------------------------------- |
|
739 | #-------------------------------------------------------------------------- | |
740 |
|
740 | |||
741 | def cleanup_connection_file(self): |
|
741 | def cleanup_connection_file(self): | |
742 | """cleanup connection file *if we wrote it* |
|
742 | """cleanup connection file *if we wrote it* | |
743 |
|
743 | |||
744 | Will not raise if the connection file was already removed somehow. |
|
744 | Will not raise if the connection file was already removed somehow. | |
745 | """ |
|
745 | """ | |
746 | if self._connection_file_written: |
|
746 | if self._connection_file_written: | |
747 | # cleanup connection files on full shutdown of kernel we started |
|
747 | # cleanup connection files on full shutdown of kernel we started | |
748 | self._connection_file_written = False |
|
748 | self._connection_file_written = False | |
749 | try: |
|
749 | try: | |
750 | os.remove(self.connection_file) |
|
750 | os.remove(self.connection_file) | |
751 | except OSError: |
|
751 | except OSError: | |
752 | pass |
|
752 | pass | |
753 |
|
753 | |||
754 | def load_connection_file(self): |
|
754 | def load_connection_file(self): | |
755 | """load connection info from JSON dict in self.connection_file""" |
|
755 | """load connection info from JSON dict in self.connection_file""" | |
756 | with open(self.connection_file) as f: |
|
756 | with open(self.connection_file) as f: | |
757 | cfg = json.loads(f.read()) |
|
757 | cfg = json.loads(f.read()) | |
758 |
|
758 | |||
759 | self.ip = cfg['ip'] |
|
759 | self.ip = cfg['ip'] | |
760 | self.shell_port = cfg['shell_port'] |
|
760 | self.shell_port = cfg['shell_port'] | |
761 | self.stdin_port = cfg['stdin_port'] |
|
761 | self.stdin_port = cfg['stdin_port'] | |
762 | self.iopub_port = cfg['iopub_port'] |
|
762 | self.iopub_port = cfg['iopub_port'] | |
763 | self.hb_port = cfg['hb_port'] |
|
763 | self.hb_port = cfg['hb_port'] | |
764 | self.session.key = str_to_bytes(cfg['key']) |
|
764 | self.session.key = str_to_bytes(cfg['key']) | |
765 |
|
765 | |||
766 | def write_connection_file(self): |
|
766 | def write_connection_file(self): | |
767 | """write connection info to JSON dict in self.connection_file""" |
|
767 | """write connection info to JSON dict in self.connection_file""" | |
768 | if self._connection_file_written: |
|
768 | if self._connection_file_written: | |
769 | return |
|
769 | return | |
770 | self.connection_file,cfg = write_connection_file(self.connection_file, |
|
770 | self.connection_file,cfg = write_connection_file(self.connection_file, | |
771 | ip=self.ip, key=self.session.key, |
|
771 | ip=self.ip, key=self.session.key, | |
772 | stdin_port=self.stdin_port, iopub_port=self.iopub_port, |
|
772 | stdin_port=self.stdin_port, iopub_port=self.iopub_port, | |
773 | shell_port=self.shell_port, hb_port=self.hb_port) |
|
773 | shell_port=self.shell_port, hb_port=self.hb_port) | |
774 | # write_connection_file also sets default ports: |
|
774 | # write_connection_file also sets default ports: | |
775 | self.shell_port = cfg['shell_port'] |
|
775 | self.shell_port = cfg['shell_port'] | |
776 | self.stdin_port = cfg['stdin_port'] |
|
776 | self.stdin_port = cfg['stdin_port'] | |
777 | self.iopub_port = cfg['iopub_port'] |
|
777 | self.iopub_port = cfg['iopub_port'] | |
778 | self.hb_port = cfg['hb_port'] |
|
778 | self.hb_port = cfg['hb_port'] | |
779 |
|
779 | |||
780 | self._connection_file_written = True |
|
780 | self._connection_file_written = True | |
781 |
|
781 | |||
782 | def start_kernel(self, **kw): |
|
782 | def start_kernel(self, **kw): | |
783 | """Starts a kernel process and configures the manager to use it. |
|
783 | """Starts a kernel process and configures the manager to use it. | |
784 |
|
784 | |||
785 | If random ports (port=0) are being used, this method must be called |
|
785 | If random ports (port=0) are being used, this method must be called | |
786 | before the channels are created. |
|
786 | before the channels are created. | |
787 |
|
787 | |||
788 | Parameters: |
|
788 | Parameters: | |
789 | ----------- |
|
789 | ----------- | |
790 | launcher : callable, optional (default None) |
|
790 | launcher : callable, optional (default None) | |
791 | A custom function for launching the kernel process (generally a |
|
791 | A custom function for launching the kernel process (generally a | |
792 | wrapper around ``entry_point.base_launch_kernel``). In most cases, |
|
792 | wrapper around ``entry_point.base_launch_kernel``). In most cases, | |
793 | it should not be necessary to use this parameter. |
|
793 | it should not be necessary to use this parameter. | |
794 |
|
794 | |||
795 | **kw : optional |
|
795 | **kw : optional | |
796 | See respective options for IPython and Python kernels. |
|
796 | See respective options for IPython and Python kernels. | |
797 | """ |
|
797 | """ | |
798 | if self.ip not in LOCAL_IPS: |
|
798 | if self.ip not in LOCAL_IPS: | |
799 | raise RuntimeError("Can only launch a kernel on a local interface. " |
|
799 | raise RuntimeError("Can only launch a kernel on a local interface. " | |
800 | "Make sure that the '*_address' attributes are " |
|
800 | "Make sure that the '*_address' attributes are " | |
801 | "configured properly. " |
|
801 | "configured properly. " | |
802 | "Currently valid addresses are: %s"%LOCAL_IPS |
|
802 | "Currently valid addresses are: %s"%LOCAL_IPS | |
803 | ) |
|
803 | ) | |
804 |
|
804 | |||
805 | # write connection file / get default ports |
|
805 | # write connection file / get default ports | |
806 | self.write_connection_file() |
|
806 | self.write_connection_file() | |
807 |
|
807 | |||
808 | self._launch_args = kw.copy() |
|
808 | self._launch_args = kw.copy() | |
809 | launch_kernel = kw.pop('launcher', None) |
|
809 | launch_kernel = kw.pop('launcher', None) | |
810 | if launch_kernel is None: |
|
810 | if launch_kernel is None: | |
811 | from ipkernel import launch_kernel |
|
811 | from ipkernel import launch_kernel | |
812 | self.kernel = launch_kernel(fname=self.connection_file, **kw) |
|
812 | self.kernel = launch_kernel(fname=self.connection_file, **kw) | |
813 |
|
813 | |||
814 | def shutdown_kernel(self, restart=False): |
|
814 | def shutdown_kernel(self, restart=False): | |
815 |
""" Attempts to the stop the kernel process cleanly. |
|
815 | """ Attempts to the stop the kernel process cleanly. | |
816 | cannot be stopped, it is killed, if possible. |
|
816 | ||
|
817 | If the kernel cannot be stopped and the kernel is local, it is killed. | |||
817 | """ |
|
818 | """ | |
818 | # FIXME: Shutdown does not work on Windows due to ZMQ errors! |
|
819 | # FIXME: Shutdown does not work on Windows due to ZMQ errors! | |
819 | if sys.platform == 'win32': |
|
820 | if sys.platform == 'win32': | |
820 | self.kill_kernel() |
|
821 | self.kill_kernel() | |
821 | return |
|
822 | return | |
822 |
|
823 | |||
823 | # Pause the heart beat channel if it exists. |
|
824 | # Pause the heart beat channel if it exists. | |
824 | if self._hb_channel is not None: |
|
825 | if self._hb_channel is not None: | |
825 | self._hb_channel.pause() |
|
826 | self._hb_channel.pause() | |
826 |
|
827 | |||
827 | # Don't send any additional kernel kill messages immediately, to give |
|
828 | # Don't send any additional kernel kill messages immediately, to give | |
828 | # the kernel a chance to properly execute shutdown actions. Wait for at |
|
829 | # the kernel a chance to properly execute shutdown actions. Wait for at | |
829 | # most 1s, checking every 0.1s. |
|
830 | # most 1s, checking every 0.1s. | |
830 | self.shell_channel.shutdown(restart=restart) |
|
831 | self.shell_channel.shutdown(restart=restart) | |
831 | for i in range(10): |
|
832 | for i in range(10): | |
832 | if self.is_alive: |
|
833 | if self.is_alive: | |
833 | time.sleep(0.1) |
|
834 | time.sleep(0.1) | |
834 | else: |
|
835 | else: | |
835 | break |
|
836 | break | |
836 | else: |
|
837 | else: | |
837 | # OK, we've waited long enough. |
|
838 | # OK, we've waited long enough. | |
838 | if self.has_kernel: |
|
839 | if self.has_kernel: | |
839 | self.kill_kernel() |
|
840 | self.kill_kernel() | |
840 |
|
841 | |||
841 | if not restart and self._connection_file_written: |
|
842 | if not restart and self._connection_file_written: | |
842 | # cleanup connection files on full shutdown of kernel we started |
|
843 | # cleanup connection files on full shutdown of kernel we started | |
843 | self._connection_file_written = False |
|
844 | self._connection_file_written = False | |
844 | try: |
|
845 | try: | |
845 | os.remove(self.connection_file) |
|
846 | os.remove(self.connection_file) | |
846 | except IOError: |
|
847 | except IOError: | |
847 | pass |
|
848 | pass | |
848 |
|
849 | |||
849 | def restart_kernel(self, now=False, **kw): |
|
850 | def restart_kernel(self, now=False, **kw): | |
850 | """Restarts a kernel with the arguments that were used to launch it. |
|
851 | """Restarts a kernel with the arguments that were used to launch it. | |
851 |
|
852 | |||
852 | If the old kernel was launched with random ports, the same ports will be |
|
853 | If the old kernel was launched with random ports, the same ports will be | |
853 | used for the new kernel. |
|
854 | used for the new kernel. | |
854 |
|
855 | |||
855 | Parameters |
|
856 | Parameters | |
856 | ---------- |
|
857 | ---------- | |
857 | now : bool, optional |
|
858 | now : bool, optional | |
858 | If True, the kernel is forcefully restarted *immediately*, without |
|
859 | If True, the kernel is forcefully restarted *immediately*, without | |
859 | having a chance to do any cleanup action. Otherwise the kernel is |
|
860 | having a chance to do any cleanup action. Otherwise the kernel is | |
860 | given 1s to clean up before a forceful restart is issued. |
|
861 | given 1s to clean up before a forceful restart is issued. | |
861 |
|
862 | |||
862 | In all cases the kernel is restarted, the only difference is whether |
|
863 | In all cases the kernel is restarted, the only difference is whether | |
863 | it is given a chance to perform a clean shutdown or not. |
|
864 | it is given a chance to perform a clean shutdown or not. | |
864 |
|
865 | |||
865 | **kw : optional |
|
866 | **kw : optional | |
866 | Any options specified here will replace those used to launch the |
|
867 | Any options specified here will replace those used to launch the | |
867 | kernel. |
|
868 | kernel. | |
868 | """ |
|
869 | """ | |
869 | if self._launch_args is None: |
|
870 | if self._launch_args is None: | |
870 | raise RuntimeError("Cannot restart the kernel. " |
|
871 | raise RuntimeError("Cannot restart the kernel. " | |
871 | "No previous call to 'start_kernel'.") |
|
872 | "No previous call to 'start_kernel'.") | |
872 | else: |
|
873 | else: | |
873 | # Stop currently running kernel. |
|
874 | # Stop currently running kernel. | |
874 | if self.has_kernel: |
|
875 | if self.has_kernel: | |
875 | if now: |
|
876 | if now: | |
876 | self.kill_kernel() |
|
877 | self.kill_kernel() | |
877 | else: |
|
878 | else: | |
878 | self.shutdown_kernel(restart=True) |
|
879 | self.shutdown_kernel(restart=True) | |
879 |
|
880 | |||
880 | # Start new kernel. |
|
881 | # Start new kernel. | |
881 | self._launch_args.update(kw) |
|
882 | self._launch_args.update(kw) | |
882 | self.start_kernel(**self._launch_args) |
|
883 | self.start_kernel(**self._launch_args) | |
883 |
|
884 | |||
884 | # FIXME: Messages get dropped in Windows due to probable ZMQ bug |
|
885 | # FIXME: Messages get dropped in Windows due to probable ZMQ bug | |
885 | # unless there is some delay here. |
|
886 | # unless there is some delay here. | |
886 | if sys.platform == 'win32': |
|
887 | if sys.platform == 'win32': | |
887 | time.sleep(0.2) |
|
888 | time.sleep(0.2) | |
888 |
|
889 | |||
889 | @property |
|
890 | @property | |
890 | def has_kernel(self): |
|
891 | def has_kernel(self): | |
891 | """Returns whether a kernel process has been specified for the kernel |
|
892 | """Returns whether a kernel process has been specified for the kernel | |
892 | manager. |
|
893 | manager. | |
893 | """ |
|
894 | """ | |
894 | return self.kernel is not None |
|
895 | return self.kernel is not None | |
895 |
|
896 | |||
896 | def kill_kernel(self): |
|
897 | def kill_kernel(self): | |
897 |
""" Kill the running kernel. |
|
898 | """ Kill the running kernel. | |
|
899 | ||||
|
900 | This method blocks until the kernel process has terminated. | |||
|
901 | """ | |||
898 | if self.has_kernel: |
|
902 | if self.has_kernel: | |
899 | # Pause the heart beat channel if it exists. |
|
903 | # Pause the heart beat channel if it exists. | |
900 | if self._hb_channel is not None: |
|
904 | if self._hb_channel is not None: | |
901 | self._hb_channel.pause() |
|
905 | self._hb_channel.pause() | |
902 |
|
906 | |||
903 | # Attempt to kill the kernel. |
|
907 | # Signal the kernel to terminate (sends SIGKILL on Unix and calls | |
|
908 | # TerminateProcess() on Win32). | |||
904 | try: |
|
909 | try: | |
905 | self.kernel.kill() |
|
910 | self.kernel.kill() | |
906 | except OSError as e: |
|
911 | except OSError as e: | |
907 | # In Windows, we will get an Access Denied error if the process |
|
912 | # In Windows, we will get an Access Denied error if the process | |
908 | # has already terminated. Ignore it. |
|
913 | # has already terminated. Ignore it. | |
909 | if sys.platform == 'win32': |
|
914 | if sys.platform == 'win32': | |
910 | if e.winerror != 5: |
|
915 | if e.winerror != 5: | |
911 | raise |
|
916 | raise | |
912 | # On Unix, we may get an ESRCH error if the process has already |
|
917 | # On Unix, we may get an ESRCH error if the process has already | |
913 | # terminated. Ignore it. |
|
918 | # terminated. Ignore it. | |
914 | else: |
|
919 | else: | |
915 | from errno import ESRCH |
|
920 | from errno import ESRCH | |
916 | if e.errno != ESRCH: |
|
921 | if e.errno != ESRCH: | |
917 | raise |
|
922 | raise | |
|
923 | ||||
|
924 | # Block until the kernel terminates. | |||
|
925 | self.kernel.wait() | |||
918 | self.kernel = None |
|
926 | self.kernel = None | |
919 | else: |
|
927 | else: | |
920 | raise RuntimeError("Cannot kill kernel. No kernel is running!") |
|
928 | raise RuntimeError("Cannot kill kernel. No kernel is running!") | |
921 |
|
929 | |||
922 | def interrupt_kernel(self): |
|
930 | def interrupt_kernel(self): | |
923 |
""" Interrupts the kernel. |
|
931 | """ Interrupts the kernel. | |
924 | well supported on all platforms. |
|
932 | ||
|
933 | Unlike ``signal_kernel``, this operation is well supported on all | |||
|
934 | platforms. | |||
925 | """ |
|
935 | """ | |
926 | if self.has_kernel: |
|
936 | if self.has_kernel: | |
927 | if sys.platform == 'win32': |
|
937 | if sys.platform == 'win32': | |
928 | from parentpoller import ParentPollerWindows as Poller |
|
938 | from parentpoller import ParentPollerWindows as Poller | |
929 | Poller.send_interrupt(self.kernel.win32_interrupt_event) |
|
939 | Poller.send_interrupt(self.kernel.win32_interrupt_event) | |
930 | else: |
|
940 | else: | |
931 | self.kernel.send_signal(signal.SIGINT) |
|
941 | self.kernel.send_signal(signal.SIGINT) | |
932 | else: |
|
942 | else: | |
933 | raise RuntimeError("Cannot interrupt kernel. No kernel is running!") |
|
943 | raise RuntimeError("Cannot interrupt kernel. No kernel is running!") | |
934 |
|
944 | |||
935 | def signal_kernel(self, signum): |
|
945 | def signal_kernel(self, signum): | |
936 |
""" Sends a signal to the kernel. |
|
946 | """ Sends a signal to the kernel. | |
937 | supported on Windows, this function is only useful on Unix systems. |
|
947 | ||
|
948 | Note that since only SIGTERM is supported on Windows, this function is | |||
|
949 | only useful on Unix systems. | |||
938 | """ |
|
950 | """ | |
939 | if self.has_kernel: |
|
951 | if self.has_kernel: | |
940 | self.kernel.send_signal(signum) |
|
952 | self.kernel.send_signal(signum) | |
941 | else: |
|
953 | else: | |
942 | raise RuntimeError("Cannot signal kernel. No kernel is running!") |
|
954 | raise RuntimeError("Cannot signal kernel. No kernel is running!") | |
943 |
|
955 | |||
944 | @property |
|
956 | @property | |
945 | def is_alive(self): |
|
957 | def is_alive(self): | |
946 | """Is the kernel process still running?""" |
|
958 | """Is the kernel process still running?""" | |
947 | if self.has_kernel: |
|
959 | if self.has_kernel: | |
948 | if self.kernel.poll() is None: |
|
960 | if self.kernel.poll() is None: | |
949 | return True |
|
961 | return True | |
950 | else: |
|
962 | else: | |
951 | return False |
|
963 | return False | |
952 | elif self._hb_channel is not None: |
|
964 | elif self._hb_channel is not None: | |
953 | # We didn't start the kernel with this KernelManager so we |
|
965 | # We didn't start the kernel with this KernelManager so we | |
954 | # use the heartbeat. |
|
966 | # use the heartbeat. | |
955 | return self._hb_channel.is_beating() |
|
967 | return self._hb_channel.is_beating() | |
956 | else: |
|
968 | else: | |
957 | # no heartbeat and not local, we can't tell if it's running, |
|
969 | # no heartbeat and not local, we can't tell if it's running, | |
958 | # so naively return True |
|
970 | # so naively return True | |
959 | return True |
|
971 | return True | |
960 |
|
972 | |||
961 | #-------------------------------------------------------------------------- |
|
973 | #-------------------------------------------------------------------------- | |
962 | # Channels used for communication with the kernel: |
|
974 | # Channels used for communication with the kernel: | |
963 | #-------------------------------------------------------------------------- |
|
975 | #-------------------------------------------------------------------------- | |
964 |
|
976 | |||
965 | @property |
|
977 | @property | |
966 | def shell_channel(self): |
|
978 | def shell_channel(self): | |
967 | """Get the REQ socket channel object to make requests of the kernel.""" |
|
979 | """Get the REQ socket channel object to make requests of the kernel.""" | |
968 | if self._shell_channel is None: |
|
980 | if self._shell_channel is None: | |
969 | self._shell_channel = self.shell_channel_class(self.context, |
|
981 | self._shell_channel = self.shell_channel_class(self.context, | |
970 | self.session, |
|
982 | self.session, | |
971 | (self.ip, self.shell_port)) |
|
983 | (self.ip, self.shell_port)) | |
972 | return self._shell_channel |
|
984 | return self._shell_channel | |
973 |
|
985 | |||
974 | @property |
|
986 | @property | |
975 | def sub_channel(self): |
|
987 | def sub_channel(self): | |
976 | """Get the SUB socket channel object.""" |
|
988 | """Get the SUB socket channel object.""" | |
977 | if self._sub_channel is None: |
|
989 | if self._sub_channel is None: | |
978 | self._sub_channel = self.sub_channel_class(self.context, |
|
990 | self._sub_channel = self.sub_channel_class(self.context, | |
979 | self.session, |
|
991 | self.session, | |
980 | (self.ip, self.iopub_port)) |
|
992 | (self.ip, self.iopub_port)) | |
981 | return self._sub_channel |
|
993 | return self._sub_channel | |
982 |
|
994 | |||
983 | @property |
|
995 | @property | |
984 | def stdin_channel(self): |
|
996 | def stdin_channel(self): | |
985 | """Get the REP socket channel object to handle stdin (raw_input).""" |
|
997 | """Get the REP socket channel object to handle stdin (raw_input).""" | |
986 | if self._stdin_channel is None: |
|
998 | if self._stdin_channel is None: | |
987 | self._stdin_channel = self.stdin_channel_class(self.context, |
|
999 | self._stdin_channel = self.stdin_channel_class(self.context, | |
988 | self.session, |
|
1000 | self.session, | |
989 | (self.ip, self.stdin_port)) |
|
1001 | (self.ip, self.stdin_port)) | |
990 | return self._stdin_channel |
|
1002 | return self._stdin_channel | |
991 |
|
1003 | |||
992 | @property |
|
1004 | @property | |
993 | def hb_channel(self): |
|
1005 | def hb_channel(self): | |
994 | """Get the heartbeat socket channel object to check that the |
|
1006 | """Get the heartbeat socket channel object to check that the | |
995 | kernel is alive.""" |
|
1007 | kernel is alive.""" | |
996 | if self._hb_channel is None: |
|
1008 | if self._hb_channel is None: | |
997 | self._hb_channel = self.hb_channel_class(self.context, |
|
1009 | self._hb_channel = self.hb_channel_class(self.context, | |
998 | self.session, |
|
1010 | self.session, | |
999 | (self.ip, self.hb_port)) |
|
1011 | (self.ip, self.hb_port)) | |
1000 | return self._hb_channel |
|
1012 | return self._hb_channel |
General Comments 0
You need to be logged in to leave comments.
Login now