Show More
@@ -1,1721 +1,1731 b'' | |||||
1 | """A semi-synchronous Client for the ZMQ cluster |
|
1 | """A semi-synchronous Client for the ZMQ cluster | |
2 |
|
2 | |||
3 | Authors: |
|
3 | Authors: | |
4 |
|
4 | |||
5 | * MinRK |
|
5 | * MinRK | |
6 | """ |
|
6 | """ | |
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2010-2011 The IPython Development Team |
|
8 | # Copyright (C) 2010-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 | import os |
|
18 | import os | |
19 | import json |
|
19 | import json | |
20 | import sys |
|
20 | import sys | |
21 | from threading import Thread, Event |
|
21 | from threading import Thread, Event | |
22 | import time |
|
22 | import time | |
23 | import warnings |
|
23 | import warnings | |
24 | from datetime import datetime |
|
24 | from datetime import datetime | |
25 | from getpass import getpass |
|
25 | from getpass import getpass | |
26 | from pprint import pprint |
|
26 | from pprint import pprint | |
27 |
|
27 | |||
28 | pjoin = os.path.join |
|
28 | pjoin = os.path.join | |
29 |
|
29 | |||
30 | import zmq |
|
30 | import zmq | |
31 | # from zmq.eventloop import ioloop, zmqstream |
|
31 | # from zmq.eventloop import ioloop, zmqstream | |
32 |
|
32 | |||
33 | from IPython.config.configurable import MultipleInstanceError |
|
33 | from IPython.config.configurable import MultipleInstanceError | |
34 | from IPython.core.application import BaseIPythonApplication |
|
34 | from IPython.core.application import BaseIPythonApplication | |
35 | from IPython.core.profiledir import ProfileDir, ProfileDirError |
|
35 | from IPython.core.profiledir import ProfileDir, ProfileDirError | |
36 |
|
36 | |||
37 | from IPython.utils.coloransi import TermColors |
|
37 | from IPython.utils.coloransi import TermColors | |
38 | from IPython.utils.jsonutil import rekey |
|
38 | from IPython.utils.jsonutil import rekey | |
39 | from IPython.utils.localinterfaces import LOCAL_IPS |
|
39 | from IPython.utils.localinterfaces import LOCAL_IPS | |
40 | from IPython.utils.path import get_ipython_dir |
|
40 | from IPython.utils.path import get_ipython_dir | |
41 | from IPython.utils.py3compat import cast_bytes |
|
41 | from IPython.utils.py3compat import cast_bytes | |
42 | from IPython.utils.traitlets import (HasTraits, Integer, Instance, Unicode, |
|
42 | from IPython.utils.traitlets import (HasTraits, Integer, Instance, Unicode, | |
43 | Dict, List, Bool, Set, Any) |
|
43 | Dict, List, Bool, Set, Any) | |
44 | from IPython.external.decorator import decorator |
|
44 | from IPython.external.decorator import decorator | |
45 | from IPython.external.ssh import tunnel |
|
45 | from IPython.external.ssh import tunnel | |
46 |
|
46 | |||
47 | from IPython.parallel import Reference |
|
47 | from IPython.parallel import Reference | |
48 | from IPython.parallel import error |
|
48 | from IPython.parallel import error | |
49 | from IPython.parallel import util |
|
49 | from IPython.parallel import util | |
50 |
|
50 | |||
51 | from IPython.zmq.session import Session, Message |
|
51 | from IPython.zmq.session import Session, Message | |
52 |
|
52 | |||
53 | from .asyncresult import AsyncResult, AsyncHubResult |
|
53 | from .asyncresult import AsyncResult, AsyncHubResult | |
54 | from .view import DirectView, LoadBalancedView |
|
54 | from .view import DirectView, LoadBalancedView | |
55 |
|
55 | |||
56 | if sys.version_info[0] >= 3: |
|
56 | if sys.version_info[0] >= 3: | |
57 | # xrange is used in a couple 'isinstance' tests in py2 |
|
57 | # xrange is used in a couple 'isinstance' tests in py2 | |
58 | # should be just 'range' in 3k |
|
58 | # should be just 'range' in 3k | |
59 | xrange = range |
|
59 | xrange = range | |
60 |
|
60 | |||
61 | #-------------------------------------------------------------------------- |
|
61 | #-------------------------------------------------------------------------- | |
62 | # Decorators for Client methods |
|
62 | # Decorators for Client methods | |
63 | #-------------------------------------------------------------------------- |
|
63 | #-------------------------------------------------------------------------- | |
64 |
|
64 | |||
65 | @decorator |
|
65 | @decorator | |
66 | def spin_first(f, self, *args, **kwargs): |
|
66 | def spin_first(f, self, *args, **kwargs): | |
67 | """Call spin() to sync state prior to calling the method.""" |
|
67 | """Call spin() to sync state prior to calling the method.""" | |
68 | self.spin() |
|
68 | self.spin() | |
69 | return f(self, *args, **kwargs) |
|
69 | return f(self, *args, **kwargs) | |
70 |
|
70 | |||
71 |
|
71 | |||
72 | #-------------------------------------------------------------------------- |
|
72 | #-------------------------------------------------------------------------- | |
73 | # Classes |
|
73 | # Classes | |
74 | #-------------------------------------------------------------------------- |
|
74 | #-------------------------------------------------------------------------- | |
75 |
|
75 | |||
76 |
|
76 | |||
77 | class ExecuteReply(object): |
|
77 | class ExecuteReply(object): | |
78 | """wrapper for finished Execute results""" |
|
78 | """wrapper for finished Execute results""" | |
79 | def __init__(self, msg_id, content, metadata): |
|
79 | def __init__(self, msg_id, content, metadata): | |
80 | self.msg_id = msg_id |
|
80 | self.msg_id = msg_id | |
81 | self._content = content |
|
81 | self._content = content | |
82 | self.execution_count = content['execution_count'] |
|
82 | self.execution_count = content['execution_count'] | |
83 | self.metadata = metadata |
|
83 | self.metadata = metadata | |
84 |
|
84 | |||
85 | def __getitem__(self, key): |
|
85 | def __getitem__(self, key): | |
86 | return self.metadata[key] |
|
86 | return self.metadata[key] | |
87 |
|
87 | |||
88 | def __getattr__(self, key): |
|
88 | def __getattr__(self, key): | |
89 | if key not in self.metadata: |
|
89 | if key not in self.metadata: | |
90 | raise AttributeError(key) |
|
90 | raise AttributeError(key) | |
91 | return self.metadata[key] |
|
91 | return self.metadata[key] | |
92 |
|
92 | |||
93 | def __repr__(self): |
|
93 | def __repr__(self): | |
94 | pyout = self.metadata['pyout'] or {'data':{}} |
|
94 | pyout = self.metadata['pyout'] or {'data':{}} | |
95 | text_out = pyout['data'].get('text/plain', '') |
|
95 | text_out = pyout['data'].get('text/plain', '') | |
96 | if len(text_out) > 32: |
|
96 | if len(text_out) > 32: | |
97 | text_out = text_out[:29] + '...' |
|
97 | text_out = text_out[:29] + '...' | |
98 |
|
98 | |||
99 | return "<ExecuteReply[%i]: %s>" % (self.execution_count, text_out) |
|
99 | return "<ExecuteReply[%i]: %s>" % (self.execution_count, text_out) | |
100 |
|
100 | |||
101 | def _repr_pretty_(self, p, cycle): |
|
101 | def _repr_pretty_(self, p, cycle): | |
102 | pyout = self.metadata['pyout'] or {'data':{}} |
|
102 | pyout = self.metadata['pyout'] or {'data':{}} | |
103 | text_out = pyout['data'].get('text/plain', '') |
|
103 | text_out = pyout['data'].get('text/plain', '') | |
104 |
|
104 | |||
105 | if not text_out: |
|
105 | if not text_out: | |
106 | return |
|
106 | return | |
107 |
|
107 | |||
108 | try: |
|
108 | try: | |
109 | ip = get_ipython() |
|
109 | ip = get_ipython() | |
110 | except NameError: |
|
110 | except NameError: | |
111 | colors = "NoColor" |
|
111 | colors = "NoColor" | |
112 | else: |
|
112 | else: | |
113 | colors = ip.colors |
|
113 | colors = ip.colors | |
114 |
|
114 | |||
115 | if colors == "NoColor": |
|
115 | if colors == "NoColor": | |
116 | out = normal = "" |
|
116 | out = normal = "" | |
117 | else: |
|
117 | else: | |
118 | out = TermColors.Red |
|
118 | out = TermColors.Red | |
119 | normal = TermColors.Normal |
|
119 | normal = TermColors.Normal | |
120 |
|
120 | |||
121 | if '\n' in text_out and not text_out.startswith('\n'): |
|
121 | if '\n' in text_out and not text_out.startswith('\n'): | |
122 | # add newline for multiline reprs |
|
122 | # add newline for multiline reprs | |
123 | text_out = '\n' + text_out |
|
123 | text_out = '\n' + text_out | |
124 |
|
124 | |||
125 | p.text( |
|
125 | p.text( | |
126 | out + u'Out[%i:%i]: ' % ( |
|
126 | out + u'Out[%i:%i]: ' % ( | |
127 | self.metadata['engine_id'], self.execution_count |
|
127 | self.metadata['engine_id'], self.execution_count | |
128 | ) + normal + text_out |
|
128 | ) + normal + text_out | |
129 | ) |
|
129 | ) | |
130 |
|
130 | |||
131 | def _repr_html_(self): |
|
131 | def _repr_html_(self): | |
132 | pyout = self.metadata['pyout'] or {'data':{}} |
|
132 | pyout = self.metadata['pyout'] or {'data':{}} | |
133 | return pyout['data'].get("text/html") |
|
133 | return pyout['data'].get("text/html") | |
134 |
|
134 | |||
135 | def _repr_latex_(self): |
|
135 | def _repr_latex_(self): | |
136 | pyout = self.metadata['pyout'] or {'data':{}} |
|
136 | pyout = self.metadata['pyout'] or {'data':{}} | |
137 | return pyout['data'].get("text/latex") |
|
137 | return pyout['data'].get("text/latex") | |
138 |
|
138 | |||
139 | def _repr_json_(self): |
|
139 | def _repr_json_(self): | |
140 | pyout = self.metadata['pyout'] or {'data':{}} |
|
140 | pyout = self.metadata['pyout'] or {'data':{}} | |
141 | return pyout['data'].get("application/json") |
|
141 | return pyout['data'].get("application/json") | |
142 |
|
142 | |||
143 | def _repr_javascript_(self): |
|
143 | def _repr_javascript_(self): | |
144 | pyout = self.metadata['pyout'] or {'data':{}} |
|
144 | pyout = self.metadata['pyout'] or {'data':{}} | |
145 | return pyout['data'].get("application/javascript") |
|
145 | return pyout['data'].get("application/javascript") | |
146 |
|
146 | |||
147 | def _repr_png_(self): |
|
147 | def _repr_png_(self): | |
148 | pyout = self.metadata['pyout'] or {'data':{}} |
|
148 | pyout = self.metadata['pyout'] or {'data':{}} | |
149 | return pyout['data'].get("image/png") |
|
149 | return pyout['data'].get("image/png") | |
150 |
|
150 | |||
151 | def _repr_jpeg_(self): |
|
151 | def _repr_jpeg_(self): | |
152 | pyout = self.metadata['pyout'] or {'data':{}} |
|
152 | pyout = self.metadata['pyout'] or {'data':{}} | |
153 | return pyout['data'].get("image/jpeg") |
|
153 | return pyout['data'].get("image/jpeg") | |
154 |
|
154 | |||
155 | def _repr_svg_(self): |
|
155 | def _repr_svg_(self): | |
156 | pyout = self.metadata['pyout'] or {'data':{}} |
|
156 | pyout = self.metadata['pyout'] or {'data':{}} | |
157 | return pyout['data'].get("image/svg+xml") |
|
157 | return pyout['data'].get("image/svg+xml") | |
158 |
|
158 | |||
159 |
|
159 | |||
160 | class Metadata(dict): |
|
160 | class Metadata(dict): | |
161 | """Subclass of dict for initializing metadata values. |
|
161 | """Subclass of dict for initializing metadata values. | |
162 |
|
162 | |||
163 | Attribute access works on keys. |
|
163 | Attribute access works on keys. | |
164 |
|
164 | |||
165 | These objects have a strict set of keys - errors will raise if you try |
|
165 | These objects have a strict set of keys - errors will raise if you try | |
166 | to add new keys. |
|
166 | to add new keys. | |
167 | """ |
|
167 | """ | |
168 | def __init__(self, *args, **kwargs): |
|
168 | def __init__(self, *args, **kwargs): | |
169 | dict.__init__(self) |
|
169 | dict.__init__(self) | |
170 | md = {'msg_id' : None, |
|
170 | md = {'msg_id' : None, | |
171 | 'submitted' : None, |
|
171 | 'submitted' : None, | |
172 | 'started' : None, |
|
172 | 'started' : None, | |
173 | 'completed' : None, |
|
173 | 'completed' : None, | |
174 | 'received' : None, |
|
174 | 'received' : None, | |
175 | 'engine_uuid' : None, |
|
175 | 'engine_uuid' : None, | |
176 | 'engine_id' : None, |
|
176 | 'engine_id' : None, | |
177 | 'follow' : None, |
|
177 | 'follow' : None, | |
178 | 'after' : None, |
|
178 | 'after' : None, | |
179 | 'status' : None, |
|
179 | 'status' : None, | |
180 |
|
180 | |||
181 | 'pyin' : None, |
|
181 | 'pyin' : None, | |
182 | 'pyout' : None, |
|
182 | 'pyout' : None, | |
183 | 'pyerr' : None, |
|
183 | 'pyerr' : None, | |
184 | 'stdout' : '', |
|
184 | 'stdout' : '', | |
185 | 'stderr' : '', |
|
185 | 'stderr' : '', | |
186 | 'outputs' : [], |
|
186 | 'outputs' : [], | |
187 | 'outputs_ready' : False, |
|
187 | 'outputs_ready' : False, | |
188 | } |
|
188 | } | |
189 | self.update(md) |
|
189 | self.update(md) | |
190 | self.update(dict(*args, **kwargs)) |
|
190 | self.update(dict(*args, **kwargs)) | |
191 |
|
191 | |||
192 | def __getattr__(self, key): |
|
192 | def __getattr__(self, key): | |
193 | """getattr aliased to getitem""" |
|
193 | """getattr aliased to getitem""" | |
194 | if key in self.iterkeys(): |
|
194 | if key in self.iterkeys(): | |
195 | return self[key] |
|
195 | return self[key] | |
196 | else: |
|
196 | else: | |
197 | raise AttributeError(key) |
|
197 | raise AttributeError(key) | |
198 |
|
198 | |||
199 | def __setattr__(self, key, value): |
|
199 | def __setattr__(self, key, value): | |
200 | """setattr aliased to setitem, with strict""" |
|
200 | """setattr aliased to setitem, with strict""" | |
201 | if key in self.iterkeys(): |
|
201 | if key in self.iterkeys(): | |
202 | self[key] = value |
|
202 | self[key] = value | |
203 | else: |
|
203 | else: | |
204 | raise AttributeError(key) |
|
204 | raise AttributeError(key) | |
205 |
|
205 | |||
206 | def __setitem__(self, key, value): |
|
206 | def __setitem__(self, key, value): | |
207 | """strict static key enforcement""" |
|
207 | """strict static key enforcement""" | |
208 | if key in self.iterkeys(): |
|
208 | if key in self.iterkeys(): | |
209 | dict.__setitem__(self, key, value) |
|
209 | dict.__setitem__(self, key, value) | |
210 | else: |
|
210 | else: | |
211 | raise KeyError(key) |
|
211 | raise KeyError(key) | |
212 |
|
212 | |||
213 |
|
213 | |||
214 | class Client(HasTraits): |
|
214 | class Client(HasTraits): | |
215 | """A semi-synchronous client to the IPython ZMQ cluster |
|
215 | """A semi-synchronous client to the IPython ZMQ cluster | |
216 |
|
216 | |||
217 | Parameters |
|
217 | Parameters | |
218 | ---------- |
|
218 | ---------- | |
219 |
|
219 | |||
220 | url_or_file : bytes or unicode; zmq url or path to ipcontroller-client.json |
|
220 | url_or_file : bytes or unicode; zmq url or path to ipcontroller-client.json | |
221 | Connection information for the Hub's registration. If a json connector |
|
221 | Connection information for the Hub's registration. If a json connector | |
222 | file is given, then likely no further configuration is necessary. |
|
222 | file is given, then likely no further configuration is necessary. | |
223 | [Default: use profile] |
|
223 | [Default: use profile] | |
224 | profile : bytes |
|
224 | profile : bytes | |
225 | The name of the Cluster profile to be used to find connector information. |
|
225 | The name of the Cluster profile to be used to find connector information. | |
226 | If run from an IPython application, the default profile will be the same |
|
226 | If run from an IPython application, the default profile will be the same | |
227 | as the running application, otherwise it will be 'default'. |
|
227 | as the running application, otherwise it will be 'default'. | |
228 | context : zmq.Context |
|
228 | context : zmq.Context | |
229 | Pass an existing zmq.Context instance, otherwise the client will create its own. |
|
229 | Pass an existing zmq.Context instance, otherwise the client will create its own. | |
230 | debug : bool |
|
230 | debug : bool | |
231 | flag for lots of message printing for debug purposes |
|
231 | flag for lots of message printing for debug purposes | |
232 | timeout : int/float |
|
232 | timeout : int/float | |
233 | time (in seconds) to wait for connection replies from the Hub |
|
233 | time (in seconds) to wait for connection replies from the Hub | |
234 | [Default: 10] |
|
234 | [Default: 10] | |
235 |
|
235 | |||
236 | #-------------- session related args ---------------- |
|
236 | #-------------- session related args ---------------- | |
237 |
|
237 | |||
238 | config : Config object |
|
238 | config : Config object | |
239 | If specified, this will be relayed to the Session for configuration |
|
239 | If specified, this will be relayed to the Session for configuration | |
240 | username : str |
|
240 | username : str | |
241 | set username for the session object |
|
241 | set username for the session object | |
242 | packer : str (import_string) or callable |
|
242 | packer : str (import_string) or callable | |
243 | Can be either the simple keyword 'json' or 'pickle', or an import_string to a |
|
243 | Can be either the simple keyword 'json' or 'pickle', or an import_string to a | |
244 | function to serialize messages. Must support same input as |
|
244 | function to serialize messages. Must support same input as | |
245 | JSON, and output must be bytes. |
|
245 | JSON, and output must be bytes. | |
246 | You can pass a callable directly as `pack` |
|
246 | You can pass a callable directly as `pack` | |
247 | unpacker : str (import_string) or callable |
|
247 | unpacker : str (import_string) or callable | |
248 | The inverse of packer. Only necessary if packer is specified as *not* one |
|
248 | The inverse of packer. Only necessary if packer is specified as *not* one | |
249 | of 'json' or 'pickle'. |
|
249 | of 'json' or 'pickle'. | |
250 |
|
250 | |||
251 | #-------------- ssh related args ---------------- |
|
251 | #-------------- ssh related args ---------------- | |
252 | # These are args for configuring the ssh tunnel to be used |
|
252 | # These are args for configuring the ssh tunnel to be used | |
253 | # credentials are used to forward connections over ssh to the Controller |
|
253 | # credentials are used to forward connections over ssh to the Controller | |
254 | # Note that the ip given in `addr` needs to be relative to sshserver |
|
254 | # Note that the ip given in `addr` needs to be relative to sshserver | |
255 | # The most basic case is to leave addr as pointing to localhost (127.0.0.1), |
|
255 | # The most basic case is to leave addr as pointing to localhost (127.0.0.1), | |
256 | # and set sshserver as the same machine the Controller is on. However, |
|
256 | # and set sshserver as the same machine the Controller is on. However, | |
257 | # the only requirement is that sshserver is able to see the Controller |
|
257 | # the only requirement is that sshserver is able to see the Controller | |
258 | # (i.e. is within the same trusted network). |
|
258 | # (i.e. is within the same trusted network). | |
259 |
|
259 | |||
260 | sshserver : str |
|
260 | sshserver : str | |
261 | A string of the form passed to ssh, i.e. 'server.tld' or 'user@server.tld:port' |
|
261 | A string of the form passed to ssh, i.e. 'server.tld' or 'user@server.tld:port' | |
262 | If keyfile or password is specified, and this is not, it will default to |
|
262 | If keyfile or password is specified, and this is not, it will default to | |
263 | the ip given in addr. |
|
263 | the ip given in addr. | |
264 | sshkey : str; path to ssh private key file |
|
264 | sshkey : str; path to ssh private key file | |
265 | This specifies a key to be used in ssh login, default None. |
|
265 | This specifies a key to be used in ssh login, default None. | |
266 | Regular default ssh keys will be used without specifying this argument. |
|
266 | Regular default ssh keys will be used without specifying this argument. | |
267 | password : str |
|
267 | password : str | |
268 | Your ssh password to sshserver. Note that if this is left None, |
|
268 | Your ssh password to sshserver. Note that if this is left None, | |
269 | you will be prompted for it if passwordless key based login is unavailable. |
|
269 | you will be prompted for it if passwordless key based login is unavailable. | |
270 | paramiko : bool |
|
270 | paramiko : bool | |
271 | flag for whether to use paramiko instead of shell ssh for tunneling. |
|
271 | flag for whether to use paramiko instead of shell ssh for tunneling. | |
272 | [default: True on win32, False else] |
|
272 | [default: True on win32, False else] | |
273 |
|
273 | |||
274 | ------- exec authentication args ------- |
|
274 | ------- exec authentication args ------- | |
275 | If even localhost is untrusted, you can have some protection against |
|
275 | If even localhost is untrusted, you can have some protection against | |
276 | unauthorized execution by signing messages with HMAC digests. |
|
276 | unauthorized execution by signing messages with HMAC digests. | |
277 | Messages are still sent as cleartext, so if someone can snoop your |
|
277 | Messages are still sent as cleartext, so if someone can snoop your | |
278 | loopback traffic this will not protect your privacy, but will prevent |
|
278 | loopback traffic this will not protect your privacy, but will prevent | |
279 | unauthorized execution. |
|
279 | unauthorized execution. | |
280 |
|
280 | |||
281 | exec_key : str |
|
281 | exec_key : str | |
282 | an authentication key or file containing a key |
|
282 | an authentication key or file containing a key | |
283 | default: None |
|
283 | default: None | |
284 |
|
284 | |||
285 |
|
285 | |||
286 | Attributes |
|
286 | Attributes | |
287 | ---------- |
|
287 | ---------- | |
288 |
|
288 | |||
289 | ids : list of int engine IDs |
|
289 | ids : list of int engine IDs | |
290 | requesting the ids attribute always synchronizes |
|
290 | requesting the ids attribute always synchronizes | |
291 | the registration state. To request ids without synchronization, |
|
291 | the registration state. To request ids without synchronization, | |
292 | use semi-private _ids attributes. |
|
292 | use semi-private _ids attributes. | |
293 |
|
293 | |||
294 | history : list of msg_ids |
|
294 | history : list of msg_ids | |
295 | a list of msg_ids, keeping track of all the execution |
|
295 | a list of msg_ids, keeping track of all the execution | |
296 | messages you have submitted in order. |
|
296 | messages you have submitted in order. | |
297 |
|
297 | |||
298 | outstanding : set of msg_ids |
|
298 | outstanding : set of msg_ids | |
299 | a set of msg_ids that have been submitted, but whose |
|
299 | a set of msg_ids that have been submitted, but whose | |
300 | results have not yet been received. |
|
300 | results have not yet been received. | |
301 |
|
301 | |||
302 | results : dict |
|
302 | results : dict | |
303 | a dict of all our results, keyed by msg_id |
|
303 | a dict of all our results, keyed by msg_id | |
304 |
|
304 | |||
305 | block : bool |
|
305 | block : bool | |
306 | determines default behavior when block not specified |
|
306 | determines default behavior when block not specified | |
307 | in execution methods |
|
307 | in execution methods | |
308 |
|
308 | |||
309 | Methods |
|
309 | Methods | |
310 | ------- |
|
310 | ------- | |
311 |
|
311 | |||
312 | spin |
|
312 | spin | |
313 | flushes incoming results and registration state changes |
|
313 | flushes incoming results and registration state changes | |
314 | control methods spin, and requesting `ids` also ensures up to date |
|
314 | control methods spin, and requesting `ids` also ensures up to date | |
315 |
|
315 | |||
316 | wait |
|
316 | wait | |
317 | wait on one or more msg_ids |
|
317 | wait on one or more msg_ids | |
318 |
|
318 | |||
319 | execution methods |
|
319 | execution methods | |
320 | apply |
|
320 | apply | |
321 | legacy: execute, run |
|
321 | legacy: execute, run | |
322 |
|
322 | |||
323 | data movement |
|
323 | data movement | |
324 | push, pull, scatter, gather |
|
324 | push, pull, scatter, gather | |
325 |
|
325 | |||
326 | query methods |
|
326 | query methods | |
327 | queue_status, get_result, purge, result_status |
|
327 | queue_status, get_result, purge, result_status | |
328 |
|
328 | |||
329 | control methods |
|
329 | control methods | |
330 | abort, shutdown |
|
330 | abort, shutdown | |
331 |
|
331 | |||
332 | """ |
|
332 | """ | |
333 |
|
333 | |||
334 |
|
334 | |||
335 | block = Bool(False) |
|
335 | block = Bool(False) | |
336 | outstanding = Set() |
|
336 | outstanding = Set() | |
337 | results = Instance('collections.defaultdict', (dict,)) |
|
337 | results = Instance('collections.defaultdict', (dict,)) | |
338 | metadata = Instance('collections.defaultdict', (Metadata,)) |
|
338 | metadata = Instance('collections.defaultdict', (Metadata,)) | |
339 | history = List() |
|
339 | history = List() | |
340 | debug = Bool(False) |
|
340 | debug = Bool(False) | |
341 | _spin_thread = Any() |
|
341 | _spin_thread = Any() | |
342 | _stop_spinning = Any() |
|
342 | _stop_spinning = Any() | |
343 |
|
343 | |||
344 | profile=Unicode() |
|
344 | profile=Unicode() | |
345 | def _profile_default(self): |
|
345 | def _profile_default(self): | |
346 | if BaseIPythonApplication.initialized(): |
|
346 | if BaseIPythonApplication.initialized(): | |
347 | # an IPython app *might* be running, try to get its profile |
|
347 | # an IPython app *might* be running, try to get its profile | |
348 | try: |
|
348 | try: | |
349 | return BaseIPythonApplication.instance().profile |
|
349 | return BaseIPythonApplication.instance().profile | |
350 | except (AttributeError, MultipleInstanceError): |
|
350 | except (AttributeError, MultipleInstanceError): | |
351 | # could be a *different* subclass of config.Application, |
|
351 | # could be a *different* subclass of config.Application, | |
352 | # which would raise one of these two errors. |
|
352 | # which would raise one of these two errors. | |
353 | return u'default' |
|
353 | return u'default' | |
354 | else: |
|
354 | else: | |
355 | return u'default' |
|
355 | return u'default' | |
356 |
|
356 | |||
357 |
|
357 | |||
358 | _outstanding_dict = Instance('collections.defaultdict', (set,)) |
|
358 | _outstanding_dict = Instance('collections.defaultdict', (set,)) | |
359 | _ids = List() |
|
359 | _ids = List() | |
360 | _connected=Bool(False) |
|
360 | _connected=Bool(False) | |
361 | _ssh=Bool(False) |
|
361 | _ssh=Bool(False) | |
362 | _context = Instance('zmq.Context') |
|
362 | _context = Instance('zmq.Context') | |
363 | _config = Dict() |
|
363 | _config = Dict() | |
364 | _engines=Instance(util.ReverseDict, (), {}) |
|
364 | _engines=Instance(util.ReverseDict, (), {}) | |
365 | # _hub_socket=Instance('zmq.Socket') |
|
365 | # _hub_socket=Instance('zmq.Socket') | |
366 | _query_socket=Instance('zmq.Socket') |
|
366 | _query_socket=Instance('zmq.Socket') | |
367 | _control_socket=Instance('zmq.Socket') |
|
367 | _control_socket=Instance('zmq.Socket') | |
368 | _iopub_socket=Instance('zmq.Socket') |
|
368 | _iopub_socket=Instance('zmq.Socket') | |
369 | _notification_socket=Instance('zmq.Socket') |
|
369 | _notification_socket=Instance('zmq.Socket') | |
370 | _mux_socket=Instance('zmq.Socket') |
|
370 | _mux_socket=Instance('zmq.Socket') | |
371 | _task_socket=Instance('zmq.Socket') |
|
371 | _task_socket=Instance('zmq.Socket') | |
372 | _task_scheme=Unicode() |
|
372 | _task_scheme=Unicode() | |
373 | _closed = False |
|
373 | _closed = False | |
374 | _ignored_control_replies=Integer(0) |
|
374 | _ignored_control_replies=Integer(0) | |
375 | _ignored_hub_replies=Integer(0) |
|
375 | _ignored_hub_replies=Integer(0) | |
376 |
|
376 | |||
377 | def __new__(self, *args, **kw): |
|
377 | def __new__(self, *args, **kw): | |
378 | # don't raise on positional args |
|
378 | # don't raise on positional args | |
379 | return HasTraits.__new__(self, **kw) |
|
379 | return HasTraits.__new__(self, **kw) | |
380 |
|
380 | |||
381 | def __init__(self, url_or_file=None, profile=None, profile_dir=None, ipython_dir=None, |
|
381 | def __init__(self, url_or_file=None, profile=None, profile_dir=None, ipython_dir=None, | |
382 | context=None, debug=False, exec_key=None, |
|
382 | context=None, debug=False, exec_key=None, | |
383 | sshserver=None, sshkey=None, password=None, paramiko=None, |
|
383 | sshserver=None, sshkey=None, password=None, paramiko=None, | |
384 | timeout=10, **extra_args |
|
384 | timeout=10, **extra_args | |
385 | ): |
|
385 | ): | |
386 | if profile: |
|
386 | if profile: | |
387 | super(Client, self).__init__(debug=debug, profile=profile) |
|
387 | super(Client, self).__init__(debug=debug, profile=profile) | |
388 | else: |
|
388 | else: | |
389 | super(Client, self).__init__(debug=debug) |
|
389 | super(Client, self).__init__(debug=debug) | |
390 | if context is None: |
|
390 | if context is None: | |
391 | context = zmq.Context.instance() |
|
391 | context = zmq.Context.instance() | |
392 | self._context = context |
|
392 | self._context = context | |
393 | self._stop_spinning = Event() |
|
393 | self._stop_spinning = Event() | |
394 |
|
394 | |||
395 | self._setup_profile_dir(self.profile, profile_dir, ipython_dir) |
|
395 | self._setup_profile_dir(self.profile, profile_dir, ipython_dir) | |
396 | if self._cd is not None: |
|
396 | if self._cd is not None: | |
397 | if url_or_file is None: |
|
397 | if url_or_file is None: | |
398 | url_or_file = pjoin(self._cd.security_dir, 'ipcontroller-client.json') |
|
398 | url_or_file = pjoin(self._cd.security_dir, 'ipcontroller-client.json') | |
399 | if url_or_file is None: |
|
399 | if url_or_file is None: | |
400 | raise ValueError( |
|
400 | raise ValueError( | |
401 | "I can't find enough information to connect to a hub!" |
|
401 | "I can't find enough information to connect to a hub!" | |
402 | " Please specify at least one of url_or_file or profile." |
|
402 | " Please specify at least one of url_or_file or profile." | |
403 | ) |
|
403 | ) | |
404 |
|
404 | |||
405 | if not util.is_url(url_or_file): |
|
405 | if not util.is_url(url_or_file): | |
406 | # it's not a url, try for a file |
|
406 | # it's not a url, try for a file | |
407 | if not os.path.exists(url_or_file): |
|
407 | if not os.path.exists(url_or_file): | |
408 | if self._cd: |
|
408 | if self._cd: | |
409 | url_or_file = os.path.join(self._cd.security_dir, url_or_file) |
|
409 | url_or_file = os.path.join(self._cd.security_dir, url_or_file) | |
410 | if not os.path.exists(url_or_file): |
|
410 | if not os.path.exists(url_or_file): | |
411 | raise IOError("Connection file not found: %r" % url_or_file) |
|
411 | raise IOError("Connection file not found: %r" % url_or_file) | |
412 | with open(url_or_file) as f: |
|
412 | with open(url_or_file) as f: | |
413 | cfg = json.loads(f.read()) |
|
413 | cfg = json.loads(f.read()) | |
414 | else: |
|
414 | else: | |
415 | cfg = {'url':url_or_file} |
|
415 | cfg = {'url':url_or_file} | |
416 |
|
416 | |||
417 | # sync defaults from args, json: |
|
417 | # sync defaults from args, json: | |
418 | if sshserver: |
|
418 | if sshserver: | |
419 | cfg['ssh'] = sshserver |
|
419 | cfg['ssh'] = sshserver | |
420 | if exec_key: |
|
420 | if exec_key: | |
421 | cfg['exec_key'] = exec_key |
|
421 | cfg['exec_key'] = exec_key | |
422 | exec_key = cfg['exec_key'] |
|
422 | exec_key = cfg['exec_key'] | |
423 | location = cfg.setdefault('location', None) |
|
423 | location = cfg.setdefault('location', None) | |
424 | cfg['url'] = util.disambiguate_url(cfg['url'], location) |
|
424 | cfg['url'] = util.disambiguate_url(cfg['url'], location) | |
425 | url = cfg['url'] |
|
425 | url = cfg['url'] | |
426 | proto,addr,port = util.split_url(url) |
|
426 | proto,addr,port = util.split_url(url) | |
427 | if location is not None and addr == '127.0.0.1': |
|
427 | if location is not None and addr == '127.0.0.1': | |
428 | # location specified, and connection is expected to be local |
|
428 | # location specified, and connection is expected to be local | |
429 | if location not in LOCAL_IPS and not sshserver: |
|
429 | if location not in LOCAL_IPS and not sshserver: | |
430 | # load ssh from JSON *only* if the controller is not on |
|
430 | # load ssh from JSON *only* if the controller is not on | |
431 | # this machine |
|
431 | # this machine | |
432 | sshserver=cfg['ssh'] |
|
432 | sshserver=cfg['ssh'] | |
433 | if location not in LOCAL_IPS and not sshserver: |
|
433 | if location not in LOCAL_IPS and not sshserver: | |
434 | # warn if no ssh specified, but SSH is probably needed |
|
434 | # warn if no ssh specified, but SSH is probably needed | |
435 | # This is only a warning, because the most likely cause |
|
435 | # This is only a warning, because the most likely cause | |
436 | # is a local Controller on a laptop whose IP is dynamic |
|
436 | # is a local Controller on a laptop whose IP is dynamic | |
437 | warnings.warn(""" |
|
437 | warnings.warn(""" | |
438 | Controller appears to be listening on localhost, but not on this machine. |
|
438 | Controller appears to be listening on localhost, but not on this machine. | |
439 | If this is true, you should specify Client(...,sshserver='you@%s') |
|
439 | If this is true, you should specify Client(...,sshserver='you@%s') | |
440 | or instruct your controller to listen on an external IP."""%location, |
|
440 | or instruct your controller to listen on an external IP."""%location, | |
441 | RuntimeWarning) |
|
441 | RuntimeWarning) | |
442 | elif not sshserver: |
|
442 | elif not sshserver: | |
443 | # otherwise sync with cfg |
|
443 | # otherwise sync with cfg | |
444 | sshserver = cfg['ssh'] |
|
444 | sshserver = cfg['ssh'] | |
445 |
|
445 | |||
446 | self._config = cfg |
|
446 | self._config = cfg | |
447 |
|
447 | |||
448 | self._ssh = bool(sshserver or sshkey or password) |
|
448 | self._ssh = bool(sshserver or sshkey or password) | |
449 | if self._ssh and sshserver is None: |
|
449 | if self._ssh and sshserver is None: | |
450 | # default to ssh via localhost |
|
450 | # default to ssh via localhost | |
451 | sshserver = url.split('://')[1].split(':')[0] |
|
451 | sshserver = url.split('://')[1].split(':')[0] | |
452 | if self._ssh and password is None: |
|
452 | if self._ssh and password is None: | |
453 | if tunnel.try_passwordless_ssh(sshserver, sshkey, paramiko): |
|
453 | if tunnel.try_passwordless_ssh(sshserver, sshkey, paramiko): | |
454 | password=False |
|
454 | password=False | |
455 | else: |
|
455 | else: | |
456 | password = getpass("SSH Password for %s: "%sshserver) |
|
456 | password = getpass("SSH Password for %s: "%sshserver) | |
457 | ssh_kwargs = dict(keyfile=sshkey, password=password, paramiko=paramiko) |
|
457 | ssh_kwargs = dict(keyfile=sshkey, password=password, paramiko=paramiko) | |
458 |
|
458 | |||
459 | # configure and construct the session |
|
459 | # configure and construct the session | |
460 | if exec_key is not None: |
|
460 | if exec_key is not None: | |
461 | if os.path.isfile(exec_key): |
|
461 | if os.path.isfile(exec_key): | |
462 | extra_args['keyfile'] = exec_key |
|
462 | extra_args['keyfile'] = exec_key | |
463 | else: |
|
463 | else: | |
464 | exec_key = cast_bytes(exec_key) |
|
464 | exec_key = cast_bytes(exec_key) | |
465 | extra_args['key'] = exec_key |
|
465 | extra_args['key'] = exec_key | |
466 | self.session = Session(**extra_args) |
|
466 | self.session = Session(**extra_args) | |
467 |
|
467 | |||
468 | self._query_socket = self._context.socket(zmq.DEALER) |
|
468 | self._query_socket = self._context.socket(zmq.DEALER) | |
469 | self._query_socket.setsockopt(zmq.IDENTITY, self.session.bsession) |
|
469 | self._query_socket.setsockopt(zmq.IDENTITY, self.session.bsession) | |
470 | if self._ssh: |
|
470 | if self._ssh: | |
471 | tunnel.tunnel_connection(self._query_socket, url, sshserver, **ssh_kwargs) |
|
471 | tunnel.tunnel_connection(self._query_socket, url, sshserver, **ssh_kwargs) | |
472 | else: |
|
472 | else: | |
473 | self._query_socket.connect(url) |
|
473 | self._query_socket.connect(url) | |
474 |
|
474 | |||
475 | self.session.debug = self.debug |
|
475 | self.session.debug = self.debug | |
476 |
|
476 | |||
477 | self._notification_handlers = {'registration_notification' : self._register_engine, |
|
477 | self._notification_handlers = {'registration_notification' : self._register_engine, | |
478 | 'unregistration_notification' : self._unregister_engine, |
|
478 | 'unregistration_notification' : self._unregister_engine, | |
479 | 'shutdown_notification' : lambda msg: self.close(), |
|
479 | 'shutdown_notification' : lambda msg: self.close(), | |
480 | } |
|
480 | } | |
481 | self._queue_handlers = {'execute_reply' : self._handle_execute_reply, |
|
481 | self._queue_handlers = {'execute_reply' : self._handle_execute_reply, | |
482 | 'apply_reply' : self._handle_apply_reply} |
|
482 | 'apply_reply' : self._handle_apply_reply} | |
483 | self._connect(sshserver, ssh_kwargs, timeout) |
|
483 | self._connect(sshserver, ssh_kwargs, timeout) | |
484 |
|
484 | |||
485 | # last step: setup magics, if we are in IPython: |
|
485 | # last step: setup magics, if we are in IPython: | |
486 |
|
486 | |||
487 | try: |
|
487 | try: | |
488 | ip = get_ipython() |
|
488 | ip = get_ipython() | |
489 | except NameError: |
|
489 | except NameError: | |
490 | return |
|
490 | return | |
491 | else: |
|
491 | else: | |
492 | if 'px' not in ip.magics_manager.magics: |
|
492 | if 'px' not in ip.magics_manager.magics: | |
493 | # in IPython but we are the first Client. |
|
493 | # in IPython but we are the first Client. | |
494 | # activate a default view for parallel magics. |
|
494 | # activate a default view for parallel magics. | |
495 | self.activate() |
|
495 | self.activate() | |
496 |
|
496 | |||
497 | def __del__(self): |
|
497 | def __del__(self): | |
498 | """cleanup sockets, but _not_ context.""" |
|
498 | """cleanup sockets, but _not_ context.""" | |
499 | self.close() |
|
499 | self.close() | |
500 |
|
500 | |||
501 | def _setup_profile_dir(self, profile, profile_dir, ipython_dir): |
|
501 | def _setup_profile_dir(self, profile, profile_dir, ipython_dir): | |
502 | if ipython_dir is None: |
|
502 | if ipython_dir is None: | |
503 | ipython_dir = get_ipython_dir() |
|
503 | ipython_dir = get_ipython_dir() | |
504 | if profile_dir is not None: |
|
504 | if profile_dir is not None: | |
505 | try: |
|
505 | try: | |
506 | self._cd = ProfileDir.find_profile_dir(profile_dir) |
|
506 | self._cd = ProfileDir.find_profile_dir(profile_dir) | |
507 | return |
|
507 | return | |
508 | except ProfileDirError: |
|
508 | except ProfileDirError: | |
509 | pass |
|
509 | pass | |
510 | elif profile is not None: |
|
510 | elif profile is not None: | |
511 | try: |
|
511 | try: | |
512 | self._cd = ProfileDir.find_profile_dir_by_name( |
|
512 | self._cd = ProfileDir.find_profile_dir_by_name( | |
513 | ipython_dir, profile) |
|
513 | ipython_dir, profile) | |
514 | return |
|
514 | return | |
515 | except ProfileDirError: |
|
515 | except ProfileDirError: | |
516 | pass |
|
516 | pass | |
517 | self._cd = None |
|
517 | self._cd = None | |
518 |
|
518 | |||
519 | def _update_engines(self, engines): |
|
519 | def _update_engines(self, engines): | |
520 | """Update our engines dict and _ids from a dict of the form: {id:uuid}.""" |
|
520 | """Update our engines dict and _ids from a dict of the form: {id:uuid}.""" | |
521 | for k,v in engines.iteritems(): |
|
521 | for k,v in engines.iteritems(): | |
522 | eid = int(k) |
|
522 | eid = int(k) | |
523 | self._engines[eid] = v |
|
523 | self._engines[eid] = v | |
524 | self._ids.append(eid) |
|
524 | self._ids.append(eid) | |
525 | self._ids = sorted(self._ids) |
|
525 | self._ids = sorted(self._ids) | |
526 | if sorted(self._engines.keys()) != range(len(self._engines)) and \ |
|
526 | if sorted(self._engines.keys()) != range(len(self._engines)) and \ | |
527 | self._task_scheme == 'pure' and self._task_socket: |
|
527 | self._task_scheme == 'pure' and self._task_socket: | |
528 | self._stop_scheduling_tasks() |
|
528 | self._stop_scheduling_tasks() | |
529 |
|
529 | |||
530 | def _stop_scheduling_tasks(self): |
|
530 | def _stop_scheduling_tasks(self): | |
531 | """Stop scheduling tasks because an engine has been unregistered |
|
531 | """Stop scheduling tasks because an engine has been unregistered | |
532 | from a pure ZMQ scheduler. |
|
532 | from a pure ZMQ scheduler. | |
533 | """ |
|
533 | """ | |
534 | self._task_socket.close() |
|
534 | self._task_socket.close() | |
535 | self._task_socket = None |
|
535 | self._task_socket = None | |
536 | msg = "An engine has been unregistered, and we are using pure " +\ |
|
536 | msg = "An engine has been unregistered, and we are using pure " +\ | |
537 | "ZMQ task scheduling. Task farming will be disabled." |
|
537 | "ZMQ task scheduling. Task farming will be disabled." | |
538 | if self.outstanding: |
|
538 | if self.outstanding: | |
539 | msg += " If you were running tasks when this happened, " +\ |
|
539 | msg += " If you were running tasks when this happened, " +\ | |
540 | "some `outstanding` msg_ids may never resolve." |
|
540 | "some `outstanding` msg_ids may never resolve." | |
541 | warnings.warn(msg, RuntimeWarning) |
|
541 | warnings.warn(msg, RuntimeWarning) | |
542 |
|
542 | |||
543 | def _build_targets(self, targets): |
|
543 | def _build_targets(self, targets): | |
544 | """Turn valid target IDs or 'all' into two lists: |
|
544 | """Turn valid target IDs or 'all' into two lists: | |
545 | (int_ids, uuids). |
|
545 | (int_ids, uuids). | |
546 | """ |
|
546 | """ | |
547 | if not self._ids: |
|
547 | if not self._ids: | |
548 | # flush notification socket if no engines yet, just in case |
|
548 | # flush notification socket if no engines yet, just in case | |
549 | if not self.ids: |
|
549 | if not self.ids: | |
550 | raise error.NoEnginesRegistered("Can't build targets without any engines") |
|
550 | raise error.NoEnginesRegistered("Can't build targets without any engines") | |
551 |
|
551 | |||
552 | if targets is None: |
|
552 | if targets is None: | |
553 | targets = self._ids |
|
553 | targets = self._ids | |
554 | elif isinstance(targets, basestring): |
|
554 | elif isinstance(targets, basestring): | |
555 | if targets.lower() == 'all': |
|
555 | if targets.lower() == 'all': | |
556 | targets = self._ids |
|
556 | targets = self._ids | |
557 | else: |
|
557 | else: | |
558 | raise TypeError("%r not valid str target, must be 'all'"%(targets)) |
|
558 | raise TypeError("%r not valid str target, must be 'all'"%(targets)) | |
559 | elif isinstance(targets, int): |
|
559 | elif isinstance(targets, int): | |
560 | if targets < 0: |
|
560 | if targets < 0: | |
561 | targets = self.ids[targets] |
|
561 | targets = self.ids[targets] | |
562 | if targets not in self._ids: |
|
562 | if targets not in self._ids: | |
563 | raise IndexError("No such engine: %i"%targets) |
|
563 | raise IndexError("No such engine: %i"%targets) | |
564 | targets = [targets] |
|
564 | targets = [targets] | |
565 |
|
565 | |||
566 | if isinstance(targets, slice): |
|
566 | if isinstance(targets, slice): | |
567 | indices = range(len(self._ids))[targets] |
|
567 | indices = range(len(self._ids))[targets] | |
568 | ids = self.ids |
|
568 | ids = self.ids | |
569 | targets = [ ids[i] for i in indices ] |
|
569 | targets = [ ids[i] for i in indices ] | |
570 |
|
570 | |||
571 | if not isinstance(targets, (tuple, list, xrange)): |
|
571 | if not isinstance(targets, (tuple, list, xrange)): | |
572 | raise TypeError("targets by int/slice/collection of ints only, not %s"%(type(targets))) |
|
572 | raise TypeError("targets by int/slice/collection of ints only, not %s"%(type(targets))) | |
573 |
|
573 | |||
574 | return [cast_bytes(self._engines[t]) for t in targets], list(targets) |
|
574 | return [cast_bytes(self._engines[t]) for t in targets], list(targets) | |
575 |
|
575 | |||
576 | def _connect(self, sshserver, ssh_kwargs, timeout): |
|
576 | def _connect(self, sshserver, ssh_kwargs, timeout): | |
577 | """setup all our socket connections to the cluster. This is called from |
|
577 | """setup all our socket connections to the cluster. This is called from | |
578 | __init__.""" |
|
578 | __init__.""" | |
579 |
|
579 | |||
580 | # Maybe allow reconnecting? |
|
580 | # Maybe allow reconnecting? | |
581 | if self._connected: |
|
581 | if self._connected: | |
582 | return |
|
582 | return | |
583 | self._connected=True |
|
583 | self._connected=True | |
584 |
|
584 | |||
585 | def connect_socket(s, url): |
|
585 | def connect_socket(s, url): | |
586 | url = util.disambiguate_url(url, self._config['location']) |
|
586 | url = util.disambiguate_url(url, self._config['location']) | |
587 | if self._ssh: |
|
587 | if self._ssh: | |
588 | return tunnel.tunnel_connection(s, url, sshserver, **ssh_kwargs) |
|
588 | return tunnel.tunnel_connection(s, url, sshserver, **ssh_kwargs) | |
589 | else: |
|
589 | else: | |
590 | return s.connect(url) |
|
590 | return s.connect(url) | |
591 |
|
591 | |||
592 | self.session.send(self._query_socket, 'connection_request') |
|
592 | self.session.send(self._query_socket, 'connection_request') | |
593 | # use Poller because zmq.select has wrong units in pyzmq 2.1.7 |
|
593 | # use Poller because zmq.select has wrong units in pyzmq 2.1.7 | |
594 | poller = zmq.Poller() |
|
594 | poller = zmq.Poller() | |
595 | poller.register(self._query_socket, zmq.POLLIN) |
|
595 | poller.register(self._query_socket, zmq.POLLIN) | |
596 | # poll expects milliseconds, timeout is seconds |
|
596 | # poll expects milliseconds, timeout is seconds | |
597 | evts = poller.poll(timeout*1000) |
|
597 | evts = poller.poll(timeout*1000) | |
598 | if not evts: |
|
598 | if not evts: | |
599 | raise error.TimeoutError("Hub connection request timed out") |
|
599 | raise error.TimeoutError("Hub connection request timed out") | |
600 | idents,msg = self.session.recv(self._query_socket,mode=0) |
|
600 | idents,msg = self.session.recv(self._query_socket,mode=0) | |
601 | if self.debug: |
|
601 | if self.debug: | |
602 | pprint(msg) |
|
602 | pprint(msg) | |
603 | msg = Message(msg) |
|
603 | msg = Message(msg) | |
604 | content = msg.content |
|
604 | content = msg.content | |
605 | self._config['registration'] = dict(content) |
|
605 | self._config['registration'] = dict(content) | |
606 | if content.status == 'ok': |
|
606 | if content.status == 'ok': | |
607 | ident = self.session.bsession |
|
607 | ident = self.session.bsession | |
608 | if content.mux: |
|
608 | if content.mux: | |
609 | self._mux_socket = self._context.socket(zmq.DEALER) |
|
609 | self._mux_socket = self._context.socket(zmq.DEALER) | |
610 | self._mux_socket.setsockopt(zmq.IDENTITY, ident) |
|
610 | self._mux_socket.setsockopt(zmq.IDENTITY, ident) | |
611 | connect_socket(self._mux_socket, content.mux) |
|
611 | connect_socket(self._mux_socket, content.mux) | |
612 | if content.task: |
|
612 | if content.task: | |
613 | self._task_scheme, task_addr = content.task |
|
613 | self._task_scheme, task_addr = content.task | |
614 | self._task_socket = self._context.socket(zmq.DEALER) |
|
614 | self._task_socket = self._context.socket(zmq.DEALER) | |
615 | self._task_socket.setsockopt(zmq.IDENTITY, ident) |
|
615 | self._task_socket.setsockopt(zmq.IDENTITY, ident) | |
616 | connect_socket(self._task_socket, task_addr) |
|
616 | connect_socket(self._task_socket, task_addr) | |
617 | if content.notification: |
|
617 | if content.notification: | |
618 | self._notification_socket = self._context.socket(zmq.SUB) |
|
618 | self._notification_socket = self._context.socket(zmq.SUB) | |
619 | connect_socket(self._notification_socket, content.notification) |
|
619 | connect_socket(self._notification_socket, content.notification) | |
620 | self._notification_socket.setsockopt(zmq.SUBSCRIBE, b'') |
|
620 | self._notification_socket.setsockopt(zmq.SUBSCRIBE, b'') | |
621 | # if content.query: |
|
621 | # if content.query: | |
622 | # self._query_socket = self._context.socket(zmq.DEALER) |
|
622 | # self._query_socket = self._context.socket(zmq.DEALER) | |
623 | # self._query_socket.setsockopt(zmq.IDENTITY, self.session.bsession) |
|
623 | # self._query_socket.setsockopt(zmq.IDENTITY, self.session.bsession) | |
624 | # connect_socket(self._query_socket, content.query) |
|
624 | # connect_socket(self._query_socket, content.query) | |
625 | if content.control: |
|
625 | if content.control: | |
626 | self._control_socket = self._context.socket(zmq.DEALER) |
|
626 | self._control_socket = self._context.socket(zmq.DEALER) | |
627 | self._control_socket.setsockopt(zmq.IDENTITY, ident) |
|
627 | self._control_socket.setsockopt(zmq.IDENTITY, ident) | |
628 | connect_socket(self._control_socket, content.control) |
|
628 | connect_socket(self._control_socket, content.control) | |
629 | if content.iopub: |
|
629 | if content.iopub: | |
630 | self._iopub_socket = self._context.socket(zmq.SUB) |
|
630 | self._iopub_socket = self._context.socket(zmq.SUB) | |
631 | self._iopub_socket.setsockopt(zmq.SUBSCRIBE, b'') |
|
631 | self._iopub_socket.setsockopt(zmq.SUBSCRIBE, b'') | |
632 | self._iopub_socket.setsockopt(zmq.IDENTITY, ident) |
|
632 | self._iopub_socket.setsockopt(zmq.IDENTITY, ident) | |
633 | connect_socket(self._iopub_socket, content.iopub) |
|
633 | connect_socket(self._iopub_socket, content.iopub) | |
634 | self._update_engines(dict(content.engines)) |
|
634 | self._update_engines(dict(content.engines)) | |
635 | else: |
|
635 | else: | |
636 | self._connected = False |
|
636 | self._connected = False | |
637 | raise Exception("Failed to connect!") |
|
637 | raise Exception("Failed to connect!") | |
638 |
|
638 | |||
639 | #-------------------------------------------------------------------------- |
|
639 | #-------------------------------------------------------------------------- | |
640 | # handlers and callbacks for incoming messages |
|
640 | # handlers and callbacks for incoming messages | |
641 | #-------------------------------------------------------------------------- |
|
641 | #-------------------------------------------------------------------------- | |
642 |
|
642 | |||
643 | def _unwrap_exception(self, content): |
|
643 | def _unwrap_exception(self, content): | |
644 | """unwrap exception, and remap engine_id to int.""" |
|
644 | """unwrap exception, and remap engine_id to int.""" | |
645 | e = error.unwrap_exception(content) |
|
645 | e = error.unwrap_exception(content) | |
646 | # print e.traceback |
|
646 | # print e.traceback | |
647 | if e.engine_info: |
|
647 | if e.engine_info: | |
648 | e_uuid = e.engine_info['engine_uuid'] |
|
648 | e_uuid = e.engine_info['engine_uuid'] | |
649 | eid = self._engines[e_uuid] |
|
649 | eid = self._engines[e_uuid] | |
650 | e.engine_info['engine_id'] = eid |
|
650 | e.engine_info['engine_id'] = eid | |
651 | return e |
|
651 | return e | |
652 |
|
652 | |||
653 |
def _extract_metadata(self, |
|
653 | def _extract_metadata(self, msg): | |
|
654 | header = msg['header'] | |||
|
655 | parent = msg['parent_header'] | |||
|
656 | msg_meta = msg['metadata'] | |||
|
657 | content = msg['content'] | |||
654 | md = {'msg_id' : parent['msg_id'], |
|
658 | md = {'msg_id' : parent['msg_id'], | |
655 | 'received' : datetime.now(), |
|
659 | 'received' : datetime.now(), | |
656 |
'engine_uuid' : |
|
660 | 'engine_uuid' : msg_meta.get('engine', None), | |
657 |
'follow' : |
|
661 | 'follow' : msg_meta.get('follow', []), | |
658 |
'after' : |
|
662 | 'after' : msg_meta.get('after', []), | |
659 | 'status' : content['status'], |
|
663 | 'status' : content['status'], | |
660 | } |
|
664 | } | |
661 |
|
665 | |||
662 | if md['engine_uuid'] is not None: |
|
666 | if md['engine_uuid'] is not None: | |
663 | md['engine_id'] = self._engines.get(md['engine_uuid'], None) |
|
667 | md['engine_id'] = self._engines.get(md['engine_uuid'], None) | |
664 |
|
668 | |||
665 | if 'date' in parent: |
|
669 | if 'date' in parent: | |
666 | md['submitted'] = parent['date'] |
|
670 | md['submitted'] = parent['date'] | |
667 |
if 'started' in |
|
671 | if 'started' in msg_meta: | |
668 |
md['started'] = |
|
672 | md['started'] = msg_meta['started'] | |
669 | if 'date' in header: |
|
673 | if 'date' in header: | |
670 | md['completed'] = header['date'] |
|
674 | md['completed'] = header['date'] | |
671 | return md |
|
675 | return md | |
672 |
|
676 | |||
673 | def _register_engine(self, msg): |
|
677 | def _register_engine(self, msg): | |
674 | """Register a new engine, and update our connection info.""" |
|
678 | """Register a new engine, and update our connection info.""" | |
675 | content = msg['content'] |
|
679 | content = msg['content'] | |
676 | eid = content['id'] |
|
680 | eid = content['id'] | |
677 | d = {eid : content['queue']} |
|
681 | d = {eid : content['queue']} | |
678 | self._update_engines(d) |
|
682 | self._update_engines(d) | |
679 |
|
683 | |||
680 | def _unregister_engine(self, msg): |
|
684 | def _unregister_engine(self, msg): | |
681 | """Unregister an engine that has died.""" |
|
685 | """Unregister an engine that has died.""" | |
682 | content = msg['content'] |
|
686 | content = msg['content'] | |
683 | eid = int(content['id']) |
|
687 | eid = int(content['id']) | |
684 | if eid in self._ids: |
|
688 | if eid in self._ids: | |
685 | self._ids.remove(eid) |
|
689 | self._ids.remove(eid) | |
686 | uuid = self._engines.pop(eid) |
|
690 | uuid = self._engines.pop(eid) | |
687 |
|
691 | |||
688 | self._handle_stranded_msgs(eid, uuid) |
|
692 | self._handle_stranded_msgs(eid, uuid) | |
689 |
|
693 | |||
690 | if self._task_socket and self._task_scheme == 'pure': |
|
694 | if self._task_socket and self._task_scheme == 'pure': | |
691 | self._stop_scheduling_tasks() |
|
695 | self._stop_scheduling_tasks() | |
692 |
|
696 | |||
693 | def _handle_stranded_msgs(self, eid, uuid): |
|
697 | def _handle_stranded_msgs(self, eid, uuid): | |
694 | """Handle messages known to be on an engine when the engine unregisters. |
|
698 | """Handle messages known to be on an engine when the engine unregisters. | |
695 |
|
699 | |||
696 | It is possible that this will fire prematurely - that is, an engine will |
|
700 | It is possible that this will fire prematurely - that is, an engine will | |
697 | go down after completing a result, and the client will be notified |
|
701 | go down after completing a result, and the client will be notified | |
698 | of the unregistration and later receive the successful result. |
|
702 | of the unregistration and later receive the successful result. | |
699 | """ |
|
703 | """ | |
700 |
|
704 | |||
701 | outstanding = self._outstanding_dict[uuid] |
|
705 | outstanding = self._outstanding_dict[uuid] | |
702 |
|
706 | |||
703 | for msg_id in list(outstanding): |
|
707 | for msg_id in list(outstanding): | |
704 | if msg_id in self.results: |
|
708 | if msg_id in self.results: | |
705 | # we already |
|
709 | # we already | |
706 | continue |
|
710 | continue | |
707 | try: |
|
711 | try: | |
708 | raise error.EngineError("Engine %r died while running task %r"%(eid, msg_id)) |
|
712 | raise error.EngineError("Engine %r died while running task %r"%(eid, msg_id)) | |
709 | except: |
|
713 | except: | |
710 | content = error.wrap_exception() |
|
714 | content = error.wrap_exception() | |
711 | # build a fake message: |
|
715 | # build a fake message: | |
712 | parent = {} |
|
716 | parent = {} | |
713 | header = {} |
|
717 | header = {} | |
714 | parent['msg_id'] = msg_id |
|
718 | parent['msg_id'] = msg_id | |
715 | header['engine'] = uuid |
|
719 | header['engine'] = uuid | |
716 | header['date'] = datetime.now() |
|
720 | header['date'] = datetime.now() | |
717 | msg = dict(parent_header=parent, header=header, content=content) |
|
721 | msg = dict(parent_header=parent, header=header, content=content) | |
718 | self._handle_apply_reply(msg) |
|
722 | self._handle_apply_reply(msg) | |
719 |
|
723 | |||
720 | def _handle_execute_reply(self, msg): |
|
724 | def _handle_execute_reply(self, msg): | |
721 | """Save the reply to an execute_request into our results. |
|
725 | """Save the reply to an execute_request into our results. | |
722 |
|
726 | |||
723 | execute messages are never actually used. apply is used instead. |
|
727 | execute messages are never actually used. apply is used instead. | |
724 | """ |
|
728 | """ | |
725 |
|
729 | |||
726 | parent = msg['parent_header'] |
|
730 | parent = msg['parent_header'] | |
727 | msg_id = parent['msg_id'] |
|
731 | msg_id = parent['msg_id'] | |
728 | if msg_id not in self.outstanding: |
|
732 | if msg_id not in self.outstanding: | |
729 | if msg_id in self.history: |
|
733 | if msg_id in self.history: | |
730 | print ("got stale result: %s"%msg_id) |
|
734 | print ("got stale result: %s"%msg_id) | |
731 | else: |
|
735 | else: | |
732 | print ("got unknown result: %s"%msg_id) |
|
736 | print ("got unknown result: %s"%msg_id) | |
733 | else: |
|
737 | else: | |
734 | self.outstanding.remove(msg_id) |
|
738 | self.outstanding.remove(msg_id) | |
735 |
|
739 | |||
736 | content = msg['content'] |
|
740 | content = msg['content'] | |
737 | header = msg['header'] |
|
741 | header = msg['header'] | |
738 |
|
742 | |||
739 | # construct metadata: |
|
743 | # construct metadata: | |
740 | md = self.metadata[msg_id] |
|
744 | md = self.metadata[msg_id] | |
741 |
md.update(self._extract_metadata( |
|
745 | md.update(self._extract_metadata(msg)) | |
742 | # is this redundant? |
|
746 | # is this redundant? | |
743 | self.metadata[msg_id] = md |
|
747 | self.metadata[msg_id] = md | |
744 |
|
748 | |||
745 | e_outstanding = self._outstanding_dict[md['engine_uuid']] |
|
749 | e_outstanding = self._outstanding_dict[md['engine_uuid']] | |
746 | if msg_id in e_outstanding: |
|
750 | if msg_id in e_outstanding: | |
747 | e_outstanding.remove(msg_id) |
|
751 | e_outstanding.remove(msg_id) | |
748 |
|
752 | |||
749 | # construct result: |
|
753 | # construct result: | |
750 | if content['status'] == 'ok': |
|
754 | if content['status'] == 'ok': | |
751 | self.results[msg_id] = ExecuteReply(msg_id, content, md) |
|
755 | self.results[msg_id] = ExecuteReply(msg_id, content, md) | |
752 | elif content['status'] == 'aborted': |
|
756 | elif content['status'] == 'aborted': | |
753 | self.results[msg_id] = error.TaskAborted(msg_id) |
|
757 | self.results[msg_id] = error.TaskAborted(msg_id) | |
754 | elif content['status'] == 'resubmitted': |
|
758 | elif content['status'] == 'resubmitted': | |
755 | # TODO: handle resubmission |
|
759 | # TODO: handle resubmission | |
756 | pass |
|
760 | pass | |
757 | else: |
|
761 | else: | |
758 | self.results[msg_id] = self._unwrap_exception(content) |
|
762 | self.results[msg_id] = self._unwrap_exception(content) | |
759 |
|
763 | |||
760 | def _handle_apply_reply(self, msg): |
|
764 | def _handle_apply_reply(self, msg): | |
761 | """Save the reply to an apply_request into our results.""" |
|
765 | """Save the reply to an apply_request into our results.""" | |
762 | parent = msg['parent_header'] |
|
766 | parent = msg['parent_header'] | |
763 | msg_id = parent['msg_id'] |
|
767 | msg_id = parent['msg_id'] | |
764 | if msg_id not in self.outstanding: |
|
768 | if msg_id not in self.outstanding: | |
765 | if msg_id in self.history: |
|
769 | if msg_id in self.history: | |
766 | print ("got stale result: %s"%msg_id) |
|
770 | print ("got stale result: %s"%msg_id) | |
767 | print self.results[msg_id] |
|
771 | print self.results[msg_id] | |
768 | print msg |
|
772 | print msg | |
769 | else: |
|
773 | else: | |
770 | print ("got unknown result: %s"%msg_id) |
|
774 | print ("got unknown result: %s"%msg_id) | |
771 | else: |
|
775 | else: | |
772 | self.outstanding.remove(msg_id) |
|
776 | self.outstanding.remove(msg_id) | |
773 | content = msg['content'] |
|
777 | content = msg['content'] | |
774 | header = msg['header'] |
|
778 | header = msg['header'] | |
775 |
|
779 | |||
776 | # construct metadata: |
|
780 | # construct metadata: | |
777 | md = self.metadata[msg_id] |
|
781 | md = self.metadata[msg_id] | |
778 |
md.update(self._extract_metadata( |
|
782 | md.update(self._extract_metadata(msg)) | |
779 | # is this redundant? |
|
783 | # is this redundant? | |
780 | self.metadata[msg_id] = md |
|
784 | self.metadata[msg_id] = md | |
781 |
|
785 | |||
782 | e_outstanding = self._outstanding_dict[md['engine_uuid']] |
|
786 | e_outstanding = self._outstanding_dict[md['engine_uuid']] | |
783 | if msg_id in e_outstanding: |
|
787 | if msg_id in e_outstanding: | |
784 | e_outstanding.remove(msg_id) |
|
788 | e_outstanding.remove(msg_id) | |
785 |
|
789 | |||
786 | # construct result: |
|
790 | # construct result: | |
787 | if content['status'] == 'ok': |
|
791 | if content['status'] == 'ok': | |
788 | self.results[msg_id] = util.unserialize_object(msg['buffers'])[0] |
|
792 | self.results[msg_id] = util.unserialize_object(msg['buffers'])[0] | |
789 | elif content['status'] == 'aborted': |
|
793 | elif content['status'] == 'aborted': | |
790 | self.results[msg_id] = error.TaskAborted(msg_id) |
|
794 | self.results[msg_id] = error.TaskAborted(msg_id) | |
791 | elif content['status'] == 'resubmitted': |
|
795 | elif content['status'] == 'resubmitted': | |
792 | # TODO: handle resubmission |
|
796 | # TODO: handle resubmission | |
793 | pass |
|
797 | pass | |
794 | else: |
|
798 | else: | |
795 | self.results[msg_id] = self._unwrap_exception(content) |
|
799 | self.results[msg_id] = self._unwrap_exception(content) | |
796 |
|
800 | |||
797 | def _flush_notifications(self): |
|
801 | def _flush_notifications(self): | |
798 | """Flush notifications of engine registrations waiting |
|
802 | """Flush notifications of engine registrations waiting | |
799 | in ZMQ queue.""" |
|
803 | in ZMQ queue.""" | |
800 | idents,msg = self.session.recv(self._notification_socket, mode=zmq.NOBLOCK) |
|
804 | idents,msg = self.session.recv(self._notification_socket, mode=zmq.NOBLOCK) | |
801 | while msg is not None: |
|
805 | while msg is not None: | |
802 | if self.debug: |
|
806 | if self.debug: | |
803 | pprint(msg) |
|
807 | pprint(msg) | |
804 | msg_type = msg['header']['msg_type'] |
|
808 | msg_type = msg['header']['msg_type'] | |
805 | handler = self._notification_handlers.get(msg_type, None) |
|
809 | handler = self._notification_handlers.get(msg_type, None) | |
806 | if handler is None: |
|
810 | if handler is None: | |
807 | raise Exception("Unhandled message type: %s"%msg.msg_type) |
|
811 | raise Exception("Unhandled message type: %s"%msg.msg_type) | |
808 | else: |
|
812 | else: | |
809 | handler(msg) |
|
813 | handler(msg) | |
810 | idents,msg = self.session.recv(self._notification_socket, mode=zmq.NOBLOCK) |
|
814 | idents,msg = self.session.recv(self._notification_socket, mode=zmq.NOBLOCK) | |
811 |
|
815 | |||
812 | def _flush_results(self, sock): |
|
816 | def _flush_results(self, sock): | |
813 | """Flush task or queue results waiting in ZMQ queue.""" |
|
817 | """Flush task or queue results waiting in ZMQ queue.""" | |
814 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) |
|
818 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) | |
815 | while msg is not None: |
|
819 | while msg is not None: | |
816 | if self.debug: |
|
820 | if self.debug: | |
817 | pprint(msg) |
|
821 | pprint(msg) | |
818 | msg_type = msg['header']['msg_type'] |
|
822 | msg_type = msg['header']['msg_type'] | |
819 | handler = self._queue_handlers.get(msg_type, None) |
|
823 | handler = self._queue_handlers.get(msg_type, None) | |
820 | if handler is None: |
|
824 | if handler is None: | |
821 | raise Exception("Unhandled message type: %s"%msg.msg_type) |
|
825 | raise Exception("Unhandled message type: %s"%msg.msg_type) | |
822 | else: |
|
826 | else: | |
823 | handler(msg) |
|
827 | handler(msg) | |
824 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) |
|
828 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) | |
825 |
|
829 | |||
826 | def _flush_control(self, sock): |
|
830 | def _flush_control(self, sock): | |
827 | """Flush replies from the control channel waiting |
|
831 | """Flush replies from the control channel waiting | |
828 | in the ZMQ queue. |
|
832 | in the ZMQ queue. | |
829 |
|
833 | |||
830 | Currently: ignore them.""" |
|
834 | Currently: ignore them.""" | |
831 | if self._ignored_control_replies <= 0: |
|
835 | if self._ignored_control_replies <= 0: | |
832 | return |
|
836 | return | |
833 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) |
|
837 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) | |
834 | while msg is not None: |
|
838 | while msg is not None: | |
835 | self._ignored_control_replies -= 1 |
|
839 | self._ignored_control_replies -= 1 | |
836 | if self.debug: |
|
840 | if self.debug: | |
837 | pprint(msg) |
|
841 | pprint(msg) | |
838 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) |
|
842 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) | |
839 |
|
843 | |||
840 | def _flush_ignored_control(self): |
|
844 | def _flush_ignored_control(self): | |
841 | """flush ignored control replies""" |
|
845 | """flush ignored control replies""" | |
842 | while self._ignored_control_replies > 0: |
|
846 | while self._ignored_control_replies > 0: | |
843 | self.session.recv(self._control_socket) |
|
847 | self.session.recv(self._control_socket) | |
844 | self._ignored_control_replies -= 1 |
|
848 | self._ignored_control_replies -= 1 | |
845 |
|
849 | |||
846 | def _flush_ignored_hub_replies(self): |
|
850 | def _flush_ignored_hub_replies(self): | |
847 | ident,msg = self.session.recv(self._query_socket, mode=zmq.NOBLOCK) |
|
851 | ident,msg = self.session.recv(self._query_socket, mode=zmq.NOBLOCK) | |
848 | while msg is not None: |
|
852 | while msg is not None: | |
849 | ident,msg = self.session.recv(self._query_socket, mode=zmq.NOBLOCK) |
|
853 | ident,msg = self.session.recv(self._query_socket, mode=zmq.NOBLOCK) | |
850 |
|
854 | |||
851 | def _flush_iopub(self, sock): |
|
855 | def _flush_iopub(self, sock): | |
852 | """Flush replies from the iopub channel waiting |
|
856 | """Flush replies from the iopub channel waiting | |
853 | in the ZMQ queue. |
|
857 | in the ZMQ queue. | |
854 | """ |
|
858 | """ | |
855 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) |
|
859 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) | |
856 | while msg is not None: |
|
860 | while msg is not None: | |
857 | if self.debug: |
|
861 | if self.debug: | |
858 | pprint(msg) |
|
862 | pprint(msg) | |
859 | parent = msg['parent_header'] |
|
863 | parent = msg['parent_header'] | |
860 | # ignore IOPub messages with no parent. |
|
864 | # ignore IOPub messages with no parent. | |
861 | # Caused by print statements or warnings from before the first execution. |
|
865 | # Caused by print statements or warnings from before the first execution. | |
862 | if not parent: |
|
866 | if not parent: | |
863 | continue |
|
867 | continue | |
864 | msg_id = parent['msg_id'] |
|
868 | msg_id = parent['msg_id'] | |
865 | content = msg['content'] |
|
869 | content = msg['content'] | |
866 | header = msg['header'] |
|
870 | header = msg['header'] | |
867 | msg_type = msg['header']['msg_type'] |
|
871 | msg_type = msg['header']['msg_type'] | |
868 |
|
872 | |||
869 | # init metadata: |
|
873 | # init metadata: | |
870 | md = self.metadata[msg_id] |
|
874 | md = self.metadata[msg_id] | |
871 |
|
875 | |||
872 | if msg_type == 'stream': |
|
876 | if msg_type == 'stream': | |
873 | name = content['name'] |
|
877 | name = content['name'] | |
874 | s = md[name] or '' |
|
878 | s = md[name] or '' | |
875 | md[name] = s + content['data'] |
|
879 | md[name] = s + content['data'] | |
876 | elif msg_type == 'pyerr': |
|
880 | elif msg_type == 'pyerr': | |
877 | md.update({'pyerr' : self._unwrap_exception(content)}) |
|
881 | md.update({'pyerr' : self._unwrap_exception(content)}) | |
878 | elif msg_type == 'pyin': |
|
882 | elif msg_type == 'pyin': | |
879 | md.update({'pyin' : content['code']}) |
|
883 | md.update({'pyin' : content['code']}) | |
880 | elif msg_type == 'display_data': |
|
884 | elif msg_type == 'display_data': | |
881 | md['outputs'].append(content) |
|
885 | md['outputs'].append(content) | |
882 | elif msg_type == 'pyout': |
|
886 | elif msg_type == 'pyout': | |
883 | md['pyout'] = content |
|
887 | md['pyout'] = content | |
884 | elif msg_type == 'status': |
|
888 | elif msg_type == 'status': | |
885 | # idle message comes after all outputs |
|
889 | # idle message comes after all outputs | |
886 | if content['execution_state'] == 'idle': |
|
890 | if content['execution_state'] == 'idle': | |
887 | md['outputs_ready'] = True |
|
891 | md['outputs_ready'] = True | |
888 | else: |
|
892 | else: | |
889 | # unhandled msg_type (status, etc.) |
|
893 | # unhandled msg_type (status, etc.) | |
890 | pass |
|
894 | pass | |
891 |
|
895 | |||
892 | # reduntant? |
|
896 | # reduntant? | |
893 | self.metadata[msg_id] = md |
|
897 | self.metadata[msg_id] = md | |
894 |
|
898 | |||
895 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) |
|
899 | idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) | |
896 |
|
900 | |||
897 | #-------------------------------------------------------------------------- |
|
901 | #-------------------------------------------------------------------------- | |
898 | # len, getitem |
|
902 | # len, getitem | |
899 | #-------------------------------------------------------------------------- |
|
903 | #-------------------------------------------------------------------------- | |
900 |
|
904 | |||
901 | def __len__(self): |
|
905 | def __len__(self): | |
902 | """len(client) returns # of engines.""" |
|
906 | """len(client) returns # of engines.""" | |
903 | return len(self.ids) |
|
907 | return len(self.ids) | |
904 |
|
908 | |||
905 | def __getitem__(self, key): |
|
909 | def __getitem__(self, key): | |
906 | """index access returns DirectView multiplexer objects |
|
910 | """index access returns DirectView multiplexer objects | |
907 |
|
911 | |||
908 | Must be int, slice, or list/tuple/xrange of ints""" |
|
912 | Must be int, slice, or list/tuple/xrange of ints""" | |
909 | if not isinstance(key, (int, slice, tuple, list, xrange)): |
|
913 | if not isinstance(key, (int, slice, tuple, list, xrange)): | |
910 | raise TypeError("key by int/slice/iterable of ints only, not %s"%(type(key))) |
|
914 | raise TypeError("key by int/slice/iterable of ints only, not %s"%(type(key))) | |
911 | else: |
|
915 | else: | |
912 | return self.direct_view(key) |
|
916 | return self.direct_view(key) | |
913 |
|
917 | |||
914 | #-------------------------------------------------------------------------- |
|
918 | #-------------------------------------------------------------------------- | |
915 | # Begin public methods |
|
919 | # Begin public methods | |
916 | #-------------------------------------------------------------------------- |
|
920 | #-------------------------------------------------------------------------- | |
917 |
|
921 | |||
918 | @property |
|
922 | @property | |
919 | def ids(self): |
|
923 | def ids(self): | |
920 | """Always up-to-date ids property.""" |
|
924 | """Always up-to-date ids property.""" | |
921 | self._flush_notifications() |
|
925 | self._flush_notifications() | |
922 | # always copy: |
|
926 | # always copy: | |
923 | return list(self._ids) |
|
927 | return list(self._ids) | |
924 |
|
928 | |||
925 | def activate(self, targets='all', suffix=''): |
|
929 | def activate(self, targets='all', suffix=''): | |
926 | """Create a DirectView and register it with IPython magics |
|
930 | """Create a DirectView and register it with IPython magics | |
927 |
|
931 | |||
928 | Defines the magics `%px, %autopx, %pxresult, %%px` |
|
932 | Defines the magics `%px, %autopx, %pxresult, %%px` | |
929 |
|
933 | |||
930 | Parameters |
|
934 | Parameters | |
931 | ---------- |
|
935 | ---------- | |
932 |
|
936 | |||
933 | targets: int, list of ints, or 'all' |
|
937 | targets: int, list of ints, or 'all' | |
934 | The engines on which the view's magics will run |
|
938 | The engines on which the view's magics will run | |
935 | suffix: str [default: ''] |
|
939 | suffix: str [default: ''] | |
936 | The suffix, if any, for the magics. This allows you to have |
|
940 | The suffix, if any, for the magics. This allows you to have | |
937 | multiple views associated with parallel magics at the same time. |
|
941 | multiple views associated with parallel magics at the same time. | |
938 |
|
942 | |||
939 | e.g. ``rc.activate(targets=0, suffix='0')`` will give you |
|
943 | e.g. ``rc.activate(targets=0, suffix='0')`` will give you | |
940 | the magics ``%px0``, ``%pxresult0``, etc. for running magics just |
|
944 | the magics ``%px0``, ``%pxresult0``, etc. for running magics just | |
941 | on engine 0. |
|
945 | on engine 0. | |
942 | """ |
|
946 | """ | |
943 | view = self.direct_view(targets) |
|
947 | view = self.direct_view(targets) | |
944 | view.block = True |
|
948 | view.block = True | |
945 | view.activate(suffix) |
|
949 | view.activate(suffix) | |
946 | return view |
|
950 | return view | |
947 |
|
951 | |||
948 | def close(self): |
|
952 | def close(self): | |
949 | if self._closed: |
|
953 | if self._closed: | |
950 | return |
|
954 | return | |
951 | self.stop_spin_thread() |
|
955 | self.stop_spin_thread() | |
952 | snames = filter(lambda n: n.endswith('socket'), dir(self)) |
|
956 | snames = filter(lambda n: n.endswith('socket'), dir(self)) | |
953 | for socket in map(lambda name: getattr(self, name), snames): |
|
957 | for socket in map(lambda name: getattr(self, name), snames): | |
954 | if isinstance(socket, zmq.Socket) and not socket.closed: |
|
958 | if isinstance(socket, zmq.Socket) and not socket.closed: | |
955 | socket.close() |
|
959 | socket.close() | |
956 | self._closed = True |
|
960 | self._closed = True | |
957 |
|
961 | |||
958 | def _spin_every(self, interval=1): |
|
962 | def _spin_every(self, interval=1): | |
959 | """target func for use in spin_thread""" |
|
963 | """target func for use in spin_thread""" | |
960 | while True: |
|
964 | while True: | |
961 | if self._stop_spinning.is_set(): |
|
965 | if self._stop_spinning.is_set(): | |
962 | return |
|
966 | return | |
963 | time.sleep(interval) |
|
967 | time.sleep(interval) | |
964 | self.spin() |
|
968 | self.spin() | |
965 |
|
969 | |||
966 | def spin_thread(self, interval=1): |
|
970 | def spin_thread(self, interval=1): | |
967 | """call Client.spin() in a background thread on some regular interval |
|
971 | """call Client.spin() in a background thread on some regular interval | |
968 |
|
972 | |||
969 | This helps ensure that messages don't pile up too much in the zmq queue |
|
973 | This helps ensure that messages don't pile up too much in the zmq queue | |
970 | while you are working on other things, or just leaving an idle terminal. |
|
974 | while you are working on other things, or just leaving an idle terminal. | |
971 |
|
975 | |||
972 | It also helps limit potential padding of the `received` timestamp |
|
976 | It also helps limit potential padding of the `received` timestamp | |
973 | on AsyncResult objects, used for timings. |
|
977 | on AsyncResult objects, used for timings. | |
974 |
|
978 | |||
975 | Parameters |
|
979 | Parameters | |
976 | ---------- |
|
980 | ---------- | |
977 |
|
981 | |||
978 | interval : float, optional |
|
982 | interval : float, optional | |
979 | The interval on which to spin the client in the background thread |
|
983 | The interval on which to spin the client in the background thread | |
980 | (simply passed to time.sleep). |
|
984 | (simply passed to time.sleep). | |
981 |
|
985 | |||
982 | Notes |
|
986 | Notes | |
983 | ----- |
|
987 | ----- | |
984 |
|
988 | |||
985 | For precision timing, you may want to use this method to put a bound |
|
989 | For precision timing, you may want to use this method to put a bound | |
986 | on the jitter (in seconds) in `received` timestamps used |
|
990 | on the jitter (in seconds) in `received` timestamps used | |
987 | in AsyncResult.wall_time. |
|
991 | in AsyncResult.wall_time. | |
988 |
|
992 | |||
989 | """ |
|
993 | """ | |
990 | if self._spin_thread is not None: |
|
994 | if self._spin_thread is not None: | |
991 | self.stop_spin_thread() |
|
995 | self.stop_spin_thread() | |
992 | self._stop_spinning.clear() |
|
996 | self._stop_spinning.clear() | |
993 | self._spin_thread = Thread(target=self._spin_every, args=(interval,)) |
|
997 | self._spin_thread = Thread(target=self._spin_every, args=(interval,)) | |
994 | self._spin_thread.daemon = True |
|
998 | self._spin_thread.daemon = True | |
995 | self._spin_thread.start() |
|
999 | self._spin_thread.start() | |
996 |
|
1000 | |||
997 | def stop_spin_thread(self): |
|
1001 | def stop_spin_thread(self): | |
998 | """stop background spin_thread, if any""" |
|
1002 | """stop background spin_thread, if any""" | |
999 | if self._spin_thread is not None: |
|
1003 | if self._spin_thread is not None: | |
1000 | self._stop_spinning.set() |
|
1004 | self._stop_spinning.set() | |
1001 | self._spin_thread.join() |
|
1005 | self._spin_thread.join() | |
1002 | self._spin_thread = None |
|
1006 | self._spin_thread = None | |
1003 |
|
1007 | |||
1004 | def spin(self): |
|
1008 | def spin(self): | |
1005 | """Flush any registration notifications and execution results |
|
1009 | """Flush any registration notifications and execution results | |
1006 | waiting in the ZMQ queue. |
|
1010 | waiting in the ZMQ queue. | |
1007 | """ |
|
1011 | """ | |
1008 | if self._notification_socket: |
|
1012 | if self._notification_socket: | |
1009 | self._flush_notifications() |
|
1013 | self._flush_notifications() | |
1010 | if self._iopub_socket: |
|
1014 | if self._iopub_socket: | |
1011 | self._flush_iopub(self._iopub_socket) |
|
1015 | self._flush_iopub(self._iopub_socket) | |
1012 | if self._mux_socket: |
|
1016 | if self._mux_socket: | |
1013 | self._flush_results(self._mux_socket) |
|
1017 | self._flush_results(self._mux_socket) | |
1014 | if self._task_socket: |
|
1018 | if self._task_socket: | |
1015 | self._flush_results(self._task_socket) |
|
1019 | self._flush_results(self._task_socket) | |
1016 | if self._control_socket: |
|
1020 | if self._control_socket: | |
1017 | self._flush_control(self._control_socket) |
|
1021 | self._flush_control(self._control_socket) | |
1018 | if self._query_socket: |
|
1022 | if self._query_socket: | |
1019 | self._flush_ignored_hub_replies() |
|
1023 | self._flush_ignored_hub_replies() | |
1020 |
|
1024 | |||
1021 | def wait(self, jobs=None, timeout=-1): |
|
1025 | def wait(self, jobs=None, timeout=-1): | |
1022 | """waits on one or more `jobs`, for up to `timeout` seconds. |
|
1026 | """waits on one or more `jobs`, for up to `timeout` seconds. | |
1023 |
|
1027 | |||
1024 | Parameters |
|
1028 | Parameters | |
1025 | ---------- |
|
1029 | ---------- | |
1026 |
|
1030 | |||
1027 | jobs : int, str, or list of ints and/or strs, or one or more AsyncResult objects |
|
1031 | jobs : int, str, or list of ints and/or strs, or one or more AsyncResult objects | |
1028 | ints are indices to self.history |
|
1032 | ints are indices to self.history | |
1029 | strs are msg_ids |
|
1033 | strs are msg_ids | |
1030 | default: wait on all outstanding messages |
|
1034 | default: wait on all outstanding messages | |
1031 | timeout : float |
|
1035 | timeout : float | |
1032 | a time in seconds, after which to give up. |
|
1036 | a time in seconds, after which to give up. | |
1033 | default is -1, which means no timeout |
|
1037 | default is -1, which means no timeout | |
1034 |
|
1038 | |||
1035 | Returns |
|
1039 | Returns | |
1036 | ------- |
|
1040 | ------- | |
1037 |
|
1041 | |||
1038 | True : when all msg_ids are done |
|
1042 | True : when all msg_ids are done | |
1039 | False : timeout reached, some msg_ids still outstanding |
|
1043 | False : timeout reached, some msg_ids still outstanding | |
1040 | """ |
|
1044 | """ | |
1041 | tic = time.time() |
|
1045 | tic = time.time() | |
1042 | if jobs is None: |
|
1046 | if jobs is None: | |
1043 | theids = self.outstanding |
|
1047 | theids = self.outstanding | |
1044 | else: |
|
1048 | else: | |
1045 | if isinstance(jobs, (int, basestring, AsyncResult)): |
|
1049 | if isinstance(jobs, (int, basestring, AsyncResult)): | |
1046 | jobs = [jobs] |
|
1050 | jobs = [jobs] | |
1047 | theids = set() |
|
1051 | theids = set() | |
1048 | for job in jobs: |
|
1052 | for job in jobs: | |
1049 | if isinstance(job, int): |
|
1053 | if isinstance(job, int): | |
1050 | # index access |
|
1054 | # index access | |
1051 | job = self.history[job] |
|
1055 | job = self.history[job] | |
1052 | elif isinstance(job, AsyncResult): |
|
1056 | elif isinstance(job, AsyncResult): | |
1053 | map(theids.add, job.msg_ids) |
|
1057 | map(theids.add, job.msg_ids) | |
1054 | continue |
|
1058 | continue | |
1055 | theids.add(job) |
|
1059 | theids.add(job) | |
1056 | if not theids.intersection(self.outstanding): |
|
1060 | if not theids.intersection(self.outstanding): | |
1057 | return True |
|
1061 | return True | |
1058 | self.spin() |
|
1062 | self.spin() | |
1059 | while theids.intersection(self.outstanding): |
|
1063 | while theids.intersection(self.outstanding): | |
1060 | if timeout >= 0 and ( time.time()-tic ) > timeout: |
|
1064 | if timeout >= 0 and ( time.time()-tic ) > timeout: | |
1061 | break |
|
1065 | break | |
1062 | time.sleep(1e-3) |
|
1066 | time.sleep(1e-3) | |
1063 | self.spin() |
|
1067 | self.spin() | |
1064 | return len(theids.intersection(self.outstanding)) == 0 |
|
1068 | return len(theids.intersection(self.outstanding)) == 0 | |
1065 |
|
1069 | |||
1066 | #-------------------------------------------------------------------------- |
|
1070 | #-------------------------------------------------------------------------- | |
1067 | # Control methods |
|
1071 | # Control methods | |
1068 | #-------------------------------------------------------------------------- |
|
1072 | #-------------------------------------------------------------------------- | |
1069 |
|
1073 | |||
1070 | @spin_first |
|
1074 | @spin_first | |
1071 | def clear(self, targets=None, block=None): |
|
1075 | def clear(self, targets=None, block=None): | |
1072 | """Clear the namespace in target(s).""" |
|
1076 | """Clear the namespace in target(s).""" | |
1073 | block = self.block if block is None else block |
|
1077 | block = self.block if block is None else block | |
1074 | targets = self._build_targets(targets)[0] |
|
1078 | targets = self._build_targets(targets)[0] | |
1075 | for t in targets: |
|
1079 | for t in targets: | |
1076 | self.session.send(self._control_socket, 'clear_request', content={}, ident=t) |
|
1080 | self.session.send(self._control_socket, 'clear_request', content={}, ident=t) | |
1077 | error = False |
|
1081 | error = False | |
1078 | if block: |
|
1082 | if block: | |
1079 | self._flush_ignored_control() |
|
1083 | self._flush_ignored_control() | |
1080 | for i in range(len(targets)): |
|
1084 | for i in range(len(targets)): | |
1081 | idents,msg = self.session.recv(self._control_socket,0) |
|
1085 | idents,msg = self.session.recv(self._control_socket,0) | |
1082 | if self.debug: |
|
1086 | if self.debug: | |
1083 | pprint(msg) |
|
1087 | pprint(msg) | |
1084 | if msg['content']['status'] != 'ok': |
|
1088 | if msg['content']['status'] != 'ok': | |
1085 | error = self._unwrap_exception(msg['content']) |
|
1089 | error = self._unwrap_exception(msg['content']) | |
1086 | else: |
|
1090 | else: | |
1087 | self._ignored_control_replies += len(targets) |
|
1091 | self._ignored_control_replies += len(targets) | |
1088 | if error: |
|
1092 | if error: | |
1089 | raise error |
|
1093 | raise error | |
1090 |
|
1094 | |||
1091 |
|
1095 | |||
1092 | @spin_first |
|
1096 | @spin_first | |
1093 | def abort(self, jobs=None, targets=None, block=None): |
|
1097 | def abort(self, jobs=None, targets=None, block=None): | |
1094 | """Abort specific jobs from the execution queues of target(s). |
|
1098 | """Abort specific jobs from the execution queues of target(s). | |
1095 |
|
1099 | |||
1096 | This is a mechanism to prevent jobs that have already been submitted |
|
1100 | This is a mechanism to prevent jobs that have already been submitted | |
1097 | from executing. |
|
1101 | from executing. | |
1098 |
|
1102 | |||
1099 | Parameters |
|
1103 | Parameters | |
1100 | ---------- |
|
1104 | ---------- | |
1101 |
|
1105 | |||
1102 | jobs : msg_id, list of msg_ids, or AsyncResult |
|
1106 | jobs : msg_id, list of msg_ids, or AsyncResult | |
1103 | The jobs to be aborted |
|
1107 | The jobs to be aborted | |
1104 |
|
1108 | |||
1105 | If unspecified/None: abort all outstanding jobs. |
|
1109 | If unspecified/None: abort all outstanding jobs. | |
1106 |
|
1110 | |||
1107 | """ |
|
1111 | """ | |
1108 | block = self.block if block is None else block |
|
1112 | block = self.block if block is None else block | |
1109 | jobs = jobs if jobs is not None else list(self.outstanding) |
|
1113 | jobs = jobs if jobs is not None else list(self.outstanding) | |
1110 | targets = self._build_targets(targets)[0] |
|
1114 | targets = self._build_targets(targets)[0] | |
1111 |
|
1115 | |||
1112 | msg_ids = [] |
|
1116 | msg_ids = [] | |
1113 | if isinstance(jobs, (basestring,AsyncResult)): |
|
1117 | if isinstance(jobs, (basestring,AsyncResult)): | |
1114 | jobs = [jobs] |
|
1118 | jobs = [jobs] | |
1115 | bad_ids = filter(lambda obj: not isinstance(obj, (basestring, AsyncResult)), jobs) |
|
1119 | bad_ids = filter(lambda obj: not isinstance(obj, (basestring, AsyncResult)), jobs) | |
1116 | if bad_ids: |
|
1120 | if bad_ids: | |
1117 | raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0]) |
|
1121 | raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0]) | |
1118 | for j in jobs: |
|
1122 | for j in jobs: | |
1119 | if isinstance(j, AsyncResult): |
|
1123 | if isinstance(j, AsyncResult): | |
1120 | msg_ids.extend(j.msg_ids) |
|
1124 | msg_ids.extend(j.msg_ids) | |
1121 | else: |
|
1125 | else: | |
1122 | msg_ids.append(j) |
|
1126 | msg_ids.append(j) | |
1123 | content = dict(msg_ids=msg_ids) |
|
1127 | content = dict(msg_ids=msg_ids) | |
1124 | for t in targets: |
|
1128 | for t in targets: | |
1125 | self.session.send(self._control_socket, 'abort_request', |
|
1129 | self.session.send(self._control_socket, 'abort_request', | |
1126 | content=content, ident=t) |
|
1130 | content=content, ident=t) | |
1127 | error = False |
|
1131 | error = False | |
1128 | if block: |
|
1132 | if block: | |
1129 | self._flush_ignored_control() |
|
1133 | self._flush_ignored_control() | |
1130 | for i in range(len(targets)): |
|
1134 | for i in range(len(targets)): | |
1131 | idents,msg = self.session.recv(self._control_socket,0) |
|
1135 | idents,msg = self.session.recv(self._control_socket,0) | |
1132 | if self.debug: |
|
1136 | if self.debug: | |
1133 | pprint(msg) |
|
1137 | pprint(msg) | |
1134 | if msg['content']['status'] != 'ok': |
|
1138 | if msg['content']['status'] != 'ok': | |
1135 | error = self._unwrap_exception(msg['content']) |
|
1139 | error = self._unwrap_exception(msg['content']) | |
1136 | else: |
|
1140 | else: | |
1137 | self._ignored_control_replies += len(targets) |
|
1141 | self._ignored_control_replies += len(targets) | |
1138 | if error: |
|
1142 | if error: | |
1139 | raise error |
|
1143 | raise error | |
1140 |
|
1144 | |||
1141 | @spin_first |
|
1145 | @spin_first | |
1142 | def shutdown(self, targets='all', restart=False, hub=False, block=None): |
|
1146 | def shutdown(self, targets='all', restart=False, hub=False, block=None): | |
1143 | """Terminates one or more engine processes, optionally including the hub. |
|
1147 | """Terminates one or more engine processes, optionally including the hub. | |
1144 |
|
1148 | |||
1145 | Parameters |
|
1149 | Parameters | |
1146 | ---------- |
|
1150 | ---------- | |
1147 |
|
1151 | |||
1148 | targets: list of ints or 'all' [default: all] |
|
1152 | targets: list of ints or 'all' [default: all] | |
1149 | Which engines to shutdown. |
|
1153 | Which engines to shutdown. | |
1150 | hub: bool [default: False] |
|
1154 | hub: bool [default: False] | |
1151 | Whether to include the Hub. hub=True implies targets='all'. |
|
1155 | Whether to include the Hub. hub=True implies targets='all'. | |
1152 | block: bool [default: self.block] |
|
1156 | block: bool [default: self.block] | |
1153 | Whether to wait for clean shutdown replies or not. |
|
1157 | Whether to wait for clean shutdown replies or not. | |
1154 | restart: bool [default: False] |
|
1158 | restart: bool [default: False] | |
1155 | NOT IMPLEMENTED |
|
1159 | NOT IMPLEMENTED | |
1156 | whether to restart engines after shutting them down. |
|
1160 | whether to restart engines after shutting them down. | |
1157 | """ |
|
1161 | """ | |
1158 |
|
1162 | |||
1159 | if restart: |
|
1163 | if restart: | |
1160 | raise NotImplementedError("Engine restart is not yet implemented") |
|
1164 | raise NotImplementedError("Engine restart is not yet implemented") | |
1161 |
|
1165 | |||
1162 | block = self.block if block is None else block |
|
1166 | block = self.block if block is None else block | |
1163 | if hub: |
|
1167 | if hub: | |
1164 | targets = 'all' |
|
1168 | targets = 'all' | |
1165 | targets = self._build_targets(targets)[0] |
|
1169 | targets = self._build_targets(targets)[0] | |
1166 | for t in targets: |
|
1170 | for t in targets: | |
1167 | self.session.send(self._control_socket, 'shutdown_request', |
|
1171 | self.session.send(self._control_socket, 'shutdown_request', | |
1168 | content={'restart':restart},ident=t) |
|
1172 | content={'restart':restart},ident=t) | |
1169 | error = False |
|
1173 | error = False | |
1170 | if block or hub: |
|
1174 | if block or hub: | |
1171 | self._flush_ignored_control() |
|
1175 | self._flush_ignored_control() | |
1172 | for i in range(len(targets)): |
|
1176 | for i in range(len(targets)): | |
1173 | idents,msg = self.session.recv(self._control_socket, 0) |
|
1177 | idents,msg = self.session.recv(self._control_socket, 0) | |
1174 | if self.debug: |
|
1178 | if self.debug: | |
1175 | pprint(msg) |
|
1179 | pprint(msg) | |
1176 | if msg['content']['status'] != 'ok': |
|
1180 | if msg['content']['status'] != 'ok': | |
1177 | error = self._unwrap_exception(msg['content']) |
|
1181 | error = self._unwrap_exception(msg['content']) | |
1178 | else: |
|
1182 | else: | |
1179 | self._ignored_control_replies += len(targets) |
|
1183 | self._ignored_control_replies += len(targets) | |
1180 |
|
1184 | |||
1181 | if hub: |
|
1185 | if hub: | |
1182 | time.sleep(0.25) |
|
1186 | time.sleep(0.25) | |
1183 | self.session.send(self._query_socket, 'shutdown_request') |
|
1187 | self.session.send(self._query_socket, 'shutdown_request') | |
1184 | idents,msg = self.session.recv(self._query_socket, 0) |
|
1188 | idents,msg = self.session.recv(self._query_socket, 0) | |
1185 | if self.debug: |
|
1189 | if self.debug: | |
1186 | pprint(msg) |
|
1190 | pprint(msg) | |
1187 | if msg['content']['status'] != 'ok': |
|
1191 | if msg['content']['status'] != 'ok': | |
1188 | error = self._unwrap_exception(msg['content']) |
|
1192 | error = self._unwrap_exception(msg['content']) | |
1189 |
|
1193 | |||
1190 | if error: |
|
1194 | if error: | |
1191 | raise error |
|
1195 | raise error | |
1192 |
|
1196 | |||
1193 | #-------------------------------------------------------------------------- |
|
1197 | #-------------------------------------------------------------------------- | |
1194 | # Execution related methods |
|
1198 | # Execution related methods | |
1195 | #-------------------------------------------------------------------------- |
|
1199 | #-------------------------------------------------------------------------- | |
1196 |
|
1200 | |||
1197 | def _maybe_raise(self, result): |
|
1201 | def _maybe_raise(self, result): | |
1198 | """wrapper for maybe raising an exception if apply failed.""" |
|
1202 | """wrapper for maybe raising an exception if apply failed.""" | |
1199 | if isinstance(result, error.RemoteError): |
|
1203 | if isinstance(result, error.RemoteError): | |
1200 | raise result |
|
1204 | raise result | |
1201 |
|
1205 | |||
1202 | return result |
|
1206 | return result | |
1203 |
|
1207 | |||
1204 |
def send_apply_request(self, socket, f, args=None, kwargs=None, |
|
1208 | def send_apply_request(self, socket, f, args=None, kwargs=None, metadata=None, track=False, | |
1205 | ident=None): |
|
1209 | ident=None): | |
1206 | """construct and send an apply message via a socket. |
|
1210 | """construct and send an apply message via a socket. | |
1207 |
|
1211 | |||
1208 | This is the principal method with which all engine execution is performed by views. |
|
1212 | This is the principal method with which all engine execution is performed by views. | |
1209 | """ |
|
1213 | """ | |
1210 |
|
1214 | |||
1211 | if self._closed: |
|
1215 | if self._closed: | |
1212 | raise RuntimeError("Client cannot be used after its sockets have been closed") |
|
1216 | raise RuntimeError("Client cannot be used after its sockets have been closed") | |
1213 |
|
1217 | |||
1214 | # defaults: |
|
1218 | # defaults: | |
1215 | args = args if args is not None else [] |
|
1219 | args = args if args is not None else [] | |
1216 | kwargs = kwargs if kwargs is not None else {} |
|
1220 | kwargs = kwargs if kwargs is not None else {} | |
1217 |
|
|
1221 | metadata = metadata if metadata is not None else {} | |
1218 |
|
1222 | |||
1219 | # validate arguments |
|
1223 | # validate arguments | |
1220 | if not callable(f) and not isinstance(f, Reference): |
|
1224 | if not callable(f) and not isinstance(f, Reference): | |
1221 | raise TypeError("f must be callable, not %s"%type(f)) |
|
1225 | raise TypeError("f must be callable, not %s"%type(f)) | |
1222 | if not isinstance(args, (tuple, list)): |
|
1226 | if not isinstance(args, (tuple, list)): | |
1223 | raise TypeError("args must be tuple or list, not %s"%type(args)) |
|
1227 | raise TypeError("args must be tuple or list, not %s"%type(args)) | |
1224 | if not isinstance(kwargs, dict): |
|
1228 | if not isinstance(kwargs, dict): | |
1225 | raise TypeError("kwargs must be dict, not %s"%type(kwargs)) |
|
1229 | raise TypeError("kwargs must be dict, not %s"%type(kwargs)) | |
1226 |
if not isinstance( |
|
1230 | if not isinstance(metadata, dict): | |
1227 |
raise TypeError(" |
|
1231 | raise TypeError("metadata must be dict, not %s"%type(metadata)) | |
1228 |
|
1232 | |||
1229 | bufs = util.pack_apply_message(f,args,kwargs) |
|
1233 | bufs = util.pack_apply_message(f,args,kwargs) | |
1230 |
|
1234 | |||
1231 | msg = self.session.send(socket, "apply_request", buffers=bufs, ident=ident, |
|
1235 | msg = self.session.send(socket, "apply_request", buffers=bufs, ident=ident, | |
1232 |
|
|
1236 | metadata=metadata, track=track) | |
1233 |
|
1237 | |||
1234 | msg_id = msg['header']['msg_id'] |
|
1238 | msg_id = msg['header']['msg_id'] | |
1235 | self.outstanding.add(msg_id) |
|
1239 | self.outstanding.add(msg_id) | |
1236 | if ident: |
|
1240 | if ident: | |
1237 | # possibly routed to a specific engine |
|
1241 | # possibly routed to a specific engine | |
1238 | if isinstance(ident, list): |
|
1242 | if isinstance(ident, list): | |
1239 | ident = ident[-1] |
|
1243 | ident = ident[-1] | |
1240 | if ident in self._engines.values(): |
|
1244 | if ident in self._engines.values(): | |
1241 | # save for later, in case of engine death |
|
1245 | # save for later, in case of engine death | |
1242 | self._outstanding_dict[ident].add(msg_id) |
|
1246 | self._outstanding_dict[ident].add(msg_id) | |
1243 | self.history.append(msg_id) |
|
1247 | self.history.append(msg_id) | |
1244 | self.metadata[msg_id]['submitted'] = datetime.now() |
|
1248 | self.metadata[msg_id]['submitted'] = datetime.now() | |
1245 |
|
1249 | |||
1246 | return msg |
|
1250 | return msg | |
1247 |
|
1251 | |||
1248 |
def send_execute_request(self, socket, code, silent=True, |
|
1252 | def send_execute_request(self, socket, code, silent=True, metadata=None, ident=None): | |
1249 | """construct and send an execute request via a socket. |
|
1253 | """construct and send an execute request via a socket. | |
1250 |
|
1254 | |||
1251 | """ |
|
1255 | """ | |
1252 |
|
1256 | |||
1253 | if self._closed: |
|
1257 | if self._closed: | |
1254 | raise RuntimeError("Client cannot be used after its sockets have been closed") |
|
1258 | raise RuntimeError("Client cannot be used after its sockets have been closed") | |
1255 |
|
1259 | |||
1256 | # defaults: |
|
1260 | # defaults: | |
1257 |
|
|
1261 | metadata = metadata if metadata is not None else {} | |
1258 |
|
1262 | |||
1259 | # validate arguments |
|
1263 | # validate arguments | |
1260 | if not isinstance(code, basestring): |
|
1264 | if not isinstance(code, basestring): | |
1261 | raise TypeError("code must be text, not %s" % type(code)) |
|
1265 | raise TypeError("code must be text, not %s" % type(code)) | |
1262 |
if not isinstance( |
|
1266 | if not isinstance(metadata, dict): | |
1263 |
raise TypeError(" |
|
1267 | raise TypeError("metadata must be dict, not %s" % type(metadata)) | |
1264 |
|
1268 | |||
1265 | content = dict(code=code, silent=bool(silent), user_variables=[], user_expressions={}) |
|
1269 | content = dict(code=code, silent=bool(silent), user_variables=[], user_expressions={}) | |
1266 |
|
1270 | |||
1267 |
|
1271 | |||
1268 | msg = self.session.send(socket, "execute_request", content=content, ident=ident, |
|
1272 | msg = self.session.send(socket, "execute_request", content=content, ident=ident, | |
1269 |
|
|
1273 | metadata=metadata) | |
1270 |
|
1274 | |||
1271 | msg_id = msg['header']['msg_id'] |
|
1275 | msg_id = msg['header']['msg_id'] | |
1272 | self.outstanding.add(msg_id) |
|
1276 | self.outstanding.add(msg_id) | |
1273 | if ident: |
|
1277 | if ident: | |
1274 | # possibly routed to a specific engine |
|
1278 | # possibly routed to a specific engine | |
1275 | if isinstance(ident, list): |
|
1279 | if isinstance(ident, list): | |
1276 | ident = ident[-1] |
|
1280 | ident = ident[-1] | |
1277 | if ident in self._engines.values(): |
|
1281 | if ident in self._engines.values(): | |
1278 | # save for later, in case of engine death |
|
1282 | # save for later, in case of engine death | |
1279 | self._outstanding_dict[ident].add(msg_id) |
|
1283 | self._outstanding_dict[ident].add(msg_id) | |
1280 | self.history.append(msg_id) |
|
1284 | self.history.append(msg_id) | |
1281 | self.metadata[msg_id]['submitted'] = datetime.now() |
|
1285 | self.metadata[msg_id]['submitted'] = datetime.now() | |
1282 |
|
1286 | |||
1283 | return msg |
|
1287 | return msg | |
1284 |
|
1288 | |||
1285 | #-------------------------------------------------------------------------- |
|
1289 | #-------------------------------------------------------------------------- | |
1286 | # construct a View object |
|
1290 | # construct a View object | |
1287 | #-------------------------------------------------------------------------- |
|
1291 | #-------------------------------------------------------------------------- | |
1288 |
|
1292 | |||
1289 | def load_balanced_view(self, targets=None): |
|
1293 | def load_balanced_view(self, targets=None): | |
1290 | """construct a DirectView object. |
|
1294 | """construct a DirectView object. | |
1291 |
|
1295 | |||
1292 | If no arguments are specified, create a LoadBalancedView |
|
1296 | If no arguments are specified, create a LoadBalancedView | |
1293 | using all engines. |
|
1297 | using all engines. | |
1294 |
|
1298 | |||
1295 | Parameters |
|
1299 | Parameters | |
1296 | ---------- |
|
1300 | ---------- | |
1297 |
|
1301 | |||
1298 | targets: list,slice,int,etc. [default: use all engines] |
|
1302 | targets: list,slice,int,etc. [default: use all engines] | |
1299 | The subset of engines across which to load-balance |
|
1303 | The subset of engines across which to load-balance | |
1300 | """ |
|
1304 | """ | |
1301 | if targets == 'all': |
|
1305 | if targets == 'all': | |
1302 | targets = None |
|
1306 | targets = None | |
1303 | if targets is not None: |
|
1307 | if targets is not None: | |
1304 | targets = self._build_targets(targets)[1] |
|
1308 | targets = self._build_targets(targets)[1] | |
1305 | return LoadBalancedView(client=self, socket=self._task_socket, targets=targets) |
|
1309 | return LoadBalancedView(client=self, socket=self._task_socket, targets=targets) | |
1306 |
|
1310 | |||
1307 | def direct_view(self, targets='all'): |
|
1311 | def direct_view(self, targets='all'): | |
1308 | """construct a DirectView object. |
|
1312 | """construct a DirectView object. | |
1309 |
|
1313 | |||
1310 | If no targets are specified, create a DirectView using all engines. |
|
1314 | If no targets are specified, create a DirectView using all engines. | |
1311 |
|
1315 | |||
1312 | rc.direct_view('all') is distinguished from rc[:] in that 'all' will |
|
1316 | rc.direct_view('all') is distinguished from rc[:] in that 'all' will | |
1313 | evaluate the target engines at each execution, whereas rc[:] will connect to |
|
1317 | evaluate the target engines at each execution, whereas rc[:] will connect to | |
1314 | all *current* engines, and that list will not change. |
|
1318 | all *current* engines, and that list will not change. | |
1315 |
|
1319 | |||
1316 | That is, 'all' will always use all engines, whereas rc[:] will not use |
|
1320 | That is, 'all' will always use all engines, whereas rc[:] will not use | |
1317 | engines added after the DirectView is constructed. |
|
1321 | engines added after the DirectView is constructed. | |
1318 |
|
1322 | |||
1319 | Parameters |
|
1323 | Parameters | |
1320 | ---------- |
|
1324 | ---------- | |
1321 |
|
1325 | |||
1322 | targets: list,slice,int,etc. [default: use all engines] |
|
1326 | targets: list,slice,int,etc. [default: use all engines] | |
1323 | The engines to use for the View |
|
1327 | The engines to use for the View | |
1324 | """ |
|
1328 | """ | |
1325 | single = isinstance(targets, int) |
|
1329 | single = isinstance(targets, int) | |
1326 | # allow 'all' to be lazily evaluated at each execution |
|
1330 | # allow 'all' to be lazily evaluated at each execution | |
1327 | if targets != 'all': |
|
1331 | if targets != 'all': | |
1328 | targets = self._build_targets(targets)[1] |
|
1332 | targets = self._build_targets(targets)[1] | |
1329 | if single: |
|
1333 | if single: | |
1330 | targets = targets[0] |
|
1334 | targets = targets[0] | |
1331 | return DirectView(client=self, socket=self._mux_socket, targets=targets) |
|
1335 | return DirectView(client=self, socket=self._mux_socket, targets=targets) | |
1332 |
|
1336 | |||
1333 | #-------------------------------------------------------------------------- |
|
1337 | #-------------------------------------------------------------------------- | |
1334 | # Query methods |
|
1338 | # Query methods | |
1335 | #-------------------------------------------------------------------------- |
|
1339 | #-------------------------------------------------------------------------- | |
1336 |
|
1340 | |||
1337 | @spin_first |
|
1341 | @spin_first | |
1338 | def get_result(self, indices_or_msg_ids=None, block=None): |
|
1342 | def get_result(self, indices_or_msg_ids=None, block=None): | |
1339 | """Retrieve a result by msg_id or history index, wrapped in an AsyncResult object. |
|
1343 | """Retrieve a result by msg_id or history index, wrapped in an AsyncResult object. | |
1340 |
|
1344 | |||
1341 | If the client already has the results, no request to the Hub will be made. |
|
1345 | If the client already has the results, no request to the Hub will be made. | |
1342 |
|
1346 | |||
1343 | This is a convenient way to construct AsyncResult objects, which are wrappers |
|
1347 | This is a convenient way to construct AsyncResult objects, which are wrappers | |
1344 | that include metadata about execution, and allow for awaiting results that |
|
1348 | that include metadata about execution, and allow for awaiting results that | |
1345 | were not submitted by this Client. |
|
1349 | were not submitted by this Client. | |
1346 |
|
1350 | |||
1347 | It can also be a convenient way to retrieve the metadata associated with |
|
1351 | It can also be a convenient way to retrieve the metadata associated with | |
1348 | blocking execution, since it always retrieves |
|
1352 | blocking execution, since it always retrieves | |
1349 |
|
1353 | |||
1350 | Examples |
|
1354 | Examples | |
1351 | -------- |
|
1355 | -------- | |
1352 | :: |
|
1356 | :: | |
1353 |
|
1357 | |||
1354 | In [10]: r = client.apply() |
|
1358 | In [10]: r = client.apply() | |
1355 |
|
1359 | |||
1356 | Parameters |
|
1360 | Parameters | |
1357 | ---------- |
|
1361 | ---------- | |
1358 |
|
1362 | |||
1359 | indices_or_msg_ids : integer history index, str msg_id, or list of either |
|
1363 | indices_or_msg_ids : integer history index, str msg_id, or list of either | |
1360 | The indices or msg_ids of indices to be retrieved |
|
1364 | The indices or msg_ids of indices to be retrieved | |
1361 |
|
1365 | |||
1362 | block : bool |
|
1366 | block : bool | |
1363 | Whether to wait for the result to be done |
|
1367 | Whether to wait for the result to be done | |
1364 |
|
1368 | |||
1365 | Returns |
|
1369 | Returns | |
1366 | ------- |
|
1370 | ------- | |
1367 |
|
1371 | |||
1368 | AsyncResult |
|
1372 | AsyncResult | |
1369 | A single AsyncResult object will always be returned. |
|
1373 | A single AsyncResult object will always be returned. | |
1370 |
|
1374 | |||
1371 | AsyncHubResult |
|
1375 | AsyncHubResult | |
1372 | A subclass of AsyncResult that retrieves results from the Hub |
|
1376 | A subclass of AsyncResult that retrieves results from the Hub | |
1373 |
|
1377 | |||
1374 | """ |
|
1378 | """ | |
1375 | block = self.block if block is None else block |
|
1379 | block = self.block if block is None else block | |
1376 | if indices_or_msg_ids is None: |
|
1380 | if indices_or_msg_ids is None: | |
1377 | indices_or_msg_ids = -1 |
|
1381 | indices_or_msg_ids = -1 | |
1378 |
|
1382 | |||
1379 | if not isinstance(indices_or_msg_ids, (list,tuple)): |
|
1383 | if not isinstance(indices_or_msg_ids, (list,tuple)): | |
1380 | indices_or_msg_ids = [indices_or_msg_ids] |
|
1384 | indices_or_msg_ids = [indices_or_msg_ids] | |
1381 |
|
1385 | |||
1382 | theids = [] |
|
1386 | theids = [] | |
1383 | for id in indices_or_msg_ids: |
|
1387 | for id in indices_or_msg_ids: | |
1384 | if isinstance(id, int): |
|
1388 | if isinstance(id, int): | |
1385 | id = self.history[id] |
|
1389 | id = self.history[id] | |
1386 | if not isinstance(id, basestring): |
|
1390 | if not isinstance(id, basestring): | |
1387 | raise TypeError("indices must be str or int, not %r"%id) |
|
1391 | raise TypeError("indices must be str or int, not %r"%id) | |
1388 | theids.append(id) |
|
1392 | theids.append(id) | |
1389 |
|
1393 | |||
1390 | local_ids = filter(lambda msg_id: msg_id in self.history or msg_id in self.results, theids) |
|
1394 | local_ids = filter(lambda msg_id: msg_id in self.history or msg_id in self.results, theids) | |
1391 | remote_ids = filter(lambda msg_id: msg_id not in local_ids, theids) |
|
1395 | remote_ids = filter(lambda msg_id: msg_id not in local_ids, theids) | |
1392 |
|
1396 | |||
1393 | if remote_ids: |
|
1397 | if remote_ids: | |
1394 | ar = AsyncHubResult(self, msg_ids=theids) |
|
1398 | ar = AsyncHubResult(self, msg_ids=theids) | |
1395 | else: |
|
1399 | else: | |
1396 | ar = AsyncResult(self, msg_ids=theids) |
|
1400 | ar = AsyncResult(self, msg_ids=theids) | |
1397 |
|
1401 | |||
1398 | if block: |
|
1402 | if block: | |
1399 | ar.wait() |
|
1403 | ar.wait() | |
1400 |
|
1404 | |||
1401 | return ar |
|
1405 | return ar | |
1402 |
|
1406 | |||
1403 | @spin_first |
|
1407 | @spin_first | |
1404 |
def resubmit(self, indices_or_msg_ids=None, |
|
1408 | def resubmit(self, indices_or_msg_ids=None, metadata=None, block=None): | |
1405 | """Resubmit one or more tasks. |
|
1409 | """Resubmit one or more tasks. | |
1406 |
|
1410 | |||
1407 | in-flight tasks may not be resubmitted. |
|
1411 | in-flight tasks may not be resubmitted. | |
1408 |
|
1412 | |||
1409 | Parameters |
|
1413 | Parameters | |
1410 | ---------- |
|
1414 | ---------- | |
1411 |
|
1415 | |||
1412 | indices_or_msg_ids : integer history index, str msg_id, or list of either |
|
1416 | indices_or_msg_ids : integer history index, str msg_id, or list of either | |
1413 | The indices or msg_ids of indices to be retrieved |
|
1417 | The indices or msg_ids of indices to be retrieved | |
1414 |
|
1418 | |||
1415 | block : bool |
|
1419 | block : bool | |
1416 | Whether to wait for the result to be done |
|
1420 | Whether to wait for the result to be done | |
1417 |
|
1421 | |||
1418 | Returns |
|
1422 | Returns | |
1419 | ------- |
|
1423 | ------- | |
1420 |
|
1424 | |||
1421 | AsyncHubResult |
|
1425 | AsyncHubResult | |
1422 | A subclass of AsyncResult that retrieves results from the Hub |
|
1426 | A subclass of AsyncResult that retrieves results from the Hub | |
1423 |
|
1427 | |||
1424 | """ |
|
1428 | """ | |
1425 | block = self.block if block is None else block |
|
1429 | block = self.block if block is None else block | |
1426 | if indices_or_msg_ids is None: |
|
1430 | if indices_or_msg_ids is None: | |
1427 | indices_or_msg_ids = -1 |
|
1431 | indices_or_msg_ids = -1 | |
1428 |
|
1432 | |||
1429 | if not isinstance(indices_or_msg_ids, (list,tuple)): |
|
1433 | if not isinstance(indices_or_msg_ids, (list,tuple)): | |
1430 | indices_or_msg_ids = [indices_or_msg_ids] |
|
1434 | indices_or_msg_ids = [indices_or_msg_ids] | |
1431 |
|
1435 | |||
1432 | theids = [] |
|
1436 | theids = [] | |
1433 | for id in indices_or_msg_ids: |
|
1437 | for id in indices_or_msg_ids: | |
1434 | if isinstance(id, int): |
|
1438 | if isinstance(id, int): | |
1435 | id = self.history[id] |
|
1439 | id = self.history[id] | |
1436 | if not isinstance(id, basestring): |
|
1440 | if not isinstance(id, basestring): | |
1437 | raise TypeError("indices must be str or int, not %r"%id) |
|
1441 | raise TypeError("indices must be str or int, not %r"%id) | |
1438 | theids.append(id) |
|
1442 | theids.append(id) | |
1439 |
|
1443 | |||
1440 | content = dict(msg_ids = theids) |
|
1444 | content = dict(msg_ids = theids) | |
1441 |
|
1445 | |||
1442 | self.session.send(self._query_socket, 'resubmit_request', content) |
|
1446 | self.session.send(self._query_socket, 'resubmit_request', content) | |
1443 |
|
1447 | |||
1444 | zmq.select([self._query_socket], [], []) |
|
1448 | zmq.select([self._query_socket], [], []) | |
1445 | idents,msg = self.session.recv(self._query_socket, zmq.NOBLOCK) |
|
1449 | idents,msg = self.session.recv(self._query_socket, zmq.NOBLOCK) | |
1446 | if self.debug: |
|
1450 | if self.debug: | |
1447 | pprint(msg) |
|
1451 | pprint(msg) | |
1448 | content = msg['content'] |
|
1452 | content = msg['content'] | |
1449 | if content['status'] != 'ok': |
|
1453 | if content['status'] != 'ok': | |
1450 | raise self._unwrap_exception(content) |
|
1454 | raise self._unwrap_exception(content) | |
1451 | mapping = content['resubmitted'] |
|
1455 | mapping = content['resubmitted'] | |
1452 | new_ids = [ mapping[msg_id] for msg_id in theids ] |
|
1456 | new_ids = [ mapping[msg_id] for msg_id in theids ] | |
1453 |
|
1457 | |||
1454 | ar = AsyncHubResult(self, msg_ids=new_ids) |
|
1458 | ar = AsyncHubResult(self, msg_ids=new_ids) | |
1455 |
|
1459 | |||
1456 | if block: |
|
1460 | if block: | |
1457 | ar.wait() |
|
1461 | ar.wait() | |
1458 |
|
1462 | |||
1459 | return ar |
|
1463 | return ar | |
1460 |
|
1464 | |||
1461 | @spin_first |
|
1465 | @spin_first | |
1462 | def result_status(self, msg_ids, status_only=True): |
|
1466 | def result_status(self, msg_ids, status_only=True): | |
1463 | """Check on the status of the result(s) of the apply request with `msg_ids`. |
|
1467 | """Check on the status of the result(s) of the apply request with `msg_ids`. | |
1464 |
|
1468 | |||
1465 | If status_only is False, then the actual results will be retrieved, else |
|
1469 | If status_only is False, then the actual results will be retrieved, else | |
1466 | only the status of the results will be checked. |
|
1470 | only the status of the results will be checked. | |
1467 |
|
1471 | |||
1468 | Parameters |
|
1472 | Parameters | |
1469 | ---------- |
|
1473 | ---------- | |
1470 |
|
1474 | |||
1471 | msg_ids : list of msg_ids |
|
1475 | msg_ids : list of msg_ids | |
1472 | if int: |
|
1476 | if int: | |
1473 | Passed as index to self.history for convenience. |
|
1477 | Passed as index to self.history for convenience. | |
1474 | status_only : bool (default: True) |
|
1478 | status_only : bool (default: True) | |
1475 | if False: |
|
1479 | if False: | |
1476 | Retrieve the actual results of completed tasks. |
|
1480 | Retrieve the actual results of completed tasks. | |
1477 |
|
1481 | |||
1478 | Returns |
|
1482 | Returns | |
1479 | ------- |
|
1483 | ------- | |
1480 |
|
1484 | |||
1481 | results : dict |
|
1485 | results : dict | |
1482 | There will always be the keys 'pending' and 'completed', which will |
|
1486 | There will always be the keys 'pending' and 'completed', which will | |
1483 | be lists of msg_ids that are incomplete or complete. If `status_only` |
|
1487 | be lists of msg_ids that are incomplete or complete. If `status_only` | |
1484 | is False, then completed results will be keyed by their `msg_id`. |
|
1488 | is False, then completed results will be keyed by their `msg_id`. | |
1485 | """ |
|
1489 | """ | |
1486 | if not isinstance(msg_ids, (list,tuple)): |
|
1490 | if not isinstance(msg_ids, (list,tuple)): | |
1487 | msg_ids = [msg_ids] |
|
1491 | msg_ids = [msg_ids] | |
1488 |
|
1492 | |||
1489 | theids = [] |
|
1493 | theids = [] | |
1490 | for msg_id in msg_ids: |
|
1494 | for msg_id in msg_ids: | |
1491 | if isinstance(msg_id, int): |
|
1495 | if isinstance(msg_id, int): | |
1492 | msg_id = self.history[msg_id] |
|
1496 | msg_id = self.history[msg_id] | |
1493 | if not isinstance(msg_id, basestring): |
|
1497 | if not isinstance(msg_id, basestring): | |
1494 | raise TypeError("msg_ids must be str, not %r"%msg_id) |
|
1498 | raise TypeError("msg_ids must be str, not %r"%msg_id) | |
1495 | theids.append(msg_id) |
|
1499 | theids.append(msg_id) | |
1496 |
|
1500 | |||
1497 | completed = [] |
|
1501 | completed = [] | |
1498 | local_results = {} |
|
1502 | local_results = {} | |
1499 |
|
1503 | |||
1500 | # comment this block out to temporarily disable local shortcut: |
|
1504 | # comment this block out to temporarily disable local shortcut: | |
1501 | for msg_id in theids: |
|
1505 | for msg_id in theids: | |
1502 | if msg_id in self.results: |
|
1506 | if msg_id in self.results: | |
1503 | completed.append(msg_id) |
|
1507 | completed.append(msg_id) | |
1504 | local_results[msg_id] = self.results[msg_id] |
|
1508 | local_results[msg_id] = self.results[msg_id] | |
1505 | theids.remove(msg_id) |
|
1509 | theids.remove(msg_id) | |
1506 |
|
1510 | |||
1507 | if theids: # some not locally cached |
|
1511 | if theids: # some not locally cached | |
1508 | content = dict(msg_ids=theids, status_only=status_only) |
|
1512 | content = dict(msg_ids=theids, status_only=status_only) | |
1509 | msg = self.session.send(self._query_socket, "result_request", content=content) |
|
1513 | msg = self.session.send(self._query_socket, "result_request", content=content) | |
1510 | zmq.select([self._query_socket], [], []) |
|
1514 | zmq.select([self._query_socket], [], []) | |
1511 | idents,msg = self.session.recv(self._query_socket, zmq.NOBLOCK) |
|
1515 | idents,msg = self.session.recv(self._query_socket, zmq.NOBLOCK) | |
1512 | if self.debug: |
|
1516 | if self.debug: | |
1513 | pprint(msg) |
|
1517 | pprint(msg) | |
1514 | content = msg['content'] |
|
1518 | content = msg['content'] | |
1515 | if content['status'] != 'ok': |
|
1519 | if content['status'] != 'ok': | |
1516 | raise self._unwrap_exception(content) |
|
1520 | raise self._unwrap_exception(content) | |
1517 | buffers = msg['buffers'] |
|
1521 | buffers = msg['buffers'] | |
1518 | else: |
|
1522 | else: | |
1519 | content = dict(completed=[],pending=[]) |
|
1523 | content = dict(completed=[],pending=[]) | |
1520 |
|
1524 | |||
1521 | content['completed'].extend(completed) |
|
1525 | content['completed'].extend(completed) | |
1522 |
|
1526 | |||
1523 | if status_only: |
|
1527 | if status_only: | |
1524 | return content |
|
1528 | return content | |
1525 |
|
1529 | |||
1526 | failures = [] |
|
1530 | failures = [] | |
1527 | # load cached results into result: |
|
1531 | # load cached results into result: | |
1528 | content.update(local_results) |
|
1532 | content.update(local_results) | |
1529 |
|
1533 | |||
1530 | # update cache with results: |
|
1534 | # update cache with results: | |
1531 | for msg_id in sorted(theids): |
|
1535 | for msg_id in sorted(theids): | |
1532 | if msg_id in content['completed']: |
|
1536 | if msg_id in content['completed']: | |
1533 | rec = content[msg_id] |
|
1537 | rec = content[msg_id] | |
1534 | parent = rec['header'] |
|
1538 | parent = rec['header'] | |
1535 | header = rec['result_header'] |
|
1539 | header = rec['result_header'] | |
1536 | rcontent = rec['result_content'] |
|
1540 | rcontent = rec['result_content'] | |
1537 | iodict = rec['io'] |
|
1541 | iodict = rec['io'] | |
1538 | if isinstance(rcontent, str): |
|
1542 | if isinstance(rcontent, str): | |
1539 | rcontent = self.session.unpack(rcontent) |
|
1543 | rcontent = self.session.unpack(rcontent) | |
1540 |
|
1544 | |||
1541 | md = self.metadata[msg_id] |
|
1545 | md = self.metadata[msg_id] | |
1542 | md.update(self._extract_metadata(header, parent, rcontent)) |
|
1546 | md_msg = dict( | |
|
1547 | content=rcontent, | |||
|
1548 | parent_header=parent, | |||
|
1549 | header=header, | |||
|
1550 | metadata=rec['result_metadata'], | |||
|
1551 | ) | |||
|
1552 | md.update(self._extract_metadata(md_msg)) | |||
1543 | if rec.get('received'): |
|
1553 | if rec.get('received'): | |
1544 | md['received'] = rec['received'] |
|
1554 | md['received'] = rec['received'] | |
1545 | md.update(iodict) |
|
1555 | md.update(iodict) | |
1546 |
|
1556 | |||
1547 | if rcontent['status'] == 'ok': |
|
1557 | if rcontent['status'] == 'ok': | |
1548 | if header['msg_type'] == 'apply_reply': |
|
1558 | if header['msg_type'] == 'apply_reply': | |
1549 | res,buffers = util.unserialize_object(buffers) |
|
1559 | res,buffers = util.unserialize_object(buffers) | |
1550 | elif header['msg_type'] == 'execute_reply': |
|
1560 | elif header['msg_type'] == 'execute_reply': | |
1551 | res = ExecuteReply(msg_id, rcontent, md) |
|
1561 | res = ExecuteReply(msg_id, rcontent, md) | |
1552 | else: |
|
1562 | else: | |
1553 | raise KeyError("unhandled msg type: %r" % header[msg_type]) |
|
1563 | raise KeyError("unhandled msg type: %r" % header[msg_type]) | |
1554 | else: |
|
1564 | else: | |
1555 | res = self._unwrap_exception(rcontent) |
|
1565 | res = self._unwrap_exception(rcontent) | |
1556 | failures.append(res) |
|
1566 | failures.append(res) | |
1557 |
|
1567 | |||
1558 | self.results[msg_id] = res |
|
1568 | self.results[msg_id] = res | |
1559 | content[msg_id] = res |
|
1569 | content[msg_id] = res | |
1560 |
|
1570 | |||
1561 | if len(theids) == 1 and failures: |
|
1571 | if len(theids) == 1 and failures: | |
1562 | raise failures[0] |
|
1572 | raise failures[0] | |
1563 |
|
1573 | |||
1564 | error.collect_exceptions(failures, "result_status") |
|
1574 | error.collect_exceptions(failures, "result_status") | |
1565 | return content |
|
1575 | return content | |
1566 |
|
1576 | |||
1567 | @spin_first |
|
1577 | @spin_first | |
1568 | def queue_status(self, targets='all', verbose=False): |
|
1578 | def queue_status(self, targets='all', verbose=False): | |
1569 | """Fetch the status of engine queues. |
|
1579 | """Fetch the status of engine queues. | |
1570 |
|
1580 | |||
1571 | Parameters |
|
1581 | Parameters | |
1572 | ---------- |
|
1582 | ---------- | |
1573 |
|
1583 | |||
1574 | targets : int/str/list of ints/strs |
|
1584 | targets : int/str/list of ints/strs | |
1575 | the engines whose states are to be queried. |
|
1585 | the engines whose states are to be queried. | |
1576 | default : all |
|
1586 | default : all | |
1577 | verbose : bool |
|
1587 | verbose : bool | |
1578 | Whether to return lengths only, or lists of ids for each element |
|
1588 | Whether to return lengths only, or lists of ids for each element | |
1579 | """ |
|
1589 | """ | |
1580 | if targets == 'all': |
|
1590 | if targets == 'all': | |
1581 | # allow 'all' to be evaluated on the engine |
|
1591 | # allow 'all' to be evaluated on the engine | |
1582 | engine_ids = None |
|
1592 | engine_ids = None | |
1583 | else: |
|
1593 | else: | |
1584 | engine_ids = self._build_targets(targets)[1] |
|
1594 | engine_ids = self._build_targets(targets)[1] | |
1585 | content = dict(targets=engine_ids, verbose=verbose) |
|
1595 | content = dict(targets=engine_ids, verbose=verbose) | |
1586 | self.session.send(self._query_socket, "queue_request", content=content) |
|
1596 | self.session.send(self._query_socket, "queue_request", content=content) | |
1587 | idents,msg = self.session.recv(self._query_socket, 0) |
|
1597 | idents,msg = self.session.recv(self._query_socket, 0) | |
1588 | if self.debug: |
|
1598 | if self.debug: | |
1589 | pprint(msg) |
|
1599 | pprint(msg) | |
1590 | content = msg['content'] |
|
1600 | content = msg['content'] | |
1591 | status = content.pop('status') |
|
1601 | status = content.pop('status') | |
1592 | if status != 'ok': |
|
1602 | if status != 'ok': | |
1593 | raise self._unwrap_exception(content) |
|
1603 | raise self._unwrap_exception(content) | |
1594 | content = rekey(content) |
|
1604 | content = rekey(content) | |
1595 | if isinstance(targets, int): |
|
1605 | if isinstance(targets, int): | |
1596 | return content[targets] |
|
1606 | return content[targets] | |
1597 | else: |
|
1607 | else: | |
1598 | return content |
|
1608 | return content | |
1599 |
|
1609 | |||
1600 | @spin_first |
|
1610 | @spin_first | |
1601 | def purge_results(self, jobs=[], targets=[]): |
|
1611 | def purge_results(self, jobs=[], targets=[]): | |
1602 | """Tell the Hub to forget results. |
|
1612 | """Tell the Hub to forget results. | |
1603 |
|
1613 | |||
1604 | Individual results can be purged by msg_id, or the entire |
|
1614 | Individual results can be purged by msg_id, or the entire | |
1605 | history of specific targets can be purged. |
|
1615 | history of specific targets can be purged. | |
1606 |
|
1616 | |||
1607 | Use `purge_results('all')` to scrub everything from the Hub's db. |
|
1617 | Use `purge_results('all')` to scrub everything from the Hub's db. | |
1608 |
|
1618 | |||
1609 | Parameters |
|
1619 | Parameters | |
1610 | ---------- |
|
1620 | ---------- | |
1611 |
|
1621 | |||
1612 | jobs : str or list of str or AsyncResult objects |
|
1622 | jobs : str or list of str or AsyncResult objects | |
1613 | the msg_ids whose results should be forgotten. |
|
1623 | the msg_ids whose results should be forgotten. | |
1614 | targets : int/str/list of ints/strs |
|
1624 | targets : int/str/list of ints/strs | |
1615 | The targets, by int_id, whose entire history is to be purged. |
|
1625 | The targets, by int_id, whose entire history is to be purged. | |
1616 |
|
1626 | |||
1617 | default : None |
|
1627 | default : None | |
1618 | """ |
|
1628 | """ | |
1619 | if not targets and not jobs: |
|
1629 | if not targets and not jobs: | |
1620 | raise ValueError("Must specify at least one of `targets` and `jobs`") |
|
1630 | raise ValueError("Must specify at least one of `targets` and `jobs`") | |
1621 | if targets: |
|
1631 | if targets: | |
1622 | targets = self._build_targets(targets)[1] |
|
1632 | targets = self._build_targets(targets)[1] | |
1623 |
|
1633 | |||
1624 | # construct msg_ids from jobs |
|
1634 | # construct msg_ids from jobs | |
1625 | if jobs == 'all': |
|
1635 | if jobs == 'all': | |
1626 | msg_ids = jobs |
|
1636 | msg_ids = jobs | |
1627 | else: |
|
1637 | else: | |
1628 | msg_ids = [] |
|
1638 | msg_ids = [] | |
1629 | if isinstance(jobs, (basestring,AsyncResult)): |
|
1639 | if isinstance(jobs, (basestring,AsyncResult)): | |
1630 | jobs = [jobs] |
|
1640 | jobs = [jobs] | |
1631 | bad_ids = filter(lambda obj: not isinstance(obj, (basestring, AsyncResult)), jobs) |
|
1641 | bad_ids = filter(lambda obj: not isinstance(obj, (basestring, AsyncResult)), jobs) | |
1632 | if bad_ids: |
|
1642 | if bad_ids: | |
1633 | raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0]) |
|
1643 | raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0]) | |
1634 | for j in jobs: |
|
1644 | for j in jobs: | |
1635 | if isinstance(j, AsyncResult): |
|
1645 | if isinstance(j, AsyncResult): | |
1636 | msg_ids.extend(j.msg_ids) |
|
1646 | msg_ids.extend(j.msg_ids) | |
1637 | else: |
|
1647 | else: | |
1638 | msg_ids.append(j) |
|
1648 | msg_ids.append(j) | |
1639 |
|
1649 | |||
1640 | content = dict(engine_ids=targets, msg_ids=msg_ids) |
|
1650 | content = dict(engine_ids=targets, msg_ids=msg_ids) | |
1641 | self.session.send(self._query_socket, "purge_request", content=content) |
|
1651 | self.session.send(self._query_socket, "purge_request", content=content) | |
1642 | idents, msg = self.session.recv(self._query_socket, 0) |
|
1652 | idents, msg = self.session.recv(self._query_socket, 0) | |
1643 | if self.debug: |
|
1653 | if self.debug: | |
1644 | pprint(msg) |
|
1654 | pprint(msg) | |
1645 | content = msg['content'] |
|
1655 | content = msg['content'] | |
1646 | if content['status'] != 'ok': |
|
1656 | if content['status'] != 'ok': | |
1647 | raise self._unwrap_exception(content) |
|
1657 | raise self._unwrap_exception(content) | |
1648 |
|
1658 | |||
1649 | @spin_first |
|
1659 | @spin_first | |
1650 | def hub_history(self): |
|
1660 | def hub_history(self): | |
1651 | """Get the Hub's history |
|
1661 | """Get the Hub's history | |
1652 |
|
1662 | |||
1653 | Just like the Client, the Hub has a history, which is a list of msg_ids. |
|
1663 | Just like the Client, the Hub has a history, which is a list of msg_ids. | |
1654 | This will contain the history of all clients, and, depending on configuration, |
|
1664 | This will contain the history of all clients, and, depending on configuration, | |
1655 | may contain history across multiple cluster sessions. |
|
1665 | may contain history across multiple cluster sessions. | |
1656 |
|
1666 | |||
1657 | Any msg_id returned here is a valid argument to `get_result`. |
|
1667 | Any msg_id returned here is a valid argument to `get_result`. | |
1658 |
|
1668 | |||
1659 | Returns |
|
1669 | Returns | |
1660 | ------- |
|
1670 | ------- | |
1661 |
|
1671 | |||
1662 | msg_ids : list of strs |
|
1672 | msg_ids : list of strs | |
1663 | list of all msg_ids, ordered by task submission time. |
|
1673 | list of all msg_ids, ordered by task submission time. | |
1664 | """ |
|
1674 | """ | |
1665 |
|
1675 | |||
1666 | self.session.send(self._query_socket, "history_request", content={}) |
|
1676 | self.session.send(self._query_socket, "history_request", content={}) | |
1667 | idents, msg = self.session.recv(self._query_socket, 0) |
|
1677 | idents, msg = self.session.recv(self._query_socket, 0) | |
1668 |
|
1678 | |||
1669 | if self.debug: |
|
1679 | if self.debug: | |
1670 | pprint(msg) |
|
1680 | pprint(msg) | |
1671 | content = msg['content'] |
|
1681 | content = msg['content'] | |
1672 | if content['status'] != 'ok': |
|
1682 | if content['status'] != 'ok': | |
1673 | raise self._unwrap_exception(content) |
|
1683 | raise self._unwrap_exception(content) | |
1674 | else: |
|
1684 | else: | |
1675 | return content['history'] |
|
1685 | return content['history'] | |
1676 |
|
1686 | |||
1677 | @spin_first |
|
1687 | @spin_first | |
1678 | def db_query(self, query, keys=None): |
|
1688 | def db_query(self, query, keys=None): | |
1679 | """Query the Hub's TaskRecord database |
|
1689 | """Query the Hub's TaskRecord database | |
1680 |
|
1690 | |||
1681 | This will return a list of task record dicts that match `query` |
|
1691 | This will return a list of task record dicts that match `query` | |
1682 |
|
1692 | |||
1683 | Parameters |
|
1693 | Parameters | |
1684 | ---------- |
|
1694 | ---------- | |
1685 |
|
1695 | |||
1686 | query : mongodb query dict |
|
1696 | query : mongodb query dict | |
1687 | The search dict. See mongodb query docs for details. |
|
1697 | The search dict. See mongodb query docs for details. | |
1688 | keys : list of strs [optional] |
|
1698 | keys : list of strs [optional] | |
1689 | The subset of keys to be returned. The default is to fetch everything but buffers. |
|
1699 | The subset of keys to be returned. The default is to fetch everything but buffers. | |
1690 | 'msg_id' will *always* be included. |
|
1700 | 'msg_id' will *always* be included. | |
1691 | """ |
|
1701 | """ | |
1692 | if isinstance(keys, basestring): |
|
1702 | if isinstance(keys, basestring): | |
1693 | keys = [keys] |
|
1703 | keys = [keys] | |
1694 | content = dict(query=query, keys=keys) |
|
1704 | content = dict(query=query, keys=keys) | |
1695 | self.session.send(self._query_socket, "db_request", content=content) |
|
1705 | self.session.send(self._query_socket, "db_request", content=content) | |
1696 | idents, msg = self.session.recv(self._query_socket, 0) |
|
1706 | idents, msg = self.session.recv(self._query_socket, 0) | |
1697 | if self.debug: |
|
1707 | if self.debug: | |
1698 | pprint(msg) |
|
1708 | pprint(msg) | |
1699 | content = msg['content'] |
|
1709 | content = msg['content'] | |
1700 | if content['status'] != 'ok': |
|
1710 | if content['status'] != 'ok': | |
1701 | raise self._unwrap_exception(content) |
|
1711 | raise self._unwrap_exception(content) | |
1702 |
|
1712 | |||
1703 | records = content['records'] |
|
1713 | records = content['records'] | |
1704 |
|
1714 | |||
1705 | buffer_lens = content['buffer_lens'] |
|
1715 | buffer_lens = content['buffer_lens'] | |
1706 | result_buffer_lens = content['result_buffer_lens'] |
|
1716 | result_buffer_lens = content['result_buffer_lens'] | |
1707 | buffers = msg['buffers'] |
|
1717 | buffers = msg['buffers'] | |
1708 | has_bufs = buffer_lens is not None |
|
1718 | has_bufs = buffer_lens is not None | |
1709 | has_rbufs = result_buffer_lens is not None |
|
1719 | has_rbufs = result_buffer_lens is not None | |
1710 | for i,rec in enumerate(records): |
|
1720 | for i,rec in enumerate(records): | |
1711 | # relink buffers |
|
1721 | # relink buffers | |
1712 | if has_bufs: |
|
1722 | if has_bufs: | |
1713 | blen = buffer_lens[i] |
|
1723 | blen = buffer_lens[i] | |
1714 | rec['buffers'], buffers = buffers[:blen],buffers[blen:] |
|
1724 | rec['buffers'], buffers = buffers[:blen],buffers[blen:] | |
1715 | if has_rbufs: |
|
1725 | if has_rbufs: | |
1716 | blen = result_buffer_lens[i] |
|
1726 | blen = result_buffer_lens[i] | |
1717 | rec['result_buffers'], buffers = buffers[:blen],buffers[blen:] |
|
1727 | rec['result_buffers'], buffers = buffers[:blen],buffers[blen:] | |
1718 |
|
1728 | |||
1719 | return records |
|
1729 | return records | |
1720 |
|
1730 | |||
1721 | __all__ = [ 'Client' ] |
|
1731 | __all__ = [ 'Client' ] |
@@ -1,1103 +1,1103 b'' | |||||
1 | """Views of remote engines. |
|
1 | """Views of remote engines. | |
2 |
|
2 | |||
3 | Authors: |
|
3 | Authors: | |
4 |
|
4 | |||
5 | * Min RK |
|
5 | * Min RK | |
6 | """ |
|
6 | """ | |
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2010-2011 The IPython Development Team |
|
8 | # Copyright (C) 2010-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 | import imp |
|
18 | import imp | |
19 | import sys |
|
19 | import sys | |
20 | import warnings |
|
20 | import warnings | |
21 | from contextlib import contextmanager |
|
21 | from contextlib import contextmanager | |
22 | from types import ModuleType |
|
22 | from types import ModuleType | |
23 |
|
23 | |||
24 | import zmq |
|
24 | import zmq | |
25 |
|
25 | |||
26 | from IPython.testing.skipdoctest import skip_doctest |
|
26 | from IPython.testing.skipdoctest import skip_doctest | |
27 | from IPython.utils.traitlets import ( |
|
27 | from IPython.utils.traitlets import ( | |
28 | HasTraits, Any, Bool, List, Dict, Set, Instance, CFloat, Integer |
|
28 | HasTraits, Any, Bool, List, Dict, Set, Instance, CFloat, Integer | |
29 | ) |
|
29 | ) | |
30 | from IPython.external.decorator import decorator |
|
30 | from IPython.external.decorator import decorator | |
31 |
|
31 | |||
32 | from IPython.parallel import util |
|
32 | from IPython.parallel import util | |
33 | from IPython.parallel.controller.dependency import Dependency, dependent |
|
33 | from IPython.parallel.controller.dependency import Dependency, dependent | |
34 |
|
34 | |||
35 | from . import map as Map |
|
35 | from . import map as Map | |
36 | from .asyncresult import AsyncResult, AsyncMapResult |
|
36 | from .asyncresult import AsyncResult, AsyncMapResult | |
37 | from .remotefunction import ParallelFunction, parallel, remote, getname |
|
37 | from .remotefunction import ParallelFunction, parallel, remote, getname | |
38 |
|
38 | |||
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 | # Decorators |
|
40 | # Decorators | |
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 |
|
42 | |||
43 | @decorator |
|
43 | @decorator | |
44 | def save_ids(f, self, *args, **kwargs): |
|
44 | def save_ids(f, self, *args, **kwargs): | |
45 | """Keep our history and outstanding attributes up to date after a method call.""" |
|
45 | """Keep our history and outstanding attributes up to date after a method call.""" | |
46 | n_previous = len(self.client.history) |
|
46 | n_previous = len(self.client.history) | |
47 | try: |
|
47 | try: | |
48 | ret = f(self, *args, **kwargs) |
|
48 | ret = f(self, *args, **kwargs) | |
49 | finally: |
|
49 | finally: | |
50 | nmsgs = len(self.client.history) - n_previous |
|
50 | nmsgs = len(self.client.history) - n_previous | |
51 | msg_ids = self.client.history[-nmsgs:] |
|
51 | msg_ids = self.client.history[-nmsgs:] | |
52 | self.history.extend(msg_ids) |
|
52 | self.history.extend(msg_ids) | |
53 | map(self.outstanding.add, msg_ids) |
|
53 | map(self.outstanding.add, msg_ids) | |
54 | return ret |
|
54 | return ret | |
55 |
|
55 | |||
56 | @decorator |
|
56 | @decorator | |
57 | def sync_results(f, self, *args, **kwargs): |
|
57 | def sync_results(f, self, *args, **kwargs): | |
58 | """sync relevant results from self.client to our results attribute.""" |
|
58 | """sync relevant results from self.client to our results attribute.""" | |
59 | ret = f(self, *args, **kwargs) |
|
59 | ret = f(self, *args, **kwargs) | |
60 | delta = self.outstanding.difference(self.client.outstanding) |
|
60 | delta = self.outstanding.difference(self.client.outstanding) | |
61 | completed = self.outstanding.intersection(delta) |
|
61 | completed = self.outstanding.intersection(delta) | |
62 | self.outstanding = self.outstanding.difference(completed) |
|
62 | self.outstanding = self.outstanding.difference(completed) | |
63 | return ret |
|
63 | return ret | |
64 |
|
64 | |||
65 | @decorator |
|
65 | @decorator | |
66 | def spin_after(f, self, *args, **kwargs): |
|
66 | def spin_after(f, self, *args, **kwargs): | |
67 | """call spin after the method.""" |
|
67 | """call spin after the method.""" | |
68 | ret = f(self, *args, **kwargs) |
|
68 | ret = f(self, *args, **kwargs) | |
69 | self.spin() |
|
69 | self.spin() | |
70 | return ret |
|
70 | return ret | |
71 |
|
71 | |||
72 | #----------------------------------------------------------------------------- |
|
72 | #----------------------------------------------------------------------------- | |
73 | # Classes |
|
73 | # Classes | |
74 | #----------------------------------------------------------------------------- |
|
74 | #----------------------------------------------------------------------------- | |
75 |
|
75 | |||
76 | @skip_doctest |
|
76 | @skip_doctest | |
77 | class View(HasTraits): |
|
77 | class View(HasTraits): | |
78 | """Base View class for more convenint apply(f,*args,**kwargs) syntax via attributes. |
|
78 | """Base View class for more convenint apply(f,*args,**kwargs) syntax via attributes. | |
79 |
|
79 | |||
80 | Don't use this class, use subclasses. |
|
80 | Don't use this class, use subclasses. | |
81 |
|
81 | |||
82 | Methods |
|
82 | Methods | |
83 | ------- |
|
83 | ------- | |
84 |
|
84 | |||
85 | spin |
|
85 | spin | |
86 | flushes incoming results and registration state changes |
|
86 | flushes incoming results and registration state changes | |
87 | control methods spin, and requesting `ids` also ensures up to date |
|
87 | control methods spin, and requesting `ids` also ensures up to date | |
88 |
|
88 | |||
89 | wait |
|
89 | wait | |
90 | wait on one or more msg_ids |
|
90 | wait on one or more msg_ids | |
91 |
|
91 | |||
92 | execution methods |
|
92 | execution methods | |
93 | apply |
|
93 | apply | |
94 | legacy: execute, run |
|
94 | legacy: execute, run | |
95 |
|
95 | |||
96 | data movement |
|
96 | data movement | |
97 | push, pull, scatter, gather |
|
97 | push, pull, scatter, gather | |
98 |
|
98 | |||
99 | query methods |
|
99 | query methods | |
100 | get_result, queue_status, purge_results, result_status |
|
100 | get_result, queue_status, purge_results, result_status | |
101 |
|
101 | |||
102 | control methods |
|
102 | control methods | |
103 | abort, shutdown |
|
103 | abort, shutdown | |
104 |
|
104 | |||
105 | """ |
|
105 | """ | |
106 | # flags |
|
106 | # flags | |
107 | block=Bool(False) |
|
107 | block=Bool(False) | |
108 | track=Bool(True) |
|
108 | track=Bool(True) | |
109 | targets = Any() |
|
109 | targets = Any() | |
110 |
|
110 | |||
111 | history=List() |
|
111 | history=List() | |
112 | outstanding = Set() |
|
112 | outstanding = Set() | |
113 | results = Dict() |
|
113 | results = Dict() | |
114 | client = Instance('IPython.parallel.Client') |
|
114 | client = Instance('IPython.parallel.Client') | |
115 |
|
115 | |||
116 | _socket = Instance('zmq.Socket') |
|
116 | _socket = Instance('zmq.Socket') | |
117 | _flag_names = List(['targets', 'block', 'track']) |
|
117 | _flag_names = List(['targets', 'block', 'track']) | |
118 | _targets = Any() |
|
118 | _targets = Any() | |
119 | _idents = Any() |
|
119 | _idents = Any() | |
120 |
|
120 | |||
121 | def __init__(self, client=None, socket=None, **flags): |
|
121 | def __init__(self, client=None, socket=None, **flags): | |
122 | super(View, self).__init__(client=client, _socket=socket) |
|
122 | super(View, self).__init__(client=client, _socket=socket) | |
123 | self.results = client.results |
|
123 | self.results = client.results | |
124 | self.block = client.block |
|
124 | self.block = client.block | |
125 |
|
125 | |||
126 | self.set_flags(**flags) |
|
126 | self.set_flags(**flags) | |
127 |
|
127 | |||
128 | assert not self.__class__ is View, "Don't use base View objects, use subclasses" |
|
128 | assert not self.__class__ is View, "Don't use base View objects, use subclasses" | |
129 |
|
129 | |||
130 | def __repr__(self): |
|
130 | def __repr__(self): | |
131 | strtargets = str(self.targets) |
|
131 | strtargets = str(self.targets) | |
132 | if len(strtargets) > 16: |
|
132 | if len(strtargets) > 16: | |
133 | strtargets = strtargets[:12]+'...]' |
|
133 | strtargets = strtargets[:12]+'...]' | |
134 | return "<%s %s>"%(self.__class__.__name__, strtargets) |
|
134 | return "<%s %s>"%(self.__class__.__name__, strtargets) | |
135 |
|
135 | |||
136 | def __len__(self): |
|
136 | def __len__(self): | |
137 | if isinstance(self.targets, list): |
|
137 | if isinstance(self.targets, list): | |
138 | return len(self.targets) |
|
138 | return len(self.targets) | |
139 | elif isinstance(self.targets, int): |
|
139 | elif isinstance(self.targets, int): | |
140 | return 1 |
|
140 | return 1 | |
141 | else: |
|
141 | else: | |
142 | return len(self.client) |
|
142 | return len(self.client) | |
143 |
|
143 | |||
144 | def set_flags(self, **kwargs): |
|
144 | def set_flags(self, **kwargs): | |
145 | """set my attribute flags by keyword. |
|
145 | """set my attribute flags by keyword. | |
146 |
|
146 | |||
147 | Views determine behavior with a few attributes (`block`, `track`, etc.). |
|
147 | Views determine behavior with a few attributes (`block`, `track`, etc.). | |
148 | These attributes can be set all at once by name with this method. |
|
148 | These attributes can be set all at once by name with this method. | |
149 |
|
149 | |||
150 | Parameters |
|
150 | Parameters | |
151 | ---------- |
|
151 | ---------- | |
152 |
|
152 | |||
153 | block : bool |
|
153 | block : bool | |
154 | whether to wait for results |
|
154 | whether to wait for results | |
155 | track : bool |
|
155 | track : bool | |
156 | whether to create a MessageTracker to allow the user to |
|
156 | whether to create a MessageTracker to allow the user to | |
157 | safely edit after arrays and buffers during non-copying |
|
157 | safely edit after arrays and buffers during non-copying | |
158 | sends. |
|
158 | sends. | |
159 | """ |
|
159 | """ | |
160 | for name, value in kwargs.iteritems(): |
|
160 | for name, value in kwargs.iteritems(): | |
161 | if name not in self._flag_names: |
|
161 | if name not in self._flag_names: | |
162 | raise KeyError("Invalid name: %r"%name) |
|
162 | raise KeyError("Invalid name: %r"%name) | |
163 | else: |
|
163 | else: | |
164 | setattr(self, name, value) |
|
164 | setattr(self, name, value) | |
165 |
|
165 | |||
166 | @contextmanager |
|
166 | @contextmanager | |
167 | def temp_flags(self, **kwargs): |
|
167 | def temp_flags(self, **kwargs): | |
168 | """temporarily set flags, for use in `with` statements. |
|
168 | """temporarily set flags, for use in `with` statements. | |
169 |
|
169 | |||
170 | See set_flags for permanent setting of flags |
|
170 | See set_flags for permanent setting of flags | |
171 |
|
171 | |||
172 | Examples |
|
172 | Examples | |
173 | -------- |
|
173 | -------- | |
174 |
|
174 | |||
175 | >>> view.track=False |
|
175 | >>> view.track=False | |
176 | ... |
|
176 | ... | |
177 | >>> with view.temp_flags(track=True): |
|
177 | >>> with view.temp_flags(track=True): | |
178 | ... ar = view.apply(dostuff, my_big_array) |
|
178 | ... ar = view.apply(dostuff, my_big_array) | |
179 | ... ar.tracker.wait() # wait for send to finish |
|
179 | ... ar.tracker.wait() # wait for send to finish | |
180 | >>> view.track |
|
180 | >>> view.track | |
181 | False |
|
181 | False | |
182 |
|
182 | |||
183 | """ |
|
183 | """ | |
184 | # preflight: save flags, and set temporaries |
|
184 | # preflight: save flags, and set temporaries | |
185 | saved_flags = {} |
|
185 | saved_flags = {} | |
186 | for f in self._flag_names: |
|
186 | for f in self._flag_names: | |
187 | saved_flags[f] = getattr(self, f) |
|
187 | saved_flags[f] = getattr(self, f) | |
188 | self.set_flags(**kwargs) |
|
188 | self.set_flags(**kwargs) | |
189 | # yield to the with-statement block |
|
189 | # yield to the with-statement block | |
190 | try: |
|
190 | try: | |
191 | yield |
|
191 | yield | |
192 | finally: |
|
192 | finally: | |
193 | # postflight: restore saved flags |
|
193 | # postflight: restore saved flags | |
194 | self.set_flags(**saved_flags) |
|
194 | self.set_flags(**saved_flags) | |
195 |
|
195 | |||
196 |
|
196 | |||
197 | #---------------------------------------------------------------- |
|
197 | #---------------------------------------------------------------- | |
198 | # apply |
|
198 | # apply | |
199 | #---------------------------------------------------------------- |
|
199 | #---------------------------------------------------------------- | |
200 |
|
200 | |||
201 | @sync_results |
|
201 | @sync_results | |
202 | @save_ids |
|
202 | @save_ids | |
203 | def _really_apply(self, f, args, kwargs, block=None, **options): |
|
203 | def _really_apply(self, f, args, kwargs, block=None, **options): | |
204 | """wrapper for client.send_apply_request""" |
|
204 | """wrapper for client.send_apply_request""" | |
205 | raise NotImplementedError("Implement in subclasses") |
|
205 | raise NotImplementedError("Implement in subclasses") | |
206 |
|
206 | |||
207 | def apply(self, f, *args, **kwargs): |
|
207 | def apply(self, f, *args, **kwargs): | |
208 | """calls f(*args, **kwargs) on remote engines, returning the result. |
|
208 | """calls f(*args, **kwargs) on remote engines, returning the result. | |
209 |
|
209 | |||
210 | This method sets all apply flags via this View's attributes. |
|
210 | This method sets all apply flags via this View's attributes. | |
211 |
|
211 | |||
212 | if self.block is False: |
|
212 | if self.block is False: | |
213 | returns AsyncResult |
|
213 | returns AsyncResult | |
214 | else: |
|
214 | else: | |
215 | returns actual result of f(*args, **kwargs) |
|
215 | returns actual result of f(*args, **kwargs) | |
216 | """ |
|
216 | """ | |
217 | return self._really_apply(f, args, kwargs) |
|
217 | return self._really_apply(f, args, kwargs) | |
218 |
|
218 | |||
219 | def apply_async(self, f, *args, **kwargs): |
|
219 | def apply_async(self, f, *args, **kwargs): | |
220 | """calls f(*args, **kwargs) on remote engines in a nonblocking manner. |
|
220 | """calls f(*args, **kwargs) on remote engines in a nonblocking manner. | |
221 |
|
221 | |||
222 | returns AsyncResult |
|
222 | returns AsyncResult | |
223 | """ |
|
223 | """ | |
224 | return self._really_apply(f, args, kwargs, block=False) |
|
224 | return self._really_apply(f, args, kwargs, block=False) | |
225 |
|
225 | |||
226 | @spin_after |
|
226 | @spin_after | |
227 | def apply_sync(self, f, *args, **kwargs): |
|
227 | def apply_sync(self, f, *args, **kwargs): | |
228 | """calls f(*args, **kwargs) on remote engines in a blocking manner, |
|
228 | """calls f(*args, **kwargs) on remote engines in a blocking manner, | |
229 | returning the result. |
|
229 | returning the result. | |
230 |
|
230 | |||
231 | returns: actual result of f(*args, **kwargs) |
|
231 | returns: actual result of f(*args, **kwargs) | |
232 | """ |
|
232 | """ | |
233 | return self._really_apply(f, args, kwargs, block=True) |
|
233 | return self._really_apply(f, args, kwargs, block=True) | |
234 |
|
234 | |||
235 | #---------------------------------------------------------------- |
|
235 | #---------------------------------------------------------------- | |
236 | # wrappers for client and control methods |
|
236 | # wrappers for client and control methods | |
237 | #---------------------------------------------------------------- |
|
237 | #---------------------------------------------------------------- | |
238 | @sync_results |
|
238 | @sync_results | |
239 | def spin(self): |
|
239 | def spin(self): | |
240 | """spin the client, and sync""" |
|
240 | """spin the client, and sync""" | |
241 | self.client.spin() |
|
241 | self.client.spin() | |
242 |
|
242 | |||
243 | @sync_results |
|
243 | @sync_results | |
244 | def wait(self, jobs=None, timeout=-1): |
|
244 | def wait(self, jobs=None, timeout=-1): | |
245 | """waits on one or more `jobs`, for up to `timeout` seconds. |
|
245 | """waits on one or more `jobs`, for up to `timeout` seconds. | |
246 |
|
246 | |||
247 | Parameters |
|
247 | Parameters | |
248 | ---------- |
|
248 | ---------- | |
249 |
|
249 | |||
250 | jobs : int, str, or list of ints and/or strs, or one or more AsyncResult objects |
|
250 | jobs : int, str, or list of ints and/or strs, or one or more AsyncResult objects | |
251 | ints are indices to self.history |
|
251 | ints are indices to self.history | |
252 | strs are msg_ids |
|
252 | strs are msg_ids | |
253 | default: wait on all outstanding messages |
|
253 | default: wait on all outstanding messages | |
254 | timeout : float |
|
254 | timeout : float | |
255 | a time in seconds, after which to give up. |
|
255 | a time in seconds, after which to give up. | |
256 | default is -1, which means no timeout |
|
256 | default is -1, which means no timeout | |
257 |
|
257 | |||
258 | Returns |
|
258 | Returns | |
259 | ------- |
|
259 | ------- | |
260 |
|
260 | |||
261 | True : when all msg_ids are done |
|
261 | True : when all msg_ids are done | |
262 | False : timeout reached, some msg_ids still outstanding |
|
262 | False : timeout reached, some msg_ids still outstanding | |
263 | """ |
|
263 | """ | |
264 | if jobs is None: |
|
264 | if jobs is None: | |
265 | jobs = self.history |
|
265 | jobs = self.history | |
266 | return self.client.wait(jobs, timeout) |
|
266 | return self.client.wait(jobs, timeout) | |
267 |
|
267 | |||
268 | def abort(self, jobs=None, targets=None, block=None): |
|
268 | def abort(self, jobs=None, targets=None, block=None): | |
269 | """Abort jobs on my engines. |
|
269 | """Abort jobs on my engines. | |
270 |
|
270 | |||
271 | Parameters |
|
271 | Parameters | |
272 | ---------- |
|
272 | ---------- | |
273 |
|
273 | |||
274 | jobs : None, str, list of strs, optional |
|
274 | jobs : None, str, list of strs, optional | |
275 | if None: abort all jobs. |
|
275 | if None: abort all jobs. | |
276 | else: abort specific msg_id(s). |
|
276 | else: abort specific msg_id(s). | |
277 | """ |
|
277 | """ | |
278 | block = block if block is not None else self.block |
|
278 | block = block if block is not None else self.block | |
279 | targets = targets if targets is not None else self.targets |
|
279 | targets = targets if targets is not None else self.targets | |
280 | jobs = jobs if jobs is not None else list(self.outstanding) |
|
280 | jobs = jobs if jobs is not None else list(self.outstanding) | |
281 |
|
281 | |||
282 | return self.client.abort(jobs=jobs, targets=targets, block=block) |
|
282 | return self.client.abort(jobs=jobs, targets=targets, block=block) | |
283 |
|
283 | |||
284 | def queue_status(self, targets=None, verbose=False): |
|
284 | def queue_status(self, targets=None, verbose=False): | |
285 | """Fetch the Queue status of my engines""" |
|
285 | """Fetch the Queue status of my engines""" | |
286 | targets = targets if targets is not None else self.targets |
|
286 | targets = targets if targets is not None else self.targets | |
287 | return self.client.queue_status(targets=targets, verbose=verbose) |
|
287 | return self.client.queue_status(targets=targets, verbose=verbose) | |
288 |
|
288 | |||
289 | def purge_results(self, jobs=[], targets=[]): |
|
289 | def purge_results(self, jobs=[], targets=[]): | |
290 | """Instruct the controller to forget specific results.""" |
|
290 | """Instruct the controller to forget specific results.""" | |
291 | if targets is None or targets == 'all': |
|
291 | if targets is None or targets == 'all': | |
292 | targets = self.targets |
|
292 | targets = self.targets | |
293 | return self.client.purge_results(jobs=jobs, targets=targets) |
|
293 | return self.client.purge_results(jobs=jobs, targets=targets) | |
294 |
|
294 | |||
295 | def shutdown(self, targets=None, restart=False, hub=False, block=None): |
|
295 | def shutdown(self, targets=None, restart=False, hub=False, block=None): | |
296 | """Terminates one or more engine processes, optionally including the hub. |
|
296 | """Terminates one or more engine processes, optionally including the hub. | |
297 | """ |
|
297 | """ | |
298 | block = self.block if block is None else block |
|
298 | block = self.block if block is None else block | |
299 | if targets is None or targets == 'all': |
|
299 | if targets is None or targets == 'all': | |
300 | targets = self.targets |
|
300 | targets = self.targets | |
301 | return self.client.shutdown(targets=targets, restart=restart, hub=hub, block=block) |
|
301 | return self.client.shutdown(targets=targets, restart=restart, hub=hub, block=block) | |
302 |
|
302 | |||
303 | @spin_after |
|
303 | @spin_after | |
304 | def get_result(self, indices_or_msg_ids=None): |
|
304 | def get_result(self, indices_or_msg_ids=None): | |
305 | """return one or more results, specified by history index or msg_id. |
|
305 | """return one or more results, specified by history index or msg_id. | |
306 |
|
306 | |||
307 | See client.get_result for details. |
|
307 | See client.get_result for details. | |
308 |
|
308 | |||
309 | """ |
|
309 | """ | |
310 |
|
310 | |||
311 | if indices_or_msg_ids is None: |
|
311 | if indices_or_msg_ids is None: | |
312 | indices_or_msg_ids = -1 |
|
312 | indices_or_msg_ids = -1 | |
313 | if isinstance(indices_or_msg_ids, int): |
|
313 | if isinstance(indices_or_msg_ids, int): | |
314 | indices_or_msg_ids = self.history[indices_or_msg_ids] |
|
314 | indices_or_msg_ids = self.history[indices_or_msg_ids] | |
315 | elif isinstance(indices_or_msg_ids, (list,tuple,set)): |
|
315 | elif isinstance(indices_or_msg_ids, (list,tuple,set)): | |
316 | indices_or_msg_ids = list(indices_or_msg_ids) |
|
316 | indices_or_msg_ids = list(indices_or_msg_ids) | |
317 | for i,index in enumerate(indices_or_msg_ids): |
|
317 | for i,index in enumerate(indices_or_msg_ids): | |
318 | if isinstance(index, int): |
|
318 | if isinstance(index, int): | |
319 | indices_or_msg_ids[i] = self.history[index] |
|
319 | indices_or_msg_ids[i] = self.history[index] | |
320 | return self.client.get_result(indices_or_msg_ids) |
|
320 | return self.client.get_result(indices_or_msg_ids) | |
321 |
|
321 | |||
322 | #------------------------------------------------------------------- |
|
322 | #------------------------------------------------------------------- | |
323 | # Map |
|
323 | # Map | |
324 | #------------------------------------------------------------------- |
|
324 | #------------------------------------------------------------------- | |
325 |
|
325 | |||
326 | def map(self, f, *sequences, **kwargs): |
|
326 | def map(self, f, *sequences, **kwargs): | |
327 | """override in subclasses""" |
|
327 | """override in subclasses""" | |
328 | raise NotImplementedError |
|
328 | raise NotImplementedError | |
329 |
|
329 | |||
330 | def map_async(self, f, *sequences, **kwargs): |
|
330 | def map_async(self, f, *sequences, **kwargs): | |
331 | """Parallel version of builtin `map`, using this view's engines. |
|
331 | """Parallel version of builtin `map`, using this view's engines. | |
332 |
|
332 | |||
333 | This is equivalent to map(...block=False) |
|
333 | This is equivalent to map(...block=False) | |
334 |
|
334 | |||
335 | See `self.map` for details. |
|
335 | See `self.map` for details. | |
336 | """ |
|
336 | """ | |
337 | if 'block' in kwargs: |
|
337 | if 'block' in kwargs: | |
338 | raise TypeError("map_async doesn't take a `block` keyword argument.") |
|
338 | raise TypeError("map_async doesn't take a `block` keyword argument.") | |
339 | kwargs['block'] = False |
|
339 | kwargs['block'] = False | |
340 | return self.map(f,*sequences,**kwargs) |
|
340 | return self.map(f,*sequences,**kwargs) | |
341 |
|
341 | |||
342 | def map_sync(self, f, *sequences, **kwargs): |
|
342 | def map_sync(self, f, *sequences, **kwargs): | |
343 | """Parallel version of builtin `map`, using this view's engines. |
|
343 | """Parallel version of builtin `map`, using this view's engines. | |
344 |
|
344 | |||
345 | This is equivalent to map(...block=True) |
|
345 | This is equivalent to map(...block=True) | |
346 |
|
346 | |||
347 | See `self.map` for details. |
|
347 | See `self.map` for details. | |
348 | """ |
|
348 | """ | |
349 | if 'block' in kwargs: |
|
349 | if 'block' in kwargs: | |
350 | raise TypeError("map_sync doesn't take a `block` keyword argument.") |
|
350 | raise TypeError("map_sync doesn't take a `block` keyword argument.") | |
351 | kwargs['block'] = True |
|
351 | kwargs['block'] = True | |
352 | return self.map(f,*sequences,**kwargs) |
|
352 | return self.map(f,*sequences,**kwargs) | |
353 |
|
353 | |||
354 | def imap(self, f, *sequences, **kwargs): |
|
354 | def imap(self, f, *sequences, **kwargs): | |
355 | """Parallel version of `itertools.imap`. |
|
355 | """Parallel version of `itertools.imap`. | |
356 |
|
356 | |||
357 | See `self.map` for details. |
|
357 | See `self.map` for details. | |
358 |
|
358 | |||
359 | """ |
|
359 | """ | |
360 |
|
360 | |||
361 | return iter(self.map_async(f,*sequences, **kwargs)) |
|
361 | return iter(self.map_async(f,*sequences, **kwargs)) | |
362 |
|
362 | |||
363 | #------------------------------------------------------------------- |
|
363 | #------------------------------------------------------------------- | |
364 | # Decorators |
|
364 | # Decorators | |
365 | #------------------------------------------------------------------- |
|
365 | #------------------------------------------------------------------- | |
366 |
|
366 | |||
367 | def remote(self, block=True, **flags): |
|
367 | def remote(self, block=True, **flags): | |
368 | """Decorator for making a RemoteFunction""" |
|
368 | """Decorator for making a RemoteFunction""" | |
369 | block = self.block if block is None else block |
|
369 | block = self.block if block is None else block | |
370 | return remote(self, block=block, **flags) |
|
370 | return remote(self, block=block, **flags) | |
371 |
|
371 | |||
372 | def parallel(self, dist='b', block=None, **flags): |
|
372 | def parallel(self, dist='b', block=None, **flags): | |
373 | """Decorator for making a ParallelFunction""" |
|
373 | """Decorator for making a ParallelFunction""" | |
374 | block = self.block if block is None else block |
|
374 | block = self.block if block is None else block | |
375 | return parallel(self, dist=dist, block=block, **flags) |
|
375 | return parallel(self, dist=dist, block=block, **flags) | |
376 |
|
376 | |||
377 | @skip_doctest |
|
377 | @skip_doctest | |
378 | class DirectView(View): |
|
378 | class DirectView(View): | |
379 | """Direct Multiplexer View of one or more engines. |
|
379 | """Direct Multiplexer View of one or more engines. | |
380 |
|
380 | |||
381 | These are created via indexed access to a client: |
|
381 | These are created via indexed access to a client: | |
382 |
|
382 | |||
383 | >>> dv_1 = client[1] |
|
383 | >>> dv_1 = client[1] | |
384 | >>> dv_all = client[:] |
|
384 | >>> dv_all = client[:] | |
385 | >>> dv_even = client[::2] |
|
385 | >>> dv_even = client[::2] | |
386 | >>> dv_some = client[1:3] |
|
386 | >>> dv_some = client[1:3] | |
387 |
|
387 | |||
388 | This object provides dictionary access to engine namespaces: |
|
388 | This object provides dictionary access to engine namespaces: | |
389 |
|
389 | |||
390 | # push a=5: |
|
390 | # push a=5: | |
391 | >>> dv['a'] = 5 |
|
391 | >>> dv['a'] = 5 | |
392 | # pull 'foo': |
|
392 | # pull 'foo': | |
393 | >>> db['foo'] |
|
393 | >>> db['foo'] | |
394 |
|
394 | |||
395 | """ |
|
395 | """ | |
396 |
|
396 | |||
397 | def __init__(self, client=None, socket=None, targets=None): |
|
397 | def __init__(self, client=None, socket=None, targets=None): | |
398 | super(DirectView, self).__init__(client=client, socket=socket, targets=targets) |
|
398 | super(DirectView, self).__init__(client=client, socket=socket, targets=targets) | |
399 |
|
399 | |||
400 | @property |
|
400 | @property | |
401 | def importer(self): |
|
401 | def importer(self): | |
402 | """sync_imports(local=True) as a property. |
|
402 | """sync_imports(local=True) as a property. | |
403 |
|
403 | |||
404 | See sync_imports for details. |
|
404 | See sync_imports for details. | |
405 |
|
405 | |||
406 | """ |
|
406 | """ | |
407 | return self.sync_imports(True) |
|
407 | return self.sync_imports(True) | |
408 |
|
408 | |||
409 | @contextmanager |
|
409 | @contextmanager | |
410 | def sync_imports(self, local=True, quiet=False): |
|
410 | def sync_imports(self, local=True, quiet=False): | |
411 | """Context Manager for performing simultaneous local and remote imports. |
|
411 | """Context Manager for performing simultaneous local and remote imports. | |
412 |
|
412 | |||
413 | 'import x as y' will *not* work. The 'as y' part will simply be ignored. |
|
413 | 'import x as y' will *not* work. The 'as y' part will simply be ignored. | |
414 |
|
414 | |||
415 | If `local=True`, then the package will also be imported locally. |
|
415 | If `local=True`, then the package will also be imported locally. | |
416 |
|
416 | |||
417 | If `quiet=True`, no output will be produced when attempting remote |
|
417 | If `quiet=True`, no output will be produced when attempting remote | |
418 | imports. |
|
418 | imports. | |
419 |
|
419 | |||
420 | Note that remote-only (`local=False`) imports have not been implemented. |
|
420 | Note that remote-only (`local=False`) imports have not been implemented. | |
421 |
|
421 | |||
422 | >>> with view.sync_imports(): |
|
422 | >>> with view.sync_imports(): | |
423 | ... from numpy import recarray |
|
423 | ... from numpy import recarray | |
424 | importing recarray from numpy on engine(s) |
|
424 | importing recarray from numpy on engine(s) | |
425 |
|
425 | |||
426 | """ |
|
426 | """ | |
427 | import __builtin__ |
|
427 | import __builtin__ | |
428 | local_import = __builtin__.__import__ |
|
428 | local_import = __builtin__.__import__ | |
429 | modules = set() |
|
429 | modules = set() | |
430 | results = [] |
|
430 | results = [] | |
431 | @util.interactive |
|
431 | @util.interactive | |
432 | def remote_import(name, fromlist, level): |
|
432 | def remote_import(name, fromlist, level): | |
433 | """the function to be passed to apply, that actually performs the import |
|
433 | """the function to be passed to apply, that actually performs the import | |
434 | on the engine, and loads up the user namespace. |
|
434 | on the engine, and loads up the user namespace. | |
435 | """ |
|
435 | """ | |
436 | import sys |
|
436 | import sys | |
437 | user_ns = globals() |
|
437 | user_ns = globals() | |
438 | mod = __import__(name, fromlist=fromlist, level=level) |
|
438 | mod = __import__(name, fromlist=fromlist, level=level) | |
439 | if fromlist: |
|
439 | if fromlist: | |
440 | for key in fromlist: |
|
440 | for key in fromlist: | |
441 | user_ns[key] = getattr(mod, key) |
|
441 | user_ns[key] = getattr(mod, key) | |
442 | else: |
|
442 | else: | |
443 | user_ns[name] = sys.modules[name] |
|
443 | user_ns[name] = sys.modules[name] | |
444 |
|
444 | |||
445 | def view_import(name, globals={}, locals={}, fromlist=[], level=-1): |
|
445 | def view_import(name, globals={}, locals={}, fromlist=[], level=-1): | |
446 | """the drop-in replacement for __import__, that optionally imports |
|
446 | """the drop-in replacement for __import__, that optionally imports | |
447 | locally as well. |
|
447 | locally as well. | |
448 | """ |
|
448 | """ | |
449 | # don't override nested imports |
|
449 | # don't override nested imports | |
450 | save_import = __builtin__.__import__ |
|
450 | save_import = __builtin__.__import__ | |
451 | __builtin__.__import__ = local_import |
|
451 | __builtin__.__import__ = local_import | |
452 |
|
452 | |||
453 | if imp.lock_held(): |
|
453 | if imp.lock_held(): | |
454 | # this is a side-effect import, don't do it remotely, or even |
|
454 | # this is a side-effect import, don't do it remotely, or even | |
455 | # ignore the local effects |
|
455 | # ignore the local effects | |
456 | return local_import(name, globals, locals, fromlist, level) |
|
456 | return local_import(name, globals, locals, fromlist, level) | |
457 |
|
457 | |||
458 | imp.acquire_lock() |
|
458 | imp.acquire_lock() | |
459 | if local: |
|
459 | if local: | |
460 | mod = local_import(name, globals, locals, fromlist, level) |
|
460 | mod = local_import(name, globals, locals, fromlist, level) | |
461 | else: |
|
461 | else: | |
462 | raise NotImplementedError("remote-only imports not yet implemented") |
|
462 | raise NotImplementedError("remote-only imports not yet implemented") | |
463 | imp.release_lock() |
|
463 | imp.release_lock() | |
464 |
|
464 | |||
465 | key = name+':'+','.join(fromlist or []) |
|
465 | key = name+':'+','.join(fromlist or []) | |
466 | if level == -1 and key not in modules: |
|
466 | if level == -1 and key not in modules: | |
467 | modules.add(key) |
|
467 | modules.add(key) | |
468 | if not quiet: |
|
468 | if not quiet: | |
469 | if fromlist: |
|
469 | if fromlist: | |
470 | print "importing %s from %s on engine(s)"%(','.join(fromlist), name) |
|
470 | print "importing %s from %s on engine(s)"%(','.join(fromlist), name) | |
471 | else: |
|
471 | else: | |
472 | print "importing %s on engine(s)"%name |
|
472 | print "importing %s on engine(s)"%name | |
473 | results.append(self.apply_async(remote_import, name, fromlist, level)) |
|
473 | results.append(self.apply_async(remote_import, name, fromlist, level)) | |
474 | # restore override |
|
474 | # restore override | |
475 | __builtin__.__import__ = save_import |
|
475 | __builtin__.__import__ = save_import | |
476 |
|
476 | |||
477 | return mod |
|
477 | return mod | |
478 |
|
478 | |||
479 | # override __import__ |
|
479 | # override __import__ | |
480 | __builtin__.__import__ = view_import |
|
480 | __builtin__.__import__ = view_import | |
481 | try: |
|
481 | try: | |
482 | # enter the block |
|
482 | # enter the block | |
483 | yield |
|
483 | yield | |
484 | except ImportError: |
|
484 | except ImportError: | |
485 | if local: |
|
485 | if local: | |
486 | raise |
|
486 | raise | |
487 | else: |
|
487 | else: | |
488 | # ignore import errors if not doing local imports |
|
488 | # ignore import errors if not doing local imports | |
489 | pass |
|
489 | pass | |
490 | finally: |
|
490 | finally: | |
491 | # always restore __import__ |
|
491 | # always restore __import__ | |
492 | __builtin__.__import__ = local_import |
|
492 | __builtin__.__import__ = local_import | |
493 |
|
493 | |||
494 | for r in results: |
|
494 | for r in results: | |
495 | # raise possible remote ImportErrors here |
|
495 | # raise possible remote ImportErrors here | |
496 | r.get() |
|
496 | r.get() | |
497 |
|
497 | |||
498 |
|
498 | |||
499 | @sync_results |
|
499 | @sync_results | |
500 | @save_ids |
|
500 | @save_ids | |
501 | def _really_apply(self, f, args=None, kwargs=None, targets=None, block=None, track=None): |
|
501 | def _really_apply(self, f, args=None, kwargs=None, targets=None, block=None, track=None): | |
502 | """calls f(*args, **kwargs) on remote engines, returning the result. |
|
502 | """calls f(*args, **kwargs) on remote engines, returning the result. | |
503 |
|
503 | |||
504 | This method sets all of `apply`'s flags via this View's attributes. |
|
504 | This method sets all of `apply`'s flags via this View's attributes. | |
505 |
|
505 | |||
506 | Parameters |
|
506 | Parameters | |
507 | ---------- |
|
507 | ---------- | |
508 |
|
508 | |||
509 | f : callable |
|
509 | f : callable | |
510 |
|
510 | |||
511 | args : list [default: empty] |
|
511 | args : list [default: empty] | |
512 |
|
512 | |||
513 | kwargs : dict [default: empty] |
|
513 | kwargs : dict [default: empty] | |
514 |
|
514 | |||
515 | targets : target list [default: self.targets] |
|
515 | targets : target list [default: self.targets] | |
516 | where to run |
|
516 | where to run | |
517 | block : bool [default: self.block] |
|
517 | block : bool [default: self.block] | |
518 | whether to block |
|
518 | whether to block | |
519 | track : bool [default: self.track] |
|
519 | track : bool [default: self.track] | |
520 | whether to ask zmq to track the message, for safe non-copying sends |
|
520 | whether to ask zmq to track the message, for safe non-copying sends | |
521 |
|
521 | |||
522 | Returns |
|
522 | Returns | |
523 | ------- |
|
523 | ------- | |
524 |
|
524 | |||
525 | if self.block is False: |
|
525 | if self.block is False: | |
526 | returns AsyncResult |
|
526 | returns AsyncResult | |
527 | else: |
|
527 | else: | |
528 | returns actual result of f(*args, **kwargs) on the engine(s) |
|
528 | returns actual result of f(*args, **kwargs) on the engine(s) | |
529 | This will be a list of self.targets is also a list (even length 1), or |
|
529 | This will be a list of self.targets is also a list (even length 1), or | |
530 | the single result if self.targets is an integer engine id |
|
530 | the single result if self.targets is an integer engine id | |
531 | """ |
|
531 | """ | |
532 | args = [] if args is None else args |
|
532 | args = [] if args is None else args | |
533 | kwargs = {} if kwargs is None else kwargs |
|
533 | kwargs = {} if kwargs is None else kwargs | |
534 | block = self.block if block is None else block |
|
534 | block = self.block if block is None else block | |
535 | track = self.track if track is None else track |
|
535 | track = self.track if track is None else track | |
536 | targets = self.targets if targets is None else targets |
|
536 | targets = self.targets if targets is None else targets | |
537 |
|
537 | |||
538 | _idents = self.client._build_targets(targets)[0] |
|
538 | _idents = self.client._build_targets(targets)[0] | |
539 | msg_ids = [] |
|
539 | msg_ids = [] | |
540 | trackers = [] |
|
540 | trackers = [] | |
541 | for ident in _idents: |
|
541 | for ident in _idents: | |
542 | msg = self.client.send_apply_request(self._socket, f, args, kwargs, track=track, |
|
542 | msg = self.client.send_apply_request(self._socket, f, args, kwargs, track=track, | |
543 | ident=ident) |
|
543 | ident=ident) | |
544 | if track: |
|
544 | if track: | |
545 | trackers.append(msg['tracker']) |
|
545 | trackers.append(msg['tracker']) | |
546 | msg_ids.append(msg['header']['msg_id']) |
|
546 | msg_ids.append(msg['header']['msg_id']) | |
547 | tracker = None if track is False else zmq.MessageTracker(*trackers) |
|
547 | tracker = None if track is False else zmq.MessageTracker(*trackers) | |
548 | ar = AsyncResult(self.client, msg_ids, fname=getname(f), targets=targets, tracker=tracker) |
|
548 | ar = AsyncResult(self.client, msg_ids, fname=getname(f), targets=targets, tracker=tracker) | |
549 | if block: |
|
549 | if block: | |
550 | try: |
|
550 | try: | |
551 | return ar.get() |
|
551 | return ar.get() | |
552 | except KeyboardInterrupt: |
|
552 | except KeyboardInterrupt: | |
553 | pass |
|
553 | pass | |
554 | return ar |
|
554 | return ar | |
555 |
|
555 | |||
556 |
|
556 | |||
557 | @spin_after |
|
557 | @spin_after | |
558 | def map(self, f, *sequences, **kwargs): |
|
558 | def map(self, f, *sequences, **kwargs): | |
559 | """view.map(f, *sequences, block=self.block) => list|AsyncMapResult |
|
559 | """view.map(f, *sequences, block=self.block) => list|AsyncMapResult | |
560 |
|
560 | |||
561 | Parallel version of builtin `map`, using this View's `targets`. |
|
561 | Parallel version of builtin `map`, using this View's `targets`. | |
562 |
|
562 | |||
563 | There will be one task per target, so work will be chunked |
|
563 | There will be one task per target, so work will be chunked | |
564 | if the sequences are longer than `targets`. |
|
564 | if the sequences are longer than `targets`. | |
565 |
|
565 | |||
566 | Results can be iterated as they are ready, but will become available in chunks. |
|
566 | Results can be iterated as they are ready, but will become available in chunks. | |
567 |
|
567 | |||
568 | Parameters |
|
568 | Parameters | |
569 | ---------- |
|
569 | ---------- | |
570 |
|
570 | |||
571 | f : callable |
|
571 | f : callable | |
572 | function to be mapped |
|
572 | function to be mapped | |
573 | *sequences: one or more sequences of matching length |
|
573 | *sequences: one or more sequences of matching length | |
574 | the sequences to be distributed and passed to `f` |
|
574 | the sequences to be distributed and passed to `f` | |
575 | block : bool |
|
575 | block : bool | |
576 | whether to wait for the result or not [default self.block] |
|
576 | whether to wait for the result or not [default self.block] | |
577 |
|
577 | |||
578 | Returns |
|
578 | Returns | |
579 | ------- |
|
579 | ------- | |
580 |
|
580 | |||
581 | if block=False: |
|
581 | if block=False: | |
582 | AsyncMapResult |
|
582 | AsyncMapResult | |
583 | An object like AsyncResult, but which reassembles the sequence of results |
|
583 | An object like AsyncResult, but which reassembles the sequence of results | |
584 | into a single list. AsyncMapResults can be iterated through before all |
|
584 | into a single list. AsyncMapResults can be iterated through before all | |
585 | results are complete. |
|
585 | results are complete. | |
586 | else: |
|
586 | else: | |
587 | list |
|
587 | list | |
588 | the result of map(f,*sequences) |
|
588 | the result of map(f,*sequences) | |
589 | """ |
|
589 | """ | |
590 |
|
590 | |||
591 | block = kwargs.pop('block', self.block) |
|
591 | block = kwargs.pop('block', self.block) | |
592 | for k in kwargs.keys(): |
|
592 | for k in kwargs.keys(): | |
593 | if k not in ['block', 'track']: |
|
593 | if k not in ['block', 'track']: | |
594 | raise TypeError("invalid keyword arg, %r"%k) |
|
594 | raise TypeError("invalid keyword arg, %r"%k) | |
595 |
|
595 | |||
596 | assert len(sequences) > 0, "must have some sequences to map onto!" |
|
596 | assert len(sequences) > 0, "must have some sequences to map onto!" | |
597 | pf = ParallelFunction(self, f, block=block, **kwargs) |
|
597 | pf = ParallelFunction(self, f, block=block, **kwargs) | |
598 | return pf.map(*sequences) |
|
598 | return pf.map(*sequences) | |
599 |
|
599 | |||
600 | @sync_results |
|
600 | @sync_results | |
601 | @save_ids |
|
601 | @save_ids | |
602 | def execute(self, code, silent=True, targets=None, block=None): |
|
602 | def execute(self, code, silent=True, targets=None, block=None): | |
603 | """Executes `code` on `targets` in blocking or nonblocking manner. |
|
603 | """Executes `code` on `targets` in blocking or nonblocking manner. | |
604 |
|
604 | |||
605 | ``execute`` is always `bound` (affects engine namespace) |
|
605 | ``execute`` is always `bound` (affects engine namespace) | |
606 |
|
606 | |||
607 | Parameters |
|
607 | Parameters | |
608 | ---------- |
|
608 | ---------- | |
609 |
|
609 | |||
610 | code : str |
|
610 | code : str | |
611 | the code string to be executed |
|
611 | the code string to be executed | |
612 | block : bool |
|
612 | block : bool | |
613 | whether or not to wait until done to return |
|
613 | whether or not to wait until done to return | |
614 | default: self.block |
|
614 | default: self.block | |
615 | """ |
|
615 | """ | |
616 | block = self.block if block is None else block |
|
616 | block = self.block if block is None else block | |
617 | targets = self.targets if targets is None else targets |
|
617 | targets = self.targets if targets is None else targets | |
618 |
|
618 | |||
619 | _idents = self.client._build_targets(targets)[0] |
|
619 | _idents = self.client._build_targets(targets)[0] | |
620 | msg_ids = [] |
|
620 | msg_ids = [] | |
621 | trackers = [] |
|
621 | trackers = [] | |
622 | for ident in _idents: |
|
622 | for ident in _idents: | |
623 | msg = self.client.send_execute_request(self._socket, code, silent=silent, ident=ident) |
|
623 | msg = self.client.send_execute_request(self._socket, code, silent=silent, ident=ident) | |
624 | msg_ids.append(msg['header']['msg_id']) |
|
624 | msg_ids.append(msg['header']['msg_id']) | |
625 | ar = AsyncResult(self.client, msg_ids, fname='execute', targets=targets) |
|
625 | ar = AsyncResult(self.client, msg_ids, fname='execute', targets=targets) | |
626 | if block: |
|
626 | if block: | |
627 | try: |
|
627 | try: | |
628 | ar.get() |
|
628 | ar.get() | |
629 | except KeyboardInterrupt: |
|
629 | except KeyboardInterrupt: | |
630 | pass |
|
630 | pass | |
631 | return ar |
|
631 | return ar | |
632 |
|
632 | |||
633 | def run(self, filename, targets=None, block=None): |
|
633 | def run(self, filename, targets=None, block=None): | |
634 | """Execute contents of `filename` on my engine(s). |
|
634 | """Execute contents of `filename` on my engine(s). | |
635 |
|
635 | |||
636 | This simply reads the contents of the file and calls `execute`. |
|
636 | This simply reads the contents of the file and calls `execute`. | |
637 |
|
637 | |||
638 | Parameters |
|
638 | Parameters | |
639 | ---------- |
|
639 | ---------- | |
640 |
|
640 | |||
641 | filename : str |
|
641 | filename : str | |
642 | The path to the file |
|
642 | The path to the file | |
643 | targets : int/str/list of ints/strs |
|
643 | targets : int/str/list of ints/strs | |
644 | the engines on which to execute |
|
644 | the engines on which to execute | |
645 | default : all |
|
645 | default : all | |
646 | block : bool |
|
646 | block : bool | |
647 | whether or not to wait until done |
|
647 | whether or not to wait until done | |
648 | default: self.block |
|
648 | default: self.block | |
649 |
|
649 | |||
650 | """ |
|
650 | """ | |
651 | with open(filename, 'r') as f: |
|
651 | with open(filename, 'r') as f: | |
652 | # add newline in case of trailing indented whitespace |
|
652 | # add newline in case of trailing indented whitespace | |
653 | # which will cause SyntaxError |
|
653 | # which will cause SyntaxError | |
654 | code = f.read()+'\n' |
|
654 | code = f.read()+'\n' | |
655 | return self.execute(code, block=block, targets=targets) |
|
655 | return self.execute(code, block=block, targets=targets) | |
656 |
|
656 | |||
657 | def update(self, ns): |
|
657 | def update(self, ns): | |
658 | """update remote namespace with dict `ns` |
|
658 | """update remote namespace with dict `ns` | |
659 |
|
659 | |||
660 | See `push` for details. |
|
660 | See `push` for details. | |
661 | """ |
|
661 | """ | |
662 | return self.push(ns, block=self.block, track=self.track) |
|
662 | return self.push(ns, block=self.block, track=self.track) | |
663 |
|
663 | |||
664 | def push(self, ns, targets=None, block=None, track=None): |
|
664 | def push(self, ns, targets=None, block=None, track=None): | |
665 | """update remote namespace with dict `ns` |
|
665 | """update remote namespace with dict `ns` | |
666 |
|
666 | |||
667 | Parameters |
|
667 | Parameters | |
668 | ---------- |
|
668 | ---------- | |
669 |
|
669 | |||
670 | ns : dict |
|
670 | ns : dict | |
671 | dict of keys with which to update engine namespace(s) |
|
671 | dict of keys with which to update engine namespace(s) | |
672 | block : bool [default : self.block] |
|
672 | block : bool [default : self.block] | |
673 | whether to wait to be notified of engine receipt |
|
673 | whether to wait to be notified of engine receipt | |
674 |
|
674 | |||
675 | """ |
|
675 | """ | |
676 |
|
676 | |||
677 | block = block if block is not None else self.block |
|
677 | block = block if block is not None else self.block | |
678 | track = track if track is not None else self.track |
|
678 | track = track if track is not None else self.track | |
679 | targets = targets if targets is not None else self.targets |
|
679 | targets = targets if targets is not None else self.targets | |
680 | # applier = self.apply_sync if block else self.apply_async |
|
680 | # applier = self.apply_sync if block else self.apply_async | |
681 | if not isinstance(ns, dict): |
|
681 | if not isinstance(ns, dict): | |
682 | raise TypeError("Must be a dict, not %s"%type(ns)) |
|
682 | raise TypeError("Must be a dict, not %s"%type(ns)) | |
683 | return self._really_apply(util._push, kwargs=ns, block=block, track=track, targets=targets) |
|
683 | return self._really_apply(util._push, kwargs=ns, block=block, track=track, targets=targets) | |
684 |
|
684 | |||
685 | def get(self, key_s): |
|
685 | def get(self, key_s): | |
686 | """get object(s) by `key_s` from remote namespace |
|
686 | """get object(s) by `key_s` from remote namespace | |
687 |
|
687 | |||
688 | see `pull` for details. |
|
688 | see `pull` for details. | |
689 | """ |
|
689 | """ | |
690 | # block = block if block is not None else self.block |
|
690 | # block = block if block is not None else self.block | |
691 | return self.pull(key_s, block=True) |
|
691 | return self.pull(key_s, block=True) | |
692 |
|
692 | |||
693 | def pull(self, names, targets=None, block=None): |
|
693 | def pull(self, names, targets=None, block=None): | |
694 | """get object(s) by `name` from remote namespace |
|
694 | """get object(s) by `name` from remote namespace | |
695 |
|
695 | |||
696 | will return one object if it is a key. |
|
696 | will return one object if it is a key. | |
697 | can also take a list of keys, in which case it will return a list of objects. |
|
697 | can also take a list of keys, in which case it will return a list of objects. | |
698 | """ |
|
698 | """ | |
699 | block = block if block is not None else self.block |
|
699 | block = block if block is not None else self.block | |
700 | targets = targets if targets is not None else self.targets |
|
700 | targets = targets if targets is not None else self.targets | |
701 | applier = self.apply_sync if block else self.apply_async |
|
701 | applier = self.apply_sync if block else self.apply_async | |
702 | if isinstance(names, basestring): |
|
702 | if isinstance(names, basestring): | |
703 | pass |
|
703 | pass | |
704 | elif isinstance(names, (list,tuple,set)): |
|
704 | elif isinstance(names, (list,tuple,set)): | |
705 | for key in names: |
|
705 | for key in names: | |
706 | if not isinstance(key, basestring): |
|
706 | if not isinstance(key, basestring): | |
707 | raise TypeError("keys must be str, not type %r"%type(key)) |
|
707 | raise TypeError("keys must be str, not type %r"%type(key)) | |
708 | else: |
|
708 | else: | |
709 | raise TypeError("names must be strs, not %r"%names) |
|
709 | raise TypeError("names must be strs, not %r"%names) | |
710 | return self._really_apply(util._pull, (names,), block=block, targets=targets) |
|
710 | return self._really_apply(util._pull, (names,), block=block, targets=targets) | |
711 |
|
711 | |||
712 | def scatter(self, key, seq, dist='b', flatten=False, targets=None, block=None, track=None): |
|
712 | def scatter(self, key, seq, dist='b', flatten=False, targets=None, block=None, track=None): | |
713 | """ |
|
713 | """ | |
714 | Partition a Python sequence and send the partitions to a set of engines. |
|
714 | Partition a Python sequence and send the partitions to a set of engines. | |
715 | """ |
|
715 | """ | |
716 | block = block if block is not None else self.block |
|
716 | block = block if block is not None else self.block | |
717 | track = track if track is not None else self.track |
|
717 | track = track if track is not None else self.track | |
718 | targets = targets if targets is not None else self.targets |
|
718 | targets = targets if targets is not None else self.targets | |
719 |
|
719 | |||
720 | # construct integer ID list: |
|
720 | # construct integer ID list: | |
721 | targets = self.client._build_targets(targets)[1] |
|
721 | targets = self.client._build_targets(targets)[1] | |
722 |
|
722 | |||
723 | mapObject = Map.dists[dist]() |
|
723 | mapObject = Map.dists[dist]() | |
724 | nparts = len(targets) |
|
724 | nparts = len(targets) | |
725 | msg_ids = [] |
|
725 | msg_ids = [] | |
726 | trackers = [] |
|
726 | trackers = [] | |
727 | for index, engineid in enumerate(targets): |
|
727 | for index, engineid in enumerate(targets): | |
728 | partition = mapObject.getPartition(seq, index, nparts) |
|
728 | partition = mapObject.getPartition(seq, index, nparts) | |
729 | if flatten and len(partition) == 1: |
|
729 | if flatten and len(partition) == 1: | |
730 | ns = {key: partition[0]} |
|
730 | ns = {key: partition[0]} | |
731 | else: |
|
731 | else: | |
732 | ns = {key: partition} |
|
732 | ns = {key: partition} | |
733 | r = self.push(ns, block=False, track=track, targets=engineid) |
|
733 | r = self.push(ns, block=False, track=track, targets=engineid) | |
734 | msg_ids.extend(r.msg_ids) |
|
734 | msg_ids.extend(r.msg_ids) | |
735 | if track: |
|
735 | if track: | |
736 | trackers.append(r._tracker) |
|
736 | trackers.append(r._tracker) | |
737 |
|
737 | |||
738 | if track: |
|
738 | if track: | |
739 | tracker = zmq.MessageTracker(*trackers) |
|
739 | tracker = zmq.MessageTracker(*trackers) | |
740 | else: |
|
740 | else: | |
741 | tracker = None |
|
741 | tracker = None | |
742 |
|
742 | |||
743 | r = AsyncResult(self.client, msg_ids, fname='scatter', targets=targets, tracker=tracker) |
|
743 | r = AsyncResult(self.client, msg_ids, fname='scatter', targets=targets, tracker=tracker) | |
744 | if block: |
|
744 | if block: | |
745 | r.wait() |
|
745 | r.wait() | |
746 | else: |
|
746 | else: | |
747 | return r |
|
747 | return r | |
748 |
|
748 | |||
749 | @sync_results |
|
749 | @sync_results | |
750 | @save_ids |
|
750 | @save_ids | |
751 | def gather(self, key, dist='b', targets=None, block=None): |
|
751 | def gather(self, key, dist='b', targets=None, block=None): | |
752 | """ |
|
752 | """ | |
753 | Gather a partitioned sequence on a set of engines as a single local seq. |
|
753 | Gather a partitioned sequence on a set of engines as a single local seq. | |
754 | """ |
|
754 | """ | |
755 | block = block if block is not None else self.block |
|
755 | block = block if block is not None else self.block | |
756 | targets = targets if targets is not None else self.targets |
|
756 | targets = targets if targets is not None else self.targets | |
757 | mapObject = Map.dists[dist]() |
|
757 | mapObject = Map.dists[dist]() | |
758 | msg_ids = [] |
|
758 | msg_ids = [] | |
759 |
|
759 | |||
760 | # construct integer ID list: |
|
760 | # construct integer ID list: | |
761 | targets = self.client._build_targets(targets)[1] |
|
761 | targets = self.client._build_targets(targets)[1] | |
762 |
|
762 | |||
763 | for index, engineid in enumerate(targets): |
|
763 | for index, engineid in enumerate(targets): | |
764 | msg_ids.extend(self.pull(key, block=False, targets=engineid).msg_ids) |
|
764 | msg_ids.extend(self.pull(key, block=False, targets=engineid).msg_ids) | |
765 |
|
765 | |||
766 | r = AsyncMapResult(self.client, msg_ids, mapObject, fname='gather') |
|
766 | r = AsyncMapResult(self.client, msg_ids, mapObject, fname='gather') | |
767 |
|
767 | |||
768 | if block: |
|
768 | if block: | |
769 | try: |
|
769 | try: | |
770 | return r.get() |
|
770 | return r.get() | |
771 | except KeyboardInterrupt: |
|
771 | except KeyboardInterrupt: | |
772 | pass |
|
772 | pass | |
773 | return r |
|
773 | return r | |
774 |
|
774 | |||
775 | def __getitem__(self, key): |
|
775 | def __getitem__(self, key): | |
776 | return self.get(key) |
|
776 | return self.get(key) | |
777 |
|
777 | |||
778 | def __setitem__(self,key, value): |
|
778 | def __setitem__(self,key, value): | |
779 | self.update({key:value}) |
|
779 | self.update({key:value}) | |
780 |
|
780 | |||
781 | def clear(self, targets=None, block=False): |
|
781 | def clear(self, targets=None, block=False): | |
782 | """Clear the remote namespaces on my engines.""" |
|
782 | """Clear the remote namespaces on my engines.""" | |
783 | block = block if block is not None else self.block |
|
783 | block = block if block is not None else self.block | |
784 | targets = targets if targets is not None else self.targets |
|
784 | targets = targets if targets is not None else self.targets | |
785 | return self.client.clear(targets=targets, block=block) |
|
785 | return self.client.clear(targets=targets, block=block) | |
786 |
|
786 | |||
787 | def kill(self, targets=None, block=True): |
|
787 | def kill(self, targets=None, block=True): | |
788 | """Kill my engines.""" |
|
788 | """Kill my engines.""" | |
789 | block = block if block is not None else self.block |
|
789 | block = block if block is not None else self.block | |
790 | targets = targets if targets is not None else self.targets |
|
790 | targets = targets if targets is not None else self.targets | |
791 | return self.client.kill(targets=targets, block=block) |
|
791 | return self.client.kill(targets=targets, block=block) | |
792 |
|
792 | |||
793 | #---------------------------------------- |
|
793 | #---------------------------------------- | |
794 | # activate for %px, %autopx, etc. magics |
|
794 | # activate for %px, %autopx, etc. magics | |
795 | #---------------------------------------- |
|
795 | #---------------------------------------- | |
796 |
|
796 | |||
797 | def activate(self, suffix=''): |
|
797 | def activate(self, suffix=''): | |
798 | """Activate IPython magics associated with this View |
|
798 | """Activate IPython magics associated with this View | |
799 |
|
799 | |||
800 | Defines the magics `%px, %autopx, %pxresult, %%px, %pxconfig` |
|
800 | Defines the magics `%px, %autopx, %pxresult, %%px, %pxconfig` | |
801 |
|
801 | |||
802 | Parameters |
|
802 | Parameters | |
803 | ---------- |
|
803 | ---------- | |
804 |
|
804 | |||
805 | suffix: str [default: ''] |
|
805 | suffix: str [default: ''] | |
806 | The suffix, if any, for the magics. This allows you to have |
|
806 | The suffix, if any, for the magics. This allows you to have | |
807 | multiple views associated with parallel magics at the same time. |
|
807 | multiple views associated with parallel magics at the same time. | |
808 |
|
808 | |||
809 | e.g. ``rc[::2].activate(suffix='_even')`` will give you |
|
809 | e.g. ``rc[::2].activate(suffix='_even')`` will give you | |
810 | the magics ``%px_even``, ``%pxresult_even``, etc. for running magics |
|
810 | the magics ``%px_even``, ``%pxresult_even``, etc. for running magics | |
811 | on the even engines. |
|
811 | on the even engines. | |
812 | """ |
|
812 | """ | |
813 |
|
813 | |||
814 | from IPython.parallel.client.magics import ParallelMagics |
|
814 | from IPython.parallel.client.magics import ParallelMagics | |
815 |
|
815 | |||
816 | try: |
|
816 | try: | |
817 | # This is injected into __builtins__. |
|
817 | # This is injected into __builtins__. | |
818 | ip = get_ipython() |
|
818 | ip = get_ipython() | |
819 | except NameError: |
|
819 | except NameError: | |
820 | print "The IPython parallel magics (%px, etc.) only work within IPython." |
|
820 | print "The IPython parallel magics (%px, etc.) only work within IPython." | |
821 | return |
|
821 | return | |
822 |
|
822 | |||
823 | M = ParallelMagics(ip, self, suffix) |
|
823 | M = ParallelMagics(ip, self, suffix) | |
824 | ip.magics_manager.register(M) |
|
824 | ip.magics_manager.register(M) | |
825 |
|
825 | |||
826 |
|
826 | |||
827 | @skip_doctest |
|
827 | @skip_doctest | |
828 | class LoadBalancedView(View): |
|
828 | class LoadBalancedView(View): | |
829 | """An load-balancing View that only executes via the Task scheduler. |
|
829 | """An load-balancing View that only executes via the Task scheduler. | |
830 |
|
830 | |||
831 | Load-balanced views can be created with the client's `view` method: |
|
831 | Load-balanced views can be created with the client's `view` method: | |
832 |
|
832 | |||
833 | >>> v = client.load_balanced_view() |
|
833 | >>> v = client.load_balanced_view() | |
834 |
|
834 | |||
835 | or targets can be specified, to restrict the potential destinations: |
|
835 | or targets can be specified, to restrict the potential destinations: | |
836 |
|
836 | |||
837 | >>> v = client.client.load_balanced_view([1,3]) |
|
837 | >>> v = client.client.load_balanced_view([1,3]) | |
838 |
|
838 | |||
839 | which would restrict loadbalancing to between engines 1 and 3. |
|
839 | which would restrict loadbalancing to between engines 1 and 3. | |
840 |
|
840 | |||
841 | """ |
|
841 | """ | |
842 |
|
842 | |||
843 | follow=Any() |
|
843 | follow=Any() | |
844 | after=Any() |
|
844 | after=Any() | |
845 | timeout=CFloat() |
|
845 | timeout=CFloat() | |
846 | retries = Integer(0) |
|
846 | retries = Integer(0) | |
847 |
|
847 | |||
848 | _task_scheme = Any() |
|
848 | _task_scheme = Any() | |
849 | _flag_names = List(['targets', 'block', 'track', 'follow', 'after', 'timeout', 'retries']) |
|
849 | _flag_names = List(['targets', 'block', 'track', 'follow', 'after', 'timeout', 'retries']) | |
850 |
|
850 | |||
851 | def __init__(self, client=None, socket=None, **flags): |
|
851 | def __init__(self, client=None, socket=None, **flags): | |
852 | super(LoadBalancedView, self).__init__(client=client, socket=socket, **flags) |
|
852 | super(LoadBalancedView, self).__init__(client=client, socket=socket, **flags) | |
853 | self._task_scheme=client._task_scheme |
|
853 | self._task_scheme=client._task_scheme | |
854 |
|
854 | |||
855 | def _validate_dependency(self, dep): |
|
855 | def _validate_dependency(self, dep): | |
856 | """validate a dependency. |
|
856 | """validate a dependency. | |
857 |
|
857 | |||
858 | For use in `set_flags`. |
|
858 | For use in `set_flags`. | |
859 | """ |
|
859 | """ | |
860 | if dep is None or isinstance(dep, (basestring, AsyncResult, Dependency)): |
|
860 | if dep is None or isinstance(dep, (basestring, AsyncResult, Dependency)): | |
861 | return True |
|
861 | return True | |
862 | elif isinstance(dep, (list,set, tuple)): |
|
862 | elif isinstance(dep, (list,set, tuple)): | |
863 | for d in dep: |
|
863 | for d in dep: | |
864 | if not isinstance(d, (basestring, AsyncResult)): |
|
864 | if not isinstance(d, (basestring, AsyncResult)): | |
865 | return False |
|
865 | return False | |
866 | elif isinstance(dep, dict): |
|
866 | elif isinstance(dep, dict): | |
867 | if set(dep.keys()) != set(Dependency().as_dict().keys()): |
|
867 | if set(dep.keys()) != set(Dependency().as_dict().keys()): | |
868 | return False |
|
868 | return False | |
869 | if not isinstance(dep['msg_ids'], list): |
|
869 | if not isinstance(dep['msg_ids'], list): | |
870 | return False |
|
870 | return False | |
871 | for d in dep['msg_ids']: |
|
871 | for d in dep['msg_ids']: | |
872 | if not isinstance(d, basestring): |
|
872 | if not isinstance(d, basestring): | |
873 | return False |
|
873 | return False | |
874 | else: |
|
874 | else: | |
875 | return False |
|
875 | return False | |
876 |
|
876 | |||
877 | return True |
|
877 | return True | |
878 |
|
878 | |||
879 | def _render_dependency(self, dep): |
|
879 | def _render_dependency(self, dep): | |
880 | """helper for building jsonable dependencies from various input forms.""" |
|
880 | """helper for building jsonable dependencies from various input forms.""" | |
881 | if isinstance(dep, Dependency): |
|
881 | if isinstance(dep, Dependency): | |
882 | return dep.as_dict() |
|
882 | return dep.as_dict() | |
883 | elif isinstance(dep, AsyncResult): |
|
883 | elif isinstance(dep, AsyncResult): | |
884 | return dep.msg_ids |
|
884 | return dep.msg_ids | |
885 | elif dep is None: |
|
885 | elif dep is None: | |
886 | return [] |
|
886 | return [] | |
887 | else: |
|
887 | else: | |
888 | # pass to Dependency constructor |
|
888 | # pass to Dependency constructor | |
889 | return list(Dependency(dep)) |
|
889 | return list(Dependency(dep)) | |
890 |
|
890 | |||
891 | def set_flags(self, **kwargs): |
|
891 | def set_flags(self, **kwargs): | |
892 | """set my attribute flags by keyword. |
|
892 | """set my attribute flags by keyword. | |
893 |
|
893 | |||
894 | A View is a wrapper for the Client's apply method, but with attributes |
|
894 | A View is a wrapper for the Client's apply method, but with attributes | |
895 | that specify keyword arguments, those attributes can be set by keyword |
|
895 | that specify keyword arguments, those attributes can be set by keyword | |
896 | argument with this method. |
|
896 | argument with this method. | |
897 |
|
897 | |||
898 | Parameters |
|
898 | Parameters | |
899 | ---------- |
|
899 | ---------- | |
900 |
|
900 | |||
901 | block : bool |
|
901 | block : bool | |
902 | whether to wait for results |
|
902 | whether to wait for results | |
903 | track : bool |
|
903 | track : bool | |
904 | whether to create a MessageTracker to allow the user to |
|
904 | whether to create a MessageTracker to allow the user to | |
905 | safely edit after arrays and buffers during non-copying |
|
905 | safely edit after arrays and buffers during non-copying | |
906 | sends. |
|
906 | sends. | |
907 |
|
907 | |||
908 | after : Dependency or collection of msg_ids |
|
908 | after : Dependency or collection of msg_ids | |
909 | Only for load-balanced execution (targets=None) |
|
909 | Only for load-balanced execution (targets=None) | |
910 | Specify a list of msg_ids as a time-based dependency. |
|
910 | Specify a list of msg_ids as a time-based dependency. | |
911 | This job will only be run *after* the dependencies |
|
911 | This job will only be run *after* the dependencies | |
912 | have been met. |
|
912 | have been met. | |
913 |
|
913 | |||
914 | follow : Dependency or collection of msg_ids |
|
914 | follow : Dependency or collection of msg_ids | |
915 | Only for load-balanced execution (targets=None) |
|
915 | Only for load-balanced execution (targets=None) | |
916 | Specify a list of msg_ids as a location-based dependency. |
|
916 | Specify a list of msg_ids as a location-based dependency. | |
917 | This job will only be run on an engine where this dependency |
|
917 | This job will only be run on an engine where this dependency | |
918 | is met. |
|
918 | is met. | |
919 |
|
919 | |||
920 | timeout : float/int or None |
|
920 | timeout : float/int or None | |
921 | Only for load-balanced execution (targets=None) |
|
921 | Only for load-balanced execution (targets=None) | |
922 | Specify an amount of time (in seconds) for the scheduler to |
|
922 | Specify an amount of time (in seconds) for the scheduler to | |
923 | wait for dependencies to be met before failing with a |
|
923 | wait for dependencies to be met before failing with a | |
924 | DependencyTimeout. |
|
924 | DependencyTimeout. | |
925 |
|
925 | |||
926 | retries : int |
|
926 | retries : int | |
927 | Number of times a task will be retried on failure. |
|
927 | Number of times a task will be retried on failure. | |
928 | """ |
|
928 | """ | |
929 |
|
929 | |||
930 | super(LoadBalancedView, self).set_flags(**kwargs) |
|
930 | super(LoadBalancedView, self).set_flags(**kwargs) | |
931 | for name in ('follow', 'after'): |
|
931 | for name in ('follow', 'after'): | |
932 | if name in kwargs: |
|
932 | if name in kwargs: | |
933 | value = kwargs[name] |
|
933 | value = kwargs[name] | |
934 | if self._validate_dependency(value): |
|
934 | if self._validate_dependency(value): | |
935 | setattr(self, name, value) |
|
935 | setattr(self, name, value) | |
936 | else: |
|
936 | else: | |
937 | raise ValueError("Invalid dependency: %r"%value) |
|
937 | raise ValueError("Invalid dependency: %r"%value) | |
938 | if 'timeout' in kwargs: |
|
938 | if 'timeout' in kwargs: | |
939 | t = kwargs['timeout'] |
|
939 | t = kwargs['timeout'] | |
940 | if not isinstance(t, (int, long, float, type(None))): |
|
940 | if not isinstance(t, (int, long, float, type(None))): | |
941 | raise TypeError("Invalid type for timeout: %r"%type(t)) |
|
941 | raise TypeError("Invalid type for timeout: %r"%type(t)) | |
942 | if t is not None: |
|
942 | if t is not None: | |
943 | if t < 0: |
|
943 | if t < 0: | |
944 | raise ValueError("Invalid timeout: %s"%t) |
|
944 | raise ValueError("Invalid timeout: %s"%t) | |
945 | self.timeout = t |
|
945 | self.timeout = t | |
946 |
|
946 | |||
947 | @sync_results |
|
947 | @sync_results | |
948 | @save_ids |
|
948 | @save_ids | |
949 | def _really_apply(self, f, args=None, kwargs=None, block=None, track=None, |
|
949 | def _really_apply(self, f, args=None, kwargs=None, block=None, track=None, | |
950 | after=None, follow=None, timeout=None, |
|
950 | after=None, follow=None, timeout=None, | |
951 | targets=None, retries=None): |
|
951 | targets=None, retries=None): | |
952 | """calls f(*args, **kwargs) on a remote engine, returning the result. |
|
952 | """calls f(*args, **kwargs) on a remote engine, returning the result. | |
953 |
|
953 | |||
954 | This method temporarily sets all of `apply`'s flags for a single call. |
|
954 | This method temporarily sets all of `apply`'s flags for a single call. | |
955 |
|
955 | |||
956 | Parameters |
|
956 | Parameters | |
957 | ---------- |
|
957 | ---------- | |
958 |
|
958 | |||
959 | f : callable |
|
959 | f : callable | |
960 |
|
960 | |||
961 | args : list [default: empty] |
|
961 | args : list [default: empty] | |
962 |
|
962 | |||
963 | kwargs : dict [default: empty] |
|
963 | kwargs : dict [default: empty] | |
964 |
|
964 | |||
965 | block : bool [default: self.block] |
|
965 | block : bool [default: self.block] | |
966 | whether to block |
|
966 | whether to block | |
967 | track : bool [default: self.track] |
|
967 | track : bool [default: self.track] | |
968 | whether to ask zmq to track the message, for safe non-copying sends |
|
968 | whether to ask zmq to track the message, for safe non-copying sends | |
969 |
|
969 | |||
970 | !!!!!! TODO: THE REST HERE !!!! |
|
970 | !!!!!! TODO: THE REST HERE !!!! | |
971 |
|
971 | |||
972 | Returns |
|
972 | Returns | |
973 | ------- |
|
973 | ------- | |
974 |
|
974 | |||
975 | if self.block is False: |
|
975 | if self.block is False: | |
976 | returns AsyncResult |
|
976 | returns AsyncResult | |
977 | else: |
|
977 | else: | |
978 | returns actual result of f(*args, **kwargs) on the engine(s) |
|
978 | returns actual result of f(*args, **kwargs) on the engine(s) | |
979 | This will be a list of self.targets is also a list (even length 1), or |
|
979 | This will be a list of self.targets is also a list (even length 1), or | |
980 | the single result if self.targets is an integer engine id |
|
980 | the single result if self.targets is an integer engine id | |
981 | """ |
|
981 | """ | |
982 |
|
982 | |||
983 | # validate whether we can run |
|
983 | # validate whether we can run | |
984 | if self._socket.closed: |
|
984 | if self._socket.closed: | |
985 | msg = "Task farming is disabled" |
|
985 | msg = "Task farming is disabled" | |
986 | if self._task_scheme == 'pure': |
|
986 | if self._task_scheme == 'pure': | |
987 | msg += " because the pure ZMQ scheduler cannot handle" |
|
987 | msg += " because the pure ZMQ scheduler cannot handle" | |
988 | msg += " disappearing engines." |
|
988 | msg += " disappearing engines." | |
989 | raise RuntimeError(msg) |
|
989 | raise RuntimeError(msg) | |
990 |
|
990 | |||
991 | if self._task_scheme == 'pure': |
|
991 | if self._task_scheme == 'pure': | |
992 | # pure zmq scheme doesn't support extra features |
|
992 | # pure zmq scheme doesn't support extra features | |
993 | msg = "Pure ZMQ scheduler doesn't support the following flags:" |
|
993 | msg = "Pure ZMQ scheduler doesn't support the following flags:" | |
994 | "follow, after, retries, targets, timeout" |
|
994 | "follow, after, retries, targets, timeout" | |
995 | if (follow or after or retries or targets or timeout): |
|
995 | if (follow or after or retries or targets or timeout): | |
996 | # hard fail on Scheduler flags |
|
996 | # hard fail on Scheduler flags | |
997 | raise RuntimeError(msg) |
|
997 | raise RuntimeError(msg) | |
998 | if isinstance(f, dependent): |
|
998 | if isinstance(f, dependent): | |
999 | # soft warn on functional dependencies |
|
999 | # soft warn on functional dependencies | |
1000 | warnings.warn(msg, RuntimeWarning) |
|
1000 | warnings.warn(msg, RuntimeWarning) | |
1001 |
|
1001 | |||
1002 | # build args |
|
1002 | # build args | |
1003 | args = [] if args is None else args |
|
1003 | args = [] if args is None else args | |
1004 | kwargs = {} if kwargs is None else kwargs |
|
1004 | kwargs = {} if kwargs is None else kwargs | |
1005 | block = self.block if block is None else block |
|
1005 | block = self.block if block is None else block | |
1006 | track = self.track if track is None else track |
|
1006 | track = self.track if track is None else track | |
1007 | after = self.after if after is None else after |
|
1007 | after = self.after if after is None else after | |
1008 | retries = self.retries if retries is None else retries |
|
1008 | retries = self.retries if retries is None else retries | |
1009 | follow = self.follow if follow is None else follow |
|
1009 | follow = self.follow if follow is None else follow | |
1010 | timeout = self.timeout if timeout is None else timeout |
|
1010 | timeout = self.timeout if timeout is None else timeout | |
1011 | targets = self.targets if targets is None else targets |
|
1011 | targets = self.targets if targets is None else targets | |
1012 |
|
1012 | |||
1013 | if not isinstance(retries, int): |
|
1013 | if not isinstance(retries, int): | |
1014 | raise TypeError('retries must be int, not %r'%type(retries)) |
|
1014 | raise TypeError('retries must be int, not %r'%type(retries)) | |
1015 |
|
1015 | |||
1016 | if targets is None: |
|
1016 | if targets is None: | |
1017 | idents = [] |
|
1017 | idents = [] | |
1018 | else: |
|
1018 | else: | |
1019 | idents = self.client._build_targets(targets)[0] |
|
1019 | idents = self.client._build_targets(targets)[0] | |
1020 | # ensure *not* bytes |
|
1020 | # ensure *not* bytes | |
1021 | idents = [ ident.decode() for ident in idents ] |
|
1021 | idents = [ ident.decode() for ident in idents ] | |
1022 |
|
1022 | |||
1023 | after = self._render_dependency(after) |
|
1023 | after = self._render_dependency(after) | |
1024 | follow = self._render_dependency(follow) |
|
1024 | follow = self._render_dependency(follow) | |
1025 |
|
|
1025 | metadata = dict(after=after, follow=follow, timeout=timeout, targets=idents, retries=retries) | |
1026 |
|
1026 | |||
1027 | msg = self.client.send_apply_request(self._socket, f, args, kwargs, track=track, |
|
1027 | msg = self.client.send_apply_request(self._socket, f, args, kwargs, track=track, | |
1028 |
|
|
1028 | metadata=metadata) | |
1029 | tracker = None if track is False else msg['tracker'] |
|
1029 | tracker = None if track is False else msg['tracker'] | |
1030 |
|
1030 | |||
1031 | ar = AsyncResult(self.client, msg['header']['msg_id'], fname=getname(f), targets=None, tracker=tracker) |
|
1031 | ar = AsyncResult(self.client, msg['header']['msg_id'], fname=getname(f), targets=None, tracker=tracker) | |
1032 |
|
1032 | |||
1033 | if block: |
|
1033 | if block: | |
1034 | try: |
|
1034 | try: | |
1035 | return ar.get() |
|
1035 | return ar.get() | |
1036 | except KeyboardInterrupt: |
|
1036 | except KeyboardInterrupt: | |
1037 | pass |
|
1037 | pass | |
1038 | return ar |
|
1038 | return ar | |
1039 |
|
1039 | |||
1040 | @spin_after |
|
1040 | @spin_after | |
1041 | @save_ids |
|
1041 | @save_ids | |
1042 | def map(self, f, *sequences, **kwargs): |
|
1042 | def map(self, f, *sequences, **kwargs): | |
1043 | """view.map(f, *sequences, block=self.block, chunksize=1, ordered=True) => list|AsyncMapResult |
|
1043 | """view.map(f, *sequences, block=self.block, chunksize=1, ordered=True) => list|AsyncMapResult | |
1044 |
|
1044 | |||
1045 | Parallel version of builtin `map`, load-balanced by this View. |
|
1045 | Parallel version of builtin `map`, load-balanced by this View. | |
1046 |
|
1046 | |||
1047 | `block`, and `chunksize` can be specified by keyword only. |
|
1047 | `block`, and `chunksize` can be specified by keyword only. | |
1048 |
|
1048 | |||
1049 | Each `chunksize` elements will be a separate task, and will be |
|
1049 | Each `chunksize` elements will be a separate task, and will be | |
1050 | load-balanced. This lets individual elements be available for iteration |
|
1050 | load-balanced. This lets individual elements be available for iteration | |
1051 | as soon as they arrive. |
|
1051 | as soon as they arrive. | |
1052 |
|
1052 | |||
1053 | Parameters |
|
1053 | Parameters | |
1054 | ---------- |
|
1054 | ---------- | |
1055 |
|
1055 | |||
1056 | f : callable |
|
1056 | f : callable | |
1057 | function to be mapped |
|
1057 | function to be mapped | |
1058 | *sequences: one or more sequences of matching length |
|
1058 | *sequences: one or more sequences of matching length | |
1059 | the sequences to be distributed and passed to `f` |
|
1059 | the sequences to be distributed and passed to `f` | |
1060 | block : bool [default self.block] |
|
1060 | block : bool [default self.block] | |
1061 | whether to wait for the result or not |
|
1061 | whether to wait for the result or not | |
1062 | track : bool |
|
1062 | track : bool | |
1063 | whether to create a MessageTracker to allow the user to |
|
1063 | whether to create a MessageTracker to allow the user to | |
1064 | safely edit after arrays and buffers during non-copying |
|
1064 | safely edit after arrays and buffers during non-copying | |
1065 | sends. |
|
1065 | sends. | |
1066 | chunksize : int [default 1] |
|
1066 | chunksize : int [default 1] | |
1067 | how many elements should be in each task. |
|
1067 | how many elements should be in each task. | |
1068 | ordered : bool [default True] |
|
1068 | ordered : bool [default True] | |
1069 | Whether the results should be gathered as they arrive, or enforce |
|
1069 | Whether the results should be gathered as they arrive, or enforce | |
1070 | the order of submission. |
|
1070 | the order of submission. | |
1071 |
|
1071 | |||
1072 | Only applies when iterating through AsyncMapResult as results arrive. |
|
1072 | Only applies when iterating through AsyncMapResult as results arrive. | |
1073 | Has no effect when block=True. |
|
1073 | Has no effect when block=True. | |
1074 |
|
1074 | |||
1075 | Returns |
|
1075 | Returns | |
1076 | ------- |
|
1076 | ------- | |
1077 |
|
1077 | |||
1078 | if block=False: |
|
1078 | if block=False: | |
1079 | AsyncMapResult |
|
1079 | AsyncMapResult | |
1080 | An object like AsyncResult, but which reassembles the sequence of results |
|
1080 | An object like AsyncResult, but which reassembles the sequence of results | |
1081 | into a single list. AsyncMapResults can be iterated through before all |
|
1081 | into a single list. AsyncMapResults can be iterated through before all | |
1082 | results are complete. |
|
1082 | results are complete. | |
1083 | else: |
|
1083 | else: | |
1084 | the result of map(f,*sequences) |
|
1084 | the result of map(f,*sequences) | |
1085 |
|
1085 | |||
1086 | """ |
|
1086 | """ | |
1087 |
|
1087 | |||
1088 | # default |
|
1088 | # default | |
1089 | block = kwargs.get('block', self.block) |
|
1089 | block = kwargs.get('block', self.block) | |
1090 | chunksize = kwargs.get('chunksize', 1) |
|
1090 | chunksize = kwargs.get('chunksize', 1) | |
1091 | ordered = kwargs.get('ordered', True) |
|
1091 | ordered = kwargs.get('ordered', True) | |
1092 |
|
1092 | |||
1093 | keyset = set(kwargs.keys()) |
|
1093 | keyset = set(kwargs.keys()) | |
1094 | extra_keys = keyset.difference_update(set(['block', 'chunksize'])) |
|
1094 | extra_keys = keyset.difference_update(set(['block', 'chunksize'])) | |
1095 | if extra_keys: |
|
1095 | if extra_keys: | |
1096 | raise TypeError("Invalid kwargs: %s"%list(extra_keys)) |
|
1096 | raise TypeError("Invalid kwargs: %s"%list(extra_keys)) | |
1097 |
|
1097 | |||
1098 | assert len(sequences) > 0, "must have some sequences to map onto!" |
|
1098 | assert len(sequences) > 0, "must have some sequences to map onto!" | |
1099 |
|
1099 | |||
1100 | pf = ParallelFunction(self, f, block=block, chunksize=chunksize, ordered=ordered) |
|
1100 | pf = ParallelFunction(self, f, block=block, chunksize=chunksize, ordered=ordered) | |
1101 | return pf.map(*sequences) |
|
1101 | return pf.map(*sequences) | |
1102 |
|
1102 | |||
1103 | __all__ = ['LoadBalancedView', 'DirectView'] |
|
1103 | __all__ = ['LoadBalancedView', 'DirectView'] |
@@ -1,1337 +1,1348 b'' | |||||
1 | """The IPython Controller Hub with 0MQ |
|
1 | """The IPython Controller Hub with 0MQ | |
2 | This is the master object that handles connections from engines and clients, |
|
2 | This is the master object that handles connections from engines and clients, | |
3 | and monitors traffic through the various queues. |
|
3 | and monitors traffic through the various queues. | |
4 |
|
4 | |||
5 | Authors: |
|
5 | Authors: | |
6 |
|
6 | |||
7 | * Min RK |
|
7 | * Min RK | |
8 | """ |
|
8 | """ | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 | # Copyright (C) 2010-2011 The IPython Development Team |
|
10 | # Copyright (C) 2010-2011 The IPython Development Team | |
11 | # |
|
11 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Imports |
|
17 | # Imports | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | from __future__ import print_function |
|
19 | from __future__ import print_function | |
20 |
|
20 | |||
21 | import sys |
|
21 | import sys | |
22 | import time |
|
22 | import time | |
23 | from datetime import datetime |
|
23 | from datetime import datetime | |
24 |
|
24 | |||
25 | import zmq |
|
25 | import zmq | |
26 | from zmq.eventloop import ioloop |
|
26 | from zmq.eventloop import ioloop | |
27 | from zmq.eventloop.zmqstream import ZMQStream |
|
27 | from zmq.eventloop.zmqstream import ZMQStream | |
28 |
|
28 | |||
29 | # internal: |
|
29 | # internal: | |
30 | from IPython.utils.importstring import import_item |
|
30 | from IPython.utils.importstring import import_item | |
31 | from IPython.utils.py3compat import cast_bytes |
|
31 | from IPython.utils.py3compat import cast_bytes | |
32 | from IPython.utils.traitlets import ( |
|
32 | from IPython.utils.traitlets import ( | |
33 | HasTraits, Instance, Integer, Unicode, Dict, Set, Tuple, CBytes, DottedObjectName |
|
33 | HasTraits, Instance, Integer, Unicode, Dict, Set, Tuple, CBytes, DottedObjectName | |
34 | ) |
|
34 | ) | |
35 |
|
35 | |||
36 | from IPython.parallel import error, util |
|
36 | from IPython.parallel import error, util | |
37 | from IPython.parallel.factory import RegistrationFactory |
|
37 | from IPython.parallel.factory import RegistrationFactory | |
38 |
|
38 | |||
39 | from IPython.zmq.session import SessionFactory |
|
39 | from IPython.zmq.session import SessionFactory | |
40 |
|
40 | |||
41 | from .heartmonitor import HeartMonitor |
|
41 | from .heartmonitor import HeartMonitor | |
42 |
|
42 | |||
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 | # Code |
|
44 | # Code | |
45 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
46 |
|
46 | |||
47 | def _passer(*args, **kwargs): |
|
47 | def _passer(*args, **kwargs): | |
48 | return |
|
48 | return | |
49 |
|
49 | |||
50 | def _printer(*args, **kwargs): |
|
50 | def _printer(*args, **kwargs): | |
51 | print (args) |
|
51 | print (args) | |
52 | print (kwargs) |
|
52 | print (kwargs) | |
53 |
|
53 | |||
54 | def empty_record(): |
|
54 | def empty_record(): | |
55 | """Return an empty dict with all record keys.""" |
|
55 | """Return an empty dict with all record keys.""" | |
56 | return { |
|
56 | return { | |
57 | 'msg_id' : None, |
|
57 | 'msg_id' : None, | |
58 | 'header' : None, |
|
58 | 'header' : None, | |
|
59 | 'metadata' : None, | |||
59 | 'content': None, |
|
60 | 'content': None, | |
60 | 'buffers': None, |
|
61 | 'buffers': None, | |
61 | 'submitted': None, |
|
62 | 'submitted': None, | |
62 | 'client_uuid' : None, |
|
63 | 'client_uuid' : None, | |
63 | 'engine_uuid' : None, |
|
64 | 'engine_uuid' : None, | |
64 | 'started': None, |
|
65 | 'started': None, | |
65 | 'completed': None, |
|
66 | 'completed': None, | |
66 | 'resubmitted': None, |
|
67 | 'resubmitted': None, | |
67 | 'received': None, |
|
68 | 'received': None, | |
68 | 'result_header' : None, |
|
69 | 'result_header' : None, | |
|
70 | 'result_metadata' : None, | |||
69 | 'result_content' : None, |
|
71 | 'result_content' : None, | |
70 | 'result_buffers' : None, |
|
72 | 'result_buffers' : None, | |
71 | 'queue' : None, |
|
73 | 'queue' : None, | |
72 | 'pyin' : None, |
|
74 | 'pyin' : None, | |
73 | 'pyout': None, |
|
75 | 'pyout': None, | |
74 | 'pyerr': None, |
|
76 | 'pyerr': None, | |
75 | 'stdout': '', |
|
77 | 'stdout': '', | |
76 | 'stderr': '', |
|
78 | 'stderr': '', | |
77 | } |
|
79 | } | |
78 |
|
80 | |||
79 | def init_record(msg): |
|
81 | def init_record(msg): | |
80 | """Initialize a TaskRecord based on a request.""" |
|
82 | """Initialize a TaskRecord based on a request.""" | |
81 | header = msg['header'] |
|
83 | header = msg['header'] | |
82 | return { |
|
84 | return { | |
83 | 'msg_id' : header['msg_id'], |
|
85 | 'msg_id' : header['msg_id'], | |
84 | 'header' : header, |
|
86 | 'header' : header, | |
85 | 'content': msg['content'], |
|
87 | 'content': msg['content'], | |
|
88 | 'metadata': msg['metadata'], | |||
86 | 'buffers': msg['buffers'], |
|
89 | 'buffers': msg['buffers'], | |
87 | 'submitted': header['date'], |
|
90 | 'submitted': header['date'], | |
88 | 'client_uuid' : None, |
|
91 | 'client_uuid' : None, | |
89 | 'engine_uuid' : None, |
|
92 | 'engine_uuid' : None, | |
90 | 'started': None, |
|
93 | 'started': None, | |
91 | 'completed': None, |
|
94 | 'completed': None, | |
92 | 'resubmitted': None, |
|
95 | 'resubmitted': None, | |
93 | 'received': None, |
|
96 | 'received': None, | |
94 | 'result_header' : None, |
|
97 | 'result_header' : None, | |
|
98 | 'result_metadata': None, | |||
95 | 'result_content' : None, |
|
99 | 'result_content' : None, | |
96 | 'result_buffers' : None, |
|
100 | 'result_buffers' : None, | |
97 | 'queue' : None, |
|
101 | 'queue' : None, | |
98 | 'pyin' : None, |
|
102 | 'pyin' : None, | |
99 | 'pyout': None, |
|
103 | 'pyout': None, | |
100 | 'pyerr': None, |
|
104 | 'pyerr': None, | |
101 | 'stdout': '', |
|
105 | 'stdout': '', | |
102 | 'stderr': '', |
|
106 | 'stderr': '', | |
103 | } |
|
107 | } | |
104 |
|
108 | |||
105 |
|
109 | |||
106 | class EngineConnector(HasTraits): |
|
110 | class EngineConnector(HasTraits): | |
107 | """A simple object for accessing the various zmq connections of an object. |
|
111 | """A simple object for accessing the various zmq connections of an object. | |
108 | Attributes are: |
|
112 | Attributes are: | |
109 | id (int): engine ID |
|
113 | id (int): engine ID | |
110 | uuid (str): uuid (unused?) |
|
114 | uuid (str): uuid (unused?) | |
111 | queue (str): identity of queue's DEALER socket |
|
115 | queue (str): identity of queue's DEALER socket | |
112 | registration (str): identity of registration DEALER socket |
|
116 | registration (str): identity of registration DEALER socket | |
113 | heartbeat (str): identity of heartbeat DEALER socket |
|
117 | heartbeat (str): identity of heartbeat DEALER socket | |
114 | """ |
|
118 | """ | |
115 | id=Integer(0) |
|
119 | id=Integer(0) | |
116 | queue=CBytes() |
|
120 | queue=CBytes() | |
117 | control=CBytes() |
|
121 | control=CBytes() | |
118 | registration=CBytes() |
|
122 | registration=CBytes() | |
119 | heartbeat=CBytes() |
|
123 | heartbeat=CBytes() | |
120 | pending=Set() |
|
124 | pending=Set() | |
121 |
|
125 | |||
122 | _db_shortcuts = { |
|
126 | _db_shortcuts = { | |
123 | 'sqlitedb' : 'IPython.parallel.controller.sqlitedb.SQLiteDB', |
|
127 | 'sqlitedb' : 'IPython.parallel.controller.sqlitedb.SQLiteDB', | |
124 | 'mongodb' : 'IPython.parallel.controller.mongodb.MongoDB', |
|
128 | 'mongodb' : 'IPython.parallel.controller.mongodb.MongoDB', | |
125 | 'dictdb' : 'IPython.parallel.controller.dictdb.DictDB', |
|
129 | 'dictdb' : 'IPython.parallel.controller.dictdb.DictDB', | |
126 | 'nodb' : 'IPython.parallel.controller.dictdb.NoDB', |
|
130 | 'nodb' : 'IPython.parallel.controller.dictdb.NoDB', | |
127 | } |
|
131 | } | |
128 |
|
132 | |||
129 | class HubFactory(RegistrationFactory): |
|
133 | class HubFactory(RegistrationFactory): | |
130 | """The Configurable for setting up a Hub.""" |
|
134 | """The Configurable for setting up a Hub.""" | |
131 |
|
135 | |||
132 | # port-pairs for monitoredqueues: |
|
136 | # port-pairs for monitoredqueues: | |
133 | hb = Tuple(Integer,Integer,config=True, |
|
137 | hb = Tuple(Integer,Integer,config=True, | |
134 | help="""DEALER/SUB Port pair for Engine heartbeats""") |
|
138 | help="""DEALER/SUB Port pair for Engine heartbeats""") | |
135 | def _hb_default(self): |
|
139 | def _hb_default(self): | |
136 | return tuple(util.select_random_ports(2)) |
|
140 | return tuple(util.select_random_ports(2)) | |
137 |
|
141 | |||
138 | mux = Tuple(Integer,Integer,config=True, |
|
142 | mux = Tuple(Integer,Integer,config=True, | |
139 | help="""Engine/Client Port pair for MUX queue""") |
|
143 | help="""Engine/Client Port pair for MUX queue""") | |
140 |
|
144 | |||
141 | def _mux_default(self): |
|
145 | def _mux_default(self): | |
142 | return tuple(util.select_random_ports(2)) |
|
146 | return tuple(util.select_random_ports(2)) | |
143 |
|
147 | |||
144 | task = Tuple(Integer,Integer,config=True, |
|
148 | task = Tuple(Integer,Integer,config=True, | |
145 | help="""Engine/Client Port pair for Task queue""") |
|
149 | help="""Engine/Client Port pair for Task queue""") | |
146 | def _task_default(self): |
|
150 | def _task_default(self): | |
147 | return tuple(util.select_random_ports(2)) |
|
151 | return tuple(util.select_random_ports(2)) | |
148 |
|
152 | |||
149 | control = Tuple(Integer,Integer,config=True, |
|
153 | control = Tuple(Integer,Integer,config=True, | |
150 | help="""Engine/Client Port pair for Control queue""") |
|
154 | help="""Engine/Client Port pair for Control queue""") | |
151 |
|
155 | |||
152 | def _control_default(self): |
|
156 | def _control_default(self): | |
153 | return tuple(util.select_random_ports(2)) |
|
157 | return tuple(util.select_random_ports(2)) | |
154 |
|
158 | |||
155 | iopub = Tuple(Integer,Integer,config=True, |
|
159 | iopub = Tuple(Integer,Integer,config=True, | |
156 | help="""Engine/Client Port pair for IOPub relay""") |
|
160 | help="""Engine/Client Port pair for IOPub relay""") | |
157 |
|
161 | |||
158 | def _iopub_default(self): |
|
162 | def _iopub_default(self): | |
159 | return tuple(util.select_random_ports(2)) |
|
163 | return tuple(util.select_random_ports(2)) | |
160 |
|
164 | |||
161 | # single ports: |
|
165 | # single ports: | |
162 | mon_port = Integer(config=True, |
|
166 | mon_port = Integer(config=True, | |
163 | help="""Monitor (SUB) port for queue traffic""") |
|
167 | help="""Monitor (SUB) port for queue traffic""") | |
164 |
|
168 | |||
165 | def _mon_port_default(self): |
|
169 | def _mon_port_default(self): | |
166 | return util.select_random_ports(1)[0] |
|
170 | return util.select_random_ports(1)[0] | |
167 |
|
171 | |||
168 | notifier_port = Integer(config=True, |
|
172 | notifier_port = Integer(config=True, | |
169 | help="""PUB port for sending engine status notifications""") |
|
173 | help="""PUB port for sending engine status notifications""") | |
170 |
|
174 | |||
171 | def _notifier_port_default(self): |
|
175 | def _notifier_port_default(self): | |
172 | return util.select_random_ports(1)[0] |
|
176 | return util.select_random_ports(1)[0] | |
173 |
|
177 | |||
174 | engine_ip = Unicode('127.0.0.1', config=True, |
|
178 | engine_ip = Unicode('127.0.0.1', config=True, | |
175 | help="IP on which to listen for engine connections. [default: loopback]") |
|
179 | help="IP on which to listen for engine connections. [default: loopback]") | |
176 | engine_transport = Unicode('tcp', config=True, |
|
180 | engine_transport = Unicode('tcp', config=True, | |
177 | help="0MQ transport for engine connections. [default: tcp]") |
|
181 | help="0MQ transport for engine connections. [default: tcp]") | |
178 |
|
182 | |||
179 | client_ip = Unicode('127.0.0.1', config=True, |
|
183 | client_ip = Unicode('127.0.0.1', config=True, | |
180 | help="IP on which to listen for client connections. [default: loopback]") |
|
184 | help="IP on which to listen for client connections. [default: loopback]") | |
181 | client_transport = Unicode('tcp', config=True, |
|
185 | client_transport = Unicode('tcp', config=True, | |
182 | help="0MQ transport for client connections. [default : tcp]") |
|
186 | help="0MQ transport for client connections. [default : tcp]") | |
183 |
|
187 | |||
184 | monitor_ip = Unicode('127.0.0.1', config=True, |
|
188 | monitor_ip = Unicode('127.0.0.1', config=True, | |
185 | help="IP on which to listen for monitor messages. [default: loopback]") |
|
189 | help="IP on which to listen for monitor messages. [default: loopback]") | |
186 | monitor_transport = Unicode('tcp', config=True, |
|
190 | monitor_transport = Unicode('tcp', config=True, | |
187 | help="0MQ transport for monitor messages. [default : tcp]") |
|
191 | help="0MQ transport for monitor messages. [default : tcp]") | |
188 |
|
192 | |||
189 | monitor_url = Unicode('') |
|
193 | monitor_url = Unicode('') | |
190 |
|
194 | |||
191 | db_class = DottedObjectName('NoDB', |
|
195 | db_class = DottedObjectName('NoDB', | |
192 | config=True, help="""The class to use for the DB backend |
|
196 | config=True, help="""The class to use for the DB backend | |
193 |
|
197 | |||
194 | Options include: |
|
198 | Options include: | |
195 |
|
199 | |||
196 | SQLiteDB: SQLite |
|
200 | SQLiteDB: SQLite | |
197 | MongoDB : use MongoDB |
|
201 | MongoDB : use MongoDB | |
198 | DictDB : in-memory storage (fastest, but be mindful of memory growth of the Hub) |
|
202 | DictDB : in-memory storage (fastest, but be mindful of memory growth of the Hub) | |
199 | NoDB : disable database altogether (default) |
|
203 | NoDB : disable database altogether (default) | |
200 |
|
204 | |||
201 | """) |
|
205 | """) | |
202 |
|
206 | |||
203 | # not configurable |
|
207 | # not configurable | |
204 | db = Instance('IPython.parallel.controller.dictdb.BaseDB') |
|
208 | db = Instance('IPython.parallel.controller.dictdb.BaseDB') | |
205 | heartmonitor = Instance('IPython.parallel.controller.heartmonitor.HeartMonitor') |
|
209 | heartmonitor = Instance('IPython.parallel.controller.heartmonitor.HeartMonitor') | |
206 |
|
210 | |||
207 | def _ip_changed(self, name, old, new): |
|
211 | def _ip_changed(self, name, old, new): | |
208 | self.engine_ip = new |
|
212 | self.engine_ip = new | |
209 | self.client_ip = new |
|
213 | self.client_ip = new | |
210 | self.monitor_ip = new |
|
214 | self.monitor_ip = new | |
211 | self._update_monitor_url() |
|
215 | self._update_monitor_url() | |
212 |
|
216 | |||
213 | def _update_monitor_url(self): |
|
217 | def _update_monitor_url(self): | |
214 | self.monitor_url = "%s://%s:%i" % (self.monitor_transport, self.monitor_ip, self.mon_port) |
|
218 | self.monitor_url = "%s://%s:%i" % (self.monitor_transport, self.monitor_ip, self.mon_port) | |
215 |
|
219 | |||
216 | def _transport_changed(self, name, old, new): |
|
220 | def _transport_changed(self, name, old, new): | |
217 | self.engine_transport = new |
|
221 | self.engine_transport = new | |
218 | self.client_transport = new |
|
222 | self.client_transport = new | |
219 | self.monitor_transport = new |
|
223 | self.monitor_transport = new | |
220 | self._update_monitor_url() |
|
224 | self._update_monitor_url() | |
221 |
|
225 | |||
222 | def __init__(self, **kwargs): |
|
226 | def __init__(self, **kwargs): | |
223 | super(HubFactory, self).__init__(**kwargs) |
|
227 | super(HubFactory, self).__init__(**kwargs) | |
224 | self._update_monitor_url() |
|
228 | self._update_monitor_url() | |
225 |
|
229 | |||
226 |
|
230 | |||
227 | def construct(self): |
|
231 | def construct(self): | |
228 | self.init_hub() |
|
232 | self.init_hub() | |
229 |
|
233 | |||
230 | def start(self): |
|
234 | def start(self): | |
231 | self.heartmonitor.start() |
|
235 | self.heartmonitor.start() | |
232 | self.log.info("Heartmonitor started") |
|
236 | self.log.info("Heartmonitor started") | |
233 |
|
237 | |||
234 | def init_hub(self): |
|
238 | def init_hub(self): | |
235 | """construct""" |
|
239 | """construct""" | |
236 | client_iface = "%s://%s:" % (self.client_transport, self.client_ip) + "%i" |
|
240 | client_iface = "%s://%s:" % (self.client_transport, self.client_ip) + "%i" | |
237 | engine_iface = "%s://%s:" % (self.engine_transport, self.engine_ip) + "%i" |
|
241 | engine_iface = "%s://%s:" % (self.engine_transport, self.engine_ip) + "%i" | |
238 |
|
242 | |||
239 | ctx = self.context |
|
243 | ctx = self.context | |
240 | loop = self.loop |
|
244 | loop = self.loop | |
241 |
|
245 | |||
242 | # Registrar socket |
|
246 | # Registrar socket | |
243 | q = ZMQStream(ctx.socket(zmq.ROUTER), loop) |
|
247 | q = ZMQStream(ctx.socket(zmq.ROUTER), loop) | |
244 | q.bind(client_iface % self.regport) |
|
248 | q.bind(client_iface % self.regport) | |
245 | self.log.info("Hub listening on %s for registration.", client_iface % self.regport) |
|
249 | self.log.info("Hub listening on %s for registration.", client_iface % self.regport) | |
246 | if self.client_ip != self.engine_ip: |
|
250 | if self.client_ip != self.engine_ip: | |
247 | q.bind(engine_iface % self.regport) |
|
251 | q.bind(engine_iface % self.regport) | |
248 | self.log.info("Hub listening on %s for registration.", engine_iface % self.regport) |
|
252 | self.log.info("Hub listening on %s for registration.", engine_iface % self.regport) | |
249 |
|
253 | |||
250 | ### Engine connections ### |
|
254 | ### Engine connections ### | |
251 |
|
255 | |||
252 | # heartbeat |
|
256 | # heartbeat | |
253 | hpub = ctx.socket(zmq.PUB) |
|
257 | hpub = ctx.socket(zmq.PUB) | |
254 | hpub.bind(engine_iface % self.hb[0]) |
|
258 | hpub.bind(engine_iface % self.hb[0]) | |
255 | hrep = ctx.socket(zmq.ROUTER) |
|
259 | hrep = ctx.socket(zmq.ROUTER) | |
256 | hrep.bind(engine_iface % self.hb[1]) |
|
260 | hrep.bind(engine_iface % self.hb[1]) | |
257 | self.heartmonitor = HeartMonitor(loop=loop, config=self.config, log=self.log, |
|
261 | self.heartmonitor = HeartMonitor(loop=loop, config=self.config, log=self.log, | |
258 | pingstream=ZMQStream(hpub,loop), |
|
262 | pingstream=ZMQStream(hpub,loop), | |
259 | pongstream=ZMQStream(hrep,loop) |
|
263 | pongstream=ZMQStream(hrep,loop) | |
260 | ) |
|
264 | ) | |
261 |
|
265 | |||
262 | ### Client connections ### |
|
266 | ### Client connections ### | |
263 | # Notifier socket |
|
267 | # Notifier socket | |
264 | n = ZMQStream(ctx.socket(zmq.PUB), loop) |
|
268 | n = ZMQStream(ctx.socket(zmq.PUB), loop) | |
265 | n.bind(client_iface%self.notifier_port) |
|
269 | n.bind(client_iface%self.notifier_port) | |
266 |
|
270 | |||
267 | ### build and launch the queues ### |
|
271 | ### build and launch the queues ### | |
268 |
|
272 | |||
269 | # monitor socket |
|
273 | # monitor socket | |
270 | sub = ctx.socket(zmq.SUB) |
|
274 | sub = ctx.socket(zmq.SUB) | |
271 | sub.setsockopt(zmq.SUBSCRIBE, b"") |
|
275 | sub.setsockopt(zmq.SUBSCRIBE, b"") | |
272 | sub.bind(self.monitor_url) |
|
276 | sub.bind(self.monitor_url) | |
273 | sub.bind('inproc://monitor') |
|
277 | sub.bind('inproc://monitor') | |
274 | sub = ZMQStream(sub, loop) |
|
278 | sub = ZMQStream(sub, loop) | |
275 |
|
279 | |||
276 | # connect the db |
|
280 | # connect the db | |
277 | db_class = _db_shortcuts.get(self.db_class.lower(), self.db_class) |
|
281 | db_class = _db_shortcuts.get(self.db_class.lower(), self.db_class) | |
278 | self.log.info('Hub using DB backend: %r', (db_class.split('.')[-1])) |
|
282 | self.log.info('Hub using DB backend: %r', (db_class.split('.')[-1])) | |
279 | self.db = import_item(str(db_class))(session=self.session.session, |
|
283 | self.db = import_item(str(db_class))(session=self.session.session, | |
280 | config=self.config, log=self.log) |
|
284 | config=self.config, log=self.log) | |
281 | time.sleep(.25) |
|
285 | time.sleep(.25) | |
282 | try: |
|
286 | try: | |
283 | scheme = self.config.TaskScheduler.scheme_name |
|
287 | scheme = self.config.TaskScheduler.scheme_name | |
284 | except AttributeError: |
|
288 | except AttributeError: | |
285 | from .scheduler import TaskScheduler |
|
289 | from .scheduler import TaskScheduler | |
286 | scheme = TaskScheduler.scheme_name.get_default_value() |
|
290 | scheme = TaskScheduler.scheme_name.get_default_value() | |
287 | # build connection dicts |
|
291 | # build connection dicts | |
288 | self.engine_info = { |
|
292 | self.engine_info = { | |
289 | 'control' : engine_iface%self.control[1], |
|
293 | 'control' : engine_iface%self.control[1], | |
290 | 'mux': engine_iface%self.mux[1], |
|
294 | 'mux': engine_iface%self.mux[1], | |
291 | 'heartbeat': (engine_iface%self.hb[0], engine_iface%self.hb[1]), |
|
295 | 'heartbeat': (engine_iface%self.hb[0], engine_iface%self.hb[1]), | |
292 | 'task' : engine_iface%self.task[1], |
|
296 | 'task' : engine_iface%self.task[1], | |
293 | 'iopub' : engine_iface%self.iopub[1], |
|
297 | 'iopub' : engine_iface%self.iopub[1], | |
294 | # 'monitor' : engine_iface%self.mon_port, |
|
298 | # 'monitor' : engine_iface%self.mon_port, | |
295 | } |
|
299 | } | |
296 |
|
300 | |||
297 | self.client_info = { |
|
301 | self.client_info = { | |
298 | 'control' : client_iface%self.control[0], |
|
302 | 'control' : client_iface%self.control[0], | |
299 | 'mux': client_iface%self.mux[0], |
|
303 | 'mux': client_iface%self.mux[0], | |
300 | 'task' : (scheme, client_iface%self.task[0]), |
|
304 | 'task' : (scheme, client_iface%self.task[0]), | |
301 | 'iopub' : client_iface%self.iopub[0], |
|
305 | 'iopub' : client_iface%self.iopub[0], | |
302 | 'notification': client_iface%self.notifier_port |
|
306 | 'notification': client_iface%self.notifier_port | |
303 | } |
|
307 | } | |
304 | self.log.debug("Hub engine addrs: %s", self.engine_info) |
|
308 | self.log.debug("Hub engine addrs: %s", self.engine_info) | |
305 | self.log.debug("Hub client addrs: %s", self.client_info) |
|
309 | self.log.debug("Hub client addrs: %s", self.client_info) | |
306 |
|
310 | |||
307 | # resubmit stream |
|
311 | # resubmit stream | |
308 | r = ZMQStream(ctx.socket(zmq.DEALER), loop) |
|
312 | r = ZMQStream(ctx.socket(zmq.DEALER), loop) | |
309 | url = util.disambiguate_url(self.client_info['task'][-1]) |
|
313 | url = util.disambiguate_url(self.client_info['task'][-1]) | |
310 | r.setsockopt(zmq.IDENTITY, self.session.bsession) |
|
314 | r.setsockopt(zmq.IDENTITY, self.session.bsession) | |
311 | r.connect(url) |
|
315 | r.connect(url) | |
312 |
|
316 | |||
313 | self.hub = Hub(loop=loop, session=self.session, monitor=sub, heartmonitor=self.heartmonitor, |
|
317 | self.hub = Hub(loop=loop, session=self.session, monitor=sub, heartmonitor=self.heartmonitor, | |
314 | query=q, notifier=n, resubmit=r, db=self.db, |
|
318 | query=q, notifier=n, resubmit=r, db=self.db, | |
315 | engine_info=self.engine_info, client_info=self.client_info, |
|
319 | engine_info=self.engine_info, client_info=self.client_info, | |
316 | log=self.log) |
|
320 | log=self.log) | |
317 |
|
321 | |||
318 |
|
322 | |||
319 | class Hub(SessionFactory): |
|
323 | class Hub(SessionFactory): | |
320 | """The IPython Controller Hub with 0MQ connections |
|
324 | """The IPython Controller Hub with 0MQ connections | |
321 |
|
325 | |||
322 | Parameters |
|
326 | Parameters | |
323 | ========== |
|
327 | ========== | |
324 | loop: zmq IOLoop instance |
|
328 | loop: zmq IOLoop instance | |
325 | session: Session object |
|
329 | session: Session object | |
326 | <removed> context: zmq context for creating new connections (?) |
|
330 | <removed> context: zmq context for creating new connections (?) | |
327 | queue: ZMQStream for monitoring the command queue (SUB) |
|
331 | queue: ZMQStream for monitoring the command queue (SUB) | |
328 | query: ZMQStream for engine registration and client queries requests (ROUTER) |
|
332 | query: ZMQStream for engine registration and client queries requests (ROUTER) | |
329 | heartbeat: HeartMonitor object checking the pulse of the engines |
|
333 | heartbeat: HeartMonitor object checking the pulse of the engines | |
330 | notifier: ZMQStream for broadcasting engine registration changes (PUB) |
|
334 | notifier: ZMQStream for broadcasting engine registration changes (PUB) | |
331 | db: connection to db for out of memory logging of commands |
|
335 | db: connection to db for out of memory logging of commands | |
332 | NotImplemented |
|
336 | NotImplemented | |
333 | engine_info: dict of zmq connection information for engines to connect |
|
337 | engine_info: dict of zmq connection information for engines to connect | |
334 | to the queues. |
|
338 | to the queues. | |
335 | client_info: dict of zmq connection information for engines to connect |
|
339 | client_info: dict of zmq connection information for engines to connect | |
336 | to the queues. |
|
340 | to the queues. | |
337 | """ |
|
341 | """ | |
338 | # internal data structures: |
|
342 | # internal data structures: | |
339 | ids=Set() # engine IDs |
|
343 | ids=Set() # engine IDs | |
340 | keytable=Dict() |
|
344 | keytable=Dict() | |
341 | by_ident=Dict() |
|
345 | by_ident=Dict() | |
342 | engines=Dict() |
|
346 | engines=Dict() | |
343 | clients=Dict() |
|
347 | clients=Dict() | |
344 | hearts=Dict() |
|
348 | hearts=Dict() | |
345 | pending=Set() |
|
349 | pending=Set() | |
346 | queues=Dict() # pending msg_ids keyed by engine_id |
|
350 | queues=Dict() # pending msg_ids keyed by engine_id | |
347 | tasks=Dict() # pending msg_ids submitted as tasks, keyed by client_id |
|
351 | tasks=Dict() # pending msg_ids submitted as tasks, keyed by client_id | |
348 | completed=Dict() # completed msg_ids keyed by engine_id |
|
352 | completed=Dict() # completed msg_ids keyed by engine_id | |
349 | all_completed=Set() # completed msg_ids keyed by engine_id |
|
353 | all_completed=Set() # completed msg_ids keyed by engine_id | |
350 | dead_engines=Set() # completed msg_ids keyed by engine_id |
|
354 | dead_engines=Set() # completed msg_ids keyed by engine_id | |
351 | unassigned=Set() # set of task msg_ds not yet assigned a destination |
|
355 | unassigned=Set() # set of task msg_ds not yet assigned a destination | |
352 | incoming_registrations=Dict() |
|
356 | incoming_registrations=Dict() | |
353 | registration_timeout=Integer() |
|
357 | registration_timeout=Integer() | |
354 | _idcounter=Integer(0) |
|
358 | _idcounter=Integer(0) | |
355 |
|
359 | |||
356 | # objects from constructor: |
|
360 | # objects from constructor: | |
357 | query=Instance(ZMQStream) |
|
361 | query=Instance(ZMQStream) | |
358 | monitor=Instance(ZMQStream) |
|
362 | monitor=Instance(ZMQStream) | |
359 | notifier=Instance(ZMQStream) |
|
363 | notifier=Instance(ZMQStream) | |
360 | resubmit=Instance(ZMQStream) |
|
364 | resubmit=Instance(ZMQStream) | |
361 | heartmonitor=Instance(HeartMonitor) |
|
365 | heartmonitor=Instance(HeartMonitor) | |
362 | db=Instance(object) |
|
366 | db=Instance(object) | |
363 | client_info=Dict() |
|
367 | client_info=Dict() | |
364 | engine_info=Dict() |
|
368 | engine_info=Dict() | |
365 |
|
369 | |||
366 |
|
370 | |||
367 | def __init__(self, **kwargs): |
|
371 | def __init__(self, **kwargs): | |
368 | """ |
|
372 | """ | |
369 | # universal: |
|
373 | # universal: | |
370 | loop: IOLoop for creating future connections |
|
374 | loop: IOLoop for creating future connections | |
371 | session: streamsession for sending serialized data |
|
375 | session: streamsession for sending serialized data | |
372 | # engine: |
|
376 | # engine: | |
373 | queue: ZMQStream for monitoring queue messages |
|
377 | queue: ZMQStream for monitoring queue messages | |
374 | query: ZMQStream for engine+client registration and client requests |
|
378 | query: ZMQStream for engine+client registration and client requests | |
375 | heartbeat: HeartMonitor object for tracking engines |
|
379 | heartbeat: HeartMonitor object for tracking engines | |
376 | # extra: |
|
380 | # extra: | |
377 | db: ZMQStream for db connection (NotImplemented) |
|
381 | db: ZMQStream for db connection (NotImplemented) | |
378 | engine_info: zmq address/protocol dict for engine connections |
|
382 | engine_info: zmq address/protocol dict for engine connections | |
379 | client_info: zmq address/protocol dict for client connections |
|
383 | client_info: zmq address/protocol dict for client connections | |
380 | """ |
|
384 | """ | |
381 |
|
385 | |||
382 | super(Hub, self).__init__(**kwargs) |
|
386 | super(Hub, self).__init__(**kwargs) | |
383 | self.registration_timeout = max(5000, 2*self.heartmonitor.period) |
|
387 | self.registration_timeout = max(5000, 2*self.heartmonitor.period) | |
384 |
|
388 | |||
385 | # validate connection dicts: |
|
389 | # validate connection dicts: | |
386 | for k,v in self.client_info.iteritems(): |
|
390 | for k,v in self.client_info.iteritems(): | |
387 | if k == 'task': |
|
391 | if k == 'task': | |
388 | util.validate_url_container(v[1]) |
|
392 | util.validate_url_container(v[1]) | |
389 | else: |
|
393 | else: | |
390 | util.validate_url_container(v) |
|
394 | util.validate_url_container(v) | |
391 | # util.validate_url_container(self.client_info) |
|
395 | # util.validate_url_container(self.client_info) | |
392 | util.validate_url_container(self.engine_info) |
|
396 | util.validate_url_container(self.engine_info) | |
393 |
|
397 | |||
394 | # register our callbacks |
|
398 | # register our callbacks | |
395 | self.query.on_recv(self.dispatch_query) |
|
399 | self.query.on_recv(self.dispatch_query) | |
396 | self.monitor.on_recv(self.dispatch_monitor_traffic) |
|
400 | self.monitor.on_recv(self.dispatch_monitor_traffic) | |
397 |
|
401 | |||
398 | self.heartmonitor.add_heart_failure_handler(self.handle_heart_failure) |
|
402 | self.heartmonitor.add_heart_failure_handler(self.handle_heart_failure) | |
399 | self.heartmonitor.add_new_heart_handler(self.handle_new_heart) |
|
403 | self.heartmonitor.add_new_heart_handler(self.handle_new_heart) | |
400 |
|
404 | |||
401 | self.monitor_handlers = {b'in' : self.save_queue_request, |
|
405 | self.monitor_handlers = {b'in' : self.save_queue_request, | |
402 | b'out': self.save_queue_result, |
|
406 | b'out': self.save_queue_result, | |
403 | b'intask': self.save_task_request, |
|
407 | b'intask': self.save_task_request, | |
404 | b'outtask': self.save_task_result, |
|
408 | b'outtask': self.save_task_result, | |
405 | b'tracktask': self.save_task_destination, |
|
409 | b'tracktask': self.save_task_destination, | |
406 | b'incontrol': _passer, |
|
410 | b'incontrol': _passer, | |
407 | b'outcontrol': _passer, |
|
411 | b'outcontrol': _passer, | |
408 | b'iopub': self.save_iopub_message, |
|
412 | b'iopub': self.save_iopub_message, | |
409 | } |
|
413 | } | |
410 |
|
414 | |||
411 | self.query_handlers = {'queue_request': self.queue_status, |
|
415 | self.query_handlers = {'queue_request': self.queue_status, | |
412 | 'result_request': self.get_results, |
|
416 | 'result_request': self.get_results, | |
413 | 'history_request': self.get_history, |
|
417 | 'history_request': self.get_history, | |
414 | 'db_request': self.db_query, |
|
418 | 'db_request': self.db_query, | |
415 | 'purge_request': self.purge_results, |
|
419 | 'purge_request': self.purge_results, | |
416 | 'load_request': self.check_load, |
|
420 | 'load_request': self.check_load, | |
417 | 'resubmit_request': self.resubmit_task, |
|
421 | 'resubmit_request': self.resubmit_task, | |
418 | 'shutdown_request': self.shutdown_request, |
|
422 | 'shutdown_request': self.shutdown_request, | |
419 | 'registration_request' : self.register_engine, |
|
423 | 'registration_request' : self.register_engine, | |
420 | 'unregistration_request' : self.unregister_engine, |
|
424 | 'unregistration_request' : self.unregister_engine, | |
421 | 'connection_request': self.connection_request, |
|
425 | 'connection_request': self.connection_request, | |
422 | } |
|
426 | } | |
423 |
|
427 | |||
424 | # ignore resubmit replies |
|
428 | # ignore resubmit replies | |
425 | self.resubmit.on_recv(lambda msg: None, copy=False) |
|
429 | self.resubmit.on_recv(lambda msg: None, copy=False) | |
426 |
|
430 | |||
427 | self.log.info("hub::created hub") |
|
431 | self.log.info("hub::created hub") | |
428 |
|
432 | |||
429 | @property |
|
433 | @property | |
430 | def _next_id(self): |
|
434 | def _next_id(self): | |
431 | """gemerate a new ID. |
|
435 | """gemerate a new ID. | |
432 |
|
436 | |||
433 | No longer reuse old ids, just count from 0.""" |
|
437 | No longer reuse old ids, just count from 0.""" | |
434 | newid = self._idcounter |
|
438 | newid = self._idcounter | |
435 | self._idcounter += 1 |
|
439 | self._idcounter += 1 | |
436 | return newid |
|
440 | return newid | |
437 | # newid = 0 |
|
441 | # newid = 0 | |
438 | # incoming = [id[0] for id in self.incoming_registrations.itervalues()] |
|
442 | # incoming = [id[0] for id in self.incoming_registrations.itervalues()] | |
439 | # # print newid, self.ids, self.incoming_registrations |
|
443 | # # print newid, self.ids, self.incoming_registrations | |
440 | # while newid in self.ids or newid in incoming: |
|
444 | # while newid in self.ids or newid in incoming: | |
441 | # newid += 1 |
|
445 | # newid += 1 | |
442 | # return newid |
|
446 | # return newid | |
443 |
|
447 | |||
444 | #----------------------------------------------------------------------------- |
|
448 | #----------------------------------------------------------------------------- | |
445 | # message validation |
|
449 | # message validation | |
446 | #----------------------------------------------------------------------------- |
|
450 | #----------------------------------------------------------------------------- | |
447 |
|
451 | |||
448 | def _validate_targets(self, targets): |
|
452 | def _validate_targets(self, targets): | |
449 | """turn any valid targets argument into a list of integer ids""" |
|
453 | """turn any valid targets argument into a list of integer ids""" | |
450 | if targets is None: |
|
454 | if targets is None: | |
451 | # default to all |
|
455 | # default to all | |
452 | return self.ids |
|
456 | return self.ids | |
453 |
|
457 | |||
454 | if isinstance(targets, (int,str,unicode)): |
|
458 | if isinstance(targets, (int,str,unicode)): | |
455 | # only one target specified |
|
459 | # only one target specified | |
456 | targets = [targets] |
|
460 | targets = [targets] | |
457 | _targets = [] |
|
461 | _targets = [] | |
458 | for t in targets: |
|
462 | for t in targets: | |
459 | # map raw identities to ids |
|
463 | # map raw identities to ids | |
460 | if isinstance(t, (str,unicode)): |
|
464 | if isinstance(t, (str,unicode)): | |
461 | t = self.by_ident.get(cast_bytes(t), t) |
|
465 | t = self.by_ident.get(cast_bytes(t), t) | |
462 | _targets.append(t) |
|
466 | _targets.append(t) | |
463 | targets = _targets |
|
467 | targets = _targets | |
464 | bad_targets = [ t for t in targets if t not in self.ids ] |
|
468 | bad_targets = [ t for t in targets if t not in self.ids ] | |
465 | if bad_targets: |
|
469 | if bad_targets: | |
466 | raise IndexError("No Such Engine: %r" % bad_targets) |
|
470 | raise IndexError("No Such Engine: %r" % bad_targets) | |
467 | if not targets: |
|
471 | if not targets: | |
468 | raise IndexError("No Engines Registered") |
|
472 | raise IndexError("No Engines Registered") | |
469 | return targets |
|
473 | return targets | |
470 |
|
474 | |||
471 | #----------------------------------------------------------------------------- |
|
475 | #----------------------------------------------------------------------------- | |
472 | # dispatch methods (1 per stream) |
|
476 | # dispatch methods (1 per stream) | |
473 | #----------------------------------------------------------------------------- |
|
477 | #----------------------------------------------------------------------------- | |
474 |
|
478 | |||
475 |
|
479 | |||
476 | @util.log_errors |
|
480 | @util.log_errors | |
477 | def dispatch_monitor_traffic(self, msg): |
|
481 | def dispatch_monitor_traffic(self, msg): | |
478 | """all ME and Task queue messages come through here, as well as |
|
482 | """all ME and Task queue messages come through here, as well as | |
479 | IOPub traffic.""" |
|
483 | IOPub traffic.""" | |
480 | self.log.debug("monitor traffic: %r", msg[0]) |
|
484 | self.log.debug("monitor traffic: %r", msg[0]) | |
481 | switch = msg[0] |
|
485 | switch = msg[0] | |
482 | try: |
|
486 | try: | |
483 | idents, msg = self.session.feed_identities(msg[1:]) |
|
487 | idents, msg = self.session.feed_identities(msg[1:]) | |
484 | except ValueError: |
|
488 | except ValueError: | |
485 | idents=[] |
|
489 | idents=[] | |
486 | if not idents: |
|
490 | if not idents: | |
487 | self.log.error("Monitor message without topic: %r", msg) |
|
491 | self.log.error("Monitor message without topic: %r", msg) | |
488 | return |
|
492 | return | |
489 | handler = self.monitor_handlers.get(switch, None) |
|
493 | handler = self.monitor_handlers.get(switch, None) | |
490 | if handler is not None: |
|
494 | if handler is not None: | |
491 | handler(idents, msg) |
|
495 | handler(idents, msg) | |
492 | else: |
|
496 | else: | |
493 | self.log.error("Unrecognized monitor topic: %r", switch) |
|
497 | self.log.error("Unrecognized monitor topic: %r", switch) | |
494 |
|
498 | |||
495 |
|
499 | |||
496 | @util.log_errors |
|
500 | @util.log_errors | |
497 | def dispatch_query(self, msg): |
|
501 | def dispatch_query(self, msg): | |
498 | """Route registration requests and queries from clients.""" |
|
502 | """Route registration requests and queries from clients.""" | |
499 | try: |
|
503 | try: | |
500 | idents, msg = self.session.feed_identities(msg) |
|
504 | idents, msg = self.session.feed_identities(msg) | |
501 | except ValueError: |
|
505 | except ValueError: | |
502 | idents = [] |
|
506 | idents = [] | |
503 | if not idents: |
|
507 | if not idents: | |
504 | self.log.error("Bad Query Message: %r", msg) |
|
508 | self.log.error("Bad Query Message: %r", msg) | |
505 | return |
|
509 | return | |
506 | client_id = idents[0] |
|
510 | client_id = idents[0] | |
507 | try: |
|
511 | try: | |
508 | msg = self.session.unserialize(msg, content=True) |
|
512 | msg = self.session.unserialize(msg, content=True) | |
509 | except Exception: |
|
513 | except Exception: | |
510 | content = error.wrap_exception() |
|
514 | content = error.wrap_exception() | |
511 | self.log.error("Bad Query Message: %r", msg, exc_info=True) |
|
515 | self.log.error("Bad Query Message: %r", msg, exc_info=True) | |
512 | self.session.send(self.query, "hub_error", ident=client_id, |
|
516 | self.session.send(self.query, "hub_error", ident=client_id, | |
513 | content=content) |
|
517 | content=content) | |
514 | return |
|
518 | return | |
515 | # print client_id, header, parent, content |
|
519 | # print client_id, header, parent, content | |
516 | #switch on message type: |
|
520 | #switch on message type: | |
517 | msg_type = msg['header']['msg_type'] |
|
521 | msg_type = msg['header']['msg_type'] | |
518 | self.log.info("client::client %r requested %r", client_id, msg_type) |
|
522 | self.log.info("client::client %r requested %r", client_id, msg_type) | |
519 | handler = self.query_handlers.get(msg_type, None) |
|
523 | handler = self.query_handlers.get(msg_type, None) | |
520 | try: |
|
524 | try: | |
521 | assert handler is not None, "Bad Message Type: %r" % msg_type |
|
525 | assert handler is not None, "Bad Message Type: %r" % msg_type | |
522 | except: |
|
526 | except: | |
523 | content = error.wrap_exception() |
|
527 | content = error.wrap_exception() | |
524 | self.log.error("Bad Message Type: %r", msg_type, exc_info=True) |
|
528 | self.log.error("Bad Message Type: %r", msg_type, exc_info=True) | |
525 | self.session.send(self.query, "hub_error", ident=client_id, |
|
529 | self.session.send(self.query, "hub_error", ident=client_id, | |
526 | content=content) |
|
530 | content=content) | |
527 | return |
|
531 | return | |
528 |
|
532 | |||
529 | else: |
|
533 | else: | |
530 | handler(idents, msg) |
|
534 | handler(idents, msg) | |
531 |
|
535 | |||
532 | def dispatch_db(self, msg): |
|
536 | def dispatch_db(self, msg): | |
533 | """""" |
|
537 | """""" | |
534 | raise NotImplementedError |
|
538 | raise NotImplementedError | |
535 |
|
539 | |||
536 | #--------------------------------------------------------------------------- |
|
540 | #--------------------------------------------------------------------------- | |
537 | # handler methods (1 per event) |
|
541 | # handler methods (1 per event) | |
538 | #--------------------------------------------------------------------------- |
|
542 | #--------------------------------------------------------------------------- | |
539 |
|
543 | |||
540 | #----------------------- Heartbeat -------------------------------------- |
|
544 | #----------------------- Heartbeat -------------------------------------- | |
541 |
|
545 | |||
542 | def handle_new_heart(self, heart): |
|
546 | def handle_new_heart(self, heart): | |
543 | """handler to attach to heartbeater. |
|
547 | """handler to attach to heartbeater. | |
544 | Called when a new heart starts to beat. |
|
548 | Called when a new heart starts to beat. | |
545 | Triggers completion of registration.""" |
|
549 | Triggers completion of registration.""" | |
546 | self.log.debug("heartbeat::handle_new_heart(%r)", heart) |
|
550 | self.log.debug("heartbeat::handle_new_heart(%r)", heart) | |
547 | if heart not in self.incoming_registrations: |
|
551 | if heart not in self.incoming_registrations: | |
548 | self.log.info("heartbeat::ignoring new heart: %r", heart) |
|
552 | self.log.info("heartbeat::ignoring new heart: %r", heart) | |
549 | else: |
|
553 | else: | |
550 | self.finish_registration(heart) |
|
554 | self.finish_registration(heart) | |
551 |
|
555 | |||
552 |
|
556 | |||
553 | def handle_heart_failure(self, heart): |
|
557 | def handle_heart_failure(self, heart): | |
554 | """handler to attach to heartbeater. |
|
558 | """handler to attach to heartbeater. | |
555 | called when a previously registered heart fails to respond to beat request. |
|
559 | called when a previously registered heart fails to respond to beat request. | |
556 | triggers unregistration""" |
|
560 | triggers unregistration""" | |
557 | self.log.debug("heartbeat::handle_heart_failure(%r)", heart) |
|
561 | self.log.debug("heartbeat::handle_heart_failure(%r)", heart) | |
558 | eid = self.hearts.get(heart, None) |
|
562 | eid = self.hearts.get(heart, None) | |
559 | queue = self.engines[eid].queue |
|
563 | queue = self.engines[eid].queue | |
560 | if eid is None or self.keytable[eid] in self.dead_engines: |
|
564 | if eid is None or self.keytable[eid] in self.dead_engines: | |
561 | self.log.info("heartbeat::ignoring heart failure %r (not an engine or already dead)", heart) |
|
565 | self.log.info("heartbeat::ignoring heart failure %r (not an engine or already dead)", heart) | |
562 | else: |
|
566 | else: | |
563 | self.unregister_engine(heart, dict(content=dict(id=eid, queue=queue))) |
|
567 | self.unregister_engine(heart, dict(content=dict(id=eid, queue=queue))) | |
564 |
|
568 | |||
565 | #----------------------- MUX Queue Traffic ------------------------------ |
|
569 | #----------------------- MUX Queue Traffic ------------------------------ | |
566 |
|
570 | |||
567 | def save_queue_request(self, idents, msg): |
|
571 | def save_queue_request(self, idents, msg): | |
568 | if len(idents) < 2: |
|
572 | if len(idents) < 2: | |
569 | self.log.error("invalid identity prefix: %r", idents) |
|
573 | self.log.error("invalid identity prefix: %r", idents) | |
570 | return |
|
574 | return | |
571 | queue_id, client_id = idents[:2] |
|
575 | queue_id, client_id = idents[:2] | |
572 | try: |
|
576 | try: | |
573 | msg = self.session.unserialize(msg) |
|
577 | msg = self.session.unserialize(msg) | |
574 | except Exception: |
|
578 | except Exception: | |
575 | self.log.error("queue::client %r sent invalid message to %r: %r", client_id, queue_id, msg, exc_info=True) |
|
579 | self.log.error("queue::client %r sent invalid message to %r: %r", client_id, queue_id, msg, exc_info=True) | |
576 | return |
|
580 | return | |
577 |
|
581 | |||
578 | eid = self.by_ident.get(queue_id, None) |
|
582 | eid = self.by_ident.get(queue_id, None) | |
579 | if eid is None: |
|
583 | if eid is None: | |
580 | self.log.error("queue::target %r not registered", queue_id) |
|
584 | self.log.error("queue::target %r not registered", queue_id) | |
581 | self.log.debug("queue:: valid are: %r", self.by_ident.keys()) |
|
585 | self.log.debug("queue:: valid are: %r", self.by_ident.keys()) | |
582 | return |
|
586 | return | |
583 | record = init_record(msg) |
|
587 | record = init_record(msg) | |
584 | msg_id = record['msg_id'] |
|
588 | msg_id = record['msg_id'] | |
585 | self.log.info("queue::client %r submitted request %r to %s", client_id, msg_id, eid) |
|
589 | self.log.info("queue::client %r submitted request %r to %s", client_id, msg_id, eid) | |
586 | # Unicode in records |
|
590 | # Unicode in records | |
587 | record['engine_uuid'] = queue_id.decode('ascii') |
|
591 | record['engine_uuid'] = queue_id.decode('ascii') | |
588 | record['client_uuid'] = client_id.decode('ascii') |
|
592 | record['client_uuid'] = client_id.decode('ascii') | |
589 | record['queue'] = 'mux' |
|
593 | record['queue'] = 'mux' | |
590 |
|
594 | |||
591 | try: |
|
595 | try: | |
592 | # it's posible iopub arrived first: |
|
596 | # it's posible iopub arrived first: | |
593 | existing = self.db.get_record(msg_id) |
|
597 | existing = self.db.get_record(msg_id) | |
594 | for key,evalue in existing.iteritems(): |
|
598 | for key,evalue in existing.iteritems(): | |
595 | rvalue = record.get(key, None) |
|
599 | rvalue = record.get(key, None) | |
596 | if evalue and rvalue and evalue != rvalue: |
|
600 | if evalue and rvalue and evalue != rvalue: | |
597 | self.log.warn("conflicting initial state for record: %r:%r <%r> %r", msg_id, rvalue, key, evalue) |
|
601 | self.log.warn("conflicting initial state for record: %r:%r <%r> %r", msg_id, rvalue, key, evalue) | |
598 | elif evalue and not rvalue: |
|
602 | elif evalue and not rvalue: | |
599 | record[key] = evalue |
|
603 | record[key] = evalue | |
600 | try: |
|
604 | try: | |
601 | self.db.update_record(msg_id, record) |
|
605 | self.db.update_record(msg_id, record) | |
602 | except Exception: |
|
606 | except Exception: | |
603 | self.log.error("DB Error updating record %r", msg_id, exc_info=True) |
|
607 | self.log.error("DB Error updating record %r", msg_id, exc_info=True) | |
604 | except KeyError: |
|
608 | except KeyError: | |
605 | try: |
|
609 | try: | |
606 | self.db.add_record(msg_id, record) |
|
610 | self.db.add_record(msg_id, record) | |
607 | except Exception: |
|
611 | except Exception: | |
608 | self.log.error("DB Error adding record %r", msg_id, exc_info=True) |
|
612 | self.log.error("DB Error adding record %r", msg_id, exc_info=True) | |
609 |
|
613 | |||
610 |
|
614 | |||
611 | self.pending.add(msg_id) |
|
615 | self.pending.add(msg_id) | |
612 | self.queues[eid].append(msg_id) |
|
616 | self.queues[eid].append(msg_id) | |
613 |
|
617 | |||
614 | def save_queue_result(self, idents, msg): |
|
618 | def save_queue_result(self, idents, msg): | |
615 | if len(idents) < 2: |
|
619 | if len(idents) < 2: | |
616 | self.log.error("invalid identity prefix: %r", idents) |
|
620 | self.log.error("invalid identity prefix: %r", idents) | |
617 | return |
|
621 | return | |
618 |
|
622 | |||
619 | client_id, queue_id = idents[:2] |
|
623 | client_id, queue_id = idents[:2] | |
620 | try: |
|
624 | try: | |
621 | msg = self.session.unserialize(msg) |
|
625 | msg = self.session.unserialize(msg) | |
622 | except Exception: |
|
626 | except Exception: | |
623 | self.log.error("queue::engine %r sent invalid message to %r: %r", |
|
627 | self.log.error("queue::engine %r sent invalid message to %r: %r", | |
624 | queue_id, client_id, msg, exc_info=True) |
|
628 | queue_id, client_id, msg, exc_info=True) | |
625 | return |
|
629 | return | |
626 |
|
630 | |||
627 | eid = self.by_ident.get(queue_id, None) |
|
631 | eid = self.by_ident.get(queue_id, None) | |
628 | if eid is None: |
|
632 | if eid is None: | |
629 | self.log.error("queue::unknown engine %r is sending a reply: ", queue_id) |
|
633 | self.log.error("queue::unknown engine %r is sending a reply: ", queue_id) | |
630 | return |
|
634 | return | |
631 |
|
635 | |||
632 | parent = msg['parent_header'] |
|
636 | parent = msg['parent_header'] | |
633 | if not parent: |
|
637 | if not parent: | |
634 | return |
|
638 | return | |
635 | msg_id = parent['msg_id'] |
|
639 | msg_id = parent['msg_id'] | |
636 | if msg_id in self.pending: |
|
640 | if msg_id in self.pending: | |
637 | self.pending.remove(msg_id) |
|
641 | self.pending.remove(msg_id) | |
638 | self.all_completed.add(msg_id) |
|
642 | self.all_completed.add(msg_id) | |
639 | self.queues[eid].remove(msg_id) |
|
643 | self.queues[eid].remove(msg_id) | |
640 | self.completed[eid].append(msg_id) |
|
644 | self.completed[eid].append(msg_id) | |
641 | self.log.info("queue::request %r completed on %s", msg_id, eid) |
|
645 | self.log.info("queue::request %r completed on %s", msg_id, eid) | |
642 | elif msg_id not in self.all_completed: |
|
646 | elif msg_id not in self.all_completed: | |
643 | # it could be a result from a dead engine that died before delivering the |
|
647 | # it could be a result from a dead engine that died before delivering the | |
644 | # result |
|
648 | # result | |
645 | self.log.warn("queue:: unknown msg finished %r", msg_id) |
|
649 | self.log.warn("queue:: unknown msg finished %r", msg_id) | |
646 | return |
|
650 | return | |
647 | # update record anyway, because the unregistration could have been premature |
|
651 | # update record anyway, because the unregistration could have been premature | |
648 | rheader = msg['header'] |
|
652 | rheader = msg['header'] | |
|
653 | md = msg['metadata'] | |||
649 | completed = rheader['date'] |
|
654 | completed = rheader['date'] | |
650 |
started = |
|
655 | started = md.get('started', None) | |
651 | result = { |
|
656 | result = { | |
652 | 'result_header' : rheader, |
|
657 | 'result_header' : rheader, | |
|
658 | 'result_metadata': md, | |||
653 | 'result_content': msg['content'], |
|
659 | 'result_content': msg['content'], | |
654 | 'received': datetime.now(), |
|
660 | 'received': datetime.now(), | |
655 | 'started' : started, |
|
661 | 'started' : started, | |
656 | 'completed' : completed |
|
662 | 'completed' : completed | |
657 | } |
|
663 | } | |
658 |
|
664 | |||
659 | result['result_buffers'] = msg['buffers'] |
|
665 | result['result_buffers'] = msg['buffers'] | |
660 | try: |
|
666 | try: | |
661 | self.db.update_record(msg_id, result) |
|
667 | self.db.update_record(msg_id, result) | |
662 | except Exception: |
|
668 | except Exception: | |
663 | self.log.error("DB Error updating record %r", msg_id, exc_info=True) |
|
669 | self.log.error("DB Error updating record %r", msg_id, exc_info=True) | |
664 |
|
670 | |||
665 |
|
671 | |||
666 | #--------------------- Task Queue Traffic ------------------------------ |
|
672 | #--------------------- Task Queue Traffic ------------------------------ | |
667 |
|
673 | |||
668 | def save_task_request(self, idents, msg): |
|
674 | def save_task_request(self, idents, msg): | |
669 | """Save the submission of a task.""" |
|
675 | """Save the submission of a task.""" | |
670 | client_id = idents[0] |
|
676 | client_id = idents[0] | |
671 |
|
677 | |||
672 | try: |
|
678 | try: | |
673 | msg = self.session.unserialize(msg) |
|
679 | msg = self.session.unserialize(msg) | |
674 | except Exception: |
|
680 | except Exception: | |
675 | self.log.error("task::client %r sent invalid task message: %r", |
|
681 | self.log.error("task::client %r sent invalid task message: %r", | |
676 | client_id, msg, exc_info=True) |
|
682 | client_id, msg, exc_info=True) | |
677 | return |
|
683 | return | |
678 | record = init_record(msg) |
|
684 | record = init_record(msg) | |
679 |
|
685 | |||
680 | record['client_uuid'] = client_id.decode('ascii') |
|
686 | record['client_uuid'] = client_id.decode('ascii') | |
681 | record['queue'] = 'task' |
|
687 | record['queue'] = 'task' | |
682 | header = msg['header'] |
|
688 | header = msg['header'] | |
683 | msg_id = header['msg_id'] |
|
689 | msg_id = header['msg_id'] | |
684 | self.pending.add(msg_id) |
|
690 | self.pending.add(msg_id) | |
685 | self.unassigned.add(msg_id) |
|
691 | self.unassigned.add(msg_id) | |
686 | try: |
|
692 | try: | |
687 | # it's posible iopub arrived first: |
|
693 | # it's posible iopub arrived first: | |
688 | existing = self.db.get_record(msg_id) |
|
694 | existing = self.db.get_record(msg_id) | |
689 | if existing['resubmitted']: |
|
695 | if existing['resubmitted']: | |
690 | for key in ('submitted', 'client_uuid', 'buffers'): |
|
696 | for key in ('submitted', 'client_uuid', 'buffers'): | |
691 | # don't clobber these keys on resubmit |
|
697 | # don't clobber these keys on resubmit | |
692 | # submitted and client_uuid should be different |
|
698 | # submitted and client_uuid should be different | |
693 | # and buffers might be big, and shouldn't have changed |
|
699 | # and buffers might be big, and shouldn't have changed | |
694 | record.pop(key) |
|
700 | record.pop(key) | |
695 | # still check content,header which should not change |
|
701 | # still check content,header which should not change | |
696 | # but are not expensive to compare as buffers |
|
702 | # but are not expensive to compare as buffers | |
697 |
|
703 | |||
698 | for key,evalue in existing.iteritems(): |
|
704 | for key,evalue in existing.iteritems(): | |
699 | if key.endswith('buffers'): |
|
705 | if key.endswith('buffers'): | |
700 | # don't compare buffers |
|
706 | # don't compare buffers | |
701 | continue |
|
707 | continue | |
702 | rvalue = record.get(key, None) |
|
708 | rvalue = record.get(key, None) | |
703 | if evalue and rvalue and evalue != rvalue: |
|
709 | if evalue and rvalue and evalue != rvalue: | |
704 | self.log.warn("conflicting initial state for record: %r:%r <%r> %r", msg_id, rvalue, key, evalue) |
|
710 | self.log.warn("conflicting initial state for record: %r:%r <%r> %r", msg_id, rvalue, key, evalue) | |
705 | elif evalue and not rvalue: |
|
711 | elif evalue and not rvalue: | |
706 | record[key] = evalue |
|
712 | record[key] = evalue | |
707 | try: |
|
713 | try: | |
708 | self.db.update_record(msg_id, record) |
|
714 | self.db.update_record(msg_id, record) | |
709 | except Exception: |
|
715 | except Exception: | |
710 | self.log.error("DB Error updating record %r", msg_id, exc_info=True) |
|
716 | self.log.error("DB Error updating record %r", msg_id, exc_info=True) | |
711 | except KeyError: |
|
717 | except KeyError: | |
712 | try: |
|
718 | try: | |
713 | self.db.add_record(msg_id, record) |
|
719 | self.db.add_record(msg_id, record) | |
714 | except Exception: |
|
720 | except Exception: | |
715 | self.log.error("DB Error adding record %r", msg_id, exc_info=True) |
|
721 | self.log.error("DB Error adding record %r", msg_id, exc_info=True) | |
716 | except Exception: |
|
722 | except Exception: | |
717 | self.log.error("DB Error saving task request %r", msg_id, exc_info=True) |
|
723 | self.log.error("DB Error saving task request %r", msg_id, exc_info=True) | |
718 |
|
724 | |||
719 | def save_task_result(self, idents, msg): |
|
725 | def save_task_result(self, idents, msg): | |
720 | """save the result of a completed task.""" |
|
726 | """save the result of a completed task.""" | |
721 | client_id = idents[0] |
|
727 | client_id = idents[0] | |
722 | try: |
|
728 | try: | |
723 | msg = self.session.unserialize(msg) |
|
729 | msg = self.session.unserialize(msg) | |
724 | except Exception: |
|
730 | except Exception: | |
725 | self.log.error("task::invalid task result message send to %r: %r", |
|
731 | self.log.error("task::invalid task result message send to %r: %r", | |
726 | client_id, msg, exc_info=True) |
|
732 | client_id, msg, exc_info=True) | |
727 | return |
|
733 | return | |
728 |
|
734 | |||
729 | parent = msg['parent_header'] |
|
735 | parent = msg['parent_header'] | |
730 | if not parent: |
|
736 | if not parent: | |
731 | # print msg |
|
737 | # print msg | |
732 | self.log.warn("Task %r had no parent!", msg) |
|
738 | self.log.warn("Task %r had no parent!", msg) | |
733 | return |
|
739 | return | |
734 | msg_id = parent['msg_id'] |
|
740 | msg_id = parent['msg_id'] | |
735 | if msg_id in self.unassigned: |
|
741 | if msg_id in self.unassigned: | |
736 | self.unassigned.remove(msg_id) |
|
742 | self.unassigned.remove(msg_id) | |
737 |
|
743 | |||
738 | header = msg['header'] |
|
744 | header = msg['header'] | |
739 | engine_uuid = header.get('engine', u'') |
|
745 | md = msg['metadata'] | |
|
746 | engine_uuid = md.get('engine', u'') | |||
740 | eid = self.by_ident.get(cast_bytes(engine_uuid), None) |
|
747 | eid = self.by_ident.get(cast_bytes(engine_uuid), None) | |
741 |
|
748 | |||
742 |
status = |
|
749 | status = md.get('status', None) | |
743 |
|
750 | |||
744 | if msg_id in self.pending: |
|
751 | if msg_id in self.pending: | |
745 | self.log.info("task::task %r finished on %s", msg_id, eid) |
|
752 | self.log.info("task::task %r finished on %s", msg_id, eid) | |
746 | self.pending.remove(msg_id) |
|
753 | self.pending.remove(msg_id) | |
747 | self.all_completed.add(msg_id) |
|
754 | self.all_completed.add(msg_id) | |
748 | if eid is not None: |
|
755 | if eid is not None: | |
749 | if status != 'aborted': |
|
756 | if status != 'aborted': | |
750 | self.completed[eid].append(msg_id) |
|
757 | self.completed[eid].append(msg_id) | |
751 | if msg_id in self.tasks[eid]: |
|
758 | if msg_id in self.tasks[eid]: | |
752 | self.tasks[eid].remove(msg_id) |
|
759 | self.tasks[eid].remove(msg_id) | |
753 | completed = header['date'] |
|
760 | completed = header['date'] | |
754 |
started = |
|
761 | started = md.get('started', None) | |
755 | result = { |
|
762 | result = { | |
756 | 'result_header' : header, |
|
763 | 'result_header' : header, | |
|
764 | 'result_metadata': msg['metadata'], | |||
757 | 'result_content': msg['content'], |
|
765 | 'result_content': msg['content'], | |
758 | 'started' : started, |
|
766 | 'started' : started, | |
759 | 'completed' : completed, |
|
767 | 'completed' : completed, | |
760 | 'received' : datetime.now(), |
|
768 | 'received' : datetime.now(), | |
761 | 'engine_uuid': engine_uuid, |
|
769 | 'engine_uuid': engine_uuid, | |
762 | } |
|
770 | } | |
763 |
|
771 | |||
764 | result['result_buffers'] = msg['buffers'] |
|
772 | result['result_buffers'] = msg['buffers'] | |
765 | try: |
|
773 | try: | |
766 | self.db.update_record(msg_id, result) |
|
774 | self.db.update_record(msg_id, result) | |
767 | except Exception: |
|
775 | except Exception: | |
768 | self.log.error("DB Error saving task request %r", msg_id, exc_info=True) |
|
776 | self.log.error("DB Error saving task request %r", msg_id, exc_info=True) | |
769 |
|
777 | |||
770 | else: |
|
778 | else: | |
771 | self.log.debug("task::unknown task %r finished", msg_id) |
|
779 | self.log.debug("task::unknown task %r finished", msg_id) | |
772 |
|
780 | |||
773 | def save_task_destination(self, idents, msg): |
|
781 | def save_task_destination(self, idents, msg): | |
774 | try: |
|
782 | try: | |
775 | msg = self.session.unserialize(msg, content=True) |
|
783 | msg = self.session.unserialize(msg, content=True) | |
776 | except Exception: |
|
784 | except Exception: | |
777 | self.log.error("task::invalid task tracking message", exc_info=True) |
|
785 | self.log.error("task::invalid task tracking message", exc_info=True) | |
778 | return |
|
786 | return | |
779 | content = msg['content'] |
|
787 | content = msg['content'] | |
780 | # print (content) |
|
788 | # print (content) | |
781 | msg_id = content['msg_id'] |
|
789 | msg_id = content['msg_id'] | |
782 | engine_uuid = content['engine_id'] |
|
790 | engine_uuid = content['engine_id'] | |
783 | eid = self.by_ident[cast_bytes(engine_uuid)] |
|
791 | eid = self.by_ident[cast_bytes(engine_uuid)] | |
784 |
|
792 | |||
785 | self.log.info("task::task %r arrived on %r", msg_id, eid) |
|
793 | self.log.info("task::task %r arrived on %r", msg_id, eid) | |
786 | if msg_id in self.unassigned: |
|
794 | if msg_id in self.unassigned: | |
787 | self.unassigned.remove(msg_id) |
|
795 | self.unassigned.remove(msg_id) | |
788 | # else: |
|
796 | # else: | |
789 | # self.log.debug("task::task %r not listed as MIA?!"%(msg_id)) |
|
797 | # self.log.debug("task::task %r not listed as MIA?!"%(msg_id)) | |
790 |
|
798 | |||
791 | self.tasks[eid].append(msg_id) |
|
799 | self.tasks[eid].append(msg_id) | |
792 | # self.pending[msg_id][1].update(received=datetime.now(),engine=(eid,engine_uuid)) |
|
800 | # self.pending[msg_id][1].update(received=datetime.now(),engine=(eid,engine_uuid)) | |
793 | try: |
|
801 | try: | |
794 | self.db.update_record(msg_id, dict(engine_uuid=engine_uuid)) |
|
802 | self.db.update_record(msg_id, dict(engine_uuid=engine_uuid)) | |
795 | except Exception: |
|
803 | except Exception: | |
796 | self.log.error("DB Error saving task destination %r", msg_id, exc_info=True) |
|
804 | self.log.error("DB Error saving task destination %r", msg_id, exc_info=True) | |
797 |
|
805 | |||
798 |
|
806 | |||
799 | def mia_task_request(self, idents, msg): |
|
807 | def mia_task_request(self, idents, msg): | |
800 | raise NotImplementedError |
|
808 | raise NotImplementedError | |
801 | client_id = idents[0] |
|
809 | client_id = idents[0] | |
802 | # content = dict(mia=self.mia,status='ok') |
|
810 | # content = dict(mia=self.mia,status='ok') | |
803 | # self.session.send('mia_reply', content=content, idents=client_id) |
|
811 | # self.session.send('mia_reply', content=content, idents=client_id) | |
804 |
|
812 | |||
805 |
|
813 | |||
806 | #--------------------- IOPub Traffic ------------------------------ |
|
814 | #--------------------- IOPub Traffic ------------------------------ | |
807 |
|
815 | |||
808 | def save_iopub_message(self, topics, msg): |
|
816 | def save_iopub_message(self, topics, msg): | |
809 | """save an iopub message into the db""" |
|
817 | """save an iopub message into the db""" | |
810 | # print (topics) |
|
818 | # print (topics) | |
811 | try: |
|
819 | try: | |
812 | msg = self.session.unserialize(msg, content=True) |
|
820 | msg = self.session.unserialize(msg, content=True) | |
813 | except Exception: |
|
821 | except Exception: | |
814 | self.log.error("iopub::invalid IOPub message", exc_info=True) |
|
822 | self.log.error("iopub::invalid IOPub message", exc_info=True) | |
815 | return |
|
823 | return | |
816 |
|
824 | |||
817 | parent = msg['parent_header'] |
|
825 | parent = msg['parent_header'] | |
818 | if not parent: |
|
826 | if not parent: | |
819 | self.log.warn("iopub::IOPub message lacks parent: %r", msg) |
|
827 | self.log.warn("iopub::IOPub message lacks parent: %r", msg) | |
820 | return |
|
828 | return | |
821 | msg_id = parent['msg_id'] |
|
829 | msg_id = parent['msg_id'] | |
822 | msg_type = msg['header']['msg_type'] |
|
830 | msg_type = msg['header']['msg_type'] | |
823 | content = msg['content'] |
|
831 | content = msg['content'] | |
824 |
|
832 | |||
825 | # ensure msg_id is in db |
|
833 | # ensure msg_id is in db | |
826 | try: |
|
834 | try: | |
827 | rec = self.db.get_record(msg_id) |
|
835 | rec = self.db.get_record(msg_id) | |
828 | except KeyError: |
|
836 | except KeyError: | |
829 | rec = empty_record() |
|
837 | rec = empty_record() | |
830 | rec['msg_id'] = msg_id |
|
838 | rec['msg_id'] = msg_id | |
831 | self.db.add_record(msg_id, rec) |
|
839 | self.db.add_record(msg_id, rec) | |
832 | # stream |
|
840 | # stream | |
833 | d = {} |
|
841 | d = {} | |
834 | if msg_type == 'stream': |
|
842 | if msg_type == 'stream': | |
835 | name = content['name'] |
|
843 | name = content['name'] | |
836 | s = rec[name] or '' |
|
844 | s = rec[name] or '' | |
837 | d[name] = s + content['data'] |
|
845 | d[name] = s + content['data'] | |
838 |
|
846 | |||
839 | elif msg_type == 'pyerr': |
|
847 | elif msg_type == 'pyerr': | |
840 | d['pyerr'] = content |
|
848 | d['pyerr'] = content | |
841 | elif msg_type == 'pyin': |
|
849 | elif msg_type == 'pyin': | |
842 | d['pyin'] = content['code'] |
|
850 | d['pyin'] = content['code'] | |
843 | elif msg_type in ('display_data', 'pyout'): |
|
851 | elif msg_type in ('display_data', 'pyout'): | |
844 | d[msg_type] = content |
|
852 | d[msg_type] = content | |
845 | elif msg_type == 'status': |
|
853 | elif msg_type == 'status': | |
846 | pass |
|
854 | pass | |
847 | else: |
|
855 | else: | |
848 | self.log.warn("unhandled iopub msg_type: %r", msg_type) |
|
856 | self.log.warn("unhandled iopub msg_type: %r", msg_type) | |
849 |
|
857 | |||
850 | if not d: |
|
858 | if not d: | |
851 | return |
|
859 | return | |
852 |
|
860 | |||
853 | try: |
|
861 | try: | |
854 | self.db.update_record(msg_id, d) |
|
862 | self.db.update_record(msg_id, d) | |
855 | except Exception: |
|
863 | except Exception: | |
856 | self.log.error("DB Error saving iopub message %r", msg_id, exc_info=True) |
|
864 | self.log.error("DB Error saving iopub message %r", msg_id, exc_info=True) | |
857 |
|
865 | |||
858 |
|
866 | |||
859 |
|
867 | |||
860 | #------------------------------------------------------------------------- |
|
868 | #------------------------------------------------------------------------- | |
861 | # Registration requests |
|
869 | # Registration requests | |
862 | #------------------------------------------------------------------------- |
|
870 | #------------------------------------------------------------------------- | |
863 |
|
871 | |||
864 | def connection_request(self, client_id, msg): |
|
872 | def connection_request(self, client_id, msg): | |
865 | """Reply with connection addresses for clients.""" |
|
873 | """Reply with connection addresses for clients.""" | |
866 | self.log.info("client::client %r connected", client_id) |
|
874 | self.log.info("client::client %r connected", client_id) | |
867 | content = dict(status='ok') |
|
875 | content = dict(status='ok') | |
868 | content.update(self.client_info) |
|
876 | content.update(self.client_info) | |
869 | jsonable = {} |
|
877 | jsonable = {} | |
870 | for k,v in self.keytable.iteritems(): |
|
878 | for k,v in self.keytable.iteritems(): | |
871 | if v not in self.dead_engines: |
|
879 | if v not in self.dead_engines: | |
872 | jsonable[str(k)] = v.decode('ascii') |
|
880 | jsonable[str(k)] = v.decode('ascii') | |
873 | content['engines'] = jsonable |
|
881 | content['engines'] = jsonable | |
874 | self.session.send(self.query, 'connection_reply', content, parent=msg, ident=client_id) |
|
882 | self.session.send(self.query, 'connection_reply', content, parent=msg, ident=client_id) | |
875 |
|
883 | |||
876 | def register_engine(self, reg, msg): |
|
884 | def register_engine(self, reg, msg): | |
877 | """Register a new engine.""" |
|
885 | """Register a new engine.""" | |
878 | content = msg['content'] |
|
886 | content = msg['content'] | |
879 | try: |
|
887 | try: | |
880 | queue = cast_bytes(content['queue']) |
|
888 | queue = cast_bytes(content['queue']) | |
881 | except KeyError: |
|
889 | except KeyError: | |
882 | self.log.error("registration::queue not specified", exc_info=True) |
|
890 | self.log.error("registration::queue not specified", exc_info=True) | |
883 | return |
|
891 | return | |
884 | heart = content.get('heartbeat', None) |
|
892 | heart = content.get('heartbeat', None) | |
885 | if heart: |
|
893 | if heart: | |
886 | heart = cast_bytes(heart) |
|
894 | heart = cast_bytes(heart) | |
887 | """register a new engine, and create the socket(s) necessary""" |
|
895 | """register a new engine, and create the socket(s) necessary""" | |
888 | eid = self._next_id |
|
896 | eid = self._next_id | |
889 | # print (eid, queue, reg, heart) |
|
897 | # print (eid, queue, reg, heart) | |
890 |
|
898 | |||
891 | self.log.debug("registration::register_engine(%i, %r, %r, %r)", eid, queue, reg, heart) |
|
899 | self.log.debug("registration::register_engine(%i, %r, %r, %r)", eid, queue, reg, heart) | |
892 |
|
900 | |||
893 | content = dict(id=eid,status='ok') |
|
901 | content = dict(id=eid,status='ok') | |
894 | content.update(self.engine_info) |
|
902 | content.update(self.engine_info) | |
895 | # check if requesting available IDs: |
|
903 | # check if requesting available IDs: | |
896 | if queue in self.by_ident: |
|
904 | if queue in self.by_ident: | |
897 | try: |
|
905 | try: | |
898 | raise KeyError("queue_id %r in use" % queue) |
|
906 | raise KeyError("queue_id %r in use" % queue) | |
899 | except: |
|
907 | except: | |
900 | content = error.wrap_exception() |
|
908 | content = error.wrap_exception() | |
901 | self.log.error("queue_id %r in use", queue, exc_info=True) |
|
909 | self.log.error("queue_id %r in use", queue, exc_info=True) | |
902 | elif heart in self.hearts: # need to check unique hearts? |
|
910 | elif heart in self.hearts: # need to check unique hearts? | |
903 | try: |
|
911 | try: | |
904 | raise KeyError("heart_id %r in use" % heart) |
|
912 | raise KeyError("heart_id %r in use" % heart) | |
905 | except: |
|
913 | except: | |
906 | self.log.error("heart_id %r in use", heart, exc_info=True) |
|
914 | self.log.error("heart_id %r in use", heart, exc_info=True) | |
907 | content = error.wrap_exception() |
|
915 | content = error.wrap_exception() | |
908 | else: |
|
916 | else: | |
909 | for h, pack in self.incoming_registrations.iteritems(): |
|
917 | for h, pack in self.incoming_registrations.iteritems(): | |
910 | if heart == h: |
|
918 | if heart == h: | |
911 | try: |
|
919 | try: | |
912 | raise KeyError("heart_id %r in use" % heart) |
|
920 | raise KeyError("heart_id %r in use" % heart) | |
913 | except: |
|
921 | except: | |
914 | self.log.error("heart_id %r in use", heart, exc_info=True) |
|
922 | self.log.error("heart_id %r in use", heart, exc_info=True) | |
915 | content = error.wrap_exception() |
|
923 | content = error.wrap_exception() | |
916 | break |
|
924 | break | |
917 | elif queue == pack[1]: |
|
925 | elif queue == pack[1]: | |
918 | try: |
|
926 | try: | |
919 | raise KeyError("queue_id %r in use" % queue) |
|
927 | raise KeyError("queue_id %r in use" % queue) | |
920 | except: |
|
928 | except: | |
921 | self.log.error("queue_id %r in use", queue, exc_info=True) |
|
929 | self.log.error("queue_id %r in use", queue, exc_info=True) | |
922 | content = error.wrap_exception() |
|
930 | content = error.wrap_exception() | |
923 | break |
|
931 | break | |
924 |
|
932 | |||
925 | msg = self.session.send(self.query, "registration_reply", |
|
933 | msg = self.session.send(self.query, "registration_reply", | |
926 | content=content, |
|
934 | content=content, | |
927 | ident=reg) |
|
935 | ident=reg) | |
928 |
|
936 | |||
929 | if content['status'] == 'ok': |
|
937 | if content['status'] == 'ok': | |
930 | if heart in self.heartmonitor.hearts: |
|
938 | if heart in self.heartmonitor.hearts: | |
931 | # already beating |
|
939 | # already beating | |
932 | self.incoming_registrations[heart] = (eid,queue,reg[0],None) |
|
940 | self.incoming_registrations[heart] = (eid,queue,reg[0],None) | |
933 | self.finish_registration(heart) |
|
941 | self.finish_registration(heart) | |
934 | else: |
|
942 | else: | |
935 | purge = lambda : self._purge_stalled_registration(heart) |
|
943 | purge = lambda : self._purge_stalled_registration(heart) | |
936 | dc = ioloop.DelayedCallback(purge, self.registration_timeout, self.loop) |
|
944 | dc = ioloop.DelayedCallback(purge, self.registration_timeout, self.loop) | |
937 | dc.start() |
|
945 | dc.start() | |
938 | self.incoming_registrations[heart] = (eid,queue,reg[0],dc) |
|
946 | self.incoming_registrations[heart] = (eid,queue,reg[0],dc) | |
939 | else: |
|
947 | else: | |
940 | self.log.error("registration::registration %i failed: %r", eid, content['evalue']) |
|
948 | self.log.error("registration::registration %i failed: %r", eid, content['evalue']) | |
941 | return eid |
|
949 | return eid | |
942 |
|
950 | |||
943 | def unregister_engine(self, ident, msg): |
|
951 | def unregister_engine(self, ident, msg): | |
944 | """Unregister an engine that explicitly requested to leave.""" |
|
952 | """Unregister an engine that explicitly requested to leave.""" | |
945 | try: |
|
953 | try: | |
946 | eid = msg['content']['id'] |
|
954 | eid = msg['content']['id'] | |
947 | except: |
|
955 | except: | |
948 | self.log.error("registration::bad engine id for unregistration: %r", ident, exc_info=True) |
|
956 | self.log.error("registration::bad engine id for unregistration: %r", ident, exc_info=True) | |
949 | return |
|
957 | return | |
950 | self.log.info("registration::unregister_engine(%r)", eid) |
|
958 | self.log.info("registration::unregister_engine(%r)", eid) | |
951 | # print (eid) |
|
959 | # print (eid) | |
952 | uuid = self.keytable[eid] |
|
960 | uuid = self.keytable[eid] | |
953 | content=dict(id=eid, queue=uuid.decode('ascii')) |
|
961 | content=dict(id=eid, queue=uuid.decode('ascii')) | |
954 | self.dead_engines.add(uuid) |
|
962 | self.dead_engines.add(uuid) | |
955 | # self.ids.remove(eid) |
|
963 | # self.ids.remove(eid) | |
956 | # uuid = self.keytable.pop(eid) |
|
964 | # uuid = self.keytable.pop(eid) | |
957 | # |
|
965 | # | |
958 | # ec = self.engines.pop(eid) |
|
966 | # ec = self.engines.pop(eid) | |
959 | # self.hearts.pop(ec.heartbeat) |
|
967 | # self.hearts.pop(ec.heartbeat) | |
960 | # self.by_ident.pop(ec.queue) |
|
968 | # self.by_ident.pop(ec.queue) | |
961 | # self.completed.pop(eid) |
|
969 | # self.completed.pop(eid) | |
962 | handleit = lambda : self._handle_stranded_msgs(eid, uuid) |
|
970 | handleit = lambda : self._handle_stranded_msgs(eid, uuid) | |
963 | dc = ioloop.DelayedCallback(handleit, self.registration_timeout, self.loop) |
|
971 | dc = ioloop.DelayedCallback(handleit, self.registration_timeout, self.loop) | |
964 | dc.start() |
|
972 | dc.start() | |
965 | ############## TODO: HANDLE IT ################ |
|
973 | ############## TODO: HANDLE IT ################ | |
966 |
|
974 | |||
967 | if self.notifier: |
|
975 | if self.notifier: | |
968 | self.session.send(self.notifier, "unregistration_notification", content=content) |
|
976 | self.session.send(self.notifier, "unregistration_notification", content=content) | |
969 |
|
977 | |||
970 | def _handle_stranded_msgs(self, eid, uuid): |
|
978 | def _handle_stranded_msgs(self, eid, uuid): | |
971 | """Handle messages known to be on an engine when the engine unregisters. |
|
979 | """Handle messages known to be on an engine when the engine unregisters. | |
972 |
|
980 | |||
973 | It is possible that this will fire prematurely - that is, an engine will |
|
981 | It is possible that this will fire prematurely - that is, an engine will | |
974 | go down after completing a result, and the client will be notified |
|
982 | go down after completing a result, and the client will be notified | |
975 | that the result failed and later receive the actual result. |
|
983 | that the result failed and later receive the actual result. | |
976 | """ |
|
984 | """ | |
977 |
|
985 | |||
978 | outstanding = self.queues[eid] |
|
986 | outstanding = self.queues[eid] | |
979 |
|
987 | |||
980 | for msg_id in outstanding: |
|
988 | for msg_id in outstanding: | |
981 | self.pending.remove(msg_id) |
|
989 | self.pending.remove(msg_id) | |
982 | self.all_completed.add(msg_id) |
|
990 | self.all_completed.add(msg_id) | |
983 | try: |
|
991 | try: | |
984 | raise error.EngineError("Engine %r died while running task %r" % (eid, msg_id)) |
|
992 | raise error.EngineError("Engine %r died while running task %r" % (eid, msg_id)) | |
985 | except: |
|
993 | except: | |
986 | content = error.wrap_exception() |
|
994 | content = error.wrap_exception() | |
987 | # build a fake header: |
|
995 | # build a fake header: | |
988 | header = {} |
|
996 | header = {} | |
989 | header['engine'] = uuid |
|
997 | header['engine'] = uuid | |
990 | header['date'] = datetime.now() |
|
998 | header['date'] = datetime.now() | |
991 | rec = dict(result_content=content, result_header=header, result_buffers=[]) |
|
999 | rec = dict(result_content=content, result_header=header, result_buffers=[]) | |
992 | rec['completed'] = header['date'] |
|
1000 | rec['completed'] = header['date'] | |
993 | rec['engine_uuid'] = uuid |
|
1001 | rec['engine_uuid'] = uuid | |
994 | try: |
|
1002 | try: | |
995 | self.db.update_record(msg_id, rec) |
|
1003 | self.db.update_record(msg_id, rec) | |
996 | except Exception: |
|
1004 | except Exception: | |
997 | self.log.error("DB Error handling stranded msg %r", msg_id, exc_info=True) |
|
1005 | self.log.error("DB Error handling stranded msg %r", msg_id, exc_info=True) | |
998 |
|
1006 | |||
999 |
|
1007 | |||
1000 | def finish_registration(self, heart): |
|
1008 | def finish_registration(self, heart): | |
1001 | """Second half of engine registration, called after our HeartMonitor |
|
1009 | """Second half of engine registration, called after our HeartMonitor | |
1002 | has received a beat from the Engine's Heart.""" |
|
1010 | has received a beat from the Engine's Heart.""" | |
1003 | try: |
|
1011 | try: | |
1004 | (eid,queue,reg,purge) = self.incoming_registrations.pop(heart) |
|
1012 | (eid,queue,reg,purge) = self.incoming_registrations.pop(heart) | |
1005 | except KeyError: |
|
1013 | except KeyError: | |
1006 | self.log.error("registration::tried to finish nonexistant registration", exc_info=True) |
|
1014 | self.log.error("registration::tried to finish nonexistant registration", exc_info=True) | |
1007 | return |
|
1015 | return | |
1008 | self.log.info("registration::finished registering engine %i:%r", eid, queue) |
|
1016 | self.log.info("registration::finished registering engine %i:%r", eid, queue) | |
1009 | if purge is not None: |
|
1017 | if purge is not None: | |
1010 | purge.stop() |
|
1018 | purge.stop() | |
1011 | control = queue |
|
1019 | control = queue | |
1012 | self.ids.add(eid) |
|
1020 | self.ids.add(eid) | |
1013 | self.keytable[eid] = queue |
|
1021 | self.keytable[eid] = queue | |
1014 | self.engines[eid] = EngineConnector(id=eid, queue=queue, registration=reg, |
|
1022 | self.engines[eid] = EngineConnector(id=eid, queue=queue, registration=reg, | |
1015 | control=control, heartbeat=heart) |
|
1023 | control=control, heartbeat=heart) | |
1016 | self.by_ident[queue] = eid |
|
1024 | self.by_ident[queue] = eid | |
1017 | self.queues[eid] = list() |
|
1025 | self.queues[eid] = list() | |
1018 | self.tasks[eid] = list() |
|
1026 | self.tasks[eid] = list() | |
1019 | self.completed[eid] = list() |
|
1027 | self.completed[eid] = list() | |
1020 | self.hearts[heart] = eid |
|
1028 | self.hearts[heart] = eid | |
1021 | content = dict(id=eid, queue=self.engines[eid].queue.decode('ascii')) |
|
1029 | content = dict(id=eid, queue=self.engines[eid].queue.decode('ascii')) | |
1022 | if self.notifier: |
|
1030 | if self.notifier: | |
1023 | self.session.send(self.notifier, "registration_notification", content=content) |
|
1031 | self.session.send(self.notifier, "registration_notification", content=content) | |
1024 | self.log.info("engine::Engine Connected: %i", eid) |
|
1032 | self.log.info("engine::Engine Connected: %i", eid) | |
1025 |
|
1033 | |||
1026 | def _purge_stalled_registration(self, heart): |
|
1034 | def _purge_stalled_registration(self, heart): | |
1027 | if heart in self.incoming_registrations: |
|
1035 | if heart in self.incoming_registrations: | |
1028 | eid = self.incoming_registrations.pop(heart)[0] |
|
1036 | eid = self.incoming_registrations.pop(heart)[0] | |
1029 | self.log.info("registration::purging stalled registration: %i", eid) |
|
1037 | self.log.info("registration::purging stalled registration: %i", eid) | |
1030 | else: |
|
1038 | else: | |
1031 | pass |
|
1039 | pass | |
1032 |
|
1040 | |||
1033 | #------------------------------------------------------------------------- |
|
1041 | #------------------------------------------------------------------------- | |
1034 | # Client Requests |
|
1042 | # Client Requests | |
1035 | #------------------------------------------------------------------------- |
|
1043 | #------------------------------------------------------------------------- | |
1036 |
|
1044 | |||
1037 | def shutdown_request(self, client_id, msg): |
|
1045 | def shutdown_request(self, client_id, msg): | |
1038 | """handle shutdown request.""" |
|
1046 | """handle shutdown request.""" | |
1039 | self.session.send(self.query, 'shutdown_reply', content={'status': 'ok'}, ident=client_id) |
|
1047 | self.session.send(self.query, 'shutdown_reply', content={'status': 'ok'}, ident=client_id) | |
1040 | # also notify other clients of shutdown |
|
1048 | # also notify other clients of shutdown | |
1041 | self.session.send(self.notifier, 'shutdown_notice', content={'status': 'ok'}) |
|
1049 | self.session.send(self.notifier, 'shutdown_notice', content={'status': 'ok'}) | |
1042 | dc = ioloop.DelayedCallback(lambda : self._shutdown(), 1000, self.loop) |
|
1050 | dc = ioloop.DelayedCallback(lambda : self._shutdown(), 1000, self.loop) | |
1043 | dc.start() |
|
1051 | dc.start() | |
1044 |
|
1052 | |||
1045 | def _shutdown(self): |
|
1053 | def _shutdown(self): | |
1046 | self.log.info("hub::hub shutting down.") |
|
1054 | self.log.info("hub::hub shutting down.") | |
1047 | time.sleep(0.1) |
|
1055 | time.sleep(0.1) | |
1048 | sys.exit(0) |
|
1056 | sys.exit(0) | |
1049 |
|
1057 | |||
1050 |
|
1058 | |||
1051 | def check_load(self, client_id, msg): |
|
1059 | def check_load(self, client_id, msg): | |
1052 | content = msg['content'] |
|
1060 | content = msg['content'] | |
1053 | try: |
|
1061 | try: | |
1054 | targets = content['targets'] |
|
1062 | targets = content['targets'] | |
1055 | targets = self._validate_targets(targets) |
|
1063 | targets = self._validate_targets(targets) | |
1056 | except: |
|
1064 | except: | |
1057 | content = error.wrap_exception() |
|
1065 | content = error.wrap_exception() | |
1058 | self.session.send(self.query, "hub_error", |
|
1066 | self.session.send(self.query, "hub_error", | |
1059 | content=content, ident=client_id) |
|
1067 | content=content, ident=client_id) | |
1060 | return |
|
1068 | return | |
1061 |
|
1069 | |||
1062 | content = dict(status='ok') |
|
1070 | content = dict(status='ok') | |
1063 | # loads = {} |
|
1071 | # loads = {} | |
1064 | for t in targets: |
|
1072 | for t in targets: | |
1065 | content[bytes(t)] = len(self.queues[t])+len(self.tasks[t]) |
|
1073 | content[bytes(t)] = len(self.queues[t])+len(self.tasks[t]) | |
1066 | self.session.send(self.query, "load_reply", content=content, ident=client_id) |
|
1074 | self.session.send(self.query, "load_reply", content=content, ident=client_id) | |
1067 |
|
1075 | |||
1068 |
|
1076 | |||
1069 | def queue_status(self, client_id, msg): |
|
1077 | def queue_status(self, client_id, msg): | |
1070 | """Return the Queue status of one or more targets. |
|
1078 | """Return the Queue status of one or more targets. | |
1071 | if verbose: return the msg_ids |
|
1079 | if verbose: return the msg_ids | |
1072 | else: return len of each type. |
|
1080 | else: return len of each type. | |
1073 | keys: queue (pending MUX jobs) |
|
1081 | keys: queue (pending MUX jobs) | |
1074 | tasks (pending Task jobs) |
|
1082 | tasks (pending Task jobs) | |
1075 | completed (finished jobs from both queues)""" |
|
1083 | completed (finished jobs from both queues)""" | |
1076 | content = msg['content'] |
|
1084 | content = msg['content'] | |
1077 | targets = content['targets'] |
|
1085 | targets = content['targets'] | |
1078 | try: |
|
1086 | try: | |
1079 | targets = self._validate_targets(targets) |
|
1087 | targets = self._validate_targets(targets) | |
1080 | except: |
|
1088 | except: | |
1081 | content = error.wrap_exception() |
|
1089 | content = error.wrap_exception() | |
1082 | self.session.send(self.query, "hub_error", |
|
1090 | self.session.send(self.query, "hub_error", | |
1083 | content=content, ident=client_id) |
|
1091 | content=content, ident=client_id) | |
1084 | return |
|
1092 | return | |
1085 | verbose = content.get('verbose', False) |
|
1093 | verbose = content.get('verbose', False) | |
1086 | content = dict(status='ok') |
|
1094 | content = dict(status='ok') | |
1087 | for t in targets: |
|
1095 | for t in targets: | |
1088 | queue = self.queues[t] |
|
1096 | queue = self.queues[t] | |
1089 | completed = self.completed[t] |
|
1097 | completed = self.completed[t] | |
1090 | tasks = self.tasks[t] |
|
1098 | tasks = self.tasks[t] | |
1091 | if not verbose: |
|
1099 | if not verbose: | |
1092 | queue = len(queue) |
|
1100 | queue = len(queue) | |
1093 | completed = len(completed) |
|
1101 | completed = len(completed) | |
1094 | tasks = len(tasks) |
|
1102 | tasks = len(tasks) | |
1095 | content[str(t)] = {'queue': queue, 'completed': completed , 'tasks': tasks} |
|
1103 | content[str(t)] = {'queue': queue, 'completed': completed , 'tasks': tasks} | |
1096 | content['unassigned'] = list(self.unassigned) if verbose else len(self.unassigned) |
|
1104 | content['unassigned'] = list(self.unassigned) if verbose else len(self.unassigned) | |
1097 | # print (content) |
|
1105 | # print (content) | |
1098 | self.session.send(self.query, "queue_reply", content=content, ident=client_id) |
|
1106 | self.session.send(self.query, "queue_reply", content=content, ident=client_id) | |
1099 |
|
1107 | |||
1100 | def purge_results(self, client_id, msg): |
|
1108 | def purge_results(self, client_id, msg): | |
1101 | """Purge results from memory. This method is more valuable before we move |
|
1109 | """Purge results from memory. This method is more valuable before we move | |
1102 | to a DB based message storage mechanism.""" |
|
1110 | to a DB based message storage mechanism.""" | |
1103 | content = msg['content'] |
|
1111 | content = msg['content'] | |
1104 | self.log.info("Dropping records with %s", content) |
|
1112 | self.log.info("Dropping records with %s", content) | |
1105 | msg_ids = content.get('msg_ids', []) |
|
1113 | msg_ids = content.get('msg_ids', []) | |
1106 | reply = dict(status='ok') |
|
1114 | reply = dict(status='ok') | |
1107 | if msg_ids == 'all': |
|
1115 | if msg_ids == 'all': | |
1108 | try: |
|
1116 | try: | |
1109 | self.db.drop_matching_records(dict(completed={'$ne':None})) |
|
1117 | self.db.drop_matching_records(dict(completed={'$ne':None})) | |
1110 | except Exception: |
|
1118 | except Exception: | |
1111 | reply = error.wrap_exception() |
|
1119 | reply = error.wrap_exception() | |
1112 | else: |
|
1120 | else: | |
1113 | pending = filter(lambda m: m in self.pending, msg_ids) |
|
1121 | pending = filter(lambda m: m in self.pending, msg_ids) | |
1114 | if pending: |
|
1122 | if pending: | |
1115 | try: |
|
1123 | try: | |
1116 | raise IndexError("msg pending: %r" % pending[0]) |
|
1124 | raise IndexError("msg pending: %r" % pending[0]) | |
1117 | except: |
|
1125 | except: | |
1118 | reply = error.wrap_exception() |
|
1126 | reply = error.wrap_exception() | |
1119 | else: |
|
1127 | else: | |
1120 | try: |
|
1128 | try: | |
1121 | self.db.drop_matching_records(dict(msg_id={'$in':msg_ids})) |
|
1129 | self.db.drop_matching_records(dict(msg_id={'$in':msg_ids})) | |
1122 | except Exception: |
|
1130 | except Exception: | |
1123 | reply = error.wrap_exception() |
|
1131 | reply = error.wrap_exception() | |
1124 |
|
1132 | |||
1125 | if reply['status'] == 'ok': |
|
1133 | if reply['status'] == 'ok': | |
1126 | eids = content.get('engine_ids', []) |
|
1134 | eids = content.get('engine_ids', []) | |
1127 | for eid in eids: |
|
1135 | for eid in eids: | |
1128 | if eid not in self.engines: |
|
1136 | if eid not in self.engines: | |
1129 | try: |
|
1137 | try: | |
1130 | raise IndexError("No such engine: %i" % eid) |
|
1138 | raise IndexError("No such engine: %i" % eid) | |
1131 | except: |
|
1139 | except: | |
1132 | reply = error.wrap_exception() |
|
1140 | reply = error.wrap_exception() | |
1133 | break |
|
1141 | break | |
1134 | uid = self.engines[eid].queue |
|
1142 | uid = self.engines[eid].queue | |
1135 | try: |
|
1143 | try: | |
1136 | self.db.drop_matching_records(dict(engine_uuid=uid, completed={'$ne':None})) |
|
1144 | self.db.drop_matching_records(dict(engine_uuid=uid, completed={'$ne':None})) | |
1137 | except Exception: |
|
1145 | except Exception: | |
1138 | reply = error.wrap_exception() |
|
1146 | reply = error.wrap_exception() | |
1139 | break |
|
1147 | break | |
1140 |
|
1148 | |||
1141 | self.session.send(self.query, 'purge_reply', content=reply, ident=client_id) |
|
1149 | self.session.send(self.query, 'purge_reply', content=reply, ident=client_id) | |
1142 |
|
1150 | |||
1143 | def resubmit_task(self, client_id, msg): |
|
1151 | def resubmit_task(self, client_id, msg): | |
1144 | """Resubmit one or more tasks.""" |
|
1152 | """Resubmit one or more tasks.""" | |
1145 | def finish(reply): |
|
1153 | def finish(reply): | |
1146 | self.session.send(self.query, 'resubmit_reply', content=reply, ident=client_id) |
|
1154 | self.session.send(self.query, 'resubmit_reply', content=reply, ident=client_id) | |
1147 |
|
1155 | |||
1148 | content = msg['content'] |
|
1156 | content = msg['content'] | |
1149 | msg_ids = content['msg_ids'] |
|
1157 | msg_ids = content['msg_ids'] | |
1150 | reply = dict(status='ok') |
|
1158 | reply = dict(status='ok') | |
1151 | try: |
|
1159 | try: | |
1152 | records = self.db.find_records({'msg_id' : {'$in' : msg_ids}}, keys=[ |
|
1160 | records = self.db.find_records({'msg_id' : {'$in' : msg_ids}}, keys=[ | |
1153 | 'header', 'content', 'buffers']) |
|
1161 | 'header', 'content', 'buffers']) | |
1154 | except Exception: |
|
1162 | except Exception: | |
1155 | self.log.error('db::db error finding tasks to resubmit', exc_info=True) |
|
1163 | self.log.error('db::db error finding tasks to resubmit', exc_info=True) | |
1156 | return finish(error.wrap_exception()) |
|
1164 | return finish(error.wrap_exception()) | |
1157 |
|
1165 | |||
1158 | # validate msg_ids |
|
1166 | # validate msg_ids | |
1159 | found_ids = [ rec['msg_id'] for rec in records ] |
|
1167 | found_ids = [ rec['msg_id'] for rec in records ] | |
1160 | pending_ids = [ msg_id for msg_id in found_ids if msg_id in self.pending ] |
|
1168 | pending_ids = [ msg_id for msg_id in found_ids if msg_id in self.pending ] | |
1161 | if len(records) > len(msg_ids): |
|
1169 | if len(records) > len(msg_ids): | |
1162 | try: |
|
1170 | try: | |
1163 | raise RuntimeError("DB appears to be in an inconsistent state." |
|
1171 | raise RuntimeError("DB appears to be in an inconsistent state." | |
1164 | "More matching records were found than should exist") |
|
1172 | "More matching records were found than should exist") | |
1165 | except Exception: |
|
1173 | except Exception: | |
1166 | return finish(error.wrap_exception()) |
|
1174 | return finish(error.wrap_exception()) | |
1167 | elif len(records) < len(msg_ids): |
|
1175 | elif len(records) < len(msg_ids): | |
1168 | missing = [ m for m in msg_ids if m not in found_ids ] |
|
1176 | missing = [ m for m in msg_ids if m not in found_ids ] | |
1169 | try: |
|
1177 | try: | |
1170 | raise KeyError("No such msg(s): %r" % missing) |
|
1178 | raise KeyError("No such msg(s): %r" % missing) | |
1171 | except KeyError: |
|
1179 | except KeyError: | |
1172 | return finish(error.wrap_exception()) |
|
1180 | return finish(error.wrap_exception()) | |
1173 | elif pending_ids: |
|
1181 | elif pending_ids: | |
1174 | pass |
|
1182 | pass | |
1175 | # no need to raise on resubmit of pending task, now that we |
|
1183 | # no need to raise on resubmit of pending task, now that we | |
1176 | # resubmit under new ID, but do we want to raise anyway? |
|
1184 | # resubmit under new ID, but do we want to raise anyway? | |
1177 | # msg_id = invalid_ids[0] |
|
1185 | # msg_id = invalid_ids[0] | |
1178 | # try: |
|
1186 | # try: | |
1179 | # raise ValueError("Task(s) %r appears to be inflight" % ) |
|
1187 | # raise ValueError("Task(s) %r appears to be inflight" % ) | |
1180 | # except Exception: |
|
1188 | # except Exception: | |
1181 | # return finish(error.wrap_exception()) |
|
1189 | # return finish(error.wrap_exception()) | |
1182 |
|
1190 | |||
1183 | # mapping of original IDs to resubmitted IDs |
|
1191 | # mapping of original IDs to resubmitted IDs | |
1184 | resubmitted = {} |
|
1192 | resubmitted = {} | |
1185 |
|
1193 | |||
1186 | # send the messages |
|
1194 | # send the messages | |
1187 | for rec in records: |
|
1195 | for rec in records: | |
1188 | header = rec['header'] |
|
1196 | header = rec['header'] | |
1189 | msg = self.session.msg(header['msg_type'], parent=header) |
|
1197 | msg = self.session.msg(header['msg_type'], parent=header) | |
1190 | msg_id = msg['msg_id'] |
|
1198 | msg_id = msg['msg_id'] | |
1191 | msg['content'] = rec['content'] |
|
1199 | msg['content'] = rec['content'] | |
1192 |
|
1200 | |||
1193 | # use the old header, but update msg_id and timestamp |
|
1201 | # use the old header, but update msg_id and timestamp | |
1194 | fresh = msg['header'] |
|
1202 | fresh = msg['header'] | |
1195 | header['msg_id'] = fresh['msg_id'] |
|
1203 | header['msg_id'] = fresh['msg_id'] | |
1196 | header['date'] = fresh['date'] |
|
1204 | header['date'] = fresh['date'] | |
1197 | msg['header'] = header |
|
1205 | msg['header'] = header | |
1198 |
|
1206 | |||
1199 | self.session.send(self.resubmit, msg, buffers=rec['buffers']) |
|
1207 | self.session.send(self.resubmit, msg, buffers=rec['buffers']) | |
1200 |
|
1208 | |||
1201 | resubmitted[rec['msg_id']] = msg_id |
|
1209 | resubmitted[rec['msg_id']] = msg_id | |
1202 | self.pending.add(msg_id) |
|
1210 | self.pending.add(msg_id) | |
1203 | msg['buffers'] = rec['buffers'] |
|
1211 | msg['buffers'] = rec['buffers'] | |
1204 | try: |
|
1212 | try: | |
1205 | self.db.add_record(msg_id, init_record(msg)) |
|
1213 | self.db.add_record(msg_id, init_record(msg)) | |
1206 | except Exception: |
|
1214 | except Exception: | |
1207 | self.log.error("db::DB Error updating record: %s", msg_id, exc_info=True) |
|
1215 | self.log.error("db::DB Error updating record: %s", msg_id, exc_info=True) | |
1208 |
|
1216 | |||
1209 | finish(dict(status='ok', resubmitted=resubmitted)) |
|
1217 | finish(dict(status='ok', resubmitted=resubmitted)) | |
1210 |
|
1218 | |||
1211 | # store the new IDs in the Task DB |
|
1219 | # store the new IDs in the Task DB | |
1212 | for msg_id, resubmit_id in resubmitted.iteritems(): |
|
1220 | for msg_id, resubmit_id in resubmitted.iteritems(): | |
1213 | try: |
|
1221 | try: | |
1214 | self.db.update_record(msg_id, {'resubmitted' : resubmit_id}) |
|
1222 | self.db.update_record(msg_id, {'resubmitted' : resubmit_id}) | |
1215 | except Exception: |
|
1223 | except Exception: | |
1216 | self.log.error("db::DB Error updating record: %s", msg_id, exc_info=True) |
|
1224 | self.log.error("db::DB Error updating record: %s", msg_id, exc_info=True) | |
1217 |
|
1225 | |||
1218 |
|
1226 | |||
1219 | def _extract_record(self, rec): |
|
1227 | def _extract_record(self, rec): | |
1220 | """decompose a TaskRecord dict into subsection of reply for get_result""" |
|
1228 | """decompose a TaskRecord dict into subsection of reply for get_result""" | |
1221 | io_dict = {} |
|
1229 | io_dict = {} | |
1222 | for key in ('pyin', 'pyout', 'pyerr', 'stdout', 'stderr'): |
|
1230 | for key in ('pyin', 'pyout', 'pyerr', 'stdout', 'stderr'): | |
1223 | io_dict[key] = rec[key] |
|
1231 | io_dict[key] = rec[key] | |
1224 | content = { 'result_content': rec['result_content'], |
|
1232 | content = { | |
1225 |
|
|
1233 | 'header': rec['header'], | |
1226 | 'result_header' : rec['result_header'], |
|
1234 | 'metadata': rec['metadata'], | |
1227 | 'received' : rec['received'], |
|
1235 | 'result_metadata': rec['result_metadata'], | |
1228 | 'io' : io_dict, |
|
1236 | 'result_header' : rec['result_header'], | |
1229 | } |
|
1237 | 'result_content': rec['result_content'], | |
|
1238 | 'received' : rec['received'], | |||
|
1239 | 'io' : io_dict, | |||
|
1240 | } | |||
1230 | if rec['result_buffers']: |
|
1241 | if rec['result_buffers']: | |
1231 | buffers = map(bytes, rec['result_buffers']) |
|
1242 | buffers = map(bytes, rec['result_buffers']) | |
1232 | else: |
|
1243 | else: | |
1233 | buffers = [] |
|
1244 | buffers = [] | |
1234 |
|
1245 | |||
1235 | return content, buffers |
|
1246 | return content, buffers | |
1236 |
|
1247 | |||
1237 | def get_results(self, client_id, msg): |
|
1248 | def get_results(self, client_id, msg): | |
1238 | """Get the result of 1 or more messages.""" |
|
1249 | """Get the result of 1 or more messages.""" | |
1239 | content = msg['content'] |
|
1250 | content = msg['content'] | |
1240 | msg_ids = sorted(set(content['msg_ids'])) |
|
1251 | msg_ids = sorted(set(content['msg_ids'])) | |
1241 | statusonly = content.get('status_only', False) |
|
1252 | statusonly = content.get('status_only', False) | |
1242 | pending = [] |
|
1253 | pending = [] | |
1243 | completed = [] |
|
1254 | completed = [] | |
1244 | content = dict(status='ok') |
|
1255 | content = dict(status='ok') | |
1245 | content['pending'] = pending |
|
1256 | content['pending'] = pending | |
1246 | content['completed'] = completed |
|
1257 | content['completed'] = completed | |
1247 | buffers = [] |
|
1258 | buffers = [] | |
1248 | if not statusonly: |
|
1259 | if not statusonly: | |
1249 | try: |
|
1260 | try: | |
1250 | matches = self.db.find_records(dict(msg_id={'$in':msg_ids})) |
|
1261 | matches = self.db.find_records(dict(msg_id={'$in':msg_ids})) | |
1251 | # turn match list into dict, for faster lookup |
|
1262 | # turn match list into dict, for faster lookup | |
1252 | records = {} |
|
1263 | records = {} | |
1253 | for rec in matches: |
|
1264 | for rec in matches: | |
1254 | records[rec['msg_id']] = rec |
|
1265 | records[rec['msg_id']] = rec | |
1255 | except Exception: |
|
1266 | except Exception: | |
1256 | content = error.wrap_exception() |
|
1267 | content = error.wrap_exception() | |
1257 | self.session.send(self.query, "result_reply", content=content, |
|
1268 | self.session.send(self.query, "result_reply", content=content, | |
1258 | parent=msg, ident=client_id) |
|
1269 | parent=msg, ident=client_id) | |
1259 | return |
|
1270 | return | |
1260 | else: |
|
1271 | else: | |
1261 | records = {} |
|
1272 | records = {} | |
1262 | for msg_id in msg_ids: |
|
1273 | for msg_id in msg_ids: | |
1263 | if msg_id in self.pending: |
|
1274 | if msg_id in self.pending: | |
1264 | pending.append(msg_id) |
|
1275 | pending.append(msg_id) | |
1265 | elif msg_id in self.all_completed: |
|
1276 | elif msg_id in self.all_completed: | |
1266 | completed.append(msg_id) |
|
1277 | completed.append(msg_id) | |
1267 | if not statusonly: |
|
1278 | if not statusonly: | |
1268 | c,bufs = self._extract_record(records[msg_id]) |
|
1279 | c,bufs = self._extract_record(records[msg_id]) | |
1269 | content[msg_id] = c |
|
1280 | content[msg_id] = c | |
1270 | buffers.extend(bufs) |
|
1281 | buffers.extend(bufs) | |
1271 | elif msg_id in records: |
|
1282 | elif msg_id in records: | |
1272 | if rec['completed']: |
|
1283 | if rec['completed']: | |
1273 | completed.append(msg_id) |
|
1284 | completed.append(msg_id) | |
1274 | c,bufs = self._extract_record(records[msg_id]) |
|
1285 | c,bufs = self._extract_record(records[msg_id]) | |
1275 | content[msg_id] = c |
|
1286 | content[msg_id] = c | |
1276 | buffers.extend(bufs) |
|
1287 | buffers.extend(bufs) | |
1277 | else: |
|
1288 | else: | |
1278 | pending.append(msg_id) |
|
1289 | pending.append(msg_id) | |
1279 | else: |
|
1290 | else: | |
1280 | try: |
|
1291 | try: | |
1281 | raise KeyError('No such message: '+msg_id) |
|
1292 | raise KeyError('No such message: '+msg_id) | |
1282 | except: |
|
1293 | except: | |
1283 | content = error.wrap_exception() |
|
1294 | content = error.wrap_exception() | |
1284 | break |
|
1295 | break | |
1285 | self.session.send(self.query, "result_reply", content=content, |
|
1296 | self.session.send(self.query, "result_reply", content=content, | |
1286 | parent=msg, ident=client_id, |
|
1297 | parent=msg, ident=client_id, | |
1287 | buffers=buffers) |
|
1298 | buffers=buffers) | |
1288 |
|
1299 | |||
1289 | def get_history(self, client_id, msg): |
|
1300 | def get_history(self, client_id, msg): | |
1290 | """Get a list of all msg_ids in our DB records""" |
|
1301 | """Get a list of all msg_ids in our DB records""" | |
1291 | try: |
|
1302 | try: | |
1292 | msg_ids = self.db.get_history() |
|
1303 | msg_ids = self.db.get_history() | |
1293 | except Exception as e: |
|
1304 | except Exception as e: | |
1294 | content = error.wrap_exception() |
|
1305 | content = error.wrap_exception() | |
1295 | else: |
|
1306 | else: | |
1296 | content = dict(status='ok', history=msg_ids) |
|
1307 | content = dict(status='ok', history=msg_ids) | |
1297 |
|
1308 | |||
1298 | self.session.send(self.query, "history_reply", content=content, |
|
1309 | self.session.send(self.query, "history_reply", content=content, | |
1299 | parent=msg, ident=client_id) |
|
1310 | parent=msg, ident=client_id) | |
1300 |
|
1311 | |||
1301 | def db_query(self, client_id, msg): |
|
1312 | def db_query(self, client_id, msg): | |
1302 | """Perform a raw query on the task record database.""" |
|
1313 | """Perform a raw query on the task record database.""" | |
1303 | content = msg['content'] |
|
1314 | content = msg['content'] | |
1304 | query = content.get('query', {}) |
|
1315 | query = content.get('query', {}) | |
1305 | keys = content.get('keys', None) |
|
1316 | keys = content.get('keys', None) | |
1306 | buffers = [] |
|
1317 | buffers = [] | |
1307 | empty = list() |
|
1318 | empty = list() | |
1308 | try: |
|
1319 | try: | |
1309 | records = self.db.find_records(query, keys) |
|
1320 | records = self.db.find_records(query, keys) | |
1310 | except Exception as e: |
|
1321 | except Exception as e: | |
1311 | content = error.wrap_exception() |
|
1322 | content = error.wrap_exception() | |
1312 | else: |
|
1323 | else: | |
1313 | # extract buffers from reply content: |
|
1324 | # extract buffers from reply content: | |
1314 | if keys is not None: |
|
1325 | if keys is not None: | |
1315 | buffer_lens = [] if 'buffers' in keys else None |
|
1326 | buffer_lens = [] if 'buffers' in keys else None | |
1316 | result_buffer_lens = [] if 'result_buffers' in keys else None |
|
1327 | result_buffer_lens = [] if 'result_buffers' in keys else None | |
1317 | else: |
|
1328 | else: | |
1318 | buffer_lens = None |
|
1329 | buffer_lens = None | |
1319 | result_buffer_lens = None |
|
1330 | result_buffer_lens = None | |
1320 |
|
1331 | |||
1321 | for rec in records: |
|
1332 | for rec in records: | |
1322 | # buffers may be None, so double check |
|
1333 | # buffers may be None, so double check | |
1323 | b = rec.pop('buffers', empty) or empty |
|
1334 | b = rec.pop('buffers', empty) or empty | |
1324 | if buffer_lens is not None: |
|
1335 | if buffer_lens is not None: | |
1325 | buffer_lens.append(len(b)) |
|
1336 | buffer_lens.append(len(b)) | |
1326 | buffers.extend(b) |
|
1337 | buffers.extend(b) | |
1327 | rb = rec.pop('result_buffers', empty) or empty |
|
1338 | rb = rec.pop('result_buffers', empty) or empty | |
1328 | if result_buffer_lens is not None: |
|
1339 | if result_buffer_lens is not None: | |
1329 | result_buffer_lens.append(len(rb)) |
|
1340 | result_buffer_lens.append(len(rb)) | |
1330 | buffers.extend(rb) |
|
1341 | buffers.extend(rb) | |
1331 | content = dict(status='ok', records=records, buffer_lens=buffer_lens, |
|
1342 | content = dict(status='ok', records=records, buffer_lens=buffer_lens, | |
1332 | result_buffer_lens=result_buffer_lens) |
|
1343 | result_buffer_lens=result_buffer_lens) | |
1333 | # self.log.debug (content) |
|
1344 | # self.log.debug (content) | |
1334 | self.session.send(self.query, "db_reply", content=content, |
|
1345 | self.session.send(self.query, "db_reply", content=content, | |
1335 | parent=msg, ident=client_id, |
|
1346 | parent=msg, ident=client_id, | |
1336 | buffers=buffers) |
|
1347 | buffers=buffers) | |
1337 |
|
1348 |
@@ -1,768 +1,771 b'' | |||||
1 | """The Python scheduler for rich scheduling. |
|
1 | """The Python scheduler for rich scheduling. | |
2 |
|
2 | |||
3 | The Pure ZMQ scheduler does not allow routing schemes other than LRU, |
|
3 | The Pure ZMQ scheduler does not allow routing schemes other than LRU, | |
4 | nor does it check msg_id DAG dependencies. For those, a slightly slower |
|
4 | nor does it check msg_id DAG dependencies. For those, a slightly slower | |
5 | Python Scheduler exists. |
|
5 | Python Scheduler exists. | |
6 |
|
6 | |||
7 | Authors: |
|
7 | Authors: | |
8 |
|
8 | |||
9 | * Min RK |
|
9 | * Min RK | |
10 | """ |
|
10 | """ | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Copyright (C) 2010-2011 The IPython Development Team |
|
12 | # Copyright (C) 2010-2011 The IPython Development Team | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #---------------------------------------------------------------------- |
|
18 | #---------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #---------------------------------------------------------------------- |
|
20 | #---------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | from __future__ import print_function |
|
22 | from __future__ import print_function | |
23 |
|
23 | |||
24 | import logging |
|
24 | import logging | |
25 | import sys |
|
25 | import sys | |
26 | import time |
|
26 | import time | |
27 |
|
27 | |||
28 | from datetime import datetime, timedelta |
|
28 | from datetime import datetime, timedelta | |
29 | from random import randint, random |
|
29 | from random import randint, random | |
30 | from types import FunctionType |
|
30 | from types import FunctionType | |
31 |
|
31 | |||
32 | try: |
|
32 | try: | |
33 | import numpy |
|
33 | import numpy | |
34 | except ImportError: |
|
34 | except ImportError: | |
35 | numpy = None |
|
35 | numpy = None | |
36 |
|
36 | |||
37 | import zmq |
|
37 | import zmq | |
38 | from zmq.eventloop import ioloop, zmqstream |
|
38 | from zmq.eventloop import ioloop, zmqstream | |
39 |
|
39 | |||
40 | # local imports |
|
40 | # local imports | |
41 | from IPython.external.decorator import decorator |
|
41 | from IPython.external.decorator import decorator | |
42 | from IPython.config.application import Application |
|
42 | from IPython.config.application import Application | |
43 | from IPython.config.loader import Config |
|
43 | from IPython.config.loader import Config | |
44 | from IPython.utils.traitlets import Instance, Dict, List, Set, Integer, Enum, CBytes |
|
44 | from IPython.utils.traitlets import Instance, Dict, List, Set, Integer, Enum, CBytes | |
45 | from IPython.utils.py3compat import cast_bytes |
|
45 | from IPython.utils.py3compat import cast_bytes | |
46 |
|
46 | |||
47 | from IPython.parallel import error, util |
|
47 | from IPython.parallel import error, util | |
48 | from IPython.parallel.factory import SessionFactory |
|
48 | from IPython.parallel.factory import SessionFactory | |
49 | from IPython.parallel.util import connect_logger, local_logger |
|
49 | from IPython.parallel.util import connect_logger, local_logger | |
50 |
|
50 | |||
51 | from .dependency import Dependency |
|
51 | from .dependency import Dependency | |
52 |
|
52 | |||
53 | @decorator |
|
53 | @decorator | |
54 | def logged(f,self,*args,**kwargs): |
|
54 | def logged(f,self,*args,**kwargs): | |
55 | # print ("#--------------------") |
|
55 | # print ("#--------------------") | |
56 | self.log.debug("scheduler::%s(*%s,**%s)", f.func_name, args, kwargs) |
|
56 | self.log.debug("scheduler::%s(*%s,**%s)", f.func_name, args, kwargs) | |
57 | # print ("#--") |
|
57 | # print ("#--") | |
58 | return f(self,*args, **kwargs) |
|
58 | return f(self,*args, **kwargs) | |
59 |
|
59 | |||
60 | #---------------------------------------------------------------------- |
|
60 | #---------------------------------------------------------------------- | |
61 | # Chooser functions |
|
61 | # Chooser functions | |
62 | #---------------------------------------------------------------------- |
|
62 | #---------------------------------------------------------------------- | |
63 |
|
63 | |||
64 | def plainrandom(loads): |
|
64 | def plainrandom(loads): | |
65 | """Plain random pick.""" |
|
65 | """Plain random pick.""" | |
66 | n = len(loads) |
|
66 | n = len(loads) | |
67 | return randint(0,n-1) |
|
67 | return randint(0,n-1) | |
68 |
|
68 | |||
69 | def lru(loads): |
|
69 | def lru(loads): | |
70 | """Always pick the front of the line. |
|
70 | """Always pick the front of the line. | |
71 |
|
71 | |||
72 | The content of `loads` is ignored. |
|
72 | The content of `loads` is ignored. | |
73 |
|
73 | |||
74 | Assumes LRU ordering of loads, with oldest first. |
|
74 | Assumes LRU ordering of loads, with oldest first. | |
75 | """ |
|
75 | """ | |
76 | return 0 |
|
76 | return 0 | |
77 |
|
77 | |||
78 | def twobin(loads): |
|
78 | def twobin(loads): | |
79 | """Pick two at random, use the LRU of the two. |
|
79 | """Pick two at random, use the LRU of the two. | |
80 |
|
80 | |||
81 | The content of loads is ignored. |
|
81 | The content of loads is ignored. | |
82 |
|
82 | |||
83 | Assumes LRU ordering of loads, with oldest first. |
|
83 | Assumes LRU ordering of loads, with oldest first. | |
84 | """ |
|
84 | """ | |
85 | n = len(loads) |
|
85 | n = len(loads) | |
86 | a = randint(0,n-1) |
|
86 | a = randint(0,n-1) | |
87 | b = randint(0,n-1) |
|
87 | b = randint(0,n-1) | |
88 | return min(a,b) |
|
88 | return min(a,b) | |
89 |
|
89 | |||
90 | def weighted(loads): |
|
90 | def weighted(loads): | |
91 | """Pick two at random using inverse load as weight. |
|
91 | """Pick two at random using inverse load as weight. | |
92 |
|
92 | |||
93 | Return the less loaded of the two. |
|
93 | Return the less loaded of the two. | |
94 | """ |
|
94 | """ | |
95 | # weight 0 a million times more than 1: |
|
95 | # weight 0 a million times more than 1: | |
96 | weights = 1./(1e-6+numpy.array(loads)) |
|
96 | weights = 1./(1e-6+numpy.array(loads)) | |
97 | sums = weights.cumsum() |
|
97 | sums = weights.cumsum() | |
98 | t = sums[-1] |
|
98 | t = sums[-1] | |
99 | x = random()*t |
|
99 | x = random()*t | |
100 | y = random()*t |
|
100 | y = random()*t | |
101 | idx = 0 |
|
101 | idx = 0 | |
102 | idy = 0 |
|
102 | idy = 0 | |
103 | while sums[idx] < x: |
|
103 | while sums[idx] < x: | |
104 | idx += 1 |
|
104 | idx += 1 | |
105 | while sums[idy] < y: |
|
105 | while sums[idy] < y: | |
106 | idy += 1 |
|
106 | idy += 1 | |
107 | if weights[idy] > weights[idx]: |
|
107 | if weights[idy] > weights[idx]: | |
108 | return idy |
|
108 | return idy | |
109 | else: |
|
109 | else: | |
110 | return idx |
|
110 | return idx | |
111 |
|
111 | |||
112 | def leastload(loads): |
|
112 | def leastload(loads): | |
113 | """Always choose the lowest load. |
|
113 | """Always choose the lowest load. | |
114 |
|
114 | |||
115 | If the lowest load occurs more than once, the first |
|
115 | If the lowest load occurs more than once, the first | |
116 | occurance will be used. If loads has LRU ordering, this means |
|
116 | occurance will be used. If loads has LRU ordering, this means | |
117 | the LRU of those with the lowest load is chosen. |
|
117 | the LRU of those with the lowest load is chosen. | |
118 | """ |
|
118 | """ | |
119 | return loads.index(min(loads)) |
|
119 | return loads.index(min(loads)) | |
120 |
|
120 | |||
121 | #--------------------------------------------------------------------- |
|
121 | #--------------------------------------------------------------------- | |
122 | # Classes |
|
122 | # Classes | |
123 | #--------------------------------------------------------------------- |
|
123 | #--------------------------------------------------------------------- | |
124 |
|
124 | |||
125 |
|
125 | |||
126 | # store empty default dependency: |
|
126 | # store empty default dependency: | |
127 | MET = Dependency([]) |
|
127 | MET = Dependency([]) | |
128 |
|
128 | |||
129 |
|
129 | |||
130 | class Job(object): |
|
130 | class Job(object): | |
131 | """Simple container for a job""" |
|
131 | """Simple container for a job""" | |
132 |
def __init__(self, msg_id, raw_msg, idents, msg, header, |
|
132 | def __init__(self, msg_id, raw_msg, idents, msg, header, metadata, | |
|
133 | targets, after, follow, timeout): | |||
133 | self.msg_id = msg_id |
|
134 | self.msg_id = msg_id | |
134 | self.raw_msg = raw_msg |
|
135 | self.raw_msg = raw_msg | |
135 | self.idents = idents |
|
136 | self.idents = idents | |
136 | self.msg = msg |
|
137 | self.msg = msg | |
137 | self.header = header |
|
138 | self.header = header | |
|
139 | self.metadata = metadata | |||
138 | self.targets = targets |
|
140 | self.targets = targets | |
139 | self.after = after |
|
141 | self.after = after | |
140 | self.follow = follow |
|
142 | self.follow = follow | |
141 | self.timeout = timeout |
|
143 | self.timeout = timeout | |
142 |
|
144 | |||
143 |
|
145 | |||
144 | self.timestamp = time.time() |
|
146 | self.timestamp = time.time() | |
145 | self.blacklist = set() |
|
147 | self.blacklist = set() | |
146 |
|
148 | |||
147 | @property |
|
149 | @property | |
148 | def dependents(self): |
|
150 | def dependents(self): | |
149 | return self.follow.union(self.after) |
|
151 | return self.follow.union(self.after) | |
150 |
|
152 | |||
151 | class TaskScheduler(SessionFactory): |
|
153 | class TaskScheduler(SessionFactory): | |
152 | """Python TaskScheduler object. |
|
154 | """Python TaskScheduler object. | |
153 |
|
155 | |||
154 | This is the simplest object that supports msg_id based |
|
156 | This is the simplest object that supports msg_id based | |
155 | DAG dependencies. *Only* task msg_ids are checked, not |
|
157 | DAG dependencies. *Only* task msg_ids are checked, not | |
156 | msg_ids of jobs submitted via the MUX queue. |
|
158 | msg_ids of jobs submitted via the MUX queue. | |
157 |
|
159 | |||
158 | """ |
|
160 | """ | |
159 |
|
161 | |||
160 | hwm = Integer(1, config=True, |
|
162 | hwm = Integer(1, config=True, | |
161 | help="""specify the High Water Mark (HWM) for the downstream |
|
163 | help="""specify the High Water Mark (HWM) for the downstream | |
162 | socket in the Task scheduler. This is the maximum number |
|
164 | socket in the Task scheduler. This is the maximum number | |
163 | of allowed outstanding tasks on each engine. |
|
165 | of allowed outstanding tasks on each engine. | |
164 |
|
166 | |||
165 | The default (1) means that only one task can be outstanding on each |
|
167 | The default (1) means that only one task can be outstanding on each | |
166 | engine. Setting TaskScheduler.hwm=0 means there is no limit, and the |
|
168 | engine. Setting TaskScheduler.hwm=0 means there is no limit, and the | |
167 | engines continue to be assigned tasks while they are working, |
|
169 | engines continue to be assigned tasks while they are working, | |
168 | effectively hiding network latency behind computation, but can result |
|
170 | effectively hiding network latency behind computation, but can result | |
169 | in an imbalance of work when submitting many heterogenous tasks all at |
|
171 | in an imbalance of work when submitting many heterogenous tasks all at | |
170 | once. Any positive value greater than one is a compromise between the |
|
172 | once. Any positive value greater than one is a compromise between the | |
171 | two. |
|
173 | two. | |
172 |
|
174 | |||
173 | """ |
|
175 | """ | |
174 | ) |
|
176 | ) | |
175 | scheme_name = Enum(('leastload', 'pure', 'lru', 'plainrandom', 'weighted', 'twobin'), |
|
177 | scheme_name = Enum(('leastload', 'pure', 'lru', 'plainrandom', 'weighted', 'twobin'), | |
176 | 'leastload', config=True, allow_none=False, |
|
178 | 'leastload', config=True, allow_none=False, | |
177 | help="""select the task scheduler scheme [default: Python LRU] |
|
179 | help="""select the task scheduler scheme [default: Python LRU] | |
178 | Options are: 'pure', 'lru', 'plainrandom', 'weighted', 'twobin','leastload'""" |
|
180 | Options are: 'pure', 'lru', 'plainrandom', 'weighted', 'twobin','leastload'""" | |
179 | ) |
|
181 | ) | |
180 | def _scheme_name_changed(self, old, new): |
|
182 | def _scheme_name_changed(self, old, new): | |
181 | self.log.debug("Using scheme %r"%new) |
|
183 | self.log.debug("Using scheme %r"%new) | |
182 | self.scheme = globals()[new] |
|
184 | self.scheme = globals()[new] | |
183 |
|
185 | |||
184 | # input arguments: |
|
186 | # input arguments: | |
185 | scheme = Instance(FunctionType) # function for determining the destination |
|
187 | scheme = Instance(FunctionType) # function for determining the destination | |
186 | def _scheme_default(self): |
|
188 | def _scheme_default(self): | |
187 | return leastload |
|
189 | return leastload | |
188 | client_stream = Instance(zmqstream.ZMQStream) # client-facing stream |
|
190 | client_stream = Instance(zmqstream.ZMQStream) # client-facing stream | |
189 | engine_stream = Instance(zmqstream.ZMQStream) # engine-facing stream |
|
191 | engine_stream = Instance(zmqstream.ZMQStream) # engine-facing stream | |
190 | notifier_stream = Instance(zmqstream.ZMQStream) # hub-facing sub stream |
|
192 | notifier_stream = Instance(zmqstream.ZMQStream) # hub-facing sub stream | |
191 | mon_stream = Instance(zmqstream.ZMQStream) # hub-facing pub stream |
|
193 | mon_stream = Instance(zmqstream.ZMQStream) # hub-facing pub stream | |
192 |
|
194 | |||
193 | # internals: |
|
195 | # internals: | |
194 | graph = Dict() # dict by msg_id of [ msg_ids that depend on key ] |
|
196 | graph = Dict() # dict by msg_id of [ msg_ids that depend on key ] | |
195 | retries = Dict() # dict by msg_id of retries remaining (non-neg ints) |
|
197 | retries = Dict() # dict by msg_id of retries remaining (non-neg ints) | |
196 | # waiting = List() # list of msg_ids ready to run, but haven't due to HWM |
|
198 | # waiting = List() # list of msg_ids ready to run, but haven't due to HWM | |
197 | depending = Dict() # dict by msg_id of Jobs |
|
199 | depending = Dict() # dict by msg_id of Jobs | |
198 | pending = Dict() # dict by engine_uuid of submitted tasks |
|
200 | pending = Dict() # dict by engine_uuid of submitted tasks | |
199 | completed = Dict() # dict by engine_uuid of completed tasks |
|
201 | completed = Dict() # dict by engine_uuid of completed tasks | |
200 | failed = Dict() # dict by engine_uuid of failed tasks |
|
202 | failed = Dict() # dict by engine_uuid of failed tasks | |
201 | destinations = Dict() # dict by msg_id of engine_uuids where jobs ran (reverse of completed+failed) |
|
203 | destinations = Dict() # dict by msg_id of engine_uuids where jobs ran (reverse of completed+failed) | |
202 | clients = Dict() # dict by msg_id for who submitted the task |
|
204 | clients = Dict() # dict by msg_id for who submitted the task | |
203 | targets = List() # list of target IDENTs |
|
205 | targets = List() # list of target IDENTs | |
204 | loads = List() # list of engine loads |
|
206 | loads = List() # list of engine loads | |
205 | # full = Set() # set of IDENTs that have HWM outstanding tasks |
|
207 | # full = Set() # set of IDENTs that have HWM outstanding tasks | |
206 | all_completed = Set() # set of all completed tasks |
|
208 | all_completed = Set() # set of all completed tasks | |
207 | all_failed = Set() # set of all failed tasks |
|
209 | all_failed = Set() # set of all failed tasks | |
208 | all_done = Set() # set of all finished tasks=union(completed,failed) |
|
210 | all_done = Set() # set of all finished tasks=union(completed,failed) | |
209 | all_ids = Set() # set of all submitted task IDs |
|
211 | all_ids = Set() # set of all submitted task IDs | |
210 |
|
212 | |||
211 | auditor = Instance('zmq.eventloop.ioloop.PeriodicCallback') |
|
213 | auditor = Instance('zmq.eventloop.ioloop.PeriodicCallback') | |
212 |
|
214 | |||
213 | ident = CBytes() # ZMQ identity. This should just be self.session.session |
|
215 | ident = CBytes() # ZMQ identity. This should just be self.session.session | |
214 | # but ensure Bytes |
|
216 | # but ensure Bytes | |
215 | def _ident_default(self): |
|
217 | def _ident_default(self): | |
216 | return self.session.bsession |
|
218 | return self.session.bsession | |
217 |
|
219 | |||
218 | def start(self): |
|
220 | def start(self): | |
219 | self.engine_stream.on_recv(self.dispatch_result, copy=False) |
|
221 | self.engine_stream.on_recv(self.dispatch_result, copy=False) | |
220 | self.client_stream.on_recv(self.dispatch_submission, copy=False) |
|
222 | self.client_stream.on_recv(self.dispatch_submission, copy=False) | |
221 |
|
223 | |||
222 | self._notification_handlers = dict( |
|
224 | self._notification_handlers = dict( | |
223 | registration_notification = self._register_engine, |
|
225 | registration_notification = self._register_engine, | |
224 | unregistration_notification = self._unregister_engine |
|
226 | unregistration_notification = self._unregister_engine | |
225 | ) |
|
227 | ) | |
226 | self.notifier_stream.on_recv(self.dispatch_notification) |
|
228 | self.notifier_stream.on_recv(self.dispatch_notification) | |
227 | self.auditor = ioloop.PeriodicCallback(self.audit_timeouts, 2e3, self.loop) # 1 Hz |
|
229 | self.auditor = ioloop.PeriodicCallback(self.audit_timeouts, 2e3, self.loop) # 1 Hz | |
228 | self.auditor.start() |
|
230 | self.auditor.start() | |
229 | self.log.info("Scheduler started [%s]"%self.scheme_name) |
|
231 | self.log.info("Scheduler started [%s]"%self.scheme_name) | |
230 |
|
232 | |||
231 | def resume_receiving(self): |
|
233 | def resume_receiving(self): | |
232 | """Resume accepting jobs.""" |
|
234 | """Resume accepting jobs.""" | |
233 | self.client_stream.on_recv(self.dispatch_submission, copy=False) |
|
235 | self.client_stream.on_recv(self.dispatch_submission, copy=False) | |
234 |
|
236 | |||
235 | def stop_receiving(self): |
|
237 | def stop_receiving(self): | |
236 | """Stop accepting jobs while there are no engines. |
|
238 | """Stop accepting jobs while there are no engines. | |
237 | Leave them in the ZMQ queue.""" |
|
239 | Leave them in the ZMQ queue.""" | |
238 | self.client_stream.on_recv(None) |
|
240 | self.client_stream.on_recv(None) | |
239 |
|
241 | |||
240 | #----------------------------------------------------------------------- |
|
242 | #----------------------------------------------------------------------- | |
241 | # [Un]Registration Handling |
|
243 | # [Un]Registration Handling | |
242 | #----------------------------------------------------------------------- |
|
244 | #----------------------------------------------------------------------- | |
243 |
|
245 | |||
244 |
|
246 | |||
245 | @util.log_errors |
|
247 | @util.log_errors | |
246 | def dispatch_notification(self, msg): |
|
248 | def dispatch_notification(self, msg): | |
247 | """dispatch register/unregister events.""" |
|
249 | """dispatch register/unregister events.""" | |
248 | try: |
|
250 | try: | |
249 | idents,msg = self.session.feed_identities(msg) |
|
251 | idents,msg = self.session.feed_identities(msg) | |
250 | except ValueError: |
|
252 | except ValueError: | |
251 | self.log.warn("task::Invalid Message: %r",msg) |
|
253 | self.log.warn("task::Invalid Message: %r",msg) | |
252 | return |
|
254 | return | |
253 | try: |
|
255 | try: | |
254 | msg = self.session.unserialize(msg) |
|
256 | msg = self.session.unserialize(msg) | |
255 | except ValueError: |
|
257 | except ValueError: | |
256 | self.log.warn("task::Unauthorized message from: %r"%idents) |
|
258 | self.log.warn("task::Unauthorized message from: %r"%idents) | |
257 | return |
|
259 | return | |
258 |
|
260 | |||
259 | msg_type = msg['header']['msg_type'] |
|
261 | msg_type = msg['header']['msg_type'] | |
260 |
|
262 | |||
261 | handler = self._notification_handlers.get(msg_type, None) |
|
263 | handler = self._notification_handlers.get(msg_type, None) | |
262 | if handler is None: |
|
264 | if handler is None: | |
263 | self.log.error("Unhandled message type: %r"%msg_type) |
|
265 | self.log.error("Unhandled message type: %r"%msg_type) | |
264 | else: |
|
266 | else: | |
265 | try: |
|
267 | try: | |
266 | handler(cast_bytes(msg['content']['queue'])) |
|
268 | handler(cast_bytes(msg['content']['queue'])) | |
267 | except Exception: |
|
269 | except Exception: | |
268 | self.log.error("task::Invalid notification msg: %r", msg, exc_info=True) |
|
270 | self.log.error("task::Invalid notification msg: %r", msg, exc_info=True) | |
269 |
|
271 | |||
270 | def _register_engine(self, uid): |
|
272 | def _register_engine(self, uid): | |
271 | """New engine with ident `uid` became available.""" |
|
273 | """New engine with ident `uid` became available.""" | |
272 | # head of the line: |
|
274 | # head of the line: | |
273 | self.targets.insert(0,uid) |
|
275 | self.targets.insert(0,uid) | |
274 | self.loads.insert(0,0) |
|
276 | self.loads.insert(0,0) | |
275 |
|
277 | |||
276 | # initialize sets |
|
278 | # initialize sets | |
277 | self.completed[uid] = set() |
|
279 | self.completed[uid] = set() | |
278 | self.failed[uid] = set() |
|
280 | self.failed[uid] = set() | |
279 | self.pending[uid] = {} |
|
281 | self.pending[uid] = {} | |
280 |
|
282 | |||
281 | # rescan the graph: |
|
283 | # rescan the graph: | |
282 | self.update_graph(None) |
|
284 | self.update_graph(None) | |
283 |
|
285 | |||
284 | def _unregister_engine(self, uid): |
|
286 | def _unregister_engine(self, uid): | |
285 | """Existing engine with ident `uid` became unavailable.""" |
|
287 | """Existing engine with ident `uid` became unavailable.""" | |
286 | if len(self.targets) == 1: |
|
288 | if len(self.targets) == 1: | |
287 | # this was our only engine |
|
289 | # this was our only engine | |
288 | pass |
|
290 | pass | |
289 |
|
291 | |||
290 | # handle any potentially finished tasks: |
|
292 | # handle any potentially finished tasks: | |
291 | self.engine_stream.flush() |
|
293 | self.engine_stream.flush() | |
292 |
|
294 | |||
293 | # don't pop destinations, because they might be used later |
|
295 | # don't pop destinations, because they might be used later | |
294 | # map(self.destinations.pop, self.completed.pop(uid)) |
|
296 | # map(self.destinations.pop, self.completed.pop(uid)) | |
295 | # map(self.destinations.pop, self.failed.pop(uid)) |
|
297 | # map(self.destinations.pop, self.failed.pop(uid)) | |
296 |
|
298 | |||
297 | # prevent this engine from receiving work |
|
299 | # prevent this engine from receiving work | |
298 | idx = self.targets.index(uid) |
|
300 | idx = self.targets.index(uid) | |
299 | self.targets.pop(idx) |
|
301 | self.targets.pop(idx) | |
300 | self.loads.pop(idx) |
|
302 | self.loads.pop(idx) | |
301 |
|
303 | |||
302 | # wait 5 seconds before cleaning up pending jobs, since the results might |
|
304 | # wait 5 seconds before cleaning up pending jobs, since the results might | |
303 | # still be incoming |
|
305 | # still be incoming | |
304 | if self.pending[uid]: |
|
306 | if self.pending[uid]: | |
305 | dc = ioloop.DelayedCallback(lambda : self.handle_stranded_tasks(uid), 5000, self.loop) |
|
307 | dc = ioloop.DelayedCallback(lambda : self.handle_stranded_tasks(uid), 5000, self.loop) | |
306 | dc.start() |
|
308 | dc.start() | |
307 | else: |
|
309 | else: | |
308 | self.completed.pop(uid) |
|
310 | self.completed.pop(uid) | |
309 | self.failed.pop(uid) |
|
311 | self.failed.pop(uid) | |
310 |
|
312 | |||
311 |
|
313 | |||
312 | def handle_stranded_tasks(self, engine): |
|
314 | def handle_stranded_tasks(self, engine): | |
313 | """Deal with jobs resident in an engine that died.""" |
|
315 | """Deal with jobs resident in an engine that died.""" | |
314 | lost = self.pending[engine] |
|
316 | lost = self.pending[engine] | |
315 | for msg_id in lost.keys(): |
|
317 | for msg_id in lost.keys(): | |
316 | if msg_id not in self.pending[engine]: |
|
318 | if msg_id not in self.pending[engine]: | |
317 | # prevent double-handling of messages |
|
319 | # prevent double-handling of messages | |
318 | continue |
|
320 | continue | |
319 |
|
321 | |||
320 | raw_msg = lost[msg_id].raw_msg |
|
322 | raw_msg = lost[msg_id].raw_msg | |
321 | idents,msg = self.session.feed_identities(raw_msg, copy=False) |
|
323 | idents,msg = self.session.feed_identities(raw_msg, copy=False) | |
322 | parent = self.session.unpack(msg[1].bytes) |
|
324 | parent = self.session.unpack(msg[1].bytes) | |
323 | idents = [engine, idents[0]] |
|
325 | idents = [engine, idents[0]] | |
324 |
|
326 | |||
325 | # build fake error reply |
|
327 | # build fake error reply | |
326 | try: |
|
328 | try: | |
327 | raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id)) |
|
329 | raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id)) | |
328 | except: |
|
330 | except: | |
329 | content = error.wrap_exception() |
|
331 | content = error.wrap_exception() | |
330 |
# build fake |
|
332 | # build fake metadata | |
331 |
|
|
333 | md = dict( | |
332 | status='error', |
|
334 | status=u'error', | |
333 | engine=engine, |
|
335 | engine=engine, | |
334 | date=datetime.now(), |
|
336 | date=datetime.now(), | |
335 | ) |
|
337 | ) | |
336 |
msg = self.session.msg('apply_reply', content, parent=parent, |
|
338 | msg = self.session.msg('apply_reply', content, parent=parent, metadata=md) | |
337 | raw_reply = map(zmq.Message, self.session.serialize(msg, ident=idents)) |
|
339 | raw_reply = map(zmq.Message, self.session.serialize(msg, ident=idents)) | |
338 | # and dispatch it |
|
340 | # and dispatch it | |
339 | self.dispatch_result(raw_reply) |
|
341 | self.dispatch_result(raw_reply) | |
340 |
|
342 | |||
341 | # finally scrub completed/failed lists |
|
343 | # finally scrub completed/failed lists | |
342 | self.completed.pop(engine) |
|
344 | self.completed.pop(engine) | |
343 | self.failed.pop(engine) |
|
345 | self.failed.pop(engine) | |
344 |
|
346 | |||
345 |
|
347 | |||
346 | #----------------------------------------------------------------------- |
|
348 | #----------------------------------------------------------------------- | |
347 | # Job Submission |
|
349 | # Job Submission | |
348 | #----------------------------------------------------------------------- |
|
350 | #----------------------------------------------------------------------- | |
349 |
|
351 | |||
350 |
|
352 | |||
351 | @util.log_errors |
|
353 | @util.log_errors | |
352 | def dispatch_submission(self, raw_msg): |
|
354 | def dispatch_submission(self, raw_msg): | |
353 | """Dispatch job submission to appropriate handlers.""" |
|
355 | """Dispatch job submission to appropriate handlers.""" | |
354 | # ensure targets up to date: |
|
356 | # ensure targets up to date: | |
355 | self.notifier_stream.flush() |
|
357 | self.notifier_stream.flush() | |
356 | try: |
|
358 | try: | |
357 | idents, msg = self.session.feed_identities(raw_msg, copy=False) |
|
359 | idents, msg = self.session.feed_identities(raw_msg, copy=False) | |
358 | msg = self.session.unserialize(msg, content=False, copy=False) |
|
360 | msg = self.session.unserialize(msg, content=False, copy=False) | |
359 | except Exception: |
|
361 | except Exception: | |
360 | self.log.error("task::Invaid task msg: %r"%raw_msg, exc_info=True) |
|
362 | self.log.error("task::Invaid task msg: %r"%raw_msg, exc_info=True) | |
361 | return |
|
363 | return | |
362 |
|
364 | |||
363 |
|
365 | |||
364 | # send to monitor |
|
366 | # send to monitor | |
365 | self.mon_stream.send_multipart([b'intask']+raw_msg, copy=False) |
|
367 | self.mon_stream.send_multipart([b'intask']+raw_msg, copy=False) | |
366 |
|
368 | |||
367 | header = msg['header'] |
|
369 | header = msg['header'] | |
|
370 | md = msg['metadata'] | |||
368 | msg_id = header['msg_id'] |
|
371 | msg_id = header['msg_id'] | |
369 | self.all_ids.add(msg_id) |
|
372 | self.all_ids.add(msg_id) | |
370 |
|
373 | |||
371 | # get targets as a set of bytes objects |
|
374 | # get targets as a set of bytes objects | |
372 | # from a list of unicode objects |
|
375 | # from a list of unicode objects | |
373 |
targets = |
|
376 | targets = md.get('targets', []) | |
374 | targets = map(cast_bytes, targets) |
|
377 | targets = map(cast_bytes, targets) | |
375 | targets = set(targets) |
|
378 | targets = set(targets) | |
376 |
|
379 | |||
377 |
retries = |
|
380 | retries = md.get('retries', 0) | |
378 | self.retries[msg_id] = retries |
|
381 | self.retries[msg_id] = retries | |
379 |
|
382 | |||
380 | # time dependencies |
|
383 | # time dependencies | |
381 |
after = |
|
384 | after = md.get('after', None) | |
382 | if after: |
|
385 | if after: | |
383 | after = Dependency(after) |
|
386 | after = Dependency(after) | |
384 | if after.all: |
|
387 | if after.all: | |
385 | if after.success: |
|
388 | if after.success: | |
386 | after = Dependency(after.difference(self.all_completed), |
|
389 | after = Dependency(after.difference(self.all_completed), | |
387 | success=after.success, |
|
390 | success=after.success, | |
388 | failure=after.failure, |
|
391 | failure=after.failure, | |
389 | all=after.all, |
|
392 | all=after.all, | |
390 | ) |
|
393 | ) | |
391 | if after.failure: |
|
394 | if after.failure: | |
392 | after = Dependency(after.difference(self.all_failed), |
|
395 | after = Dependency(after.difference(self.all_failed), | |
393 | success=after.success, |
|
396 | success=after.success, | |
394 | failure=after.failure, |
|
397 | failure=after.failure, | |
395 | all=after.all, |
|
398 | all=after.all, | |
396 | ) |
|
399 | ) | |
397 | if after.check(self.all_completed, self.all_failed): |
|
400 | if after.check(self.all_completed, self.all_failed): | |
398 | # recast as empty set, if `after` already met, |
|
401 | # recast as empty set, if `after` already met, | |
399 | # to prevent unnecessary set comparisons |
|
402 | # to prevent unnecessary set comparisons | |
400 | after = MET |
|
403 | after = MET | |
401 | else: |
|
404 | else: | |
402 | after = MET |
|
405 | after = MET | |
403 |
|
406 | |||
404 | # location dependencies |
|
407 | # location dependencies | |
405 |
follow = Dependency( |
|
408 | follow = Dependency(md.get('follow', [])) | |
406 |
|
409 | |||
407 | # turn timeouts into datetime objects: |
|
410 | # turn timeouts into datetime objects: | |
408 |
timeout = |
|
411 | timeout = md.get('timeout', None) | |
409 | if timeout: |
|
412 | if timeout: | |
410 | # cast to float, because jsonlib returns floats as decimal.Decimal, |
|
413 | # cast to float, because jsonlib returns floats as decimal.Decimal, | |
411 | # which timedelta does not accept |
|
414 | # which timedelta does not accept | |
412 | timeout = datetime.now() + timedelta(0,float(timeout),0) |
|
415 | timeout = datetime.now() + timedelta(0,float(timeout),0) | |
413 |
|
416 | |||
414 | job = Job(msg_id=msg_id, raw_msg=raw_msg, idents=idents, msg=msg, |
|
417 | job = Job(msg_id=msg_id, raw_msg=raw_msg, idents=idents, msg=msg, | |
415 | header=header, targets=targets, after=after, follow=follow, |
|
418 | header=header, targets=targets, after=after, follow=follow, | |
416 | timeout=timeout, |
|
419 | timeout=timeout, metadata=md, | |
417 | ) |
|
420 | ) | |
418 |
|
421 | |||
419 | # validate and reduce dependencies: |
|
422 | # validate and reduce dependencies: | |
420 | for dep in after,follow: |
|
423 | for dep in after,follow: | |
421 | if not dep: # empty dependency |
|
424 | if not dep: # empty dependency | |
422 | continue |
|
425 | continue | |
423 | # check valid: |
|
426 | # check valid: | |
424 | if msg_id in dep or dep.difference(self.all_ids): |
|
427 | if msg_id in dep or dep.difference(self.all_ids): | |
425 | self.depending[msg_id] = job |
|
428 | self.depending[msg_id] = job | |
426 | return self.fail_unreachable(msg_id, error.InvalidDependency) |
|
429 | return self.fail_unreachable(msg_id, error.InvalidDependency) | |
427 | # check if unreachable: |
|
430 | # check if unreachable: | |
428 | if dep.unreachable(self.all_completed, self.all_failed): |
|
431 | if dep.unreachable(self.all_completed, self.all_failed): | |
429 | self.depending[msg_id] = job |
|
432 | self.depending[msg_id] = job | |
430 | return self.fail_unreachable(msg_id) |
|
433 | return self.fail_unreachable(msg_id) | |
431 |
|
434 | |||
432 | if after.check(self.all_completed, self.all_failed): |
|
435 | if after.check(self.all_completed, self.all_failed): | |
433 | # time deps already met, try to run |
|
436 | # time deps already met, try to run | |
434 | if not self.maybe_run(job): |
|
437 | if not self.maybe_run(job): | |
435 | # can't run yet |
|
438 | # can't run yet | |
436 | if msg_id not in self.all_failed: |
|
439 | if msg_id not in self.all_failed: | |
437 | # could have failed as unreachable |
|
440 | # could have failed as unreachable | |
438 | self.save_unmet(job) |
|
441 | self.save_unmet(job) | |
439 | else: |
|
442 | else: | |
440 | self.save_unmet(job) |
|
443 | self.save_unmet(job) | |
441 |
|
444 | |||
442 | def audit_timeouts(self): |
|
445 | def audit_timeouts(self): | |
443 | """Audit all waiting tasks for expired timeouts.""" |
|
446 | """Audit all waiting tasks for expired timeouts.""" | |
444 | now = datetime.now() |
|
447 | now = datetime.now() | |
445 | for msg_id in self.depending.keys(): |
|
448 | for msg_id in self.depending.keys(): | |
446 | # must recheck, in case one failure cascaded to another: |
|
449 | # must recheck, in case one failure cascaded to another: | |
447 | if msg_id in self.depending: |
|
450 | if msg_id in self.depending: | |
448 | job = self.depending[msg_id] |
|
451 | job = self.depending[msg_id] | |
449 | if job.timeout and job.timeout < now: |
|
452 | if job.timeout and job.timeout < now: | |
450 | self.fail_unreachable(msg_id, error.TaskTimeout) |
|
453 | self.fail_unreachable(msg_id, error.TaskTimeout) | |
451 |
|
454 | |||
452 | def fail_unreachable(self, msg_id, why=error.ImpossibleDependency): |
|
455 | def fail_unreachable(self, msg_id, why=error.ImpossibleDependency): | |
453 | """a task has become unreachable, send a reply with an ImpossibleDependency |
|
456 | """a task has become unreachable, send a reply with an ImpossibleDependency | |
454 | error.""" |
|
457 | error.""" | |
455 | if msg_id not in self.depending: |
|
458 | if msg_id not in self.depending: | |
456 | self.log.error("msg %r already failed!", msg_id) |
|
459 | self.log.error("msg %r already failed!", msg_id) | |
457 | return |
|
460 | return | |
458 | job = self.depending.pop(msg_id) |
|
461 | job = self.depending.pop(msg_id) | |
459 | for mid in job.dependents: |
|
462 | for mid in job.dependents: | |
460 | if mid in self.graph: |
|
463 | if mid in self.graph: | |
461 | self.graph[mid].remove(msg_id) |
|
464 | self.graph[mid].remove(msg_id) | |
462 |
|
465 | |||
463 | try: |
|
466 | try: | |
464 | raise why() |
|
467 | raise why() | |
465 | except: |
|
468 | except: | |
466 | content = error.wrap_exception() |
|
469 | content = error.wrap_exception() | |
467 |
|
470 | |||
468 | self.all_done.add(msg_id) |
|
471 | self.all_done.add(msg_id) | |
469 | self.all_failed.add(msg_id) |
|
472 | self.all_failed.add(msg_id) | |
470 |
|
473 | |||
471 | msg = self.session.send(self.client_stream, 'apply_reply', content, |
|
474 | msg = self.session.send(self.client_stream, 'apply_reply', content, | |
472 | parent=job.header, ident=job.idents) |
|
475 | parent=job.header, ident=job.idents) | |
473 | self.session.send(self.mon_stream, msg, ident=[b'outtask']+job.idents) |
|
476 | self.session.send(self.mon_stream, msg, ident=[b'outtask']+job.idents) | |
474 |
|
477 | |||
475 | self.update_graph(msg_id, success=False) |
|
478 | self.update_graph(msg_id, success=False) | |
476 |
|
479 | |||
477 | def maybe_run(self, job): |
|
480 | def maybe_run(self, job): | |
478 | """check location dependencies, and run if they are met.""" |
|
481 | """check location dependencies, and run if they are met.""" | |
479 | msg_id = job.msg_id |
|
482 | msg_id = job.msg_id | |
480 | self.log.debug("Attempting to assign task %s", msg_id) |
|
483 | self.log.debug("Attempting to assign task %s", msg_id) | |
481 | if not self.targets: |
|
484 | if not self.targets: | |
482 | # no engines, definitely can't run |
|
485 | # no engines, definitely can't run | |
483 | return False |
|
486 | return False | |
484 |
|
487 | |||
485 | if job.follow or job.targets or job.blacklist or self.hwm: |
|
488 | if job.follow or job.targets or job.blacklist or self.hwm: | |
486 | # we need a can_run filter |
|
489 | # we need a can_run filter | |
487 | def can_run(idx): |
|
490 | def can_run(idx): | |
488 | # check hwm |
|
491 | # check hwm | |
489 | if self.hwm and self.loads[idx] == self.hwm: |
|
492 | if self.hwm and self.loads[idx] == self.hwm: | |
490 | return False |
|
493 | return False | |
491 | target = self.targets[idx] |
|
494 | target = self.targets[idx] | |
492 | # check blacklist |
|
495 | # check blacklist | |
493 | if target in job.blacklist: |
|
496 | if target in job.blacklist: | |
494 | return False |
|
497 | return False | |
495 | # check targets |
|
498 | # check targets | |
496 | if job.targets and target not in job.targets: |
|
499 | if job.targets and target not in job.targets: | |
497 | return False |
|
500 | return False | |
498 | # check follow |
|
501 | # check follow | |
499 | return job.follow.check(self.completed[target], self.failed[target]) |
|
502 | return job.follow.check(self.completed[target], self.failed[target]) | |
500 |
|
503 | |||
501 | indices = filter(can_run, range(len(self.targets))) |
|
504 | indices = filter(can_run, range(len(self.targets))) | |
502 |
|
505 | |||
503 | if not indices: |
|
506 | if not indices: | |
504 | # couldn't run |
|
507 | # couldn't run | |
505 | if job.follow.all: |
|
508 | if job.follow.all: | |
506 | # check follow for impossibility |
|
509 | # check follow for impossibility | |
507 | dests = set() |
|
510 | dests = set() | |
508 | relevant = set() |
|
511 | relevant = set() | |
509 | if job.follow.success: |
|
512 | if job.follow.success: | |
510 | relevant = self.all_completed |
|
513 | relevant = self.all_completed | |
511 | if job.follow.failure: |
|
514 | if job.follow.failure: | |
512 | relevant = relevant.union(self.all_failed) |
|
515 | relevant = relevant.union(self.all_failed) | |
513 | for m in job.follow.intersection(relevant): |
|
516 | for m in job.follow.intersection(relevant): | |
514 | dests.add(self.destinations[m]) |
|
517 | dests.add(self.destinations[m]) | |
515 | if len(dests) > 1: |
|
518 | if len(dests) > 1: | |
516 | self.depending[msg_id] = job |
|
519 | self.depending[msg_id] = job | |
517 | self.fail_unreachable(msg_id) |
|
520 | self.fail_unreachable(msg_id) | |
518 | return False |
|
521 | return False | |
519 | if job.targets: |
|
522 | if job.targets: | |
520 | # check blacklist+targets for impossibility |
|
523 | # check blacklist+targets for impossibility | |
521 | job.targets.difference_update(job.blacklist) |
|
524 | job.targets.difference_update(job.blacklist) | |
522 | if not job.targets or not job.targets.intersection(self.targets): |
|
525 | if not job.targets or not job.targets.intersection(self.targets): | |
523 | self.depending[msg_id] = job |
|
526 | self.depending[msg_id] = job | |
524 | self.fail_unreachable(msg_id) |
|
527 | self.fail_unreachable(msg_id) | |
525 | return False |
|
528 | return False | |
526 | return False |
|
529 | return False | |
527 | else: |
|
530 | else: | |
528 | indices = None |
|
531 | indices = None | |
529 |
|
532 | |||
530 | self.submit_task(job, indices) |
|
533 | self.submit_task(job, indices) | |
531 | return True |
|
534 | return True | |
532 |
|
535 | |||
533 | def save_unmet(self, job): |
|
536 | def save_unmet(self, job): | |
534 | """Save a message for later submission when its dependencies are met.""" |
|
537 | """Save a message for later submission when its dependencies are met.""" | |
535 | msg_id = job.msg_id |
|
538 | msg_id = job.msg_id | |
536 | self.depending[msg_id] = job |
|
539 | self.depending[msg_id] = job | |
537 | # track the ids in follow or after, but not those already finished |
|
540 | # track the ids in follow or after, but not those already finished | |
538 | for dep_id in job.after.union(job.follow).difference(self.all_done): |
|
541 | for dep_id in job.after.union(job.follow).difference(self.all_done): | |
539 | if dep_id not in self.graph: |
|
542 | if dep_id not in self.graph: | |
540 | self.graph[dep_id] = set() |
|
543 | self.graph[dep_id] = set() | |
541 | self.graph[dep_id].add(msg_id) |
|
544 | self.graph[dep_id].add(msg_id) | |
542 |
|
545 | |||
543 | def submit_task(self, job, indices=None): |
|
546 | def submit_task(self, job, indices=None): | |
544 | """Submit a task to any of a subset of our targets.""" |
|
547 | """Submit a task to any of a subset of our targets.""" | |
545 | if indices: |
|
548 | if indices: | |
546 | loads = [self.loads[i] for i in indices] |
|
549 | loads = [self.loads[i] for i in indices] | |
547 | else: |
|
550 | else: | |
548 | loads = self.loads |
|
551 | loads = self.loads | |
549 | idx = self.scheme(loads) |
|
552 | idx = self.scheme(loads) | |
550 | if indices: |
|
553 | if indices: | |
551 | idx = indices[idx] |
|
554 | idx = indices[idx] | |
552 | target = self.targets[idx] |
|
555 | target = self.targets[idx] | |
553 | # print (target, map(str, msg[:3])) |
|
556 | # print (target, map(str, msg[:3])) | |
554 | # send job to the engine |
|
557 | # send job to the engine | |
555 | self.engine_stream.send(target, flags=zmq.SNDMORE, copy=False) |
|
558 | self.engine_stream.send(target, flags=zmq.SNDMORE, copy=False) | |
556 | self.engine_stream.send_multipart(job.raw_msg, copy=False) |
|
559 | self.engine_stream.send_multipart(job.raw_msg, copy=False) | |
557 | # update load |
|
560 | # update load | |
558 | self.add_job(idx) |
|
561 | self.add_job(idx) | |
559 | self.pending[target][job.msg_id] = job |
|
562 | self.pending[target][job.msg_id] = job | |
560 | # notify Hub |
|
563 | # notify Hub | |
561 | content = dict(msg_id=job.msg_id, engine_id=target.decode('ascii')) |
|
564 | content = dict(msg_id=job.msg_id, engine_id=target.decode('ascii')) | |
562 | self.session.send(self.mon_stream, 'task_destination', content=content, |
|
565 | self.session.send(self.mon_stream, 'task_destination', content=content, | |
563 | ident=[b'tracktask',self.ident]) |
|
566 | ident=[b'tracktask',self.ident]) | |
564 |
|
567 | |||
565 |
|
568 | |||
566 | #----------------------------------------------------------------------- |
|
569 | #----------------------------------------------------------------------- | |
567 | # Result Handling |
|
570 | # Result Handling | |
568 | #----------------------------------------------------------------------- |
|
571 | #----------------------------------------------------------------------- | |
569 |
|
572 | |||
570 |
|
573 | |||
571 | @util.log_errors |
|
574 | @util.log_errors | |
572 | def dispatch_result(self, raw_msg): |
|
575 | def dispatch_result(self, raw_msg): | |
573 | """dispatch method for result replies""" |
|
576 | """dispatch method for result replies""" | |
574 | try: |
|
577 | try: | |
575 | idents,msg = self.session.feed_identities(raw_msg, copy=False) |
|
578 | idents,msg = self.session.feed_identities(raw_msg, copy=False) | |
576 | msg = self.session.unserialize(msg, content=False, copy=False) |
|
579 | msg = self.session.unserialize(msg, content=False, copy=False) | |
577 | engine = idents[0] |
|
580 | engine = idents[0] | |
578 | try: |
|
581 | try: | |
579 | idx = self.targets.index(engine) |
|
582 | idx = self.targets.index(engine) | |
580 | except ValueError: |
|
583 | except ValueError: | |
581 | pass # skip load-update for dead engines |
|
584 | pass # skip load-update for dead engines | |
582 | else: |
|
585 | else: | |
583 | self.finish_job(idx) |
|
586 | self.finish_job(idx) | |
584 | except Exception: |
|
587 | except Exception: | |
585 | self.log.error("task::Invaid result: %r", raw_msg, exc_info=True) |
|
588 | self.log.error("task::Invaid result: %r", raw_msg, exc_info=True) | |
586 | return |
|
589 | return | |
587 |
|
590 | |||
588 |
|
|
591 | md = msg['metadata'] | |
589 | parent = msg['parent_header'] |
|
592 | parent = msg['parent_header'] | |
590 |
if |
|
593 | if md.get('dependencies_met', True): | |
591 |
success = ( |
|
594 | success = (md['status'] == 'ok') | |
592 | msg_id = parent['msg_id'] |
|
595 | msg_id = parent['msg_id'] | |
593 | retries = self.retries[msg_id] |
|
596 | retries = self.retries[msg_id] | |
594 | if not success and retries > 0: |
|
597 | if not success and retries > 0: | |
595 | # failed |
|
598 | # failed | |
596 | self.retries[msg_id] = retries - 1 |
|
599 | self.retries[msg_id] = retries - 1 | |
597 | self.handle_unmet_dependency(idents, parent) |
|
600 | self.handle_unmet_dependency(idents, parent) | |
598 | else: |
|
601 | else: | |
599 | del self.retries[msg_id] |
|
602 | del self.retries[msg_id] | |
600 | # relay to client and update graph |
|
603 | # relay to client and update graph | |
601 | self.handle_result(idents, parent, raw_msg, success) |
|
604 | self.handle_result(idents, parent, raw_msg, success) | |
602 | # send to Hub monitor |
|
605 | # send to Hub monitor | |
603 | self.mon_stream.send_multipart([b'outtask']+raw_msg, copy=False) |
|
606 | self.mon_stream.send_multipart([b'outtask']+raw_msg, copy=False) | |
604 | else: |
|
607 | else: | |
605 | self.handle_unmet_dependency(idents, parent) |
|
608 | self.handle_unmet_dependency(idents, parent) | |
606 |
|
609 | |||
607 | def handle_result(self, idents, parent, raw_msg, success=True): |
|
610 | def handle_result(self, idents, parent, raw_msg, success=True): | |
608 | """handle a real task result, either success or failure""" |
|
611 | """handle a real task result, either success or failure""" | |
609 | # first, relay result to client |
|
612 | # first, relay result to client | |
610 | engine = idents[0] |
|
613 | engine = idents[0] | |
611 | client = idents[1] |
|
614 | client = idents[1] | |
612 | # swap_ids for ROUTER-ROUTER mirror |
|
615 | # swap_ids for ROUTER-ROUTER mirror | |
613 | raw_msg[:2] = [client,engine] |
|
616 | raw_msg[:2] = [client,engine] | |
614 | # print (map(str, raw_msg[:4])) |
|
617 | # print (map(str, raw_msg[:4])) | |
615 | self.client_stream.send_multipart(raw_msg, copy=False) |
|
618 | self.client_stream.send_multipart(raw_msg, copy=False) | |
616 | # now, update our data structures |
|
619 | # now, update our data structures | |
617 | msg_id = parent['msg_id'] |
|
620 | msg_id = parent['msg_id'] | |
618 | self.pending[engine].pop(msg_id) |
|
621 | self.pending[engine].pop(msg_id) | |
619 | if success: |
|
622 | if success: | |
620 | self.completed[engine].add(msg_id) |
|
623 | self.completed[engine].add(msg_id) | |
621 | self.all_completed.add(msg_id) |
|
624 | self.all_completed.add(msg_id) | |
622 | else: |
|
625 | else: | |
623 | self.failed[engine].add(msg_id) |
|
626 | self.failed[engine].add(msg_id) | |
624 | self.all_failed.add(msg_id) |
|
627 | self.all_failed.add(msg_id) | |
625 | self.all_done.add(msg_id) |
|
628 | self.all_done.add(msg_id) | |
626 | self.destinations[msg_id] = engine |
|
629 | self.destinations[msg_id] = engine | |
627 |
|
630 | |||
628 | self.update_graph(msg_id, success) |
|
631 | self.update_graph(msg_id, success) | |
629 |
|
632 | |||
630 | def handle_unmet_dependency(self, idents, parent): |
|
633 | def handle_unmet_dependency(self, idents, parent): | |
631 | """handle an unmet dependency""" |
|
634 | """handle an unmet dependency""" | |
632 | engine = idents[0] |
|
635 | engine = idents[0] | |
633 | msg_id = parent['msg_id'] |
|
636 | msg_id = parent['msg_id'] | |
634 |
|
637 | |||
635 | job = self.pending[engine].pop(msg_id) |
|
638 | job = self.pending[engine].pop(msg_id) | |
636 | job.blacklist.add(engine) |
|
639 | job.blacklist.add(engine) | |
637 |
|
640 | |||
638 | if job.blacklist == job.targets: |
|
641 | if job.blacklist == job.targets: | |
639 | self.depending[msg_id] = job |
|
642 | self.depending[msg_id] = job | |
640 | self.fail_unreachable(msg_id) |
|
643 | self.fail_unreachable(msg_id) | |
641 | elif not self.maybe_run(job): |
|
644 | elif not self.maybe_run(job): | |
642 | # resubmit failed |
|
645 | # resubmit failed | |
643 | if msg_id not in self.all_failed: |
|
646 | if msg_id not in self.all_failed: | |
644 | # put it back in our dependency tree |
|
647 | # put it back in our dependency tree | |
645 | self.save_unmet(job) |
|
648 | self.save_unmet(job) | |
646 |
|
649 | |||
647 | if self.hwm: |
|
650 | if self.hwm: | |
648 | try: |
|
651 | try: | |
649 | idx = self.targets.index(engine) |
|
652 | idx = self.targets.index(engine) | |
650 | except ValueError: |
|
653 | except ValueError: | |
651 | pass # skip load-update for dead engines |
|
654 | pass # skip load-update for dead engines | |
652 | else: |
|
655 | else: | |
653 | if self.loads[idx] == self.hwm-1: |
|
656 | if self.loads[idx] == self.hwm-1: | |
654 | self.update_graph(None) |
|
657 | self.update_graph(None) | |
655 |
|
658 | |||
656 |
|
659 | |||
657 |
|
660 | |||
658 | def update_graph(self, dep_id=None, success=True): |
|
661 | def update_graph(self, dep_id=None, success=True): | |
659 | """dep_id just finished. Update our dependency |
|
662 | """dep_id just finished. Update our dependency | |
660 | graph and submit any jobs that just became runable. |
|
663 | graph and submit any jobs that just became runable. | |
661 |
|
664 | |||
662 | Called with dep_id=None to update entire graph for hwm, but without finishing |
|
665 | Called with dep_id=None to update entire graph for hwm, but without finishing | |
663 | a task. |
|
666 | a task. | |
664 | """ |
|
667 | """ | |
665 | # print ("\n\n***********") |
|
668 | # print ("\n\n***********") | |
666 | # pprint (dep_id) |
|
669 | # pprint (dep_id) | |
667 | # pprint (self.graph) |
|
670 | # pprint (self.graph) | |
668 | # pprint (self.depending) |
|
671 | # pprint (self.depending) | |
669 | # pprint (self.all_completed) |
|
672 | # pprint (self.all_completed) | |
670 | # pprint (self.all_failed) |
|
673 | # pprint (self.all_failed) | |
671 | # print ("\n\n***********\n\n") |
|
674 | # print ("\n\n***********\n\n") | |
672 | # update any jobs that depended on the dependency |
|
675 | # update any jobs that depended on the dependency | |
673 | jobs = self.graph.pop(dep_id, []) |
|
676 | jobs = self.graph.pop(dep_id, []) | |
674 |
|
677 | |||
675 | # recheck *all* jobs if |
|
678 | # recheck *all* jobs if | |
676 | # a) we have HWM and an engine just become no longer full |
|
679 | # a) we have HWM and an engine just become no longer full | |
677 | # or b) dep_id was given as None |
|
680 | # or b) dep_id was given as None | |
678 |
|
681 | |||
679 | if dep_id is None or self.hwm and any( [ load==self.hwm-1 for load in self.loads ]): |
|
682 | if dep_id is None or self.hwm and any( [ load==self.hwm-1 for load in self.loads ]): | |
680 | jobs = self.depending.keys() |
|
683 | jobs = self.depending.keys() | |
681 |
|
684 | |||
682 | for msg_id in sorted(jobs, key=lambda msg_id: self.depending[msg_id].timestamp): |
|
685 | for msg_id in sorted(jobs, key=lambda msg_id: self.depending[msg_id].timestamp): | |
683 | job = self.depending[msg_id] |
|
686 | job = self.depending[msg_id] | |
684 |
|
687 | |||
685 | if job.after.unreachable(self.all_completed, self.all_failed)\ |
|
688 | if job.after.unreachable(self.all_completed, self.all_failed)\ | |
686 | or job.follow.unreachable(self.all_completed, self.all_failed): |
|
689 | or job.follow.unreachable(self.all_completed, self.all_failed): | |
687 | self.fail_unreachable(msg_id) |
|
690 | self.fail_unreachable(msg_id) | |
688 |
|
691 | |||
689 | elif job.after.check(self.all_completed, self.all_failed): # time deps met, maybe run |
|
692 | elif job.after.check(self.all_completed, self.all_failed): # time deps met, maybe run | |
690 | if self.maybe_run(job): |
|
693 | if self.maybe_run(job): | |
691 |
|
694 | |||
692 | self.depending.pop(msg_id) |
|
695 | self.depending.pop(msg_id) | |
693 | for mid in job.dependents: |
|
696 | for mid in job.dependents: | |
694 | if mid in self.graph: |
|
697 | if mid in self.graph: | |
695 | self.graph[mid].remove(msg_id) |
|
698 | self.graph[mid].remove(msg_id) | |
696 |
|
699 | |||
697 | #---------------------------------------------------------------------- |
|
700 | #---------------------------------------------------------------------- | |
698 | # methods to be overridden by subclasses |
|
701 | # methods to be overridden by subclasses | |
699 | #---------------------------------------------------------------------- |
|
702 | #---------------------------------------------------------------------- | |
700 |
|
703 | |||
701 | def add_job(self, idx): |
|
704 | def add_job(self, idx): | |
702 | """Called after self.targets[idx] just got the job with header. |
|
705 | """Called after self.targets[idx] just got the job with header. | |
703 | Override with subclasses. The default ordering is simple LRU. |
|
706 | Override with subclasses. The default ordering is simple LRU. | |
704 | The default loads are the number of outstanding jobs.""" |
|
707 | The default loads are the number of outstanding jobs.""" | |
705 | self.loads[idx] += 1 |
|
708 | self.loads[idx] += 1 | |
706 | for lis in (self.targets, self.loads): |
|
709 | for lis in (self.targets, self.loads): | |
707 | lis.append(lis.pop(idx)) |
|
710 | lis.append(lis.pop(idx)) | |
708 |
|
711 | |||
709 |
|
712 | |||
710 | def finish_job(self, idx): |
|
713 | def finish_job(self, idx): | |
711 | """Called after self.targets[idx] just finished a job. |
|
714 | """Called after self.targets[idx] just finished a job. | |
712 | Override with subclasses.""" |
|
715 | Override with subclasses.""" | |
713 | self.loads[idx] -= 1 |
|
716 | self.loads[idx] -= 1 | |
714 |
|
717 | |||
715 |
|
718 | |||
716 |
|
719 | |||
717 | def launch_scheduler(in_addr, out_addr, mon_addr, not_addr, config=None, |
|
720 | def launch_scheduler(in_addr, out_addr, mon_addr, not_addr, config=None, | |
718 | logname='root', log_url=None, loglevel=logging.DEBUG, |
|
721 | logname='root', log_url=None, loglevel=logging.DEBUG, | |
719 | identity=b'task', in_thread=False): |
|
722 | identity=b'task', in_thread=False): | |
720 |
|
723 | |||
721 | ZMQStream = zmqstream.ZMQStream |
|
724 | ZMQStream = zmqstream.ZMQStream | |
722 |
|
725 | |||
723 | if config: |
|
726 | if config: | |
724 | # unwrap dict back into Config |
|
727 | # unwrap dict back into Config | |
725 | config = Config(config) |
|
728 | config = Config(config) | |
726 |
|
729 | |||
727 | if in_thread: |
|
730 | if in_thread: | |
728 | # use instance() to get the same Context/Loop as our parent |
|
731 | # use instance() to get the same Context/Loop as our parent | |
729 | ctx = zmq.Context.instance() |
|
732 | ctx = zmq.Context.instance() | |
730 | loop = ioloop.IOLoop.instance() |
|
733 | loop = ioloop.IOLoop.instance() | |
731 | else: |
|
734 | else: | |
732 | # in a process, don't use instance() |
|
735 | # in a process, don't use instance() | |
733 | # for safety with multiprocessing |
|
736 | # for safety with multiprocessing | |
734 | ctx = zmq.Context() |
|
737 | ctx = zmq.Context() | |
735 | loop = ioloop.IOLoop() |
|
738 | loop = ioloop.IOLoop() | |
736 | ins = ZMQStream(ctx.socket(zmq.ROUTER),loop) |
|
739 | ins = ZMQStream(ctx.socket(zmq.ROUTER),loop) | |
737 | ins.setsockopt(zmq.IDENTITY, identity) |
|
740 | ins.setsockopt(zmq.IDENTITY, identity) | |
738 | ins.bind(in_addr) |
|
741 | ins.bind(in_addr) | |
739 |
|
742 | |||
740 | outs = ZMQStream(ctx.socket(zmq.ROUTER),loop) |
|
743 | outs = ZMQStream(ctx.socket(zmq.ROUTER),loop) | |
741 | outs.setsockopt(zmq.IDENTITY, identity) |
|
744 | outs.setsockopt(zmq.IDENTITY, identity) | |
742 | outs.bind(out_addr) |
|
745 | outs.bind(out_addr) | |
743 | mons = zmqstream.ZMQStream(ctx.socket(zmq.PUB),loop) |
|
746 | mons = zmqstream.ZMQStream(ctx.socket(zmq.PUB),loop) | |
744 | mons.connect(mon_addr) |
|
747 | mons.connect(mon_addr) | |
745 | nots = zmqstream.ZMQStream(ctx.socket(zmq.SUB),loop) |
|
748 | nots = zmqstream.ZMQStream(ctx.socket(zmq.SUB),loop) | |
746 | nots.setsockopt(zmq.SUBSCRIBE, b'') |
|
749 | nots.setsockopt(zmq.SUBSCRIBE, b'') | |
747 | nots.connect(not_addr) |
|
750 | nots.connect(not_addr) | |
748 |
|
751 | |||
749 | # setup logging. |
|
752 | # setup logging. | |
750 | if in_thread: |
|
753 | if in_thread: | |
751 | log = Application.instance().log |
|
754 | log = Application.instance().log | |
752 | else: |
|
755 | else: | |
753 | if log_url: |
|
756 | if log_url: | |
754 | log = connect_logger(logname, ctx, log_url, root="scheduler", loglevel=loglevel) |
|
757 | log = connect_logger(logname, ctx, log_url, root="scheduler", loglevel=loglevel) | |
755 | else: |
|
758 | else: | |
756 | log = local_logger(logname, loglevel) |
|
759 | log = local_logger(logname, loglevel) | |
757 |
|
760 | |||
758 | scheduler = TaskScheduler(client_stream=ins, engine_stream=outs, |
|
761 | scheduler = TaskScheduler(client_stream=ins, engine_stream=outs, | |
759 | mon_stream=mons, notifier_stream=nots, |
|
762 | mon_stream=mons, notifier_stream=nots, | |
760 | loop=loop, log=log, |
|
763 | loop=loop, log=log, | |
761 | config=config) |
|
764 | config=config) | |
762 | scheduler.start() |
|
765 | scheduler.start() | |
763 | if not in_thread: |
|
766 | if not in_thread: | |
764 | try: |
|
767 | try: | |
765 | loop.start() |
|
768 | loop.start() | |
766 | except KeyboardInterrupt: |
|
769 | except KeyboardInterrupt: | |
767 | scheduler.log.critical("Interrupted, exiting...") |
|
770 | scheduler.log.critical("Interrupted, exiting...") | |
768 |
|
771 |
@@ -1,412 +1,418 b'' | |||||
1 | """A TaskRecord backend using sqlite3 |
|
1 | """A TaskRecord backend using sqlite3 | |
2 |
|
2 | |||
3 | Authors: |
|
3 | Authors: | |
4 |
|
4 | |||
5 | * Min RK |
|
5 | * Min RK | |
6 | """ |
|
6 | """ | |
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2011 The IPython Development Team |
|
8 | # Copyright (C) 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 | import json |
|
14 | import json | |
15 | import os |
|
15 | import os | |
16 | import cPickle as pickle |
|
16 | import cPickle as pickle | |
17 | from datetime import datetime |
|
17 | from datetime import datetime | |
18 |
|
18 | |||
19 | try: |
|
19 | try: | |
20 | import sqlite3 |
|
20 | import sqlite3 | |
21 | except ImportError: |
|
21 | except ImportError: | |
22 | sqlite3 = None |
|
22 | sqlite3 = None | |
23 |
|
23 | |||
24 | from zmq.eventloop import ioloop |
|
24 | from zmq.eventloop import ioloop | |
25 |
|
25 | |||
26 | from IPython.utils.traitlets import Unicode, Instance, List, Dict |
|
26 | from IPython.utils.traitlets import Unicode, Instance, List, Dict | |
27 | from .dictdb import BaseDB |
|
27 | from .dictdb import BaseDB | |
28 | from IPython.utils.jsonutil import date_default, extract_dates, squash_dates |
|
28 | from IPython.utils.jsonutil import date_default, extract_dates, squash_dates | |
29 |
|
29 | |||
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 | # SQLite operators, adapters, and converters |
|
31 | # SQLite operators, adapters, and converters | |
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 |
|
33 | |||
34 | try: |
|
34 | try: | |
35 | buffer |
|
35 | buffer | |
36 | except NameError: |
|
36 | except NameError: | |
37 | # py3k |
|
37 | # py3k | |
38 | buffer = memoryview |
|
38 | buffer = memoryview | |
39 |
|
39 | |||
40 | operators = { |
|
40 | operators = { | |
41 | '$lt' : "<", |
|
41 | '$lt' : "<", | |
42 | '$gt' : ">", |
|
42 | '$gt' : ">", | |
43 | # null is handled weird with ==,!= |
|
43 | # null is handled weird with ==,!= | |
44 | '$eq' : "=", |
|
44 | '$eq' : "=", | |
45 | '$ne' : "!=", |
|
45 | '$ne' : "!=", | |
46 | '$lte': "<=", |
|
46 | '$lte': "<=", | |
47 | '$gte': ">=", |
|
47 | '$gte': ">=", | |
48 | '$in' : ('=', ' OR '), |
|
48 | '$in' : ('=', ' OR '), | |
49 | '$nin': ('!=', ' AND '), |
|
49 | '$nin': ('!=', ' AND '), | |
50 | # '$all': None, |
|
50 | # '$all': None, | |
51 | # '$mod': None, |
|
51 | # '$mod': None, | |
52 | # '$exists' : None |
|
52 | # '$exists' : None | |
53 | } |
|
53 | } | |
54 | null_operators = { |
|
54 | null_operators = { | |
55 | '=' : "IS NULL", |
|
55 | '=' : "IS NULL", | |
56 | '!=' : "IS NOT NULL", |
|
56 | '!=' : "IS NOT NULL", | |
57 | } |
|
57 | } | |
58 |
|
58 | |||
59 | def _adapt_dict(d): |
|
59 | def _adapt_dict(d): | |
60 | return json.dumps(d, default=date_default) |
|
60 | return json.dumps(d, default=date_default) | |
61 |
|
61 | |||
62 | def _convert_dict(ds): |
|
62 | def _convert_dict(ds): | |
63 | if ds is None: |
|
63 | if ds is None: | |
64 | return ds |
|
64 | return ds | |
65 | else: |
|
65 | else: | |
66 | if isinstance(ds, bytes): |
|
66 | if isinstance(ds, bytes): | |
67 | # If I understand the sqlite doc correctly, this will always be utf8 |
|
67 | # If I understand the sqlite doc correctly, this will always be utf8 | |
68 | ds = ds.decode('utf8') |
|
68 | ds = ds.decode('utf8') | |
69 | return extract_dates(json.loads(ds)) |
|
69 | return extract_dates(json.loads(ds)) | |
70 |
|
70 | |||
71 | def _adapt_bufs(bufs): |
|
71 | def _adapt_bufs(bufs): | |
72 | # this is *horrible* |
|
72 | # this is *horrible* | |
73 | # copy buffers into single list and pickle it: |
|
73 | # copy buffers into single list and pickle it: | |
74 | if bufs and isinstance(bufs[0], (bytes, buffer)): |
|
74 | if bufs and isinstance(bufs[0], (bytes, buffer)): | |
75 | return sqlite3.Binary(pickle.dumps(map(bytes, bufs),-1)) |
|
75 | return sqlite3.Binary(pickle.dumps(map(bytes, bufs),-1)) | |
76 | elif bufs: |
|
76 | elif bufs: | |
77 | return bufs |
|
77 | return bufs | |
78 | else: |
|
78 | else: | |
79 | return None |
|
79 | return None | |
80 |
|
80 | |||
81 | def _convert_bufs(bs): |
|
81 | def _convert_bufs(bs): | |
82 | if bs is None: |
|
82 | if bs is None: | |
83 | return [] |
|
83 | return [] | |
84 | else: |
|
84 | else: | |
85 | return pickle.loads(bytes(bs)) |
|
85 | return pickle.loads(bytes(bs)) | |
86 |
|
86 | |||
87 | #----------------------------------------------------------------------------- |
|
87 | #----------------------------------------------------------------------------- | |
88 | # SQLiteDB class |
|
88 | # SQLiteDB class | |
89 | #----------------------------------------------------------------------------- |
|
89 | #----------------------------------------------------------------------------- | |
90 |
|
90 | |||
91 | class SQLiteDB(BaseDB): |
|
91 | class SQLiteDB(BaseDB): | |
92 | """SQLite3 TaskRecord backend.""" |
|
92 | """SQLite3 TaskRecord backend.""" | |
93 |
|
93 | |||
94 | filename = Unicode('tasks.db', config=True, |
|
94 | filename = Unicode('tasks.db', config=True, | |
95 | help="""The filename of the sqlite task database. [default: 'tasks.db']""") |
|
95 | help="""The filename of the sqlite task database. [default: 'tasks.db']""") | |
96 | location = Unicode('', config=True, |
|
96 | location = Unicode('', config=True, | |
97 | help="""The directory containing the sqlite task database. The default |
|
97 | help="""The directory containing the sqlite task database. The default | |
98 | is to use the cluster_dir location.""") |
|
98 | is to use the cluster_dir location.""") | |
99 | table = Unicode("", config=True, |
|
99 | table = Unicode("", config=True, | |
100 | help="""The SQLite Table to use for storing tasks for this session. If unspecified, |
|
100 | help="""The SQLite Table to use for storing tasks for this session. If unspecified, | |
101 | a new table will be created with the Hub's IDENT. Specifying the table will result |
|
101 | a new table will be created with the Hub's IDENT. Specifying the table will result | |
102 | in tasks from previous sessions being available via Clients' db_query and |
|
102 | in tasks from previous sessions being available via Clients' db_query and | |
103 | get_result methods.""") |
|
103 | get_result methods.""") | |
104 |
|
104 | |||
105 | if sqlite3 is not None: |
|
105 | if sqlite3 is not None: | |
106 | _db = Instance('sqlite3.Connection') |
|
106 | _db = Instance('sqlite3.Connection') | |
107 | else: |
|
107 | else: | |
108 | _db = None |
|
108 | _db = None | |
109 | # the ordered list of column names |
|
109 | # the ordered list of column names | |
110 | _keys = List(['msg_id' , |
|
110 | _keys = List(['msg_id' , | |
111 | 'header' , |
|
111 | 'header' , | |
|
112 | 'metadata', | |||
112 | 'content', |
|
113 | 'content', | |
113 | 'buffers', |
|
114 | 'buffers', | |
114 | 'submitted', |
|
115 | 'submitted', | |
115 | 'client_uuid' , |
|
116 | 'client_uuid' , | |
116 | 'engine_uuid' , |
|
117 | 'engine_uuid' , | |
117 | 'started', |
|
118 | 'started', | |
118 | 'completed', |
|
119 | 'completed', | |
119 | 'resubmitted', |
|
120 | 'resubmitted', | |
120 | 'received', |
|
121 | 'received', | |
121 | 'result_header' , |
|
122 | 'result_header' , | |
|
123 | 'result_metadata', | |||
122 | 'result_content' , |
|
124 | 'result_content' , | |
123 | 'result_buffers' , |
|
125 | 'result_buffers' , | |
124 | 'queue' , |
|
126 | 'queue' , | |
125 | 'pyin' , |
|
127 | 'pyin' , | |
126 | 'pyout', |
|
128 | 'pyout', | |
127 | 'pyerr', |
|
129 | 'pyerr', | |
128 | 'stdout', |
|
130 | 'stdout', | |
129 | 'stderr', |
|
131 | 'stderr', | |
130 | ]) |
|
132 | ]) | |
131 | # sqlite datatypes for checking that db is current format |
|
133 | # sqlite datatypes for checking that db is current format | |
132 | _types = Dict({'msg_id' : 'text' , |
|
134 | _types = Dict({'msg_id' : 'text' , | |
133 | 'header' : 'dict text', |
|
135 | 'header' : 'dict text', | |
|
136 | 'metadata' : 'dict text', | |||
134 | 'content' : 'dict text', |
|
137 | 'content' : 'dict text', | |
135 | 'buffers' : 'bufs blob', |
|
138 | 'buffers' : 'bufs blob', | |
136 | 'submitted' : 'timestamp', |
|
139 | 'submitted' : 'timestamp', | |
137 | 'client_uuid' : 'text', |
|
140 | 'client_uuid' : 'text', | |
138 | 'engine_uuid' : 'text', |
|
141 | 'engine_uuid' : 'text', | |
139 | 'started' : 'timestamp', |
|
142 | 'started' : 'timestamp', | |
140 | 'completed' : 'timestamp', |
|
143 | 'completed' : 'timestamp', | |
141 | 'resubmitted' : 'text', |
|
144 | 'resubmitted' : 'text', | |
142 | 'received' : 'timestamp', |
|
145 | 'received' : 'timestamp', | |
143 | 'result_header' : 'dict text', |
|
146 | 'result_header' : 'dict text', | |
|
147 | 'result_metadata' : 'dict text', | |||
144 | 'result_content' : 'dict text', |
|
148 | 'result_content' : 'dict text', | |
145 | 'result_buffers' : 'bufs blob', |
|
149 | 'result_buffers' : 'bufs blob', | |
146 | 'queue' : 'text', |
|
150 | 'queue' : 'text', | |
147 | 'pyin' : 'text', |
|
151 | 'pyin' : 'text', | |
148 | 'pyout' : 'text', |
|
152 | 'pyout' : 'text', | |
149 | 'pyerr' : 'text', |
|
153 | 'pyerr' : 'text', | |
150 | 'stdout' : 'text', |
|
154 | 'stdout' : 'text', | |
151 | 'stderr' : 'text', |
|
155 | 'stderr' : 'text', | |
152 | }) |
|
156 | }) | |
153 |
|
157 | |||
154 | def __init__(self, **kwargs): |
|
158 | def __init__(self, **kwargs): | |
155 | super(SQLiteDB, self).__init__(**kwargs) |
|
159 | super(SQLiteDB, self).__init__(**kwargs) | |
156 | if sqlite3 is None: |
|
160 | if sqlite3 is None: | |
157 | raise ImportError("SQLiteDB requires sqlite3") |
|
161 | raise ImportError("SQLiteDB requires sqlite3") | |
158 | if not self.table: |
|
162 | if not self.table: | |
159 | # use session, and prefix _, since starting with # is illegal |
|
163 | # use session, and prefix _, since starting with # is illegal | |
160 | self.table = '_'+self.session.replace('-','_') |
|
164 | self.table = '_'+self.session.replace('-','_') | |
161 | if not self.location: |
|
165 | if not self.location: | |
162 | # get current profile |
|
166 | # get current profile | |
163 | from IPython.core.application import BaseIPythonApplication |
|
167 | from IPython.core.application import BaseIPythonApplication | |
164 | if BaseIPythonApplication.initialized(): |
|
168 | if BaseIPythonApplication.initialized(): | |
165 | app = BaseIPythonApplication.instance() |
|
169 | app = BaseIPythonApplication.instance() | |
166 | if app.profile_dir is not None: |
|
170 | if app.profile_dir is not None: | |
167 | self.location = app.profile_dir.location |
|
171 | self.location = app.profile_dir.location | |
168 | else: |
|
172 | else: | |
169 | self.location = u'.' |
|
173 | self.location = u'.' | |
170 | else: |
|
174 | else: | |
171 | self.location = u'.' |
|
175 | self.location = u'.' | |
172 | self._init_db() |
|
176 | self._init_db() | |
173 |
|
177 | |||
174 | # register db commit as 2s periodic callback |
|
178 | # register db commit as 2s periodic callback | |
175 | # to prevent clogging pipes |
|
179 | # to prevent clogging pipes | |
176 | # assumes we are being run in a zmq ioloop app |
|
180 | # assumes we are being run in a zmq ioloop app | |
177 | loop = ioloop.IOLoop.instance() |
|
181 | loop = ioloop.IOLoop.instance() | |
178 | pc = ioloop.PeriodicCallback(self._db.commit, 2000, loop) |
|
182 | pc = ioloop.PeriodicCallback(self._db.commit, 2000, loop) | |
179 | pc.start() |
|
183 | pc.start() | |
180 |
|
184 | |||
181 | def _defaults(self, keys=None): |
|
185 | def _defaults(self, keys=None): | |
182 | """create an empty record""" |
|
186 | """create an empty record""" | |
183 | d = {} |
|
187 | d = {} | |
184 | keys = self._keys if keys is None else keys |
|
188 | keys = self._keys if keys is None else keys | |
185 | for key in keys: |
|
189 | for key in keys: | |
186 | d[key] = None |
|
190 | d[key] = None | |
187 | return d |
|
191 | return d | |
188 |
|
192 | |||
189 | def _check_table(self): |
|
193 | def _check_table(self): | |
190 | """Ensure that an incorrect table doesn't exist |
|
194 | """Ensure that an incorrect table doesn't exist | |
191 |
|
195 | |||
192 | If a bad (old) table does exist, return False |
|
196 | If a bad (old) table does exist, return False | |
193 | """ |
|
197 | """ | |
194 | cursor = self._db.execute("PRAGMA table_info(%s)"%self.table) |
|
198 | cursor = self._db.execute("PRAGMA table_info(%s)"%self.table) | |
195 | lines = cursor.fetchall() |
|
199 | lines = cursor.fetchall() | |
196 | if not lines: |
|
200 | if not lines: | |
197 | # table does not exist |
|
201 | # table does not exist | |
198 | return True |
|
202 | return True | |
199 | types = {} |
|
203 | types = {} | |
200 | keys = [] |
|
204 | keys = [] | |
201 | for line in lines: |
|
205 | for line in lines: | |
202 | keys.append(line[1]) |
|
206 | keys.append(line[1]) | |
203 | types[line[1]] = line[2] |
|
207 | types[line[1]] = line[2] | |
204 | if self._keys != keys: |
|
208 | if self._keys != keys: | |
205 | # key mismatch |
|
209 | # key mismatch | |
206 | self.log.warn('keys mismatch') |
|
210 | self.log.warn('keys mismatch') | |
207 | return False |
|
211 | return False | |
208 | for key in self._keys: |
|
212 | for key in self._keys: | |
209 | if types[key] != self._types[key]: |
|
213 | if types[key] != self._types[key]: | |
210 | self.log.warn( |
|
214 | self.log.warn( | |
211 | 'type mismatch: %s: %s != %s'%(key,types[key],self._types[key]) |
|
215 | 'type mismatch: %s: %s != %s'%(key,types[key],self._types[key]) | |
212 | ) |
|
216 | ) | |
213 | return False |
|
217 | return False | |
214 | return True |
|
218 | return True | |
215 |
|
219 | |||
216 | def _init_db(self): |
|
220 | def _init_db(self): | |
217 | """Connect to the database and get new session number.""" |
|
221 | """Connect to the database and get new session number.""" | |
218 | # register adapters |
|
222 | # register adapters | |
219 | sqlite3.register_adapter(dict, _adapt_dict) |
|
223 | sqlite3.register_adapter(dict, _adapt_dict) | |
220 | sqlite3.register_converter('dict', _convert_dict) |
|
224 | sqlite3.register_converter('dict', _convert_dict) | |
221 | sqlite3.register_adapter(list, _adapt_bufs) |
|
225 | sqlite3.register_adapter(list, _adapt_bufs) | |
222 | sqlite3.register_converter('bufs', _convert_bufs) |
|
226 | sqlite3.register_converter('bufs', _convert_bufs) | |
223 | # connect to the db |
|
227 | # connect to the db | |
224 | dbfile = os.path.join(self.location, self.filename) |
|
228 | dbfile = os.path.join(self.location, self.filename) | |
225 | self._db = sqlite3.connect(dbfile, detect_types=sqlite3.PARSE_DECLTYPES, |
|
229 | self._db = sqlite3.connect(dbfile, detect_types=sqlite3.PARSE_DECLTYPES, | |
226 | # isolation_level = None)#, |
|
230 | # isolation_level = None)#, | |
227 | cached_statements=64) |
|
231 | cached_statements=64) | |
228 | # print dir(self._db) |
|
232 | # print dir(self._db) | |
229 | first_table = previous_table = self.table |
|
233 | first_table = previous_table = self.table | |
230 | i=0 |
|
234 | i=0 | |
231 | while not self._check_table(): |
|
235 | while not self._check_table(): | |
232 | i+=1 |
|
236 | i+=1 | |
233 | self.table = first_table+'_%i'%i |
|
237 | self.table = first_table+'_%i'%i | |
234 | self.log.warn( |
|
238 | self.log.warn( | |
235 | "Table %s exists and doesn't match db format, trying %s"% |
|
239 | "Table %s exists and doesn't match db format, trying %s"% | |
236 | (previous_table, self.table) |
|
240 | (previous_table, self.table) | |
237 | ) |
|
241 | ) | |
238 | previous_table = self.table |
|
242 | previous_table = self.table | |
239 |
|
243 | |||
240 | self._db.execute("""CREATE TABLE IF NOT EXISTS %s |
|
244 | self._db.execute("""CREATE TABLE IF NOT EXISTS %s | |
241 | (msg_id text PRIMARY KEY, |
|
245 | (msg_id text PRIMARY KEY, | |
242 | header dict text, |
|
246 | header dict text, | |
|
247 | metadata dict text, | |||
243 | content dict text, |
|
248 | content dict text, | |
244 | buffers bufs blob, |
|
249 | buffers bufs blob, | |
245 | submitted timestamp, |
|
250 | submitted timestamp, | |
246 | client_uuid text, |
|
251 | client_uuid text, | |
247 | engine_uuid text, |
|
252 | engine_uuid text, | |
248 | started timestamp, |
|
253 | started timestamp, | |
249 | completed timestamp, |
|
254 | completed timestamp, | |
250 | resubmitted text, |
|
255 | resubmitted text, | |
251 | received timestamp, |
|
256 | received timestamp, | |
252 | result_header dict text, |
|
257 | result_header dict text, | |
|
258 | result_metadata dict text, | |||
253 | result_content dict text, |
|
259 | result_content dict text, | |
254 | result_buffers bufs blob, |
|
260 | result_buffers bufs blob, | |
255 | queue text, |
|
261 | queue text, | |
256 | pyin text, |
|
262 | pyin text, | |
257 | pyout text, |
|
263 | pyout text, | |
258 | pyerr text, |
|
264 | pyerr text, | |
259 | stdout text, |
|
265 | stdout text, | |
260 | stderr text) |
|
266 | stderr text) | |
261 | """%self.table) |
|
267 | """%self.table) | |
262 | self._db.commit() |
|
268 | self._db.commit() | |
263 |
|
269 | |||
264 | def _dict_to_list(self, d): |
|
270 | def _dict_to_list(self, d): | |
265 | """turn a mongodb-style record dict into a list.""" |
|
271 | """turn a mongodb-style record dict into a list.""" | |
266 |
|
272 | |||
267 | return [ d[key] for key in self._keys ] |
|
273 | return [ d[key] for key in self._keys ] | |
268 |
|
274 | |||
269 | def _list_to_dict(self, line, keys=None): |
|
275 | def _list_to_dict(self, line, keys=None): | |
270 | """Inverse of dict_to_list""" |
|
276 | """Inverse of dict_to_list""" | |
271 | keys = self._keys if keys is None else keys |
|
277 | keys = self._keys if keys is None else keys | |
272 | d = self._defaults(keys) |
|
278 | d = self._defaults(keys) | |
273 | for key,value in zip(keys, line): |
|
279 | for key,value in zip(keys, line): | |
274 | d[key] = value |
|
280 | d[key] = value | |
275 |
|
281 | |||
276 | return d |
|
282 | return d | |
277 |
|
283 | |||
278 | def _render_expression(self, check): |
|
284 | def _render_expression(self, check): | |
279 | """Turn a mongodb-style search dict into an SQL query.""" |
|
285 | """Turn a mongodb-style search dict into an SQL query.""" | |
280 | expressions = [] |
|
286 | expressions = [] | |
281 | args = [] |
|
287 | args = [] | |
282 |
|
288 | |||
283 | skeys = set(check.keys()) |
|
289 | skeys = set(check.keys()) | |
284 | skeys.difference_update(set(self._keys)) |
|
290 | skeys.difference_update(set(self._keys)) | |
285 | skeys.difference_update(set(['buffers', 'result_buffers'])) |
|
291 | skeys.difference_update(set(['buffers', 'result_buffers'])) | |
286 | if skeys: |
|
292 | if skeys: | |
287 | raise KeyError("Illegal testing key(s): %s"%skeys) |
|
293 | raise KeyError("Illegal testing key(s): %s"%skeys) | |
288 |
|
294 | |||
289 | for name,sub_check in check.iteritems(): |
|
295 | for name,sub_check in check.iteritems(): | |
290 | if isinstance(sub_check, dict): |
|
296 | if isinstance(sub_check, dict): | |
291 | for test,value in sub_check.iteritems(): |
|
297 | for test,value in sub_check.iteritems(): | |
292 | try: |
|
298 | try: | |
293 | op = operators[test] |
|
299 | op = operators[test] | |
294 | except KeyError: |
|
300 | except KeyError: | |
295 | raise KeyError("Unsupported operator: %r"%test) |
|
301 | raise KeyError("Unsupported operator: %r"%test) | |
296 | if isinstance(op, tuple): |
|
302 | if isinstance(op, tuple): | |
297 | op, join = op |
|
303 | op, join = op | |
298 |
|
304 | |||
299 | if value is None and op in null_operators: |
|
305 | if value is None and op in null_operators: | |
300 | expr = "%s %s" % (name, null_operators[op]) |
|
306 | expr = "%s %s" % (name, null_operators[op]) | |
301 | else: |
|
307 | else: | |
302 | expr = "%s %s ?"%(name, op) |
|
308 | expr = "%s %s ?"%(name, op) | |
303 | if isinstance(value, (tuple,list)): |
|
309 | if isinstance(value, (tuple,list)): | |
304 | if op in null_operators and any([v is None for v in value]): |
|
310 | if op in null_operators and any([v is None for v in value]): | |
305 | # equality tests don't work with NULL |
|
311 | # equality tests don't work with NULL | |
306 | raise ValueError("Cannot use %r test with NULL values on SQLite backend"%test) |
|
312 | raise ValueError("Cannot use %r test with NULL values on SQLite backend"%test) | |
307 | expr = '( %s )'%( join.join([expr]*len(value)) ) |
|
313 | expr = '( %s )'%( join.join([expr]*len(value)) ) | |
308 | args.extend(value) |
|
314 | args.extend(value) | |
309 | else: |
|
315 | else: | |
310 | args.append(value) |
|
316 | args.append(value) | |
311 | expressions.append(expr) |
|
317 | expressions.append(expr) | |
312 | else: |
|
318 | else: | |
313 | # it's an equality check |
|
319 | # it's an equality check | |
314 | if sub_check is None: |
|
320 | if sub_check is None: | |
315 | expressions.append("%s IS NULL" % name) |
|
321 | expressions.append("%s IS NULL" % name) | |
316 | else: |
|
322 | else: | |
317 | expressions.append("%s = ?"%name) |
|
323 | expressions.append("%s = ?"%name) | |
318 | args.append(sub_check) |
|
324 | args.append(sub_check) | |
319 |
|
325 | |||
320 | expr = " AND ".join(expressions) |
|
326 | expr = " AND ".join(expressions) | |
321 | return expr, args |
|
327 | return expr, args | |
322 |
|
328 | |||
323 | def add_record(self, msg_id, rec): |
|
329 | def add_record(self, msg_id, rec): | |
324 | """Add a new Task Record, by msg_id.""" |
|
330 | """Add a new Task Record, by msg_id.""" | |
325 | d = self._defaults() |
|
331 | d = self._defaults() | |
326 | d.update(rec) |
|
332 | d.update(rec) | |
327 | d['msg_id'] = msg_id |
|
333 | d['msg_id'] = msg_id | |
328 | line = self._dict_to_list(d) |
|
334 | line = self._dict_to_list(d) | |
329 | tups = '(%s)'%(','.join(['?']*len(line))) |
|
335 | tups = '(%s)'%(','.join(['?']*len(line))) | |
330 | self._db.execute("INSERT INTO %s VALUES %s"%(self.table, tups), line) |
|
336 | self._db.execute("INSERT INTO %s VALUES %s"%(self.table, tups), line) | |
331 | # self._db.commit() |
|
337 | # self._db.commit() | |
332 |
|
338 | |||
333 | def get_record(self, msg_id): |
|
339 | def get_record(self, msg_id): | |
334 | """Get a specific Task Record, by msg_id.""" |
|
340 | """Get a specific Task Record, by msg_id.""" | |
335 | cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) |
|
341 | cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) | |
336 | line = cursor.fetchone() |
|
342 | line = cursor.fetchone() | |
337 | if line is None: |
|
343 | if line is None: | |
338 | raise KeyError("No such msg: %r"%msg_id) |
|
344 | raise KeyError("No such msg: %r"%msg_id) | |
339 | return self._list_to_dict(line) |
|
345 | return self._list_to_dict(line) | |
340 |
|
346 | |||
341 | def update_record(self, msg_id, rec): |
|
347 | def update_record(self, msg_id, rec): | |
342 | """Update the data in an existing record.""" |
|
348 | """Update the data in an existing record.""" | |
343 | query = "UPDATE %s SET "%self.table |
|
349 | query = "UPDATE %s SET "%self.table | |
344 | sets = [] |
|
350 | sets = [] | |
345 | keys = sorted(rec.keys()) |
|
351 | keys = sorted(rec.keys()) | |
346 | values = [] |
|
352 | values = [] | |
347 | for key in keys: |
|
353 | for key in keys: | |
348 | sets.append('%s = ?'%key) |
|
354 | sets.append('%s = ?'%key) | |
349 | values.append(rec[key]) |
|
355 | values.append(rec[key]) | |
350 | query += ', '.join(sets) |
|
356 | query += ', '.join(sets) | |
351 | query += ' WHERE msg_id == ?' |
|
357 | query += ' WHERE msg_id == ?' | |
352 | values.append(msg_id) |
|
358 | values.append(msg_id) | |
353 | self._db.execute(query, values) |
|
359 | self._db.execute(query, values) | |
354 | # self._db.commit() |
|
360 | # self._db.commit() | |
355 |
|
361 | |||
356 | def drop_record(self, msg_id): |
|
362 | def drop_record(self, msg_id): | |
357 | """Remove a record from the DB.""" |
|
363 | """Remove a record from the DB.""" | |
358 | self._db.execute("""DELETE FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) |
|
364 | self._db.execute("""DELETE FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) | |
359 | # self._db.commit() |
|
365 | # self._db.commit() | |
360 |
|
366 | |||
361 | def drop_matching_records(self, check): |
|
367 | def drop_matching_records(self, check): | |
362 | """Remove a record from the DB.""" |
|
368 | """Remove a record from the DB.""" | |
363 | expr,args = self._render_expression(check) |
|
369 | expr,args = self._render_expression(check) | |
364 | query = "DELETE FROM %s WHERE %s"%(self.table, expr) |
|
370 | query = "DELETE FROM %s WHERE %s"%(self.table, expr) | |
365 | self._db.execute(query,args) |
|
371 | self._db.execute(query,args) | |
366 | # self._db.commit() |
|
372 | # self._db.commit() | |
367 |
|
373 | |||
368 | def find_records(self, check, keys=None): |
|
374 | def find_records(self, check, keys=None): | |
369 | """Find records matching a query dict, optionally extracting subset of keys. |
|
375 | """Find records matching a query dict, optionally extracting subset of keys. | |
370 |
|
376 | |||
371 | Returns list of matching records. |
|
377 | Returns list of matching records. | |
372 |
|
378 | |||
373 | Parameters |
|
379 | Parameters | |
374 | ---------- |
|
380 | ---------- | |
375 |
|
381 | |||
376 | check: dict |
|
382 | check: dict | |
377 | mongodb-style query argument |
|
383 | mongodb-style query argument | |
378 | keys: list of strs [optional] |
|
384 | keys: list of strs [optional] | |
379 | if specified, the subset of keys to extract. msg_id will *always* be |
|
385 | if specified, the subset of keys to extract. msg_id will *always* be | |
380 | included. |
|
386 | included. | |
381 | """ |
|
387 | """ | |
382 | if keys: |
|
388 | if keys: | |
383 | bad_keys = [ key for key in keys if key not in self._keys ] |
|
389 | bad_keys = [ key for key in keys if key not in self._keys ] | |
384 | if bad_keys: |
|
390 | if bad_keys: | |
385 | raise KeyError("Bad record key(s): %s"%bad_keys) |
|
391 | raise KeyError("Bad record key(s): %s"%bad_keys) | |
386 |
|
392 | |||
387 | if keys: |
|
393 | if keys: | |
388 | # ensure msg_id is present and first: |
|
394 | # ensure msg_id is present and first: | |
389 | if 'msg_id' in keys: |
|
395 | if 'msg_id' in keys: | |
390 | keys.remove('msg_id') |
|
396 | keys.remove('msg_id') | |
391 | keys.insert(0, 'msg_id') |
|
397 | keys.insert(0, 'msg_id') | |
392 | req = ', '.join(keys) |
|
398 | req = ', '.join(keys) | |
393 | else: |
|
399 | else: | |
394 | req = '*' |
|
400 | req = '*' | |
395 | expr,args = self._render_expression(check) |
|
401 | expr,args = self._render_expression(check) | |
396 | query = """SELECT %s FROM %s WHERE %s"""%(req, self.table, expr) |
|
402 | query = """SELECT %s FROM %s WHERE %s"""%(req, self.table, expr) | |
397 | cursor = self._db.execute(query, args) |
|
403 | cursor = self._db.execute(query, args) | |
398 | matches = cursor.fetchall() |
|
404 | matches = cursor.fetchall() | |
399 | records = [] |
|
405 | records = [] | |
400 | for line in matches: |
|
406 | for line in matches: | |
401 | rec = self._list_to_dict(line, keys) |
|
407 | rec = self._list_to_dict(line, keys) | |
402 | records.append(rec) |
|
408 | records.append(rec) | |
403 | return records |
|
409 | return records | |
404 |
|
410 | |||
405 | def get_history(self): |
|
411 | def get_history(self): | |
406 | """get all msg_ids, ordered by time submitted.""" |
|
412 | """get all msg_ids, ordered by time submitted.""" | |
407 | query = """SELECT msg_id FROM %s ORDER by submitted ASC"""%self.table |
|
413 | query = """SELECT msg_id FROM %s ORDER by submitted ASC"""%self.table | |
408 | cursor = self._db.execute(query) |
|
414 | cursor = self._db.execute(query) | |
409 | # will be a list of length 1 tuples |
|
415 | # will be a list of length 1 tuples | |
410 | return [ tup[0] for tup in cursor.fetchall()] |
|
416 | return [ tup[0] for tup in cursor.fetchall()] | |
411 |
|
417 | |||
412 | __all__ = ['SQLiteDB'] No newline at end of file |
|
418 | __all__ = ['SQLiteDB'] |
@@ -1,922 +1,925 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | """A simple interactive kernel that talks to a frontend over 0MQ. |
|
2 | """A simple interactive kernel that talks to a frontend over 0MQ. | |
3 |
|
3 | |||
4 | Things to do: |
|
4 | Things to do: | |
5 |
|
5 | |||
6 | * Implement `set_parent` logic. Right before doing exec, the Kernel should |
|
6 | * Implement `set_parent` logic. Right before doing exec, the Kernel should | |
7 | call set_parent on all the PUB objects with the message about to be executed. |
|
7 | call set_parent on all the PUB objects with the message about to be executed. | |
8 | * Implement random port and security key logic. |
|
8 | * Implement random port and security key logic. | |
9 | * Implement control messages. |
|
9 | * Implement control messages. | |
10 | * Implement event loop and poll version. |
|
10 | * Implement event loop and poll version. | |
11 | """ |
|
11 | """ | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Standard library imports |
|
18 | # Standard library imports | |
19 | import __builtin__ |
|
19 | import __builtin__ | |
20 | import atexit |
|
20 | import atexit | |
21 | import sys |
|
21 | import sys | |
22 | import time |
|
22 | import time | |
23 | import traceback |
|
23 | import traceback | |
24 | import logging |
|
24 | import logging | |
25 | import uuid |
|
25 | import uuid | |
26 |
|
26 | |||
27 | from datetime import datetime |
|
27 | from datetime import datetime | |
28 | from signal import ( |
|
28 | from signal import ( | |
29 | signal, getsignal, default_int_handler, SIGINT, SIG_IGN |
|
29 | signal, getsignal, default_int_handler, SIGINT, SIG_IGN | |
30 | ) |
|
30 | ) | |
31 |
|
31 | |||
32 | # System library imports |
|
32 | # System library imports | |
33 | import zmq |
|
33 | import zmq | |
34 | from zmq.eventloop import ioloop |
|
34 | from zmq.eventloop import ioloop | |
35 | from zmq.eventloop.zmqstream import ZMQStream |
|
35 | from zmq.eventloop.zmqstream import ZMQStream | |
36 |
|
36 | |||
37 | # Local imports |
|
37 | # Local imports | |
38 | from IPython.config.configurable import Configurable |
|
38 | from IPython.config.configurable import Configurable | |
39 | from IPython.config.application import boolean_flag, catch_config_error |
|
39 | from IPython.config.application import boolean_flag, catch_config_error | |
40 | from IPython.core.application import ProfileDir |
|
40 | from IPython.core.application import ProfileDir | |
41 | from IPython.core.error import StdinNotImplementedError |
|
41 | from IPython.core.error import StdinNotImplementedError | |
42 | from IPython.core.shellapp import ( |
|
42 | from IPython.core.shellapp import ( | |
43 | InteractiveShellApp, shell_flags, shell_aliases |
|
43 | InteractiveShellApp, shell_flags, shell_aliases | |
44 | ) |
|
44 | ) | |
45 | from IPython.utils import io |
|
45 | from IPython.utils import io | |
46 | from IPython.utils import py3compat |
|
46 | from IPython.utils import py3compat | |
47 | from IPython.utils.frame import extract_module_locals |
|
47 | from IPython.utils.frame import extract_module_locals | |
48 | from IPython.utils.jsonutil import json_clean |
|
48 | from IPython.utils.jsonutil import json_clean | |
49 | from IPython.utils.traitlets import ( |
|
49 | from IPython.utils.traitlets import ( | |
50 | Any, Instance, Float, Dict, CaselessStrEnum, List, Set, Integer, Unicode |
|
50 | Any, Instance, Float, Dict, CaselessStrEnum, List, Set, Integer, Unicode | |
51 | ) |
|
51 | ) | |
52 |
|
52 | |||
53 | from entry_point import base_launch_kernel |
|
53 | from entry_point import base_launch_kernel | |
54 | from kernelapp import KernelApp, kernel_flags, kernel_aliases |
|
54 | from kernelapp import KernelApp, kernel_flags, kernel_aliases | |
55 | from serialize import serialize_object, unpack_apply_message |
|
55 | from serialize import serialize_object, unpack_apply_message | |
56 | from session import Session, Message |
|
56 | from session import Session, Message | |
57 | from zmqshell import ZMQInteractiveShell |
|
57 | from zmqshell import ZMQInteractiveShell | |
58 |
|
58 | |||
59 |
|
59 | |||
60 | #----------------------------------------------------------------------------- |
|
60 | #----------------------------------------------------------------------------- | |
61 | # Main kernel class |
|
61 | # Main kernel class | |
62 | #----------------------------------------------------------------------------- |
|
62 | #----------------------------------------------------------------------------- | |
63 |
|
63 | |||
64 | class Kernel(Configurable): |
|
64 | class Kernel(Configurable): | |
65 |
|
65 | |||
66 | #--------------------------------------------------------------------------- |
|
66 | #--------------------------------------------------------------------------- | |
67 | # Kernel interface |
|
67 | # Kernel interface | |
68 | #--------------------------------------------------------------------------- |
|
68 | #--------------------------------------------------------------------------- | |
69 |
|
69 | |||
70 | # attribute to override with a GUI |
|
70 | # attribute to override with a GUI | |
71 | eventloop = Any(None) |
|
71 | eventloop = Any(None) | |
72 | def _eventloop_changed(self, name, old, new): |
|
72 | def _eventloop_changed(self, name, old, new): | |
73 | """schedule call to eventloop from IOLoop""" |
|
73 | """schedule call to eventloop from IOLoop""" | |
74 | loop = ioloop.IOLoop.instance() |
|
74 | loop = ioloop.IOLoop.instance() | |
75 | loop.add_timeout(time.time()+0.1, self.enter_eventloop) |
|
75 | loop.add_timeout(time.time()+0.1, self.enter_eventloop) | |
76 |
|
76 | |||
77 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
77 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
78 | session = Instance(Session) |
|
78 | session = Instance(Session) | |
79 | profile_dir = Instance('IPython.core.profiledir.ProfileDir') |
|
79 | profile_dir = Instance('IPython.core.profiledir.ProfileDir') | |
80 | shell_streams = List() |
|
80 | shell_streams = List() | |
81 | control_stream = Instance(ZMQStream) |
|
81 | control_stream = Instance(ZMQStream) | |
82 | iopub_socket = Instance(zmq.Socket) |
|
82 | iopub_socket = Instance(zmq.Socket) | |
83 | stdin_socket = Instance(zmq.Socket) |
|
83 | stdin_socket = Instance(zmq.Socket) | |
84 | log = Instance(logging.Logger) |
|
84 | log = Instance(logging.Logger) | |
85 |
|
85 | |||
86 | user_module = Any() |
|
86 | user_module = Any() | |
87 | def _user_module_changed(self, name, old, new): |
|
87 | def _user_module_changed(self, name, old, new): | |
88 | if self.shell is not None: |
|
88 | if self.shell is not None: | |
89 | self.shell.user_module = new |
|
89 | self.shell.user_module = new | |
90 |
|
90 | |||
91 | user_ns = Dict(default_value=None) |
|
91 | user_ns = Dict(default_value=None) | |
92 | def _user_ns_changed(self, name, old, new): |
|
92 | def _user_ns_changed(self, name, old, new): | |
93 | if self.shell is not None: |
|
93 | if self.shell is not None: | |
94 | self.shell.user_ns = new |
|
94 | self.shell.user_ns = new | |
95 | self.shell.init_user_ns() |
|
95 | self.shell.init_user_ns() | |
96 |
|
96 | |||
97 | # identities: |
|
97 | # identities: | |
98 | int_id = Integer(-1) |
|
98 | int_id = Integer(-1) | |
99 | ident = Unicode() |
|
99 | ident = Unicode() | |
100 |
|
100 | |||
101 | def _ident_default(self): |
|
101 | def _ident_default(self): | |
102 | return unicode(uuid.uuid4()) |
|
102 | return unicode(uuid.uuid4()) | |
103 |
|
103 | |||
104 |
|
104 | |||
105 | # Private interface |
|
105 | # Private interface | |
106 |
|
106 | |||
107 | # Time to sleep after flushing the stdout/err buffers in each execute |
|
107 | # Time to sleep after flushing the stdout/err buffers in each execute | |
108 | # cycle. While this introduces a hard limit on the minimal latency of the |
|
108 | # cycle. While this introduces a hard limit on the minimal latency of the | |
109 | # execute cycle, it helps prevent output synchronization problems for |
|
109 | # execute cycle, it helps prevent output synchronization problems for | |
110 | # clients. |
|
110 | # clients. | |
111 | # Units are in seconds. The minimum zmq latency on local host is probably |
|
111 | # Units are in seconds. The minimum zmq latency on local host is probably | |
112 | # ~150 microseconds, set this to 500us for now. We may need to increase it |
|
112 | # ~150 microseconds, set this to 500us for now. We may need to increase it | |
113 | # a little if it's not enough after more interactive testing. |
|
113 | # a little if it's not enough after more interactive testing. | |
114 | _execute_sleep = Float(0.0005, config=True) |
|
114 | _execute_sleep = Float(0.0005, config=True) | |
115 |
|
115 | |||
116 | # Frequency of the kernel's event loop. |
|
116 | # Frequency of the kernel's event loop. | |
117 | # Units are in seconds, kernel subclasses for GUI toolkits may need to |
|
117 | # Units are in seconds, kernel subclasses for GUI toolkits may need to | |
118 | # adapt to milliseconds. |
|
118 | # adapt to milliseconds. | |
119 | _poll_interval = Float(0.05, config=True) |
|
119 | _poll_interval = Float(0.05, config=True) | |
120 |
|
120 | |||
121 | # If the shutdown was requested over the network, we leave here the |
|
121 | # If the shutdown was requested over the network, we leave here the | |
122 | # necessary reply message so it can be sent by our registered atexit |
|
122 | # necessary reply message so it can be sent by our registered atexit | |
123 | # handler. This ensures that the reply is only sent to clients truly at |
|
123 | # handler. This ensures that the reply is only sent to clients truly at | |
124 | # the end of our shutdown process (which happens after the underlying |
|
124 | # the end of our shutdown process (which happens after the underlying | |
125 | # IPython shell's own shutdown). |
|
125 | # IPython shell's own shutdown). | |
126 | _shutdown_message = None |
|
126 | _shutdown_message = None | |
127 |
|
127 | |||
128 | # This is a dict of port number that the kernel is listening on. It is set |
|
128 | # This is a dict of port number that the kernel is listening on. It is set | |
129 | # by record_ports and used by connect_request. |
|
129 | # by record_ports and used by connect_request. | |
130 | _recorded_ports = Dict() |
|
130 | _recorded_ports = Dict() | |
131 |
|
131 | |||
132 | # set of aborted msg_ids |
|
132 | # set of aborted msg_ids | |
133 | aborted = Set() |
|
133 | aborted = Set() | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | def __init__(self, **kwargs): |
|
136 | def __init__(self, **kwargs): | |
137 | super(Kernel, self).__init__(**kwargs) |
|
137 | super(Kernel, self).__init__(**kwargs) | |
138 |
|
138 | |||
139 | # Initialize the InteractiveShell subclass |
|
139 | # Initialize the InteractiveShell subclass | |
140 | self.shell = ZMQInteractiveShell.instance(config=self.config, |
|
140 | self.shell = ZMQInteractiveShell.instance(config=self.config, | |
141 | profile_dir = self.profile_dir, |
|
141 | profile_dir = self.profile_dir, | |
142 | user_module = self.user_module, |
|
142 | user_module = self.user_module, | |
143 | user_ns = self.user_ns, |
|
143 | user_ns = self.user_ns, | |
144 | ) |
|
144 | ) | |
145 | self.shell.displayhook.session = self.session |
|
145 | self.shell.displayhook.session = self.session | |
146 | self.shell.displayhook.pub_socket = self.iopub_socket |
|
146 | self.shell.displayhook.pub_socket = self.iopub_socket | |
147 | self.shell.displayhook.topic = self._topic('pyout') |
|
147 | self.shell.displayhook.topic = self._topic('pyout') | |
148 | self.shell.display_pub.session = self.session |
|
148 | self.shell.display_pub.session = self.session | |
149 | self.shell.display_pub.pub_socket = self.iopub_socket |
|
149 | self.shell.display_pub.pub_socket = self.iopub_socket | |
150 |
|
150 | |||
151 | # TMP - hack while developing |
|
151 | # TMP - hack while developing | |
152 | self.shell._reply_content = None |
|
152 | self.shell._reply_content = None | |
153 |
|
153 | |||
154 | # Build dict of handlers for message types |
|
154 | # Build dict of handlers for message types | |
155 | msg_types = [ 'execute_request', 'complete_request', |
|
155 | msg_types = [ 'execute_request', 'complete_request', | |
156 | 'object_info_request', 'history_request', |
|
156 | 'object_info_request', 'history_request', | |
157 | 'connect_request', 'shutdown_request', |
|
157 | 'connect_request', 'shutdown_request', | |
158 | 'apply_request', |
|
158 | 'apply_request', | |
159 | ] |
|
159 | ] | |
160 | self.shell_handlers = {} |
|
160 | self.shell_handlers = {} | |
161 | for msg_type in msg_types: |
|
161 | for msg_type in msg_types: | |
162 | self.shell_handlers[msg_type] = getattr(self, msg_type) |
|
162 | self.shell_handlers[msg_type] = getattr(self, msg_type) | |
163 |
|
163 | |||
164 | control_msg_types = msg_types + [ 'clear_request', 'abort_request' ] |
|
164 | control_msg_types = msg_types + [ 'clear_request', 'abort_request' ] | |
165 | self.control_handlers = {} |
|
165 | self.control_handlers = {} | |
166 | for msg_type in control_msg_types: |
|
166 | for msg_type in control_msg_types: | |
167 | self.control_handlers[msg_type] = getattr(self, msg_type) |
|
167 | self.control_handlers[msg_type] = getattr(self, msg_type) | |
168 |
|
168 | |||
169 | def dispatch_control(self, msg): |
|
169 | def dispatch_control(self, msg): | |
170 | """dispatch control requests""" |
|
170 | """dispatch control requests""" | |
171 | idents,msg = self.session.feed_identities(msg, copy=False) |
|
171 | idents,msg = self.session.feed_identities(msg, copy=False) | |
172 | try: |
|
172 | try: | |
173 | msg = self.session.unserialize(msg, content=True, copy=False) |
|
173 | msg = self.session.unserialize(msg, content=True, copy=False) | |
174 | except: |
|
174 | except: | |
175 | self.log.error("Invalid Control Message", exc_info=True) |
|
175 | self.log.error("Invalid Control Message", exc_info=True) | |
176 | return |
|
176 | return | |
177 |
|
177 | |||
178 | self.log.debug("Control received: %s", msg) |
|
178 | self.log.debug("Control received: %s", msg) | |
179 |
|
179 | |||
180 | header = msg['header'] |
|
180 | header = msg['header'] | |
181 | msg_id = header['msg_id'] |
|
181 | msg_id = header['msg_id'] | |
182 | msg_type = header['msg_type'] |
|
182 | msg_type = header['msg_type'] | |
183 |
|
183 | |||
184 | handler = self.control_handlers.get(msg_type, None) |
|
184 | handler = self.control_handlers.get(msg_type, None) | |
185 | if handler is None: |
|
185 | if handler is None: | |
186 | self.log.error("UNKNOWN CONTROL MESSAGE TYPE: %r", msg_type) |
|
186 | self.log.error("UNKNOWN CONTROL MESSAGE TYPE: %r", msg_type) | |
187 | else: |
|
187 | else: | |
188 | try: |
|
188 | try: | |
189 | handler(self.control_stream, idents, msg) |
|
189 | handler(self.control_stream, idents, msg) | |
190 | except Exception: |
|
190 | except Exception: | |
191 | self.log.error("Exception in control handler:", exc_info=True) |
|
191 | self.log.error("Exception in control handler:", exc_info=True) | |
192 |
|
192 | |||
193 | def dispatch_shell(self, stream, msg): |
|
193 | def dispatch_shell(self, stream, msg): | |
194 | """dispatch shell requests""" |
|
194 | """dispatch shell requests""" | |
195 | # flush control requests first |
|
195 | # flush control requests first | |
196 | if self.control_stream: |
|
196 | if self.control_stream: | |
197 | self.control_stream.flush() |
|
197 | self.control_stream.flush() | |
198 |
|
198 | |||
199 | idents,msg = self.session.feed_identities(msg, copy=False) |
|
199 | idents,msg = self.session.feed_identities(msg, copy=False) | |
200 | try: |
|
200 | try: | |
201 | msg = self.session.unserialize(msg, content=True, copy=False) |
|
201 | msg = self.session.unserialize(msg, content=True, copy=False) | |
202 | except: |
|
202 | except: | |
203 | self.log.error("Invalid Message", exc_info=True) |
|
203 | self.log.error("Invalid Message", exc_info=True) | |
204 | return |
|
204 | return | |
205 |
|
205 | |||
206 | header = msg['header'] |
|
206 | header = msg['header'] | |
207 | msg_id = header['msg_id'] |
|
207 | msg_id = header['msg_id'] | |
208 | msg_type = msg['header']['msg_type'] |
|
208 | msg_type = msg['header']['msg_type'] | |
209 |
|
209 | |||
210 | # Print some info about this message and leave a '--->' marker, so it's |
|
210 | # Print some info about this message and leave a '--->' marker, so it's | |
211 | # easier to trace visually the message chain when debugging. Each |
|
211 | # easier to trace visually the message chain when debugging. Each | |
212 | # handler prints its message at the end. |
|
212 | # handler prints its message at the end. | |
213 | self.log.debug('\n*** MESSAGE TYPE:%s***', msg_type) |
|
213 | self.log.debug('\n*** MESSAGE TYPE:%s***', msg_type) | |
214 | self.log.debug(' Content: %s\n --->\n ', msg['content']) |
|
214 | self.log.debug(' Content: %s\n --->\n ', msg['content']) | |
215 |
|
215 | |||
216 | if msg_id in self.aborted: |
|
216 | if msg_id in self.aborted: | |
217 | self.aborted.remove(msg_id) |
|
217 | self.aborted.remove(msg_id) | |
218 | # is it safe to assume a msg_id will not be resubmitted? |
|
218 | # is it safe to assume a msg_id will not be resubmitted? | |
219 | reply_type = msg_type.split('_')[0] + '_reply' |
|
219 | reply_type = msg_type.split('_')[0] + '_reply' | |
220 | status = {'status' : 'aborted'} |
|
220 | status = {'status' : 'aborted'} | |
221 |
|
|
221 | md = {'engine' : self.ident} | |
222 |
|
|
222 | md.update(status) | |
223 |
reply_msg = self.session.send(stream, reply_type, |
|
223 | reply_msg = self.session.send(stream, reply_type, metadata=md, | |
224 | content=status, parent=msg, ident=idents) |
|
224 | content=status, parent=msg, ident=idents) | |
225 | return |
|
225 | return | |
226 |
|
226 | |||
227 | handler = self.shell_handlers.get(msg_type, None) |
|
227 | handler = self.shell_handlers.get(msg_type, None) | |
228 | if handler is None: |
|
228 | if handler is None: | |
229 | self.log.error("UNKNOWN MESSAGE TYPE: %r", msg_type) |
|
229 | self.log.error("UNKNOWN MESSAGE TYPE: %r", msg_type) | |
230 | else: |
|
230 | else: | |
231 | # ensure default_int_handler during handler call |
|
231 | # ensure default_int_handler during handler call | |
232 | sig = signal(SIGINT, default_int_handler) |
|
232 | sig = signal(SIGINT, default_int_handler) | |
233 | try: |
|
233 | try: | |
234 | handler(stream, idents, msg) |
|
234 | handler(stream, idents, msg) | |
235 | except Exception: |
|
235 | except Exception: | |
236 | self.log.error("Exception in message handler:", exc_info=True) |
|
236 | self.log.error("Exception in message handler:", exc_info=True) | |
237 | finally: |
|
237 | finally: | |
238 | signal(SIGINT, sig) |
|
238 | signal(SIGINT, sig) | |
239 |
|
239 | |||
240 | def enter_eventloop(self): |
|
240 | def enter_eventloop(self): | |
241 | """enter eventloop""" |
|
241 | """enter eventloop""" | |
242 | self.log.info("entering eventloop") |
|
242 | self.log.info("entering eventloop") | |
243 | # restore default_int_handler |
|
243 | # restore default_int_handler | |
244 | signal(SIGINT, default_int_handler) |
|
244 | signal(SIGINT, default_int_handler) | |
245 | while self.eventloop is not None: |
|
245 | while self.eventloop is not None: | |
246 | try: |
|
246 | try: | |
247 | self.eventloop(self) |
|
247 | self.eventloop(self) | |
248 | except KeyboardInterrupt: |
|
248 | except KeyboardInterrupt: | |
249 | # Ctrl-C shouldn't crash the kernel |
|
249 | # Ctrl-C shouldn't crash the kernel | |
250 | self.log.error("KeyboardInterrupt caught in kernel") |
|
250 | self.log.error("KeyboardInterrupt caught in kernel") | |
251 | continue |
|
251 | continue | |
252 | else: |
|
252 | else: | |
253 | # eventloop exited cleanly, this means we should stop (right?) |
|
253 | # eventloop exited cleanly, this means we should stop (right?) | |
254 | self.eventloop = None |
|
254 | self.eventloop = None | |
255 | break |
|
255 | break | |
256 | self.log.info("exiting eventloop") |
|
256 | self.log.info("exiting eventloop") | |
257 | # if eventloop exits, IOLoop should stop |
|
257 | # if eventloop exits, IOLoop should stop | |
258 | ioloop.IOLoop.instance().stop() |
|
258 | ioloop.IOLoop.instance().stop() | |
259 |
|
259 | |||
260 | def start(self): |
|
260 | def start(self): | |
261 | """register dispatchers for streams""" |
|
261 | """register dispatchers for streams""" | |
262 | self.shell.exit_now = False |
|
262 | self.shell.exit_now = False | |
263 | if self.control_stream: |
|
263 | if self.control_stream: | |
264 | self.control_stream.on_recv(self.dispatch_control, copy=False) |
|
264 | self.control_stream.on_recv(self.dispatch_control, copy=False) | |
265 |
|
265 | |||
266 | def make_dispatcher(stream): |
|
266 | def make_dispatcher(stream): | |
267 | def dispatcher(msg): |
|
267 | def dispatcher(msg): | |
268 | return self.dispatch_shell(stream, msg) |
|
268 | return self.dispatch_shell(stream, msg) | |
269 | return dispatcher |
|
269 | return dispatcher | |
270 |
|
270 | |||
271 | for s in self.shell_streams: |
|
271 | for s in self.shell_streams: | |
272 | s.on_recv(make_dispatcher(s), copy=False) |
|
272 | s.on_recv(make_dispatcher(s), copy=False) | |
273 |
|
273 | |||
274 | def do_one_iteration(self): |
|
274 | def do_one_iteration(self): | |
275 | """step eventloop just once""" |
|
275 | """step eventloop just once""" | |
276 | if self.control_stream: |
|
276 | if self.control_stream: | |
277 | self.control_stream.flush() |
|
277 | self.control_stream.flush() | |
278 | for stream in self.shell_streams: |
|
278 | for stream in self.shell_streams: | |
279 | # handle at most one request per iteration |
|
279 | # handle at most one request per iteration | |
280 | stream.flush(zmq.POLLIN, 1) |
|
280 | stream.flush(zmq.POLLIN, 1) | |
281 | stream.flush(zmq.POLLOUT) |
|
281 | stream.flush(zmq.POLLOUT) | |
282 |
|
282 | |||
283 |
|
283 | |||
284 | def record_ports(self, ports): |
|
284 | def record_ports(self, ports): | |
285 | """Record the ports that this kernel is using. |
|
285 | """Record the ports that this kernel is using. | |
286 |
|
286 | |||
287 | The creator of the Kernel instance must call this methods if they |
|
287 | The creator of the Kernel instance must call this methods if they | |
288 | want the :meth:`connect_request` method to return the port numbers. |
|
288 | want the :meth:`connect_request` method to return the port numbers. | |
289 | """ |
|
289 | """ | |
290 | self._recorded_ports = ports |
|
290 | self._recorded_ports = ports | |
291 |
|
291 | |||
292 | #--------------------------------------------------------------------------- |
|
292 | #--------------------------------------------------------------------------- | |
293 | # Kernel request handlers |
|
293 | # Kernel request handlers | |
294 | #--------------------------------------------------------------------------- |
|
294 | #--------------------------------------------------------------------------- | |
295 |
|
295 | |||
296 |
def _make_ |
|
296 | def _make_metadata(self, other=None): | |
297 |
"""init |
|
297 | """init metadata dict, for execute/apply_reply""" | |
298 |
|
|
298 | new_md = { | |
299 | 'dependencies_met' : True, |
|
299 | 'dependencies_met' : True, | |
300 | 'engine' : self.ident, |
|
300 | 'engine' : self.ident, | |
301 | 'started': datetime.now(), |
|
301 | 'started': datetime.now(), | |
302 | } |
|
302 | } | |
|
303 | if other: | |||
|
304 | new_md.update(other) | |||
|
305 | return new_md | |||
303 |
|
306 | |||
304 | def _publish_pyin(self, code, parent, execution_count): |
|
307 | def _publish_pyin(self, code, parent, execution_count): | |
305 | """Publish the code request on the pyin stream.""" |
|
308 | """Publish the code request on the pyin stream.""" | |
306 |
|
309 | |||
307 | self.session.send(self.iopub_socket, u'pyin', |
|
310 | self.session.send(self.iopub_socket, u'pyin', | |
308 | {u'code':code, u'execution_count': execution_count}, |
|
311 | {u'code':code, u'execution_count': execution_count}, | |
309 | parent=parent, ident=self._topic('pyin') |
|
312 | parent=parent, ident=self._topic('pyin') | |
310 | ) |
|
313 | ) | |
311 |
|
314 | |||
312 | def _publish_status(self, status, parent=None): |
|
315 | def _publish_status(self, status, parent=None): | |
313 | """send status (busy/idle) on IOPub""" |
|
316 | """send status (busy/idle) on IOPub""" | |
314 | self.session.send(self.iopub_socket, |
|
317 | self.session.send(self.iopub_socket, | |
315 | u'status', |
|
318 | u'status', | |
316 | {u'execution_state': status}, |
|
319 | {u'execution_state': status}, | |
317 | parent=parent, |
|
320 | parent=parent, | |
318 | ident=self._topic('status'), |
|
321 | ident=self._topic('status'), | |
319 | ) |
|
322 | ) | |
320 |
|
323 | |||
321 |
|
324 | |||
322 | def execute_request(self, stream, ident, parent): |
|
325 | def execute_request(self, stream, ident, parent): | |
323 | """handle an execute_request""" |
|
326 | """handle an execute_request""" | |
324 |
|
327 | |||
325 | self._publish_status(u'busy', parent) |
|
328 | self._publish_status(u'busy', parent) | |
326 |
|
329 | |||
327 | try: |
|
330 | try: | |
328 | content = parent[u'content'] |
|
331 | content = parent[u'content'] | |
329 | code = content[u'code'] |
|
332 | code = content[u'code'] | |
330 | silent = content[u'silent'] |
|
333 | silent = content[u'silent'] | |
331 | except: |
|
334 | except: | |
332 | self.log.error("Got bad msg: ") |
|
335 | self.log.error("Got bad msg: ") | |
333 | self.log.error("%s", parent) |
|
336 | self.log.error("%s", parent) | |
334 | return |
|
337 | return | |
335 |
|
338 | |||
336 |
|
|
339 | md = self._make_metadata(parent['metadata']) | |
337 |
|
340 | |||
338 | shell = self.shell # we'll need this a lot here |
|
341 | shell = self.shell # we'll need this a lot here | |
339 |
|
342 | |||
340 | # Replace raw_input. Note that is not sufficient to replace |
|
343 | # Replace raw_input. Note that is not sufficient to replace | |
341 | # raw_input in the user namespace. |
|
344 | # raw_input in the user namespace. | |
342 | if content.get('allow_stdin', False): |
|
345 | if content.get('allow_stdin', False): | |
343 | raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) |
|
346 | raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) | |
344 | else: |
|
347 | else: | |
345 | raw_input = lambda prompt='' : self._no_raw_input() |
|
348 | raw_input = lambda prompt='' : self._no_raw_input() | |
346 |
|
349 | |||
347 | if py3compat.PY3: |
|
350 | if py3compat.PY3: | |
348 | __builtin__.input = raw_input |
|
351 | __builtin__.input = raw_input | |
349 | else: |
|
352 | else: | |
350 | __builtin__.raw_input = raw_input |
|
353 | __builtin__.raw_input = raw_input | |
351 |
|
354 | |||
352 | # Set the parent message of the display hook and out streams. |
|
355 | # Set the parent message of the display hook and out streams. | |
353 | shell.displayhook.set_parent(parent) |
|
356 | shell.displayhook.set_parent(parent) | |
354 | shell.display_pub.set_parent(parent) |
|
357 | shell.display_pub.set_parent(parent) | |
355 | sys.stdout.set_parent(parent) |
|
358 | sys.stdout.set_parent(parent) | |
356 | sys.stderr.set_parent(parent) |
|
359 | sys.stderr.set_parent(parent) | |
357 |
|
360 | |||
358 | # Re-broadcast our input for the benefit of listening clients, and |
|
361 | # Re-broadcast our input for the benefit of listening clients, and | |
359 | # start computing output |
|
362 | # start computing output | |
360 | if not silent: |
|
363 | if not silent: | |
361 | self._publish_pyin(code, parent, shell.execution_count) |
|
364 | self._publish_pyin(code, parent, shell.execution_count) | |
362 |
|
365 | |||
363 | reply_content = {} |
|
366 | reply_content = {} | |
364 | try: |
|
367 | try: | |
365 | # FIXME: the shell calls the exception handler itself. |
|
368 | # FIXME: the shell calls the exception handler itself. | |
366 | shell.run_cell(code, store_history=not silent, silent=silent) |
|
369 | shell.run_cell(code, store_history=not silent, silent=silent) | |
367 | except: |
|
370 | except: | |
368 | status = u'error' |
|
371 | status = u'error' | |
369 | # FIXME: this code right now isn't being used yet by default, |
|
372 | # FIXME: this code right now isn't being used yet by default, | |
370 | # because the run_cell() call above directly fires off exception |
|
373 | # because the run_cell() call above directly fires off exception | |
371 | # reporting. This code, therefore, is only active in the scenario |
|
374 | # reporting. This code, therefore, is only active in the scenario | |
372 | # where runlines itself has an unhandled exception. We need to |
|
375 | # where runlines itself has an unhandled exception. We need to | |
373 | # uniformize this, for all exception construction to come from a |
|
376 | # uniformize this, for all exception construction to come from a | |
374 | # single location in the codbase. |
|
377 | # single location in the codbase. | |
375 | etype, evalue, tb = sys.exc_info() |
|
378 | etype, evalue, tb = sys.exc_info() | |
376 | tb_list = traceback.format_exception(etype, evalue, tb) |
|
379 | tb_list = traceback.format_exception(etype, evalue, tb) | |
377 | reply_content.update(shell._showtraceback(etype, evalue, tb_list)) |
|
380 | reply_content.update(shell._showtraceback(etype, evalue, tb_list)) | |
378 | else: |
|
381 | else: | |
379 | status = u'ok' |
|
382 | status = u'ok' | |
380 |
|
383 | |||
381 | reply_content[u'status'] = status |
|
384 | reply_content[u'status'] = status | |
382 |
|
385 | |||
383 | # Return the execution counter so clients can display prompts |
|
386 | # Return the execution counter so clients can display prompts | |
384 | reply_content['execution_count'] = shell.execution_count - 1 |
|
387 | reply_content['execution_count'] = shell.execution_count - 1 | |
385 |
|
388 | |||
386 | # FIXME - fish exception info out of shell, possibly left there by |
|
389 | # FIXME - fish exception info out of shell, possibly left there by | |
387 | # runlines. We'll need to clean up this logic later. |
|
390 | # runlines. We'll need to clean up this logic later. | |
388 | if shell._reply_content is not None: |
|
391 | if shell._reply_content is not None: | |
389 | reply_content.update(shell._reply_content) |
|
392 | reply_content.update(shell._reply_content) | |
390 | e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='execute') |
|
393 | e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='execute') | |
391 | reply_content['engine_info'] = e_info |
|
394 | reply_content['engine_info'] = e_info | |
392 | # reset after use |
|
395 | # reset after use | |
393 | shell._reply_content = None |
|
396 | shell._reply_content = None | |
394 |
|
397 | |||
395 | # At this point, we can tell whether the main code execution succeeded |
|
398 | # At this point, we can tell whether the main code execution succeeded | |
396 | # or not. If it did, we proceed to evaluate user_variables/expressions |
|
399 | # or not. If it did, we proceed to evaluate user_variables/expressions | |
397 | if reply_content['status'] == 'ok': |
|
400 | if reply_content['status'] == 'ok': | |
398 | reply_content[u'user_variables'] = \ |
|
401 | reply_content[u'user_variables'] = \ | |
399 | shell.user_variables(content.get(u'user_variables', [])) |
|
402 | shell.user_variables(content.get(u'user_variables', [])) | |
400 | reply_content[u'user_expressions'] = \ |
|
403 | reply_content[u'user_expressions'] = \ | |
401 | shell.user_expressions(content.get(u'user_expressions', {})) |
|
404 | shell.user_expressions(content.get(u'user_expressions', {})) | |
402 | else: |
|
405 | else: | |
403 | # If there was an error, don't even try to compute variables or |
|
406 | # If there was an error, don't even try to compute variables or | |
404 | # expressions |
|
407 | # expressions | |
405 | reply_content[u'user_variables'] = {} |
|
408 | reply_content[u'user_variables'] = {} | |
406 | reply_content[u'user_expressions'] = {} |
|
409 | reply_content[u'user_expressions'] = {} | |
407 |
|
410 | |||
408 | # Payloads should be retrieved regardless of outcome, so we can both |
|
411 | # Payloads should be retrieved regardless of outcome, so we can both | |
409 | # recover partial output (that could have been generated early in a |
|
412 | # recover partial output (that could have been generated early in a | |
410 | # block, before an error) and clear the payload system always. |
|
413 | # block, before an error) and clear the payload system always. | |
411 | reply_content[u'payload'] = shell.payload_manager.read_payload() |
|
414 | reply_content[u'payload'] = shell.payload_manager.read_payload() | |
412 | # Be agressive about clearing the payload because we don't want |
|
415 | # Be agressive about clearing the payload because we don't want | |
413 | # it to sit in memory until the next execute_request comes in. |
|
416 | # it to sit in memory until the next execute_request comes in. | |
414 | shell.payload_manager.clear_payload() |
|
417 | shell.payload_manager.clear_payload() | |
415 |
|
418 | |||
416 | # Flush output before sending the reply. |
|
419 | # Flush output before sending the reply. | |
417 | sys.stdout.flush() |
|
420 | sys.stdout.flush() | |
418 | sys.stderr.flush() |
|
421 | sys.stderr.flush() | |
419 | # FIXME: on rare occasions, the flush doesn't seem to make it to the |
|
422 | # FIXME: on rare occasions, the flush doesn't seem to make it to the | |
420 | # clients... This seems to mitigate the problem, but we definitely need |
|
423 | # clients... This seems to mitigate the problem, but we definitely need | |
421 | # to better understand what's going on. |
|
424 | # to better understand what's going on. | |
422 | if self._execute_sleep: |
|
425 | if self._execute_sleep: | |
423 | time.sleep(self._execute_sleep) |
|
426 | time.sleep(self._execute_sleep) | |
424 |
|
427 | |||
425 | # Send the reply. |
|
428 | # Send the reply. | |
426 | reply_content = json_clean(reply_content) |
|
429 | reply_content = json_clean(reply_content) | |
427 |
|
430 | |||
428 |
|
|
431 | md['status'] = reply_content['status'] | |
429 | if reply_content['status'] == 'error' and \ |
|
432 | if reply_content['status'] == 'error' and \ | |
430 | reply_content['ename'] == 'UnmetDependency': |
|
433 | reply_content['ename'] == 'UnmetDependency': | |
431 |
|
|
434 | md['dependencies_met'] = False | |
432 |
|
435 | |||
433 | reply_msg = self.session.send(stream, u'execute_reply', |
|
436 | reply_msg = self.session.send(stream, u'execute_reply', | |
434 |
reply_content, parent, |
|
437 | reply_content, parent, metadata=md, | |
435 | ident=ident) |
|
438 | ident=ident) | |
436 |
|
439 | |||
437 | self.log.debug("%s", reply_msg) |
|
440 | self.log.debug("%s", reply_msg) | |
438 |
|
441 | |||
439 | if not silent and reply_msg['content']['status'] == u'error': |
|
442 | if not silent and reply_msg['content']['status'] == u'error': | |
440 | self._abort_queues() |
|
443 | self._abort_queues() | |
441 |
|
444 | |||
442 | self._publish_status(u'idle', parent) |
|
445 | self._publish_status(u'idle', parent) | |
443 |
|
446 | |||
444 | def complete_request(self, stream, ident, parent): |
|
447 | def complete_request(self, stream, ident, parent): | |
445 | txt, matches = self._complete(parent) |
|
448 | txt, matches = self._complete(parent) | |
446 | matches = {'matches' : matches, |
|
449 | matches = {'matches' : matches, | |
447 | 'matched_text' : txt, |
|
450 | 'matched_text' : txt, | |
448 | 'status' : 'ok'} |
|
451 | 'status' : 'ok'} | |
449 | matches = json_clean(matches) |
|
452 | matches = json_clean(matches) | |
450 | completion_msg = self.session.send(stream, 'complete_reply', |
|
453 | completion_msg = self.session.send(stream, 'complete_reply', | |
451 | matches, parent, ident) |
|
454 | matches, parent, ident) | |
452 | self.log.debug("%s", completion_msg) |
|
455 | self.log.debug("%s", completion_msg) | |
453 |
|
456 | |||
454 | def object_info_request(self, stream, ident, parent): |
|
457 | def object_info_request(self, stream, ident, parent): | |
455 | content = parent['content'] |
|
458 | content = parent['content'] | |
456 | object_info = self.shell.object_inspect(content['oname'], |
|
459 | object_info = self.shell.object_inspect(content['oname'], | |
457 | detail_level = content.get('detail_level', 0) |
|
460 | detail_level = content.get('detail_level', 0) | |
458 | ) |
|
461 | ) | |
459 | # Before we send this object over, we scrub it for JSON usage |
|
462 | # Before we send this object over, we scrub it for JSON usage | |
460 | oinfo = json_clean(object_info) |
|
463 | oinfo = json_clean(object_info) | |
461 | msg = self.session.send(stream, 'object_info_reply', |
|
464 | msg = self.session.send(stream, 'object_info_reply', | |
462 | oinfo, parent, ident) |
|
465 | oinfo, parent, ident) | |
463 | self.log.debug("%s", msg) |
|
466 | self.log.debug("%s", msg) | |
464 |
|
467 | |||
465 | def history_request(self, stream, ident, parent): |
|
468 | def history_request(self, stream, ident, parent): | |
466 | # We need to pull these out, as passing **kwargs doesn't work with |
|
469 | # We need to pull these out, as passing **kwargs doesn't work with | |
467 | # unicode keys before Python 2.6.5. |
|
470 | # unicode keys before Python 2.6.5. | |
468 | hist_access_type = parent['content']['hist_access_type'] |
|
471 | hist_access_type = parent['content']['hist_access_type'] | |
469 | raw = parent['content']['raw'] |
|
472 | raw = parent['content']['raw'] | |
470 | output = parent['content']['output'] |
|
473 | output = parent['content']['output'] | |
471 | if hist_access_type == 'tail': |
|
474 | if hist_access_type == 'tail': | |
472 | n = parent['content']['n'] |
|
475 | n = parent['content']['n'] | |
473 | hist = self.shell.history_manager.get_tail(n, raw=raw, output=output, |
|
476 | hist = self.shell.history_manager.get_tail(n, raw=raw, output=output, | |
474 | include_latest=True) |
|
477 | include_latest=True) | |
475 |
|
478 | |||
476 | elif hist_access_type == 'range': |
|
479 | elif hist_access_type == 'range': | |
477 | session = parent['content']['session'] |
|
480 | session = parent['content']['session'] | |
478 | start = parent['content']['start'] |
|
481 | start = parent['content']['start'] | |
479 | stop = parent['content']['stop'] |
|
482 | stop = parent['content']['stop'] | |
480 | hist = self.shell.history_manager.get_range(session, start, stop, |
|
483 | hist = self.shell.history_manager.get_range(session, start, stop, | |
481 | raw=raw, output=output) |
|
484 | raw=raw, output=output) | |
482 |
|
485 | |||
483 | elif hist_access_type == 'search': |
|
486 | elif hist_access_type == 'search': | |
484 | pattern = parent['content']['pattern'] |
|
487 | pattern = parent['content']['pattern'] | |
485 | hist = self.shell.history_manager.search(pattern, raw=raw, |
|
488 | hist = self.shell.history_manager.search(pattern, raw=raw, | |
486 | output=output) |
|
489 | output=output) | |
487 |
|
490 | |||
488 | else: |
|
491 | else: | |
489 | hist = [] |
|
492 | hist = [] | |
490 | hist = list(hist) |
|
493 | hist = list(hist) | |
491 | content = {'history' : hist} |
|
494 | content = {'history' : hist} | |
492 | content = json_clean(content) |
|
495 | content = json_clean(content) | |
493 | msg = self.session.send(stream, 'history_reply', |
|
496 | msg = self.session.send(stream, 'history_reply', | |
494 | content, parent, ident) |
|
497 | content, parent, ident) | |
495 | self.log.debug("Sending history reply with %i entries", len(hist)) |
|
498 | self.log.debug("Sending history reply with %i entries", len(hist)) | |
496 |
|
499 | |||
497 | def connect_request(self, stream, ident, parent): |
|
500 | def connect_request(self, stream, ident, parent): | |
498 | if self._recorded_ports is not None: |
|
501 | if self._recorded_ports is not None: | |
499 | content = self._recorded_ports.copy() |
|
502 | content = self._recorded_ports.copy() | |
500 | else: |
|
503 | else: | |
501 | content = {} |
|
504 | content = {} | |
502 | msg = self.session.send(stream, 'connect_reply', |
|
505 | msg = self.session.send(stream, 'connect_reply', | |
503 | content, parent, ident) |
|
506 | content, parent, ident) | |
504 | self.log.debug("%s", msg) |
|
507 | self.log.debug("%s", msg) | |
505 |
|
508 | |||
506 | def shutdown_request(self, stream, ident, parent): |
|
509 | def shutdown_request(self, stream, ident, parent): | |
507 | self.shell.exit_now = True |
|
510 | self.shell.exit_now = True | |
508 | content = dict(status='ok') |
|
511 | content = dict(status='ok') | |
509 | content.update(parent['content']) |
|
512 | content.update(parent['content']) | |
510 | self.session.send(stream, u'shutdown_reply', content, parent, ident=ident) |
|
513 | self.session.send(stream, u'shutdown_reply', content, parent, ident=ident) | |
511 | # same content, but different msg_id for broadcasting on IOPub |
|
514 | # same content, but different msg_id for broadcasting on IOPub | |
512 | self._shutdown_message = self.session.msg(u'shutdown_reply', |
|
515 | self._shutdown_message = self.session.msg(u'shutdown_reply', | |
513 | content, parent |
|
516 | content, parent | |
514 | ) |
|
517 | ) | |
515 |
|
518 | |||
516 | self._at_shutdown() |
|
519 | self._at_shutdown() | |
517 | # call sys.exit after a short delay |
|
520 | # call sys.exit after a short delay | |
518 | loop = ioloop.IOLoop.instance() |
|
521 | loop = ioloop.IOLoop.instance() | |
519 | loop.add_timeout(time.time()+0.1, loop.stop) |
|
522 | loop.add_timeout(time.time()+0.1, loop.stop) | |
520 |
|
523 | |||
521 | #--------------------------------------------------------------------------- |
|
524 | #--------------------------------------------------------------------------- | |
522 | # Engine methods |
|
525 | # Engine methods | |
523 | #--------------------------------------------------------------------------- |
|
526 | #--------------------------------------------------------------------------- | |
524 |
|
527 | |||
525 | def apply_request(self, stream, ident, parent): |
|
528 | def apply_request(self, stream, ident, parent): | |
526 | try: |
|
529 | try: | |
527 | content = parent[u'content'] |
|
530 | content = parent[u'content'] | |
528 | bufs = parent[u'buffers'] |
|
531 | bufs = parent[u'buffers'] | |
529 | msg_id = parent['header']['msg_id'] |
|
532 | msg_id = parent['header']['msg_id'] | |
530 | except: |
|
533 | except: | |
531 | self.log.error("Got bad msg: %s", parent, exc_info=True) |
|
534 | self.log.error("Got bad msg: %s", parent, exc_info=True) | |
532 | return |
|
535 | return | |
533 |
|
536 | |||
534 | self._publish_status(u'busy', parent) |
|
537 | self._publish_status(u'busy', parent) | |
535 |
|
538 | |||
536 | # Set the parent message of the display hook and out streams. |
|
539 | # Set the parent message of the display hook and out streams. | |
537 | shell = self.shell |
|
540 | shell = self.shell | |
538 | shell.displayhook.set_parent(parent) |
|
541 | shell.displayhook.set_parent(parent) | |
539 | shell.display_pub.set_parent(parent) |
|
542 | shell.display_pub.set_parent(parent) | |
540 | sys.stdout.set_parent(parent) |
|
543 | sys.stdout.set_parent(parent) | |
541 | sys.stderr.set_parent(parent) |
|
544 | sys.stderr.set_parent(parent) | |
542 |
|
545 | |||
543 | # pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent) |
|
546 | # pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent) | |
544 | # self.iopub_socket.send(pyin_msg) |
|
547 | # self.iopub_socket.send(pyin_msg) | |
545 | # self.session.send(self.iopub_socket, u'pyin', {u'code':code},parent=parent) |
|
548 | # self.session.send(self.iopub_socket, u'pyin', {u'code':code},parent=parent) | |
546 |
|
|
549 | md = self._make_metadata(parent['metadata']) | |
547 | try: |
|
550 | try: | |
548 | working = shell.user_ns |
|
551 | working = shell.user_ns | |
549 |
|
552 | |||
550 | prefix = "_"+str(msg_id).replace("-","")+"_" |
|
553 | prefix = "_"+str(msg_id).replace("-","")+"_" | |
551 |
|
554 | |||
552 | f,args,kwargs = unpack_apply_message(bufs, working, copy=False) |
|
555 | f,args,kwargs = unpack_apply_message(bufs, working, copy=False) | |
553 |
|
556 | |||
554 | fname = getattr(f, '__name__', 'f') |
|
557 | fname = getattr(f, '__name__', 'f') | |
555 |
|
558 | |||
556 | fname = prefix+"f" |
|
559 | fname = prefix+"f" | |
557 | argname = prefix+"args" |
|
560 | argname = prefix+"args" | |
558 | kwargname = prefix+"kwargs" |
|
561 | kwargname = prefix+"kwargs" | |
559 | resultname = prefix+"result" |
|
562 | resultname = prefix+"result" | |
560 |
|
563 | |||
561 | ns = { fname : f, argname : args, kwargname : kwargs , resultname : None } |
|
564 | ns = { fname : f, argname : args, kwargname : kwargs , resultname : None } | |
562 | # print ns |
|
565 | # print ns | |
563 | working.update(ns) |
|
566 | working.update(ns) | |
564 | code = "%s = %s(*%s,**%s)" % (resultname, fname, argname, kwargname) |
|
567 | code = "%s = %s(*%s,**%s)" % (resultname, fname, argname, kwargname) | |
565 | try: |
|
568 | try: | |
566 | exec code in shell.user_global_ns, shell.user_ns |
|
569 | exec code in shell.user_global_ns, shell.user_ns | |
567 | result = working.get(resultname) |
|
570 | result = working.get(resultname) | |
568 | finally: |
|
571 | finally: | |
569 | for key in ns.iterkeys(): |
|
572 | for key in ns.iterkeys(): | |
570 | working.pop(key) |
|
573 | working.pop(key) | |
571 |
|
574 | |||
572 | packed_result,buf = serialize_object(result) |
|
575 | packed_result,buf = serialize_object(result) | |
573 | result_buf = [packed_result]+buf |
|
576 | result_buf = [packed_result]+buf | |
574 | except: |
|
577 | except: | |
575 | # invoke IPython traceback formatting |
|
578 | # invoke IPython traceback formatting | |
576 | shell.showtraceback() |
|
579 | shell.showtraceback() | |
577 | # FIXME - fish exception info out of shell, possibly left there by |
|
580 | # FIXME - fish exception info out of shell, possibly left there by | |
578 | # run_code. We'll need to clean up this logic later. |
|
581 | # run_code. We'll need to clean up this logic later. | |
579 | reply_content = {} |
|
582 | reply_content = {} | |
580 | if shell._reply_content is not None: |
|
583 | if shell._reply_content is not None: | |
581 | reply_content.update(shell._reply_content) |
|
584 | reply_content.update(shell._reply_content) | |
582 | e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='apply') |
|
585 | e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='apply') | |
583 | reply_content['engine_info'] = e_info |
|
586 | reply_content['engine_info'] = e_info | |
584 | # reset after use |
|
587 | # reset after use | |
585 | shell._reply_content = None |
|
588 | shell._reply_content = None | |
586 |
|
589 | |||
587 | self.session.send(self.iopub_socket, u'pyerr', reply_content, parent=parent, |
|
590 | self.session.send(self.iopub_socket, u'pyerr', reply_content, parent=parent, | |
588 | ident=self._topic('pyerr')) |
|
591 | ident=self._topic('pyerr')) | |
589 | result_buf = [] |
|
592 | result_buf = [] | |
590 |
|
593 | |||
591 | if reply_content['ename'] == 'UnmetDependency': |
|
594 | if reply_content['ename'] == 'UnmetDependency': | |
592 |
|
|
595 | md['dependencies_met'] = False | |
593 | else: |
|
596 | else: | |
594 | reply_content = {'status' : 'ok'} |
|
597 | reply_content = {'status' : 'ok'} | |
595 |
|
598 | |||
596 | # put 'ok'/'error' status in header, for scheduler introspection: |
|
599 | # put 'ok'/'error' status in header, for scheduler introspection: | |
597 |
|
|
600 | md['status'] = reply_content['status'] | |
598 |
|
601 | |||
599 | # flush i/o |
|
602 | # flush i/o | |
600 | sys.stdout.flush() |
|
603 | sys.stdout.flush() | |
601 | sys.stderr.flush() |
|
604 | sys.stderr.flush() | |
602 |
|
605 | |||
603 | reply_msg = self.session.send(stream, u'apply_reply', reply_content, |
|
606 | reply_msg = self.session.send(stream, u'apply_reply', reply_content, | |
604 |
parent=parent, ident=ident,buffers=result_buf, |
|
607 | parent=parent, ident=ident,buffers=result_buf, metadata=md) | |
605 |
|
608 | |||
606 | self._publish_status(u'idle', parent) |
|
609 | self._publish_status(u'idle', parent) | |
607 |
|
610 | |||
608 | #--------------------------------------------------------------------------- |
|
611 | #--------------------------------------------------------------------------- | |
609 | # Control messages |
|
612 | # Control messages | |
610 | #--------------------------------------------------------------------------- |
|
613 | #--------------------------------------------------------------------------- | |
611 |
|
614 | |||
612 | def abort_request(self, stream, ident, parent): |
|
615 | def abort_request(self, stream, ident, parent): | |
613 | """abort a specifig msg by id""" |
|
616 | """abort a specifig msg by id""" | |
614 | msg_ids = parent['content'].get('msg_ids', None) |
|
617 | msg_ids = parent['content'].get('msg_ids', None) | |
615 | if isinstance(msg_ids, basestring): |
|
618 | if isinstance(msg_ids, basestring): | |
616 | msg_ids = [msg_ids] |
|
619 | msg_ids = [msg_ids] | |
617 | if not msg_ids: |
|
620 | if not msg_ids: | |
618 | self.abort_queues() |
|
621 | self.abort_queues() | |
619 | for mid in msg_ids: |
|
622 | for mid in msg_ids: | |
620 | self.aborted.add(str(mid)) |
|
623 | self.aborted.add(str(mid)) | |
621 |
|
624 | |||
622 | content = dict(status='ok') |
|
625 | content = dict(status='ok') | |
623 | reply_msg = self.session.send(stream, 'abort_reply', content=content, |
|
626 | reply_msg = self.session.send(stream, 'abort_reply', content=content, | |
624 | parent=parent, ident=ident) |
|
627 | parent=parent, ident=ident) | |
625 | self.log.debug("%s", reply_msg) |
|
628 | self.log.debug("%s", reply_msg) | |
626 |
|
629 | |||
627 | def clear_request(self, stream, idents, parent): |
|
630 | def clear_request(self, stream, idents, parent): | |
628 | """Clear our namespace.""" |
|
631 | """Clear our namespace.""" | |
629 | self.shell.reset(False) |
|
632 | self.shell.reset(False) | |
630 | msg = self.session.send(stream, 'clear_reply', ident=idents, parent=parent, |
|
633 | msg = self.session.send(stream, 'clear_reply', ident=idents, parent=parent, | |
631 | content = dict(status='ok')) |
|
634 | content = dict(status='ok')) | |
632 |
|
635 | |||
633 |
|
636 | |||
634 | #--------------------------------------------------------------------------- |
|
637 | #--------------------------------------------------------------------------- | |
635 | # Protected interface |
|
638 | # Protected interface | |
636 | #--------------------------------------------------------------------------- |
|
639 | #--------------------------------------------------------------------------- | |
637 |
|
640 | |||
638 |
|
641 | |||
639 | def _wrap_exception(self, method=None): |
|
642 | def _wrap_exception(self, method=None): | |
640 | # import here, because _wrap_exception is only used in parallel, |
|
643 | # import here, because _wrap_exception is only used in parallel, | |
641 | # and parallel has higher min pyzmq version |
|
644 | # and parallel has higher min pyzmq version | |
642 | from IPython.parallel.error import wrap_exception |
|
645 | from IPython.parallel.error import wrap_exception | |
643 | e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method=method) |
|
646 | e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method=method) | |
644 | content = wrap_exception(e_info) |
|
647 | content = wrap_exception(e_info) | |
645 | return content |
|
648 | return content | |
646 |
|
649 | |||
647 | def _topic(self, topic): |
|
650 | def _topic(self, topic): | |
648 | """prefixed topic for IOPub messages""" |
|
651 | """prefixed topic for IOPub messages""" | |
649 | if self.int_id >= 0: |
|
652 | if self.int_id >= 0: | |
650 | base = "engine.%i" % self.int_id |
|
653 | base = "engine.%i" % self.int_id | |
651 | else: |
|
654 | else: | |
652 | base = "kernel.%s" % self.ident |
|
655 | base = "kernel.%s" % self.ident | |
653 |
|
656 | |||
654 | return py3compat.cast_bytes("%s.%s" % (base, topic)) |
|
657 | return py3compat.cast_bytes("%s.%s" % (base, topic)) | |
655 |
|
658 | |||
656 | def _abort_queues(self): |
|
659 | def _abort_queues(self): | |
657 | for stream in self.shell_streams: |
|
660 | for stream in self.shell_streams: | |
658 | if stream: |
|
661 | if stream: | |
659 | self._abort_queue(stream) |
|
662 | self._abort_queue(stream) | |
660 |
|
663 | |||
661 | def _abort_queue(self, stream): |
|
664 | def _abort_queue(self, stream): | |
662 | poller = zmq.Poller() |
|
665 | poller = zmq.Poller() | |
663 | poller.register(stream.socket, zmq.POLLIN) |
|
666 | poller.register(stream.socket, zmq.POLLIN) | |
664 | while True: |
|
667 | while True: | |
665 | idents,msg = self.session.recv(stream, zmq.NOBLOCK, content=True) |
|
668 | idents,msg = self.session.recv(stream, zmq.NOBLOCK, content=True) | |
666 | if msg is None: |
|
669 | if msg is None: | |
667 | return |
|
670 | return | |
668 |
|
671 | |||
669 | self.log.info("Aborting:") |
|
672 | self.log.info("Aborting:") | |
670 | self.log.info("%s", msg) |
|
673 | self.log.info("%s", msg) | |
671 | msg_type = msg['header']['msg_type'] |
|
674 | msg_type = msg['header']['msg_type'] | |
672 | reply_type = msg_type.split('_')[0] + '_reply' |
|
675 | reply_type = msg_type.split('_')[0] + '_reply' | |
673 |
|
676 | |||
674 | status = {'status' : 'aborted'} |
|
677 | status = {'status' : 'aborted'} | |
675 |
|
|
678 | md = {'engine' : self.ident} | |
676 |
|
|
679 | md.update(status) | |
677 |
reply_msg = self.session.send(stream, reply_type, |
|
680 | reply_msg = self.session.send(stream, reply_type, meatadata=md, | |
678 | content=status, parent=msg, ident=idents) |
|
681 | content=status, parent=msg, ident=idents) | |
679 | self.log.debug("%s", reply_msg) |
|
682 | self.log.debug("%s", reply_msg) | |
680 | # We need to wait a bit for requests to come in. This can probably |
|
683 | # We need to wait a bit for requests to come in. This can probably | |
681 | # be set shorter for true asynchronous clients. |
|
684 | # be set shorter for true asynchronous clients. | |
682 | poller.poll(50) |
|
685 | poller.poll(50) | |
683 |
|
686 | |||
684 |
|
687 | |||
685 | def _no_raw_input(self): |
|
688 | def _no_raw_input(self): | |
686 | """Raise StdinNotImplentedError if active frontend doesn't support |
|
689 | """Raise StdinNotImplentedError if active frontend doesn't support | |
687 | stdin.""" |
|
690 | stdin.""" | |
688 | raise StdinNotImplementedError("raw_input was called, but this " |
|
691 | raise StdinNotImplementedError("raw_input was called, but this " | |
689 | "frontend does not support stdin.") |
|
692 | "frontend does not support stdin.") | |
690 |
|
693 | |||
691 | def _raw_input(self, prompt, ident, parent): |
|
694 | def _raw_input(self, prompt, ident, parent): | |
692 | # Flush output before making the request. |
|
695 | # Flush output before making the request. | |
693 | sys.stderr.flush() |
|
696 | sys.stderr.flush() | |
694 | sys.stdout.flush() |
|
697 | sys.stdout.flush() | |
695 |
|
698 | |||
696 | # Send the input request. |
|
699 | # Send the input request. | |
697 | content = json_clean(dict(prompt=prompt)) |
|
700 | content = json_clean(dict(prompt=prompt)) | |
698 | self.session.send(self.stdin_socket, u'input_request', content, parent, |
|
701 | self.session.send(self.stdin_socket, u'input_request', content, parent, | |
699 | ident=ident) |
|
702 | ident=ident) | |
700 |
|
703 | |||
701 | # Await a response. |
|
704 | # Await a response. | |
702 | while True: |
|
705 | while True: | |
703 | try: |
|
706 | try: | |
704 | ident, reply = self.session.recv(self.stdin_socket, 0) |
|
707 | ident, reply = self.session.recv(self.stdin_socket, 0) | |
705 | except Exception: |
|
708 | except Exception: | |
706 | self.log.warn("Invalid Message:", exc_info=True) |
|
709 | self.log.warn("Invalid Message:", exc_info=True) | |
707 | else: |
|
710 | else: | |
708 | break |
|
711 | break | |
709 | try: |
|
712 | try: | |
710 | value = reply['content']['value'] |
|
713 | value = reply['content']['value'] | |
711 | except: |
|
714 | except: | |
712 | self.log.error("Got bad raw_input reply: ") |
|
715 | self.log.error("Got bad raw_input reply: ") | |
713 | self.log.error("%s", parent) |
|
716 | self.log.error("%s", parent) | |
714 | value = '' |
|
717 | value = '' | |
715 | if value == '\x04': |
|
718 | if value == '\x04': | |
716 | # EOF |
|
719 | # EOF | |
717 | raise EOFError |
|
720 | raise EOFError | |
718 | return value |
|
721 | return value | |
719 |
|
722 | |||
720 | def _complete(self, msg): |
|
723 | def _complete(self, msg): | |
721 | c = msg['content'] |
|
724 | c = msg['content'] | |
722 | try: |
|
725 | try: | |
723 | cpos = int(c['cursor_pos']) |
|
726 | cpos = int(c['cursor_pos']) | |
724 | except: |
|
727 | except: | |
725 | # If we don't get something that we can convert to an integer, at |
|
728 | # If we don't get something that we can convert to an integer, at | |
726 | # least attempt the completion guessing the cursor is at the end of |
|
729 | # least attempt the completion guessing the cursor is at the end of | |
727 | # the text, if there's any, and otherwise of the line |
|
730 | # the text, if there's any, and otherwise of the line | |
728 | cpos = len(c['text']) |
|
731 | cpos = len(c['text']) | |
729 | if cpos==0: |
|
732 | if cpos==0: | |
730 | cpos = len(c['line']) |
|
733 | cpos = len(c['line']) | |
731 | return self.shell.complete(c['text'], c['line'], cpos) |
|
734 | return self.shell.complete(c['text'], c['line'], cpos) | |
732 |
|
735 | |||
733 | def _object_info(self, context): |
|
736 | def _object_info(self, context): | |
734 | symbol, leftover = self._symbol_from_context(context) |
|
737 | symbol, leftover = self._symbol_from_context(context) | |
735 | if symbol is not None and not leftover: |
|
738 | if symbol is not None and not leftover: | |
736 | doc = getattr(symbol, '__doc__', '') |
|
739 | doc = getattr(symbol, '__doc__', '') | |
737 | else: |
|
740 | else: | |
738 | doc = '' |
|
741 | doc = '' | |
739 | object_info = dict(docstring = doc) |
|
742 | object_info = dict(docstring = doc) | |
740 | return object_info |
|
743 | return object_info | |
741 |
|
744 | |||
742 | def _symbol_from_context(self, context): |
|
745 | def _symbol_from_context(self, context): | |
743 | if not context: |
|
746 | if not context: | |
744 | return None, context |
|
747 | return None, context | |
745 |
|
748 | |||
746 | base_symbol_string = context[0] |
|
749 | base_symbol_string = context[0] | |
747 | symbol = self.shell.user_ns.get(base_symbol_string, None) |
|
750 | symbol = self.shell.user_ns.get(base_symbol_string, None) | |
748 | if symbol is None: |
|
751 | if symbol is None: | |
749 | symbol = __builtin__.__dict__.get(base_symbol_string, None) |
|
752 | symbol = __builtin__.__dict__.get(base_symbol_string, None) | |
750 | if symbol is None: |
|
753 | if symbol is None: | |
751 | return None, context |
|
754 | return None, context | |
752 |
|
755 | |||
753 | context = context[1:] |
|
756 | context = context[1:] | |
754 | for i, name in enumerate(context): |
|
757 | for i, name in enumerate(context): | |
755 | new_symbol = getattr(symbol, name, None) |
|
758 | new_symbol = getattr(symbol, name, None) | |
756 | if new_symbol is None: |
|
759 | if new_symbol is None: | |
757 | return symbol, context[i:] |
|
760 | return symbol, context[i:] | |
758 | else: |
|
761 | else: | |
759 | symbol = new_symbol |
|
762 | symbol = new_symbol | |
760 |
|
763 | |||
761 | return symbol, [] |
|
764 | return symbol, [] | |
762 |
|
765 | |||
763 | def _at_shutdown(self): |
|
766 | def _at_shutdown(self): | |
764 | """Actions taken at shutdown by the kernel, called by python's atexit. |
|
767 | """Actions taken at shutdown by the kernel, called by python's atexit. | |
765 | """ |
|
768 | """ | |
766 | # io.rprint("Kernel at_shutdown") # dbg |
|
769 | # io.rprint("Kernel at_shutdown") # dbg | |
767 | if self._shutdown_message is not None: |
|
770 | if self._shutdown_message is not None: | |
768 | self.session.send(self.iopub_socket, self._shutdown_message, ident=self._topic('shutdown')) |
|
771 | self.session.send(self.iopub_socket, self._shutdown_message, ident=self._topic('shutdown')) | |
769 | self.log.debug("%s", self._shutdown_message) |
|
772 | self.log.debug("%s", self._shutdown_message) | |
770 | [ s.flush(zmq.POLLOUT) for s in self.shell_streams ] |
|
773 | [ s.flush(zmq.POLLOUT) for s in self.shell_streams ] | |
771 |
|
774 | |||
772 | #----------------------------------------------------------------------------- |
|
775 | #----------------------------------------------------------------------------- | |
773 | # Aliases and Flags for the IPKernelApp |
|
776 | # Aliases and Flags for the IPKernelApp | |
774 | #----------------------------------------------------------------------------- |
|
777 | #----------------------------------------------------------------------------- | |
775 |
|
778 | |||
776 | flags = dict(kernel_flags) |
|
779 | flags = dict(kernel_flags) | |
777 | flags.update(shell_flags) |
|
780 | flags.update(shell_flags) | |
778 |
|
781 | |||
779 | addflag = lambda *args: flags.update(boolean_flag(*args)) |
|
782 | addflag = lambda *args: flags.update(boolean_flag(*args)) | |
780 |
|
783 | |||
781 | flags['pylab'] = ( |
|
784 | flags['pylab'] = ( | |
782 | {'IPKernelApp' : {'pylab' : 'auto'}}, |
|
785 | {'IPKernelApp' : {'pylab' : 'auto'}}, | |
783 | """Pre-load matplotlib and numpy for interactive use with |
|
786 | """Pre-load matplotlib and numpy for interactive use with | |
784 | the default matplotlib backend.""" |
|
787 | the default matplotlib backend.""" | |
785 | ) |
|
788 | ) | |
786 |
|
789 | |||
787 | aliases = dict(kernel_aliases) |
|
790 | aliases = dict(kernel_aliases) | |
788 | aliases.update(shell_aliases) |
|
791 | aliases.update(shell_aliases) | |
789 |
|
792 | |||
790 | #----------------------------------------------------------------------------- |
|
793 | #----------------------------------------------------------------------------- | |
791 | # The IPKernelApp class |
|
794 | # The IPKernelApp class | |
792 | #----------------------------------------------------------------------------- |
|
795 | #----------------------------------------------------------------------------- | |
793 |
|
796 | |||
794 | class IPKernelApp(KernelApp, InteractiveShellApp): |
|
797 | class IPKernelApp(KernelApp, InteractiveShellApp): | |
795 | name = 'ipkernel' |
|
798 | name = 'ipkernel' | |
796 |
|
799 | |||
797 | aliases = Dict(aliases) |
|
800 | aliases = Dict(aliases) | |
798 | flags = Dict(flags) |
|
801 | flags = Dict(flags) | |
799 | classes = [Kernel, ZMQInteractiveShell, ProfileDir, Session] |
|
802 | classes = [Kernel, ZMQInteractiveShell, ProfileDir, Session] | |
800 |
|
803 | |||
801 | @catch_config_error |
|
804 | @catch_config_error | |
802 | def initialize(self, argv=None): |
|
805 | def initialize(self, argv=None): | |
803 | super(IPKernelApp, self).initialize(argv) |
|
806 | super(IPKernelApp, self).initialize(argv) | |
804 | self.init_path() |
|
807 | self.init_path() | |
805 | self.init_shell() |
|
808 | self.init_shell() | |
806 | self.init_gui_pylab() |
|
809 | self.init_gui_pylab() | |
807 | self.init_extensions() |
|
810 | self.init_extensions() | |
808 | self.init_code() |
|
811 | self.init_code() | |
809 |
|
812 | |||
810 | def init_kernel(self): |
|
813 | def init_kernel(self): | |
811 |
|
814 | |||
812 | shell_stream = ZMQStream(self.shell_socket) |
|
815 | shell_stream = ZMQStream(self.shell_socket) | |
813 |
|
816 | |||
814 | kernel = Kernel(config=self.config, session=self.session, |
|
817 | kernel = Kernel(config=self.config, session=self.session, | |
815 | shell_streams=[shell_stream], |
|
818 | shell_streams=[shell_stream], | |
816 | iopub_socket=self.iopub_socket, |
|
819 | iopub_socket=self.iopub_socket, | |
817 | stdin_socket=self.stdin_socket, |
|
820 | stdin_socket=self.stdin_socket, | |
818 | log=self.log, |
|
821 | log=self.log, | |
819 | profile_dir=self.profile_dir, |
|
822 | profile_dir=self.profile_dir, | |
820 | ) |
|
823 | ) | |
821 | self.kernel = kernel |
|
824 | self.kernel = kernel | |
822 | kernel.record_ports(self.ports) |
|
825 | kernel.record_ports(self.ports) | |
823 | shell = kernel.shell |
|
826 | shell = kernel.shell | |
824 |
|
827 | |||
825 | def init_gui_pylab(self): |
|
828 | def init_gui_pylab(self): | |
826 | """Enable GUI event loop integration, taking pylab into account.""" |
|
829 | """Enable GUI event loop integration, taking pylab into account.""" | |
827 |
|
830 | |||
828 | # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab` |
|
831 | # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab` | |
829 | # to ensure that any exception is printed straight to stderr. |
|
832 | # to ensure that any exception is printed straight to stderr. | |
830 | # Normally _showtraceback associates the reply with an execution, |
|
833 | # Normally _showtraceback associates the reply with an execution, | |
831 | # which means frontends will never draw it, as this exception |
|
834 | # which means frontends will never draw it, as this exception | |
832 | # is not associated with any execute request. |
|
835 | # is not associated with any execute request. | |
833 |
|
836 | |||
834 | shell = self.shell |
|
837 | shell = self.shell | |
835 | _showtraceback = shell._showtraceback |
|
838 | _showtraceback = shell._showtraceback | |
836 | try: |
|
839 | try: | |
837 | # replace pyerr-sending traceback with stderr |
|
840 | # replace pyerr-sending traceback with stderr | |
838 | def print_tb(etype, evalue, stb): |
|
841 | def print_tb(etype, evalue, stb): | |
839 | print ("GUI event loop or pylab initialization failed", |
|
842 | print ("GUI event loop or pylab initialization failed", | |
840 | file=io.stderr) |
|
843 | file=io.stderr) | |
841 | print (shell.InteractiveTB.stb2text(stb), file=io.stderr) |
|
844 | print (shell.InteractiveTB.stb2text(stb), file=io.stderr) | |
842 | shell._showtraceback = print_tb |
|
845 | shell._showtraceback = print_tb | |
843 | InteractiveShellApp.init_gui_pylab(self) |
|
846 | InteractiveShellApp.init_gui_pylab(self) | |
844 | finally: |
|
847 | finally: | |
845 | shell._showtraceback = _showtraceback |
|
848 | shell._showtraceback = _showtraceback | |
846 |
|
849 | |||
847 | def init_shell(self): |
|
850 | def init_shell(self): | |
848 | self.shell = self.kernel.shell |
|
851 | self.shell = self.kernel.shell | |
849 | self.shell.configurables.append(self) |
|
852 | self.shell.configurables.append(self) | |
850 |
|
853 | |||
851 |
|
854 | |||
852 | #----------------------------------------------------------------------------- |
|
855 | #----------------------------------------------------------------------------- | |
853 | # Kernel main and launch functions |
|
856 | # Kernel main and launch functions | |
854 | #----------------------------------------------------------------------------- |
|
857 | #----------------------------------------------------------------------------- | |
855 |
|
858 | |||
856 | def launch_kernel(*args, **kwargs): |
|
859 | def launch_kernel(*args, **kwargs): | |
857 | """Launches a localhost IPython kernel, binding to the specified ports. |
|
860 | """Launches a localhost IPython kernel, binding to the specified ports. | |
858 |
|
861 | |||
859 | This function simply calls entry_point.base_launch_kernel with the right |
|
862 | This function simply calls entry_point.base_launch_kernel with the right | |
860 | first command to start an ipkernel. See base_launch_kernel for arguments. |
|
863 | first command to start an ipkernel. See base_launch_kernel for arguments. | |
861 |
|
864 | |||
862 | Returns |
|
865 | Returns | |
863 | ------- |
|
866 | ------- | |
864 | A tuple of form: |
|
867 | A tuple of form: | |
865 | (kernel_process, shell_port, iopub_port, stdin_port, hb_port) |
|
868 | (kernel_process, shell_port, iopub_port, stdin_port, hb_port) | |
866 | where kernel_process is a Popen object and the ports are integers. |
|
869 | where kernel_process is a Popen object and the ports are integers. | |
867 | """ |
|
870 | """ | |
868 | return base_launch_kernel('from IPython.zmq.ipkernel import main; main()', |
|
871 | return base_launch_kernel('from IPython.zmq.ipkernel import main; main()', | |
869 | *args, **kwargs) |
|
872 | *args, **kwargs) | |
870 |
|
873 | |||
871 |
|
874 | |||
872 | def embed_kernel(module=None, local_ns=None, **kwargs): |
|
875 | def embed_kernel(module=None, local_ns=None, **kwargs): | |
873 | """Embed and start an IPython kernel in a given scope. |
|
876 | """Embed and start an IPython kernel in a given scope. | |
874 |
|
877 | |||
875 | Parameters |
|
878 | Parameters | |
876 | ---------- |
|
879 | ---------- | |
877 | module : ModuleType, optional |
|
880 | module : ModuleType, optional | |
878 | The module to load into IPython globals (default: caller) |
|
881 | The module to load into IPython globals (default: caller) | |
879 | local_ns : dict, optional |
|
882 | local_ns : dict, optional | |
880 | The namespace to load into IPython user namespace (default: caller) |
|
883 | The namespace to load into IPython user namespace (default: caller) | |
881 |
|
884 | |||
882 | kwargs : various, optional |
|
885 | kwargs : various, optional | |
883 | Further keyword args are relayed to the KernelApp constructor, |
|
886 | Further keyword args are relayed to the KernelApp constructor, | |
884 | allowing configuration of the Kernel. Will only have an effect |
|
887 | allowing configuration of the Kernel. Will only have an effect | |
885 | on the first embed_kernel call for a given process. |
|
888 | on the first embed_kernel call for a given process. | |
886 |
|
889 | |||
887 | """ |
|
890 | """ | |
888 | # get the app if it exists, or set it up if it doesn't |
|
891 | # get the app if it exists, or set it up if it doesn't | |
889 | if IPKernelApp.initialized(): |
|
892 | if IPKernelApp.initialized(): | |
890 | app = IPKernelApp.instance() |
|
893 | app = IPKernelApp.instance() | |
891 | else: |
|
894 | else: | |
892 | app = IPKernelApp.instance(**kwargs) |
|
895 | app = IPKernelApp.instance(**kwargs) | |
893 | app.initialize([]) |
|
896 | app.initialize([]) | |
894 | # Undo unnecessary sys module mangling from init_sys_modules. |
|
897 | # Undo unnecessary sys module mangling from init_sys_modules. | |
895 | # This would not be necessary if we could prevent it |
|
898 | # This would not be necessary if we could prevent it | |
896 | # in the first place by using a different InteractiveShell |
|
899 | # in the first place by using a different InteractiveShell | |
897 | # subclass, as in the regular embed case. |
|
900 | # subclass, as in the regular embed case. | |
898 | main = app.kernel.shell._orig_sys_modules_main_mod |
|
901 | main = app.kernel.shell._orig_sys_modules_main_mod | |
899 | if main is not None: |
|
902 | if main is not None: | |
900 | sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main |
|
903 | sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main | |
901 |
|
904 | |||
902 | # load the calling scope if not given |
|
905 | # load the calling scope if not given | |
903 | (caller_module, caller_locals) = extract_module_locals(1) |
|
906 | (caller_module, caller_locals) = extract_module_locals(1) | |
904 | if module is None: |
|
907 | if module is None: | |
905 | module = caller_module |
|
908 | module = caller_module | |
906 | if local_ns is None: |
|
909 | if local_ns is None: | |
907 | local_ns = caller_locals |
|
910 | local_ns = caller_locals | |
908 |
|
911 | |||
909 | app.kernel.user_module = module |
|
912 | app.kernel.user_module = module | |
910 | app.kernel.user_ns = local_ns |
|
913 | app.kernel.user_ns = local_ns | |
911 | app.shell.set_completer_frame() |
|
914 | app.shell.set_completer_frame() | |
912 | app.start() |
|
915 | app.start() | |
913 |
|
916 | |||
914 | def main(): |
|
917 | def main(): | |
915 | """Run an IPKernel as an application""" |
|
918 | """Run an IPKernel as an application""" | |
916 | app = IPKernelApp.instance() |
|
919 | app = IPKernelApp.instance() | |
917 | app.initialize() |
|
920 | app.initialize() | |
918 | app.start() |
|
921 | app.start() | |
919 |
|
922 | |||
920 |
|
923 | |||
921 | if __name__ == '__main__': |
|
924 | if __name__ == '__main__': | |
922 | main() |
|
925 | main() |
General Comments 0
You need to be logged in to leave comments.
Login now