##// END OF EJS Templates
document data_pub messages
MinRK -
Show More
@@ -1,959 +1,997 b''
1 .. _messaging:
1 .. _messaging:
2
2
3 ======================
3 ======================
4 Messaging in IPython
4 Messaging in IPython
5 ======================
5 ======================
6
6
7
7
8 Introduction
8 Introduction
9 ============
9 ============
10
10
11 This document explains the basic communications design and messaging
11 This document explains the basic communications design and messaging
12 specification for how the various IPython objects interact over a network
12 specification for how the various IPython objects interact over a network
13 transport. The current implementation uses the ZeroMQ_ library for messaging
13 transport. The current implementation uses the ZeroMQ_ library for messaging
14 within and between hosts.
14 within and between hosts.
15
15
16 .. Note::
16 .. Note::
17
17
18 This document should be considered the authoritative description of the
18 This document should be considered the authoritative description of the
19 IPython messaging protocol, and all developers are strongly encouraged to
19 IPython messaging protocol, and all developers are strongly encouraged to
20 keep it updated as the implementation evolves, so that we have a single
20 keep it updated as the implementation evolves, so that we have a single
21 common reference for all protocol details.
21 common reference for all protocol details.
22
22
23 The basic design is explained in the following diagram:
23 The basic design is explained in the following diagram:
24
24
25 .. image:: figs/frontend-kernel.png
25 .. image:: figs/frontend-kernel.png
26 :width: 450px
26 :width: 450px
27 :alt: IPython kernel/frontend messaging architecture.
27 :alt: IPython kernel/frontend messaging architecture.
28 :align: center
28 :align: center
29 :target: ../_images/frontend-kernel.png
29 :target: ../_images/frontend-kernel.png
30
30
31 A single kernel can be simultaneously connected to one or more frontends. The
31 A single kernel can be simultaneously connected to one or more frontends. The
32 kernel has three sockets that serve the following functions:
32 kernel has three sockets that serve the following functions:
33
33
34 1. stdin: this ROUTER socket is connected to all frontends, and it allows
34 1. stdin: this ROUTER socket is connected to all frontends, and it allows
35 the kernel to request input from the active frontend when :func:`raw_input` is called.
35 the kernel to request input from the active frontend when :func:`raw_input` is called.
36 The frontend that executed the code has a DEALER socket that acts as a 'virtual keyboard'
36 The frontend that executed the code has a DEALER socket that acts as a 'virtual keyboard'
37 for the kernel while this communication is happening (illustrated in the
37 for the kernel while this communication is happening (illustrated in the
38 figure by the black outline around the central keyboard). In practice,
38 figure by the black outline around the central keyboard). In practice,
39 frontends may display such kernel requests using a special input widget or
39 frontends may display such kernel requests using a special input widget or
40 otherwise indicating that the user is to type input for the kernel instead
40 otherwise indicating that the user is to type input for the kernel instead
41 of normal commands in the frontend.
41 of normal commands in the frontend.
42
42
43 2. Shell: this single ROUTER socket allows multiple incoming connections from
43 2. Shell: this single ROUTER socket allows multiple incoming connections from
44 frontends, and this is the socket where requests for code execution, object
44 frontends, and this is the socket where requests for code execution, object
45 information, prompts, etc. are made to the kernel by any frontend. The
45 information, prompts, etc. are made to the kernel by any frontend. The
46 communication on this socket is a sequence of request/reply actions from
46 communication on this socket is a sequence of request/reply actions from
47 each frontend and the kernel.
47 each frontend and the kernel.
48
48
49 3. IOPub: this socket is the 'broadcast channel' where the kernel publishes all
49 3. IOPub: this socket is the 'broadcast channel' where the kernel publishes all
50 side effects (stdout, stderr, etc.) as well as the requests coming from any
50 side effects (stdout, stderr, etc.) as well as the requests coming from any
51 client over the shell socket and its own requests on the stdin socket. There
51 client over the shell socket and its own requests on the stdin socket. There
52 are a number of actions in Python which generate side effects: :func:`print`
52 are a number of actions in Python which generate side effects: :func:`print`
53 writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in
53 writes to ``sys.stdout``, errors generate tracebacks, etc. Additionally, in
54 a multi-client scenario, we want all frontends to be able to know what each
54 a multi-client scenario, we want all frontends to be able to know what each
55 other has sent to the kernel (this can be useful in collaborative scenarios,
55 other has sent to the kernel (this can be useful in collaborative scenarios,
56 for example). This socket allows both side effects and the information
56 for example). This socket allows both side effects and the information
57 about communications taking place with one client over the shell channel
57 about communications taking place with one client over the shell channel
58 to be made available to all clients in a uniform manner.
58 to be made available to all clients in a uniform manner.
59
59
60 All messages are tagged with enough information (details below) for clients
60 All messages are tagged with enough information (details below) for clients
61 to know which messages come from their own interaction with the kernel and
61 to know which messages come from their own interaction with the kernel and
62 which ones are from other clients, so they can display each type
62 which ones are from other clients, so they can display each type
63 appropriately.
63 appropriately.
64
64
65 The actual format of the messages allowed on each of these channels is
65 The actual format of the messages allowed on each of these channels is
66 specified below. Messages are dicts of dicts with string keys and values that
66 specified below. Messages are dicts of dicts with string keys and values that
67 are reasonably representable in JSON. Our current implementation uses JSON
67 are reasonably representable in JSON. Our current implementation uses JSON
68 explicitly as its message format, but this shouldn't be considered a permanent
68 explicitly as its message format, but this shouldn't be considered a permanent
69 feature. As we've discovered that JSON has non-trivial performance issues due
69 feature. As we've discovered that JSON has non-trivial performance issues due
70 to excessive copying, we may in the future move to a pure pickle-based raw
70 to excessive copying, we may in the future move to a pure pickle-based raw
71 message format. However, it should be possible to easily convert from the raw
71 message format. However, it should be possible to easily convert from the raw
72 objects to JSON, since we may have non-python clients (e.g. a web frontend).
72 objects to JSON, since we may have non-python clients (e.g. a web frontend).
73 As long as it's easy to make a JSON version of the objects that is a faithful
73 As long as it's easy to make a JSON version of the objects that is a faithful
74 representation of all the data, we can communicate with such clients.
74 representation of all the data, we can communicate with such clients.
75
75
76 .. Note::
76 .. Note::
77
77
78 Not all of these have yet been fully fleshed out, but the key ones are, see
78 Not all of these have yet been fully fleshed out, but the key ones are, see
79 kernel and frontend files for actual implementation details.
79 kernel and frontend files for actual implementation details.
80
80
81 General Message Format
81 General Message Format
82 ======================
82 ======================
83
83
84 A message is defined by the following four-dictionary structure::
84 A message is defined by the following four-dictionary structure::
85
85
86 {
86 {
87 # The message header contains a pair of unique identifiers for the
87 # The message header contains a pair of unique identifiers for the
88 # originating session and the actual message id, in addition to the
88 # originating session and the actual message id, in addition to the
89 # username for the process that generated the message. This is useful in
89 # username for the process that generated the message. This is useful in
90 # collaborative settings where multiple users may be interacting with the
90 # collaborative settings where multiple users may be interacting with the
91 # same kernel simultaneously, so that frontends can label the various
91 # same kernel simultaneously, so that frontends can label the various
92 # messages in a meaningful way.
92 # messages in a meaningful way.
93 'header' : {
93 'header' : {
94 'msg_id' : uuid,
94 'msg_id' : uuid,
95 'username' : str,
95 'username' : str,
96 'session' : uuid
96 'session' : uuid
97 # All recognized message type strings are listed below.
97 # All recognized message type strings are listed below.
98 'msg_type' : str,
98 'msg_type' : str,
99 },
99 },
100
100
101 # In a chain of messages, the header from the parent is copied so that
101 # In a chain of messages, the header from the parent is copied so that
102 # clients can track where messages come from.
102 # clients can track where messages come from.
103 'parent_header' : dict,
103 'parent_header' : dict,
104
104
105 # The actual content of the message must be a dict, whose structure
105 # The actual content of the message must be a dict, whose structure
106 # depends on the message type.
106 # depends on the message type.
107 'content' : dict,
107 'content' : dict,
108
108
109 # Any metadata associated with the message.
109 # Any metadata associated with the message.
110 'metadata' : dict,
110 'metadata' : dict,
111 }
111 }
112
112
113
113
114 Python functional API
114 Python functional API
115 =====================
115 =====================
116
116
117 As messages are dicts, they map naturally to a ``func(**kw)`` call form. We
117 As messages are dicts, they map naturally to a ``func(**kw)`` call form. We
118 should develop, at a few key points, functional forms of all the requests that
118 should develop, at a few key points, functional forms of all the requests that
119 take arguments in this manner and automatically construct the necessary dict
119 take arguments in this manner and automatically construct the necessary dict
120 for sending.
120 for sending.
121
121
122 In addition, the Python implementation of the message specification extends
122 In addition, the Python implementation of the message specification extends
123 messages upon deserialization to the following form for convenience::
123 messages upon deserialization to the following form for convenience::
124
124
125 {
125 {
126 'header' : dict,
126 'header' : dict,
127 # The msg's unique identifier and type are always stored in the header,
127 # The msg's unique identifier and type are always stored in the header,
128 # but the Python implementation copies them to the top level.
128 # but the Python implementation copies them to the top level.
129 'msg_id' : uuid,
129 'msg_id' : uuid,
130 'msg_type' : str,
130 'msg_type' : str,
131 'parent_header' : dict,
131 'parent_header' : dict,
132 'content' : dict,
132 'content' : dict,
133 'metadata' : dict,
133 'metadata' : dict,
134 }
134 }
135
135
136 All messages sent to or received by any IPython process should have this
136 All messages sent to or received by any IPython process should have this
137 extended structure.
137 extended structure.
138
138
139
139
140 Messages on the shell ROUTER/DEALER sockets
140 Messages on the shell ROUTER/DEALER sockets
141 ===========================================
141 ===========================================
142
142
143 .. _execute:
143 .. _execute:
144
144
145 Execute
145 Execute
146 -------
146 -------
147
147
148 This message type is used by frontends to ask the kernel to execute code on
148 This message type is used by frontends to ask the kernel to execute code on
149 behalf of the user, in a namespace reserved to the user's variables (and thus
149 behalf of the user, in a namespace reserved to the user's variables (and thus
150 separate from the kernel's own internal code and variables).
150 separate from the kernel's own internal code and variables).
151
151
152 Message type: ``execute_request``::
152 Message type: ``execute_request``::
153
153
154 content = {
154 content = {
155 # Source code to be executed by the kernel, one or more lines.
155 # Source code to be executed by the kernel, one or more lines.
156 'code' : str,
156 'code' : str,
157
157
158 # A boolean flag which, if True, signals the kernel to execute
158 # A boolean flag which, if True, signals the kernel to execute
159 # this code as quietly as possible. This means that the kernel
159 # this code as quietly as possible. This means that the kernel
160 # will compile the code with 'exec' instead of 'single' (so
160 # will compile the code with 'exec' instead of 'single' (so
161 # sys.displayhook will not fire), and will *not*:
161 # sys.displayhook will not fire), and will *not*:
162 # - broadcast exceptions on the PUB socket
162 # - broadcast exceptions on the PUB socket
163 # - do any logging
163 # - do any logging
164 # - populate any history
164 # - populate any history
165 #
165 #
166 # The default is False.
166 # The default is False.
167 'silent' : bool,
167 'silent' : bool,
168
168
169 # A list of variable names from the user's namespace to be retrieved. What
169 # A list of variable names from the user's namespace to be retrieved. What
170 # returns is a JSON string of the variable's repr(), not a python object.
170 # returns is a JSON string of the variable's repr(), not a python object.
171 'user_variables' : list,
171 'user_variables' : list,
172
172
173 # Similarly, a dict mapping names to expressions to be evaluated in the
173 # Similarly, a dict mapping names to expressions to be evaluated in the
174 # user's dict.
174 # user's dict.
175 'user_expressions' : dict,
175 'user_expressions' : dict,
176
176
177 # Some frontends (e.g. the Notebook) do not support stdin requests. If
177 # Some frontends (e.g. the Notebook) do not support stdin requests. If
178 # raw_input is called from code executed from such a frontend, a
178 # raw_input is called from code executed from such a frontend, a
179 # StdinNotImplementedError will be raised.
179 # StdinNotImplementedError will be raised.
180 'allow_stdin' : True,
180 'allow_stdin' : True,
181
181
182 }
182 }
183
183
184 The ``code`` field contains a single string (possibly multiline). The kernel
184 The ``code`` field contains a single string (possibly multiline). The kernel
185 is responsible for splitting this into one or more independent execution blocks
185 is responsible for splitting this into one or more independent execution blocks
186 and deciding whether to compile these in 'single' or 'exec' mode (see below for
186 and deciding whether to compile these in 'single' or 'exec' mode (see below for
187 detailed execution semantics).
187 detailed execution semantics).
188
188
189 The ``user_`` fields deserve a detailed explanation. In the past, IPython had
189 The ``user_`` fields deserve a detailed explanation. In the past, IPython had
190 the notion of a prompt string that allowed arbitrary code to be evaluated, and
190 the notion of a prompt string that allowed arbitrary code to be evaluated, and
191 this was put to good use by many in creating prompts that displayed system
191 this was put to good use by many in creating prompts that displayed system
192 status, path information, and even more esoteric uses like remote instrument
192 status, path information, and even more esoteric uses like remote instrument
193 status aqcuired over the network. But now that IPython has a clean separation
193 status aqcuired over the network. But now that IPython has a clean separation
194 between the kernel and the clients, the kernel has no prompt knowledge; prompts
194 between the kernel and the clients, the kernel has no prompt knowledge; prompts
195 are a frontend-side feature, and it should be even possible for different
195 are a frontend-side feature, and it should be even possible for different
196 frontends to display different prompts while interacting with the same kernel.
196 frontends to display different prompts while interacting with the same kernel.
197
197
198 The kernel now provides the ability to retrieve data from the user's namespace
198 The kernel now provides the ability to retrieve data from the user's namespace
199 after the execution of the main ``code``, thanks to two fields in the
199 after the execution of the main ``code``, thanks to two fields in the
200 ``execute_request`` message:
200 ``execute_request`` message:
201
201
202 - ``user_variables``: If only variables from the user's namespace are needed, a
202 - ``user_variables``: If only variables from the user's namespace are needed, a
203 list of variable names can be passed and a dict with these names as keys and
203 list of variable names can be passed and a dict with these names as keys and
204 their :func:`repr()` as values will be returned.
204 their :func:`repr()` as values will be returned.
205
205
206 - ``user_expressions``: For more complex expressions that require function
206 - ``user_expressions``: For more complex expressions that require function
207 evaluations, a dict can be provided with string keys and arbitrary python
207 evaluations, a dict can be provided with string keys and arbitrary python
208 expressions as values. The return message will contain also a dict with the
208 expressions as values. The return message will contain also a dict with the
209 same keys and the :func:`repr()` of the evaluated expressions as value.
209 same keys and the :func:`repr()` of the evaluated expressions as value.
210
210
211 With this information, frontends can display any status information they wish
211 With this information, frontends can display any status information they wish
212 in the form that best suits each frontend (a status line, a popup, inline for a
212 in the form that best suits each frontend (a status line, a popup, inline for a
213 terminal, etc).
213 terminal, etc).
214
214
215 .. Note::
215 .. Note::
216
216
217 In order to obtain the current execution counter for the purposes of
217 In order to obtain the current execution counter for the purposes of
218 displaying input prompts, frontends simply make an execution request with an
218 displaying input prompts, frontends simply make an execution request with an
219 empty code string and ``silent=True``.
219 empty code string and ``silent=True``.
220
220
221 Execution semantics
221 Execution semantics
222 ~~~~~~~~~~~~~~~~~~~
222 ~~~~~~~~~~~~~~~~~~~
223
223
224 When the silent flag is false, the execution of use code consists of the
224 When the silent flag is false, the execution of use code consists of the
225 following phases (in silent mode, only the ``code`` field is executed):
225 following phases (in silent mode, only the ``code`` field is executed):
226
226
227 1. Run the ``pre_runcode_hook``.
227 1. Run the ``pre_runcode_hook``.
228
228
229 2. Execute the ``code`` field, see below for details.
229 2. Execute the ``code`` field, see below for details.
230
230
231 3. If #2 succeeds, compute ``user_variables`` and ``user_expressions`` are
231 3. If #2 succeeds, compute ``user_variables`` and ``user_expressions`` are
232 computed. This ensures that any error in the latter don't harm the main
232 computed. This ensures that any error in the latter don't harm the main
233 code execution.
233 code execution.
234
234
235 4. Call any method registered with :meth:`register_post_execute`.
235 4. Call any method registered with :meth:`register_post_execute`.
236
236
237 .. warning::
237 .. warning::
238
238
239 The API for running code before/after the main code block is likely to
239 The API for running code before/after the main code block is likely to
240 change soon. Both the ``pre_runcode_hook`` and the
240 change soon. Both the ``pre_runcode_hook`` and the
241 :meth:`register_post_execute` are susceptible to modification, as we find a
241 :meth:`register_post_execute` are susceptible to modification, as we find a
242 consistent model for both.
242 consistent model for both.
243
243
244 To understand how the ``code`` field is executed, one must know that Python
244 To understand how the ``code`` field is executed, one must know that Python
245 code can be compiled in one of three modes (controlled by the ``mode`` argument
245 code can be compiled in one of three modes (controlled by the ``mode`` argument
246 to the :func:`compile` builtin):
246 to the :func:`compile` builtin):
247
247
248 *single*
248 *single*
249 Valid for a single interactive statement (though the source can contain
249 Valid for a single interactive statement (though the source can contain
250 multiple lines, such as a for loop). When compiled in this mode, the
250 multiple lines, such as a for loop). When compiled in this mode, the
251 generated bytecode contains special instructions that trigger the calling of
251 generated bytecode contains special instructions that trigger the calling of
252 :func:`sys.displayhook` for any expression in the block that returns a value.
252 :func:`sys.displayhook` for any expression in the block that returns a value.
253 This means that a single statement can actually produce multiple calls to
253 This means that a single statement can actually produce multiple calls to
254 :func:`sys.displayhook`, if for example it contains a loop where each
254 :func:`sys.displayhook`, if for example it contains a loop where each
255 iteration computes an unassigned expression would generate 10 calls::
255 iteration computes an unassigned expression would generate 10 calls::
256
256
257 for i in range(10):
257 for i in range(10):
258 i**2
258 i**2
259
259
260 *exec*
260 *exec*
261 An arbitrary amount of source code, this is how modules are compiled.
261 An arbitrary amount of source code, this is how modules are compiled.
262 :func:`sys.displayhook` is *never* implicitly called.
262 :func:`sys.displayhook` is *never* implicitly called.
263
263
264 *eval*
264 *eval*
265 A single expression that returns a value. :func:`sys.displayhook` is *never*
265 A single expression that returns a value. :func:`sys.displayhook` is *never*
266 implicitly called.
266 implicitly called.
267
267
268
268
269 The ``code`` field is split into individual blocks each of which is valid for
269 The ``code`` field is split into individual blocks each of which is valid for
270 execution in 'single' mode, and then:
270 execution in 'single' mode, and then:
271
271
272 - If there is only a single block: it is executed in 'single' mode.
272 - If there is only a single block: it is executed in 'single' mode.
273
273
274 - If there is more than one block:
274 - If there is more than one block:
275
275
276 * if the last one is a single line long, run all but the last in 'exec' mode
276 * if the last one is a single line long, run all but the last in 'exec' mode
277 and the very last one in 'single' mode. This makes it easy to type simple
277 and the very last one in 'single' mode. This makes it easy to type simple
278 expressions at the end to see computed values.
278 expressions at the end to see computed values.
279
279
280 * if the last one is no more than two lines long, run all but the last in
280 * if the last one is no more than two lines long, run all but the last in
281 'exec' mode and the very last one in 'single' mode. This makes it easy to
281 'exec' mode and the very last one in 'single' mode. This makes it easy to
282 type simple expressions at the end to see computed values. - otherwise
282 type simple expressions at the end to see computed values. - otherwise
283 (last one is also multiline), run all in 'exec' mode
283 (last one is also multiline), run all in 'exec' mode
284
284
285 * otherwise (last one is also multiline), run all in 'exec' mode as a single
285 * otherwise (last one is also multiline), run all in 'exec' mode as a single
286 unit.
286 unit.
287
287
288 Any error in retrieving the ``user_variables`` or evaluating the
288 Any error in retrieving the ``user_variables`` or evaluating the
289 ``user_expressions`` will result in a simple error message in the return fields
289 ``user_expressions`` will result in a simple error message in the return fields
290 of the form::
290 of the form::
291
291
292 [ERROR] ExceptionType: Exception message
292 [ERROR] ExceptionType: Exception message
293
293
294 The user can simply send the same variable name or expression for evaluation to
294 The user can simply send the same variable name or expression for evaluation to
295 see a regular traceback.
295 see a regular traceback.
296
296
297 Errors in any registered post_execute functions are also reported similarly,
297 Errors in any registered post_execute functions are also reported similarly,
298 and the failing function is removed from the post_execution set so that it does
298 and the failing function is removed from the post_execution set so that it does
299 not continue triggering failures.
299 not continue triggering failures.
300
300
301 Upon completion of the execution request, the kernel *always* sends a reply,
301 Upon completion of the execution request, the kernel *always* sends a reply,
302 with a status code indicating what happened and additional data depending on
302 with a status code indicating what happened and additional data depending on
303 the outcome. See :ref:`below <execution_results>` for the possible return
303 the outcome. See :ref:`below <execution_results>` for the possible return
304 codes and associated data.
304 codes and associated data.
305
305
306
306
307 Execution counter (old prompt number)
307 Execution counter (old prompt number)
308 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
308 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
309
309
310 The kernel has a single, monotonically increasing counter of all execution
310 The kernel has a single, monotonically increasing counter of all execution
311 requests that are made with ``silent=False``. This counter is used to populate
311 requests that are made with ``silent=False``. This counter is used to populate
312 the ``In[n]``, ``Out[n]`` and ``_n`` variables, so clients will likely want to
312 the ``In[n]``, ``Out[n]`` and ``_n`` variables, so clients will likely want to
313 display it in some form to the user, which will typically (but not necessarily)
313 display it in some form to the user, which will typically (but not necessarily)
314 be done in the prompts. The value of this counter will be returned as the
314 be done in the prompts. The value of this counter will be returned as the
315 ``execution_count`` field of all ``execute_reply`` messages.
315 ``execution_count`` field of all ``execute_reply`` messages.
316
316
317 .. _execution_results:
317 .. _execution_results:
318
318
319 Execution results
319 Execution results
320 ~~~~~~~~~~~~~~~~~
320 ~~~~~~~~~~~~~~~~~
321
321
322 Message type: ``execute_reply``::
322 Message type: ``execute_reply``::
323
323
324 content = {
324 content = {
325 # One of: 'ok' OR 'error' OR 'abort'
325 # One of: 'ok' OR 'error' OR 'abort'
326 'status' : str,
326 'status' : str,
327
327
328 # The global kernel counter that increases by one with each non-silent
328 # The global kernel counter that increases by one with each non-silent
329 # executed request. This will typically be used by clients to display
329 # executed request. This will typically be used by clients to display
330 # prompt numbers to the user. If the request was a silent one, this will
330 # prompt numbers to the user. If the request was a silent one, this will
331 # be the current value of the counter in the kernel.
331 # be the current value of the counter in the kernel.
332 'execution_count' : int,
332 'execution_count' : int,
333 }
333 }
334
334
335 When status is 'ok', the following extra fields are present::
335 When status is 'ok', the following extra fields are present::
336
336
337 {
337 {
338 # 'payload' will be a list of payload dicts.
338 # 'payload' will be a list of payload dicts.
339 # Each execution payload is a dict with string keys that may have been
339 # Each execution payload is a dict with string keys that may have been
340 # produced by the code being executed. It is retrieved by the kernel at
340 # produced by the code being executed. It is retrieved by the kernel at
341 # the end of the execution and sent back to the front end, which can take
341 # the end of the execution and sent back to the front end, which can take
342 # action on it as needed. See main text for further details.
342 # action on it as needed. See main text for further details.
343 'payload' : list(dict),
343 'payload' : list(dict),
344
344
345 # Results for the user_variables and user_expressions.
345 # Results for the user_variables and user_expressions.
346 'user_variables' : dict,
346 'user_variables' : dict,
347 'user_expressions' : dict,
347 'user_expressions' : dict,
348 }
348 }
349
349
350 .. admonition:: Execution payloads
350 .. admonition:: Execution payloads
351
351
352 The notion of an 'execution payload' is different from a return value of a
352 The notion of an 'execution payload' is different from a return value of a
353 given set of code, which normally is just displayed on the pyout stream
353 given set of code, which normally is just displayed on the pyout stream
354 through the PUB socket. The idea of a payload is to allow special types of
354 through the PUB socket. The idea of a payload is to allow special types of
355 code, typically magics, to populate a data container in the IPython kernel
355 code, typically magics, to populate a data container in the IPython kernel
356 that will be shipped back to the caller via this channel. The kernel
356 that will be shipped back to the caller via this channel. The kernel
357 has an API for this in the PayloadManager::
357 has an API for this in the PayloadManager::
358
358
359 ip.payload_manager.write_payload(payload_dict)
359 ip.payload_manager.write_payload(payload_dict)
360
360
361 which appends a dictionary to the list of payloads.
361 which appends a dictionary to the list of payloads.
362
362
363
363
364 When status is 'error', the following extra fields are present::
364 When status is 'error', the following extra fields are present::
365
365
366 {
366 {
367 'ename' : str, # Exception name, as a string
367 'ename' : str, # Exception name, as a string
368 'evalue' : str, # Exception value, as a string
368 'evalue' : str, # Exception value, as a string
369
369
370 # The traceback will contain a list of frames, represented each as a
370 # The traceback will contain a list of frames, represented each as a
371 # string. For now we'll stick to the existing design of ultraTB, which
371 # string. For now we'll stick to the existing design of ultraTB, which
372 # controls exception level of detail statefully. But eventually we'll
372 # controls exception level of detail statefully. But eventually we'll
373 # want to grow into a model where more information is collected and
373 # want to grow into a model where more information is collected and
374 # packed into the traceback object, with clients deciding how little or
374 # packed into the traceback object, with clients deciding how little or
375 # how much of it to unpack. But for now, let's start with a simple list
375 # how much of it to unpack. But for now, let's start with a simple list
376 # of strings, since that requires only minimal changes to ultratb as
376 # of strings, since that requires only minimal changes to ultratb as
377 # written.
377 # written.
378 'traceback' : list,
378 'traceback' : list,
379 }
379 }
380
380
381
381
382 When status is 'abort', there are for now no additional data fields. This
382 When status is 'abort', there are for now no additional data fields. This
383 happens when the kernel was interrupted by a signal.
383 happens when the kernel was interrupted by a signal.
384
384
385 Kernel attribute access
385 Kernel attribute access
386 -----------------------
386 -----------------------
387
387
388 .. warning::
388 .. warning::
389
389
390 This part of the messaging spec is not actually implemented in the kernel
390 This part of the messaging spec is not actually implemented in the kernel
391 yet.
391 yet.
392
392
393 While this protocol does not specify full RPC access to arbitrary methods of
393 While this protocol does not specify full RPC access to arbitrary methods of
394 the kernel object, the kernel does allow read (and in some cases write) access
394 the kernel object, the kernel does allow read (and in some cases write) access
395 to certain attributes.
395 to certain attributes.
396
396
397 The policy for which attributes can be read is: any attribute of the kernel, or
397 The policy for which attributes can be read is: any attribute of the kernel, or
398 its sub-objects, that belongs to a :class:`Configurable` object and has been
398 its sub-objects, that belongs to a :class:`Configurable` object and has been
399 declared at the class-level with Traits validation, is in principle accessible
399 declared at the class-level with Traits validation, is in principle accessible
400 as long as its name does not begin with a leading underscore. The attribute
400 as long as its name does not begin with a leading underscore. The attribute
401 itself will have metadata indicating whether it allows remote read and/or write
401 itself will have metadata indicating whether it allows remote read and/or write
402 access. The message spec follows for attribute read and write requests.
402 access. The message spec follows for attribute read and write requests.
403
403
404 Message type: ``getattr_request``::
404 Message type: ``getattr_request``::
405
405
406 content = {
406 content = {
407 # The (possibly dotted) name of the attribute
407 # The (possibly dotted) name of the attribute
408 'name' : str,
408 'name' : str,
409 }
409 }
410
410
411 When a ``getattr_request`` fails, there are two possible error types:
411 When a ``getattr_request`` fails, there are two possible error types:
412
412
413 - AttributeError: this type of error was raised when trying to access the
413 - AttributeError: this type of error was raised when trying to access the
414 given name by the kernel itself. This means that the attribute likely
414 given name by the kernel itself. This means that the attribute likely
415 doesn't exist.
415 doesn't exist.
416
416
417 - AccessError: the attribute exists but its value is not readable remotely.
417 - AccessError: the attribute exists but its value is not readable remotely.
418
418
419
419
420 Message type: ``getattr_reply``::
420 Message type: ``getattr_reply``::
421
421
422 content = {
422 content = {
423 # One of ['ok', 'AttributeError', 'AccessError'].
423 # One of ['ok', 'AttributeError', 'AccessError'].
424 'status' : str,
424 'status' : str,
425 # If status is 'ok', a JSON object.
425 # If status is 'ok', a JSON object.
426 'value' : object,
426 'value' : object,
427 }
427 }
428
428
429 Message type: ``setattr_request``::
429 Message type: ``setattr_request``::
430
430
431 content = {
431 content = {
432 # The (possibly dotted) name of the attribute
432 # The (possibly dotted) name of the attribute
433 'name' : str,
433 'name' : str,
434
434
435 # A JSON-encoded object, that will be validated by the Traits
435 # A JSON-encoded object, that will be validated by the Traits
436 # information in the kernel
436 # information in the kernel
437 'value' : object,
437 'value' : object,
438 }
438 }
439
439
440 When a ``setattr_request`` fails, there are also two possible error types with
440 When a ``setattr_request`` fails, there are also two possible error types with
441 similar meanings as those of the ``getattr_request`` case, but for writing.
441 similar meanings as those of the ``getattr_request`` case, but for writing.
442
442
443 Message type: ``setattr_reply``::
443 Message type: ``setattr_reply``::
444
444
445 content = {
445 content = {
446 # One of ['ok', 'AttributeError', 'AccessError'].
446 # One of ['ok', 'AttributeError', 'AccessError'].
447 'status' : str,
447 'status' : str,
448 }
448 }
449
449
450
450
451
451
452 Object information
452 Object information
453 ------------------
453 ------------------
454
454
455 One of IPython's most used capabilities is the introspection of Python objects
455 One of IPython's most used capabilities is the introspection of Python objects
456 in the user's namespace, typically invoked via the ``?`` and ``??`` characters
456 in the user's namespace, typically invoked via the ``?`` and ``??`` characters
457 (which in reality are shorthands for the ``%pinfo`` magic). This is used often
457 (which in reality are shorthands for the ``%pinfo`` magic). This is used often
458 enough that it warrants an explicit message type, especially because frontends
458 enough that it warrants an explicit message type, especially because frontends
459 may want to get object information in response to user keystrokes (like Tab or
459 may want to get object information in response to user keystrokes (like Tab or
460 F1) besides from the user explicitly typing code like ``x??``.
460 F1) besides from the user explicitly typing code like ``x??``.
461
461
462 Message type: ``object_info_request``::
462 Message type: ``object_info_request``::
463
463
464 content = {
464 content = {
465 # The (possibly dotted) name of the object to be searched in all
465 # The (possibly dotted) name of the object to be searched in all
466 # relevant namespaces
466 # relevant namespaces
467 'name' : str,
467 'name' : str,
468
468
469 # The level of detail desired. The default (0) is equivalent to typing
469 # The level of detail desired. The default (0) is equivalent to typing
470 # 'x?' at the prompt, 1 is equivalent to 'x??'.
470 # 'x?' at the prompt, 1 is equivalent to 'x??'.
471 'detail_level' : int,
471 'detail_level' : int,
472 }
472 }
473
473
474 The returned information will be a dictionary with keys very similar to the
474 The returned information will be a dictionary with keys very similar to the
475 field names that IPython prints at the terminal.
475 field names that IPython prints at the terminal.
476
476
477 Message type: ``object_info_reply``::
477 Message type: ``object_info_reply``::
478
478
479 content = {
479 content = {
480 # The name the object was requested under
480 # The name the object was requested under
481 'name' : str,
481 'name' : str,
482
482
483 # Boolean flag indicating whether the named object was found or not. If
483 # Boolean flag indicating whether the named object was found or not. If
484 # it's false, all other fields will be empty.
484 # it's false, all other fields will be empty.
485 'found' : bool,
485 'found' : bool,
486
486
487 # Flags for magics and system aliases
487 # Flags for magics and system aliases
488 'ismagic' : bool,
488 'ismagic' : bool,
489 'isalias' : bool,
489 'isalias' : bool,
490
490
491 # The name of the namespace where the object was found ('builtin',
491 # The name of the namespace where the object was found ('builtin',
492 # 'magics', 'alias', 'interactive', etc.)
492 # 'magics', 'alias', 'interactive', etc.)
493 'namespace' : str,
493 'namespace' : str,
494
494
495 # The type name will be type.__name__ for normal Python objects, but it
495 # The type name will be type.__name__ for normal Python objects, but it
496 # can also be a string like 'Magic function' or 'System alias'
496 # can also be a string like 'Magic function' or 'System alias'
497 'type_name' : str,
497 'type_name' : str,
498
498
499 # The string form of the object, possibly truncated for length if
499 # The string form of the object, possibly truncated for length if
500 # detail_level is 0
500 # detail_level is 0
501 'string_form' : str,
501 'string_form' : str,
502
502
503 # For objects with a __class__ attribute this will be set
503 # For objects with a __class__ attribute this will be set
504 'base_class' : str,
504 'base_class' : str,
505
505
506 # For objects with a __len__ attribute this will be set
506 # For objects with a __len__ attribute this will be set
507 'length' : int,
507 'length' : int,
508
508
509 # If the object is a function, class or method whose file we can find,
509 # If the object is a function, class or method whose file we can find,
510 # we give its full path
510 # we give its full path
511 'file' : str,
511 'file' : str,
512
512
513 # For pure Python callable objects, we can reconstruct the object
513 # For pure Python callable objects, we can reconstruct the object
514 # definition line which provides its call signature. For convenience this
514 # definition line which provides its call signature. For convenience this
515 # is returned as a single 'definition' field, but below the raw parts that
515 # is returned as a single 'definition' field, but below the raw parts that
516 # compose it are also returned as the argspec field.
516 # compose it are also returned as the argspec field.
517 'definition' : str,
517 'definition' : str,
518
518
519 # The individual parts that together form the definition string. Clients
519 # The individual parts that together form the definition string. Clients
520 # with rich display capabilities may use this to provide a richer and more
520 # with rich display capabilities may use this to provide a richer and more
521 # precise representation of the definition line (e.g. by highlighting
521 # precise representation of the definition line (e.g. by highlighting
522 # arguments based on the user's cursor position). For non-callable
522 # arguments based on the user's cursor position). For non-callable
523 # objects, this field is empty.
523 # objects, this field is empty.
524 'argspec' : { # The names of all the arguments
524 'argspec' : { # The names of all the arguments
525 args : list,
525 args : list,
526 # The name of the varargs (*args), if any
526 # The name of the varargs (*args), if any
527 varargs : str,
527 varargs : str,
528 # The name of the varkw (**kw), if any
528 # The name of the varkw (**kw), if any
529 varkw : str,
529 varkw : str,
530 # The values (as strings) of all default arguments. Note
530 # The values (as strings) of all default arguments. Note
531 # that these must be matched *in reverse* with the 'args'
531 # that these must be matched *in reverse* with the 'args'
532 # list above, since the first positional args have no default
532 # list above, since the first positional args have no default
533 # value at all.
533 # value at all.
534 defaults : list,
534 defaults : list,
535 },
535 },
536
536
537 # For instances, provide the constructor signature (the definition of
537 # For instances, provide the constructor signature (the definition of
538 # the __init__ method):
538 # the __init__ method):
539 'init_definition' : str,
539 'init_definition' : str,
540
540
541 # Docstrings: for any object (function, method, module, package) with a
541 # Docstrings: for any object (function, method, module, package) with a
542 # docstring, we show it. But in addition, we may provide additional
542 # docstring, we show it. But in addition, we may provide additional
543 # docstrings. For example, for instances we will show the constructor
543 # docstrings. For example, for instances we will show the constructor
544 # and class docstrings as well, if available.
544 # and class docstrings as well, if available.
545 'docstring' : str,
545 'docstring' : str,
546
546
547 # For instances, provide the constructor and class docstrings
547 # For instances, provide the constructor and class docstrings
548 'init_docstring' : str,
548 'init_docstring' : str,
549 'class_docstring' : str,
549 'class_docstring' : str,
550
550
551 # If it's a callable object whose call method has a separate docstring and
551 # If it's a callable object whose call method has a separate docstring and
552 # definition line:
552 # definition line:
553 'call_def' : str,
553 'call_def' : str,
554 'call_docstring' : str,
554 'call_docstring' : str,
555
555
556 # If detail_level was 1, we also try to find the source code that
556 # If detail_level was 1, we also try to find the source code that
557 # defines the object, if possible. The string 'None' will indicate
557 # defines the object, if possible. The string 'None' will indicate
558 # that no source was found.
558 # that no source was found.
559 'source' : str,
559 'source' : str,
560 }
560 }
561
561
562
562
563 Complete
563 Complete
564 --------
564 --------
565
565
566 Message type: ``complete_request``::
566 Message type: ``complete_request``::
567
567
568 content = {
568 content = {
569 # The text to be completed, such as 'a.is'
569 # The text to be completed, such as 'a.is'
570 'text' : str,
570 'text' : str,
571
571
572 # The full line, such as 'print a.is'. This allows completers to
572 # The full line, such as 'print a.is'. This allows completers to
573 # make decisions that may require information about more than just the
573 # make decisions that may require information about more than just the
574 # current word.
574 # current word.
575 'line' : str,
575 'line' : str,
576
576
577 # The entire block of text where the line is. This may be useful in the
577 # The entire block of text where the line is. This may be useful in the
578 # case of multiline completions where more context may be needed. Note: if
578 # case of multiline completions where more context may be needed. Note: if
579 # in practice this field proves unnecessary, remove it to lighten the
579 # in practice this field proves unnecessary, remove it to lighten the
580 # messages.
580 # messages.
581
581
582 'block' : str,
582 'block' : str,
583
583
584 # The position of the cursor where the user hit 'TAB' on the line.
584 # The position of the cursor where the user hit 'TAB' on the line.
585 'cursor_pos' : int,
585 'cursor_pos' : int,
586 }
586 }
587
587
588 Message type: ``complete_reply``::
588 Message type: ``complete_reply``::
589
589
590 content = {
590 content = {
591 # The list of all matches to the completion request, such as
591 # The list of all matches to the completion request, such as
592 # ['a.isalnum', 'a.isalpha'] for the above example.
592 # ['a.isalnum', 'a.isalpha'] for the above example.
593 'matches' : list
593 'matches' : list
594 }
594 }
595
595
596
596
597 History
597 History
598 -------
598 -------
599
599
600 For clients to explicitly request history from a kernel. The kernel has all
600 For clients to explicitly request history from a kernel. The kernel has all
601 the actual execution history stored in a single location, so clients can
601 the actual execution history stored in a single location, so clients can
602 request it from the kernel when needed.
602 request it from the kernel when needed.
603
603
604 Message type: ``history_request``::
604 Message type: ``history_request``::
605
605
606 content = {
606 content = {
607
607
608 # If True, also return output history in the resulting dict.
608 # If True, also return output history in the resulting dict.
609 'output' : bool,
609 'output' : bool,
610
610
611 # If True, return the raw input history, else the transformed input.
611 # If True, return the raw input history, else the transformed input.
612 'raw' : bool,
612 'raw' : bool,
613
613
614 # So far, this can be 'range', 'tail' or 'search'.
614 # So far, this can be 'range', 'tail' or 'search'.
615 'hist_access_type' : str,
615 'hist_access_type' : str,
616
616
617 # If hist_access_type is 'range', get a range of input cells. session can
617 # If hist_access_type is 'range', get a range of input cells. session can
618 # be a positive session number, or a negative number to count back from
618 # be a positive session number, or a negative number to count back from
619 # the current session.
619 # the current session.
620 'session' : int,
620 'session' : int,
621 # start and stop are line numbers within that session.
621 # start and stop are line numbers within that session.
622 'start' : int,
622 'start' : int,
623 'stop' : int,
623 'stop' : int,
624
624
625 # If hist_access_type is 'tail', get the last n cells.
625 # If hist_access_type is 'tail', get the last n cells.
626 'n' : int,
626 'n' : int,
627
627
628 # If hist_access_type is 'search', get cells matching the specified glob
628 # If hist_access_type is 'search', get cells matching the specified glob
629 # pattern (with * and ? as wildcards).
629 # pattern (with * and ? as wildcards).
630 'pattern' : str,
630 'pattern' : str,
631
631
632 }
632 }
633
633
634 Message type: ``history_reply``::
634 Message type: ``history_reply``::
635
635
636 content = {
636 content = {
637 # A list of 3 tuples, either:
637 # A list of 3 tuples, either:
638 # (session, line_number, input) or
638 # (session, line_number, input) or
639 # (session, line_number, (input, output)),
639 # (session, line_number, (input, output)),
640 # depending on whether output was False or True, respectively.
640 # depending on whether output was False or True, respectively.
641 'history' : list,
641 'history' : list,
642 }
642 }
643
643
644
644
645 Connect
645 Connect
646 -------
646 -------
647
647
648 When a client connects to the request/reply socket of the kernel, it can issue
648 When a client connects to the request/reply socket of the kernel, it can issue
649 a connect request to get basic information about the kernel, such as the ports
649 a connect request to get basic information about the kernel, such as the ports
650 the other ZeroMQ sockets are listening on. This allows clients to only have
650 the other ZeroMQ sockets are listening on. This allows clients to only have
651 to know about a single port (the shell channel) to connect to a kernel.
651 to know about a single port (the shell channel) to connect to a kernel.
652
652
653 Message type: ``connect_request``::
653 Message type: ``connect_request``::
654
654
655 content = {
655 content = {
656 }
656 }
657
657
658 Message type: ``connect_reply``::
658 Message type: ``connect_reply``::
659
659
660 content = {
660 content = {
661 'shell_port' : int # The port the shell ROUTER socket is listening on.
661 'shell_port' : int # The port the shell ROUTER socket is listening on.
662 'iopub_port' : int # The port the PUB socket is listening on.
662 'iopub_port' : int # The port the PUB socket is listening on.
663 'stdin_port' : int # The port the stdin ROUTER socket is listening on.
663 'stdin_port' : int # The port the stdin ROUTER socket is listening on.
664 'hb_port' : int # The port the heartbeat socket is listening on.
664 'hb_port' : int # The port the heartbeat socket is listening on.
665 }
665 }
666
666
667
667
668
668
669 Kernel shutdown
669 Kernel shutdown
670 ---------------
670 ---------------
671
671
672 The clients can request the kernel to shut itself down; this is used in
672 The clients can request the kernel to shut itself down; this is used in
673 multiple cases:
673 multiple cases:
674
674
675 - when the user chooses to close the client application via a menu or window
675 - when the user chooses to close the client application via a menu or window
676 control.
676 control.
677 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
677 - when the user types 'exit' or 'quit' (or their uppercase magic equivalents).
678 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
678 - when the user chooses a GUI method (like the 'Ctrl-C' shortcut in the
679 IPythonQt client) to force a kernel restart to get a clean kernel without
679 IPythonQt client) to force a kernel restart to get a clean kernel without
680 losing client-side state like history or inlined figures.
680 losing client-side state like history or inlined figures.
681
681
682 The client sends a shutdown request to the kernel, and once it receives the
682 The client sends a shutdown request to the kernel, and once it receives the
683 reply message (which is otherwise empty), it can assume that the kernel has
683 reply message (which is otherwise empty), it can assume that the kernel has
684 completed shutdown safely.
684 completed shutdown safely.
685
685
686 Upon their own shutdown, client applications will typically execute a last
686 Upon their own shutdown, client applications will typically execute a last
687 minute sanity check and forcefully terminate any kernel that is still alive, to
687 minute sanity check and forcefully terminate any kernel that is still alive, to
688 avoid leaving stray processes in the user's machine.
688 avoid leaving stray processes in the user's machine.
689
689
690 For both shutdown request and reply, there is no actual content that needs to
690 For both shutdown request and reply, there is no actual content that needs to
691 be sent, so the content dict is empty.
691 be sent, so the content dict is empty.
692
692
693 Message type: ``shutdown_request``::
693 Message type: ``shutdown_request``::
694
694
695 content = {
695 content = {
696 'restart' : bool # whether the shutdown is final, or precedes a restart
696 'restart' : bool # whether the shutdown is final, or precedes a restart
697 }
697 }
698
698
699 Message type: ``shutdown_reply``::
699 Message type: ``shutdown_reply``::
700
700
701 content = {
701 content = {
702 'restart' : bool # whether the shutdown is final, or precedes a restart
702 'restart' : bool # whether the shutdown is final, or precedes a restart
703 }
703 }
704
704
705 .. Note::
705 .. Note::
706
706
707 When the clients detect a dead kernel thanks to inactivity on the heartbeat
707 When the clients detect a dead kernel thanks to inactivity on the heartbeat
708 socket, they simply send a forceful process termination signal, since a dead
708 socket, they simply send a forceful process termination signal, since a dead
709 process is unlikely to respond in any useful way to messages.
709 process is unlikely to respond in any useful way to messages.
710
710
711
711
712 Messages on the PUB/SUB socket
712 Messages on the PUB/SUB socket
713 ==============================
713 ==============================
714
714
715 Streams (stdout, stderr, etc)
715 Streams (stdout, stderr, etc)
716 ------------------------------
716 ------------------------------
717
717
718 Message type: ``stream``::
718 Message type: ``stream``::
719
719
720 content = {
720 content = {
721 # The name of the stream is one of 'stdin', 'stdout', 'stderr'
721 # The name of the stream is one of 'stdin', 'stdout', 'stderr'
722 'name' : str,
722 'name' : str,
723
723
724 # The data is an arbitrary string to be written to that stream
724 # The data is an arbitrary string to be written to that stream
725 'data' : str,
725 'data' : str,
726 }
726 }
727
727
728 When a kernel receives a raw_input call, it should also broadcast it on the pub
728 When a kernel receives a raw_input call, it should also broadcast it on the pub
729 socket with the names 'stdin' and 'stdin_reply'. This will allow other clients
729 socket with the names 'stdin' and 'stdin_reply'. This will allow other clients
730 to monitor/display kernel interactions and possibly replay them to their user
730 to monitor/display kernel interactions and possibly replay them to their user
731 or otherwise expose them.
731 or otherwise expose them.
732
732
733 Display Data
733 Display Data
734 ------------
734 ------------
735
735
736 This type of message is used to bring back data that should be diplayed (text,
736 This type of message is used to bring back data that should be diplayed (text,
737 html, svg, etc.) in the frontends. This data is published to all frontends.
737 html, svg, etc.) in the frontends. This data is published to all frontends.
738 Each message can have multiple representations of the data; it is up to the
738 Each message can have multiple representations of the data; it is up to the
739 frontend to decide which to use and how. A single message should contain all
739 frontend to decide which to use and how. A single message should contain all
740 possible representations of the same information. Each representation should
740 possible representations of the same information. Each representation should
741 be a JSON'able data structure, and should be a valid MIME type.
741 be a JSON'able data structure, and should be a valid MIME type.
742
742
743 Some questions remain about this design:
743 Some questions remain about this design:
744
744
745 * Do we use this message type for pyout/displayhook? Probably not, because
745 * Do we use this message type for pyout/displayhook? Probably not, because
746 the displayhook also has to handle the Out prompt display. On the other hand
746 the displayhook also has to handle the Out prompt display. On the other hand
747 we could put that information into the metadata secion.
747 we could put that information into the metadata secion.
748
748
749 Message type: ``display_data``::
749 Message type: ``display_data``::
750
750
751 content = {
751 content = {
752
752
753 # Who create the data
753 # Who create the data
754 'source' : str,
754 'source' : str,
755
755
756 # The data dict contains key/value pairs, where the kids are MIME
756 # The data dict contains key/value pairs, where the kids are MIME
757 # types and the values are the raw data of the representation in that
757 # types and the values are the raw data of the representation in that
758 # format. The data dict must minimally contain the ``text/plain``
758 # format. The data dict must minimally contain the ``text/plain``
759 # MIME type which is used as a backup representation.
759 # MIME type which is used as a backup representation.
760 'data' : dict,
760 'data' : dict,
761
761
762 # Any metadata that describes the data
762 # Any metadata that describes the data
763 'metadata' : dict
763 'metadata' : dict
764 }
764 }
765
765
766
767 Raw Data Publication
768 --------------------
769
770 ``display_data`` lets you publish *representations* of data, such as images and html.
771 This ``data_pub`` message lets you publish *actual raw data*, sent via message buffers.
772
773 data_pub messages are constructed via the :func:`IPython.lib.datapub.publish_data` function:
774
775 .. sourcecode:: python
776
777 from IPython.zmq.datapub import publish_data
778 ns = dict(x=my_array)
779 publish_data(ns)
780
781
782 Message type: ``data_pub``::
783
784 content = {
785 # the keys of the data dict, after it has been unserialized
786 keys = ['a', 'b']
787 }
788 # the namespace dict will be serialized in the message buffers,
789 # which will have a length of at least one
790 buffers = ['pdict', ...]
791
792
793 The interpretation of a sequence of data_pub messages for a given parent request should be
794 to update a single namespace with subsequent results.
795
796 .. note::
797
798 No frontends directly handle data_pub messages at this time.
799 It is currently only used by the client/engines in :mod:`IPython.parallel`,
800 where engines may publish *data* to the Client,
801 of which the Client can then publish *representations* via ``display_data``
802 to various frontends.
803
766 Python inputs
804 Python inputs
767 -------------
805 -------------
768
806
769 These messages are the re-broadcast of the ``execute_request``.
807 These messages are the re-broadcast of the ``execute_request``.
770
808
771 Message type: ``pyin``::
809 Message type: ``pyin``::
772
810
773 content = {
811 content = {
774 'code' : str, # Source code to be executed, one or more lines
812 'code' : str, # Source code to be executed, one or more lines
775
813
776 # The counter for this execution is also provided so that clients can
814 # The counter for this execution is also provided so that clients can
777 # display it, since IPython automatically creates variables called _iN
815 # display it, since IPython automatically creates variables called _iN
778 # (for input prompt In[N]).
816 # (for input prompt In[N]).
779 'execution_count' : int
817 'execution_count' : int
780 }
818 }
781
819
782 Python outputs
820 Python outputs
783 --------------
821 --------------
784
822
785 When Python produces output from code that has been compiled in with the
823 When Python produces output from code that has been compiled in with the
786 'single' flag to :func:`compile`, any expression that produces a value (such as
824 'single' flag to :func:`compile`, any expression that produces a value (such as
787 ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with
825 ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with
788 this value whatever it wants. The default behavior of ``sys.displayhook`` in
826 this value whatever it wants. The default behavior of ``sys.displayhook`` in
789 the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of
827 the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of
790 the value as long as it is not ``None`` (which isn't printed at all). In our
828 the value as long as it is not ``None`` (which isn't printed at all). In our
791 case, the kernel instantiates as ``sys.displayhook`` an object which has
829 case, the kernel instantiates as ``sys.displayhook`` an object which has
792 similar behavior, but which instead of printing to stdout, broadcasts these
830 similar behavior, but which instead of printing to stdout, broadcasts these
793 values as ``pyout`` messages for clients to display appropriately.
831 values as ``pyout`` messages for clients to display appropriately.
794
832
795 IPython's displayhook can handle multiple simultaneous formats depending on its
833 IPython's displayhook can handle multiple simultaneous formats depending on its
796 configuration. The default pretty-printed repr text is always given with the
834 configuration. The default pretty-printed repr text is always given with the
797 ``data`` entry in this message. Any other formats are provided in the
835 ``data`` entry in this message. Any other formats are provided in the
798 ``extra_formats`` list. Frontends are free to display any or all of these
836 ``extra_formats`` list. Frontends are free to display any or all of these
799 according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID
837 according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID
800 string, a type string, and the data. The ID is unique to the formatter
838 string, a type string, and the data. The ID is unique to the formatter
801 implementation that created the data. Frontends will typically ignore the ID
839 implementation that created the data. Frontends will typically ignore the ID
802 unless if it has requested a particular formatter. The type string tells the
840 unless if it has requested a particular formatter. The type string tells the
803 frontend how to interpret the data. It is often, but not always a MIME type.
841 frontend how to interpret the data. It is often, but not always a MIME type.
804 Frontends should ignore types that it does not understand. The data itself is
842 Frontends should ignore types that it does not understand. The data itself is
805 any JSON object and depends on the format. It is often, but not always a string.
843 any JSON object and depends on the format. It is often, but not always a string.
806
844
807 Message type: ``pyout``::
845 Message type: ``pyout``::
808
846
809 content = {
847 content = {
810
848
811 # The counter for this execution is also provided so that clients can
849 # The counter for this execution is also provided so that clients can
812 # display it, since IPython automatically creates variables called _N
850 # display it, since IPython automatically creates variables called _N
813 # (for prompt N).
851 # (for prompt N).
814 'execution_count' : int,
852 'execution_count' : int,
815
853
816 # The data dict contains key/value pairs, where the kids are MIME
854 # The data dict contains key/value pairs, where the kids are MIME
817 # types and the values are the raw data of the representation in that
855 # types and the values are the raw data of the representation in that
818 # format. The data dict must minimally contain the ``text/plain``
856 # format. The data dict must minimally contain the ``text/plain``
819 # MIME type which is used as a backup representation.
857 # MIME type which is used as a backup representation.
820 'data' : dict,
858 'data' : dict,
821
859
822 }
860 }
823
861
824 Python errors
862 Python errors
825 -------------
863 -------------
826
864
827 When an error occurs during code execution
865 When an error occurs during code execution
828
866
829 Message type: ``pyerr``::
867 Message type: ``pyerr``::
830
868
831 content = {
869 content = {
832 # Similar content to the execute_reply messages for the 'error' case,
870 # Similar content to the execute_reply messages for the 'error' case,
833 # except the 'status' field is omitted.
871 # except the 'status' field is omitted.
834 }
872 }
835
873
836 Kernel status
874 Kernel status
837 -------------
875 -------------
838
876
839 This message type is used by frontends to monitor the status of the kernel.
877 This message type is used by frontends to monitor the status of the kernel.
840
878
841 Message type: ``status``::
879 Message type: ``status``::
842
880
843 content = {
881 content = {
844 # When the kernel starts to execute code, it will enter the 'busy'
882 # When the kernel starts to execute code, it will enter the 'busy'
845 # state and when it finishes, it will enter the 'idle' state.
883 # state and when it finishes, it will enter the 'idle' state.
846 execution_state : ('busy', 'idle')
884 execution_state : ('busy', 'idle')
847 }
885 }
848
886
849 Kernel crashes
887 Kernel crashes
850 --------------
888 --------------
851
889
852 When the kernel has an unexpected exception, caught by the last-resort
890 When the kernel has an unexpected exception, caught by the last-resort
853 sys.excepthook, we should broadcast the crash handler's output before exiting.
891 sys.excepthook, we should broadcast the crash handler's output before exiting.
854 This will allow clients to notice that a kernel died, inform the user and
892 This will allow clients to notice that a kernel died, inform the user and
855 propose further actions.
893 propose further actions.
856
894
857 Message type: ``crash``::
895 Message type: ``crash``::
858
896
859 content = {
897 content = {
860 # Similarly to the 'error' case for execute_reply messages, this will
898 # Similarly to the 'error' case for execute_reply messages, this will
861 # contain ename, etype and traceback fields.
899 # contain ename, etype and traceback fields.
862
900
863 # An additional field with supplementary information such as where to
901 # An additional field with supplementary information such as where to
864 # send the crash message
902 # send the crash message
865 'info' : str,
903 'info' : str,
866 }
904 }
867
905
868
906
869 Future ideas
907 Future ideas
870 ------------
908 ------------
871
909
872 Other potential message types, currently unimplemented, listed below as ideas.
910 Other potential message types, currently unimplemented, listed below as ideas.
873
911
874 Message type: ``file``::
912 Message type: ``file``::
875
913
876 content = {
914 content = {
877 'path' : 'cool.jpg',
915 'path' : 'cool.jpg',
878 'mimetype' : str,
916 'mimetype' : str,
879 'data' : str,
917 'data' : str,
880 }
918 }
881
919
882
920
883 Messages on the stdin ROUTER/DEALER sockets
921 Messages on the stdin ROUTER/DEALER sockets
884 ===========================================
922 ===========================================
885
923
886 This is a socket where the request/reply pattern goes in the opposite direction:
924 This is a socket where the request/reply pattern goes in the opposite direction:
887 from the kernel to a *single* frontend, and its purpose is to allow
925 from the kernel to a *single* frontend, and its purpose is to allow
888 ``raw_input`` and similar operations that read from ``sys.stdin`` on the kernel
926 ``raw_input`` and similar operations that read from ``sys.stdin`` on the kernel
889 to be fulfilled by the client. The request should be made to the frontend that
927 to be fulfilled by the client. The request should be made to the frontend that
890 made the execution request that prompted ``raw_input`` to be called. For now we
928 made the execution request that prompted ``raw_input`` to be called. For now we
891 will keep these messages as simple as possible, since they only mean to convey
929 will keep these messages as simple as possible, since they only mean to convey
892 the ``raw_input(prompt)`` call.
930 the ``raw_input(prompt)`` call.
893
931
894 Message type: ``input_request``::
932 Message type: ``input_request``::
895
933
896 content = { 'prompt' : str }
934 content = { 'prompt' : str }
897
935
898 Message type: ``input_reply``::
936 Message type: ``input_reply``::
899
937
900 content = { 'value' : str }
938 content = { 'value' : str }
901
939
902 .. Note::
940 .. Note::
903
941
904 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
942 We do not explicitly try to forward the raw ``sys.stdin`` object, because in
905 practice the kernel should behave like an interactive program. When a
943 practice the kernel should behave like an interactive program. When a
906 program is opened on the console, the keyboard effectively takes over the
944 program is opened on the console, the keyboard effectively takes over the
907 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
945 ``stdin`` file descriptor, and it can't be used for raw reading anymore.
908 Since the IPython kernel effectively behaves like a console program (albeit
946 Since the IPython kernel effectively behaves like a console program (albeit
909 one whose "keyboard" is actually living in a separate process and
947 one whose "keyboard" is actually living in a separate process and
910 transported over the zmq connection), raw ``stdin`` isn't expected to be
948 transported over the zmq connection), raw ``stdin`` isn't expected to be
911 available.
949 available.
912
950
913
951
914 Heartbeat for kernels
952 Heartbeat for kernels
915 =====================
953 =====================
916
954
917 Initially we had considered using messages like those above over ZMQ for a
955 Initially we had considered using messages like those above over ZMQ for a
918 kernel 'heartbeat' (a way to detect quickly and reliably whether a kernel is
956 kernel 'heartbeat' (a way to detect quickly and reliably whether a kernel is
919 alive at all, even if it may be busy executing user code). But this has the
957 alive at all, even if it may be busy executing user code). But this has the
920 problem that if the kernel is locked inside extension code, it wouldn't execute
958 problem that if the kernel is locked inside extension code, it wouldn't execute
921 the python heartbeat code. But it turns out that we can implement a basic
959 the python heartbeat code. But it turns out that we can implement a basic
922 heartbeat with pure ZMQ, without using any Python messaging at all.
960 heartbeat with pure ZMQ, without using any Python messaging at all.
923
961
924 The monitor sends out a single zmq message (right now, it is a str of the
962 The monitor sends out a single zmq message (right now, it is a str of the
925 monitor's lifetime in seconds), and gets the same message right back, prefixed
963 monitor's lifetime in seconds), and gets the same message right back, prefixed
926 with the zmq identity of the DEALER socket in the heartbeat process. This can be
964 with the zmq identity of the DEALER socket in the heartbeat process. This can be
927 a uuid, or even a full message, but there doesn't seem to be a need for packing
965 a uuid, or even a full message, but there doesn't seem to be a need for packing
928 up a message when the sender and receiver are the exact same Python object.
966 up a message when the sender and receiver are the exact same Python object.
929
967
930 The model is this::
968 The model is this::
931
969
932 monitor.send(str(self.lifetime)) # '1.2345678910'
970 monitor.send(str(self.lifetime)) # '1.2345678910'
933
971
934 and the monitor receives some number of messages of the form::
972 and the monitor receives some number of messages of the form::
935
973
936 ['uuid-abcd-dead-beef', '1.2345678910']
974 ['uuid-abcd-dead-beef', '1.2345678910']
937
975
938 where the first part is the zmq.IDENTITY of the heart's DEALER on the engine, and
976 where the first part is the zmq.IDENTITY of the heart's DEALER on the engine, and
939 the rest is the message sent by the monitor. No Python code ever has any
977 the rest is the message sent by the monitor. No Python code ever has any
940 access to the message between the monitor's send, and the monitor's recv.
978 access to the message between the monitor's send, and the monitor's recv.
941
979
942
980
943 ToDo
981 ToDo
944 ====
982 ====
945
983
946 Missing things include:
984 Missing things include:
947
985
948 * Important: finish thinking through the payload concept and API.
986 * Important: finish thinking through the payload concept and API.
949
987
950 * Important: ensure that we have a good solution for magics like %edit. It's
988 * Important: ensure that we have a good solution for magics like %edit. It's
951 likely that with the payload concept we can build a full solution, but not
989 likely that with the payload concept we can build a full solution, but not
952 100% clear yet.
990 100% clear yet.
953
991
954 * Finishing the details of the heartbeat protocol.
992 * Finishing the details of the heartbeat protocol.
955
993
956 * Signal handling: specify what kind of information kernel should broadcast (or
994 * Signal handling: specify what kind of information kernel should broadcast (or
957 not) when it receives signals.
995 not) when it receives signals.
958
996
959 .. include:: ../links.rst
997 .. include:: ../links.rst
General Comments 0
You need to be logged in to leave comments. Login now