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