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