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