kernels.scm 16.7 KB
Newer Older
1
;;; Guix-kernel -- Guix kernel for Jupyter
2
;;; Copyright (C) 2018, 2019 Pierre-Antoine Rouby <pierre-antoine.rouby@inria.fr>
3
;;; Copyright (C) 2018, 2019 Ludovic Courtès <ludovic.courtes@inria.fr>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

18
(define-module (jupyter kernels)
19
  #:use-module (jupyter messages)
20
  #:use-module (jupyter json)
21
22
  #:use-module (guix build utils)
  #:use-module (ice-9 rdelim)
23
  #:use-module (ice-9 match)
24
25
  #:use-module (simple-zmq)
  #:use-module (json)
26
  #:use-module (rnrs bytevectors)
27
  #:use-module (srfi srfi-1)
28
  #:use-module (srfi srfi-9)
29
  #:use-module (srfi srfi-9 gnu)
30
  #:use-module (srfi srfi-26)
31
32
33
  #:use-module (srfi srfi-71)
  #:export (find-kernel-specs
            find-kernel-specs-file
34
35
            run-kernel

36
37
38
39
40
41
            kernel-specs?
            kernel-specs-arguments
            kernel-specs-display-name
            kernel-specs-language
            json->kernel-specs

42
43
44
45
            kernel
            kernel?
            kernel-name
            kernel-pid
46
            kernel-key
47
48
49
50
            kernel-control
            kernel-shell
            kernel-standard-input
            kernel-heartbeat
51
52
            kernel-iosub
            kernel-iopub                          ;alias
53
            kernel-sockets
54

55
56
57
58
59
60
61
62
63
64
65
66
            connection?
            connection-transport
            connection-ip
            connection-signature-scheme
            connection-key
            connection-control-port
            connection-shell-port
            connection-stdin-port
            connection-heartbeat-port
            connection-iopub-port
            json->connection

67
68
69
70
71
72
73
74
            read-message
            send-message
            relay-message
            pub-busy
            pub-idle

            reply-html

75
            close-kernel))
76

77
78
79
80
81
82
83
;;; Commentary:
;;;
;;; This module implements Jupyter "kernels" as defined at
;;; <https://jupyter-client.readthedocs.io/en/latest/kernels.html>.
;;;
;;; Code:

84
85
86
87
;;
;; Kernel execution.
;;

88
;; Type of a Jupyter kernel.
89
(define-immutable-record-type <kernel>
90
  (%kernel name pid key control shell stdin heartbeat iosub)
91
  kernel?
92
93
  (name        kernel-name set-kernel-name)       ;string
  (pid         kernel-pid set-kernel-pid)         ;integer
94
  (key         kernel-key)                        ;bytevector
95
96
97
98
99
100
  (control     kernel-control)                    ;zmq socket
  (shell       kernel-shell)                      ;zmq socket
  (stdin       kernel-standard-input)             ;zmq socket
  (heartbeat   kernel-heartbeat)                  ;zmq socket
  (iosub       kernel-iosub))                     ;zmq socket

101
102
(define-syntax kernel-iopub (identifier-syntax kernel-iosub))

103
104
105
106
107
108
109
110
111
112
;; Kernel metadata taken from a 'kernel.json' file.
;; <https://jupyter-client.readthedocs.io/en/latest/kernels.html#kernel-specs>
(define-json-mapping <kernel-specs>
  kernel-specs kernel-specs?
  json->kernel-specs
  (arguments      kernel-specs-arguments "argv"
                  vector->list)
  (display-name   kernel-specs-display-name "display_name")
  (language       kernel-specs-language))

113
(define* (kernel name pid #:key key control shell
114
                 standard-input heartbeat iosub)
115
116
117
  (%kernel name pid key
           control shell standard-input heartbeat iosub))

118
119
120
121
122
123
124
125
126
127
(define (kernel-sockets kernel)
  "Return all the ZeroMQ sockets associated with KERNEL."
  (map (lambda (socket)
         (socket kernel))
       (list kernel-shell
             kernel-control
             kernel-standard-input
             kernel-heartbeat
             kernel-iopub)))

128
129
(define (close-kernel kernel)
  "Close all the open connections of KERNEL."
130
  (for-each zmq-close-socket (kernel-sockets kernel)))
131

132
133
134
135
136
137
138
139
140
141
(define (jupyter-kernel-path)
  "Return the default search path for Jupyter kernels."
  ;; Note: In container environments, 'JUPYTER_PATH' is typically unset
  ;; (because Jupyter itself is not in the environment) but 'GUIX_PROFILE' is
  ;; set.
  (or (and=> (getenv "JUPYTER_PATH")
             (cut string-split <> #\:))
      (and=> (getenv "GUIX_PROFILE")
             (lambda (profile)
               (list (string-append profile "/share/jupyter"))))))
142

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
(define* (find-kernel-specs kernel
                            #:optional (path (jupyter-kernel-path)))
  "Return the kernel specs for KERNEL, or #f if KERNEL could not be found in
PATH."
  (match kernel
    ("ipython"
     ;; IPython does not provide a 'kernel.json' file like other
     ;; kernels do; instead, we need to execute 'ipython' from $PATH.
     (let ((ipython (search-path (search-path->list (getenv "PATH"))
                                 "ipython")))
       (and ipython
            (kernel-specs
             (list ipython "kernel" "--quiet" "-f" "{connection_file}")
             "IPython"
             "Python"))))
    (_
     (let ((file (find-kernel-specs-file kernel)))
       (and file (call-with-input-file file json->kernel-specs))))))

(define* (find-kernel-specs-file kernel
                                 #:optional (path (jupyter-kernel-path)))
164
165
166
167
168
169
170
171
  "Return the absolute file name of the 'kernel.json' file for Jupyter kernel
KERNEL, searched for in PATH, a list of directories.  Return #f if KERNEL
could not be found."
  (any (lambda (directory)
         (let ((json (string-append directory "/kernels/"
                                    kernel "/kernel.json")))
           (and (file-exists? json) json)))
       path))
172

173

174
;;
175
;; Kernel "connection files".
176
177
;;

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
;; A "connection" represents a rendezvous between the client and a kernel:
;; <https://jupyter-client.readthedocs.io/en/stable/kernels.html#connection-files>.
;; Usually the client creates it, writes it to a "connection file", which it
;; passes to the kernel.
(define-json-mapping <connection> %connection connection?
  json->connection <=> connection->json
  (transport         connection-transport)        ;string
  (ip                connection-ip)               ;string
  (signature-scheme  connection-signature-scheme) ;string
  (key               connection-key)              ;string
  (control-port      connection-control-port      ;integer
                     "control_port")
  (shell-port        connection-shell-port        ;integer
                     "shell_port")
  (stdin-port        connection-stdin-port        ;integer
                     "stdin_port")
  (heartbeat-port    connection-heartbeat-port    ;integer
                     "hb_port")
  (iopub-port        connection-iopub-port        ;integer
                     "iopub_port"))

(define* (connection transport ip
                     #:key
                     (signature-scheme "hmac-sha256")
                     key control-port shell-port stdin-port heartbeat-port
                     iopub-port)
  (%connection transport ip signature-scheme key
               control-port shell-port stdin-port heartbeat-port
               iopub-port))

(define* (allocate-connection context transport ip key
                              #:key
                              (first-port 1024) identity)
  "Allocate ports for TRANSPORT and IP, starting at FIRST-PORT, and bind zmq
sockets for them under CONTEXT.  Return a <connection> and a <kernel>: the
connection can be passed to a kernel as its \"connection file\", and the
kernel can be used by the client to talk to it."
215
216
217
218
219
220
  (let* ((socket-control   (zmq-create-socket context ZMQ_DEALER))
         (socket-shell     (zmq-create-socket context ZMQ_DEALER))
         (socket-stdin     (zmq-create-socket context ZMQ_DEALER))
         (socket-heartbeat (zmq-create-socket context ZMQ_REQ))
         (socket-iosub     (zmq-create-socket context ZMQ_SUB))

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
         (port-control     (test-bind socket-control   first-port))
         (port-shell       (test-bind socket-shell     (+ 1 port-control)))
         (port-stdin       (test-bind socket-stdin     (+ 1 port-shell)))
         (port-heartbeat   (test-bind socket-heartbeat (+ 1 port-stdin)))
         (port-iosub       (test-bind socket-iosub     (+ 1 port-heartbeat)))

         (connection       (connection "tcp" "127.0.0.1"
                                       #:key key
                                       #:control-port port-control
                                       #:shell-port port-shell
                                       #:heartbeat-port port-heartbeat
                                       #:stdin-port port-stdin
                                       #:iopub-port port-iosub))

         (port->uri (lambda (port)
                      (string-append transport "://" ip ":"
                                     (number->string port))))

         (kernel (kernel #f #f                    ;no name and PID yet
240
                         #:key key
241
242
243
244
245
                         #:control socket-control
                         #:shell socket-shell
                         #:standard-input socket-stdin
                         #:heartbeat socket-heartbeat
                         #:iosub socket-iosub)))
246

247
    (zmq-set-socket-option socket-iosub ZMQ_SUBSCRIBE "")
248
249
250
251
252
253
254

    ;; <http://zguide.zeromq.org/page:all#The-Extended-Reply-Envelope> says
    ;; that ZeroMQ "generate[s] a 5 byte identity by default", so usually we
    ;; don't need to provide our own identity.
    (when identity
      (zmq-set-socket-option socket-shell ZMQ_IDENTITY
                             (utf8->string identity)))
255

256
    ;; Sub socket connection.
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    (zmq-connect socket-control   (port->uri port-control))
    (zmq-connect socket-shell     (port->uri port-shell))
    (zmq-connect socket-stdin     (port->uri port-stdin))
    (zmq-connect socket-heartbeat (port->uri port-heartbeat))
    (zmq-connect socket-iosub     (port->uri port-iosub))

    (values connection kernel)))

(define (spawn-kernel specs connection)
  "Spawn the kernel specified by SPECS, a <kernel-specs> record, passing it
CONNECTION serialized to a \"connection file\".  Return its PID."
  (define connection-file
    (string-append "/tmp/guix-kernel/conn/"
                   (number->string (string-hash
                                    (scm->json-string
                                     (connection->json connection))))
                   ".json"))

  (define arguments
    (map (match-lambda
           ("{connection_file}" connection-file)
           (x x))
         (kernel-specs-arguments specs)))

  (mkdir-p (dirname connection-file))
  (call-with-output-file connection-file
    (lambda (port)
      (scm->json (connection->json connection) port
                 #:pretty #t)))

  (let ((pid (primitive-fork)))
    (if (zero? pid)
        (apply execl (first arguments) arguments)
        pid)))

(define (test-bind socket port)
  (catch 'zmq-error
    (lambda ()
      (zmq-bind-socket socket (string-append "tcp://127.0.0.1:"
                                             (number->string port)))
      (zmq-unbind-socket socket (string-append "tcp://127.0.0.1:"
                                               (number->string port)))
      port)
    (lambda stuff
      (let ((errno (cadr stuff)))
        (cond
         ((= errno EADDRINUSE)          ;The requested address is
                                        ;already in use.
          (test-bind socket (+ port 1)))
         (else #f))))))

(define search-path->list
  (let ((not-colon (char-set-complement (char-set #\:))))
    (match-lambda
      (#f '())
      ((? string? str)
       (string-tokenize str not-colon)))))
314

315
316
317
318
319
320
321
322
(define* (run-kernel context specs key #:key identity)
  "Spawn the kernel specified by SPECS.  Return a <kernel> record usable by
its client."
  (let ((connection kernel (allocate-connection context "tcp" "127.0.0.1"
                                                key #:identity identity)))
    (set-kernel-pid (set-kernel-name kernel
                                     (kernel-specs-display-name specs))
                    (spawn-kernel specs connection))))
323
324
325
326
327
328


;;
;; Communicating with a kernel.
;;

329
(define* (read-message kernel #:optional (timeout -1))
330
331
332
333
334
335
336
  "Read one message from one of the sockets of KERNEL and return it.  If the
message is a \"regular\" JSON message, return it as an alist; if it's a
heartbeat message, return it as a bytevector.

If TIMEOUT is -1, wait indefinitely; otherwise wait that number of
milliseconds.  If TIMEOUT expires before a message has been received, return
#f."
337
338
339
340
341
342
343
344
345
346
347
348
349
  (define shell (kernel-shell kernel))
  (define iopub (kernel-iopub kernel))
  (define items
    (zmq-poll (map (lambda (socket)
                     (poll-item socket (logior ZMQ_POLLIN ZMQ_POLLERR)))
                   (kernel-sockets kernel))
              timeout))

  (let loop ((items items))
    (match items
      (()
       #f)
      ((item rest ...)
350
351
       (let* ((socket (poll-item-socket item))
              (parts  (zmq-get-msg-parts-bytevector socket)))
352
353
354
         ;; Heartbeat messages are raw "bytestrings" that should be echoed
         ;; back right away.
         (if (eq? socket (kernel-heartbeat kernel))
355
356
             parts
             (parts->message parts)))))))
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400

(define* (send-message kernel message
                       #:key
                       (kernel-socket kernel-shell)
                       (recipient (and=> (message-parent-header message)
                                         header-sender)))
  "Send message over the shell socket of KERNEL to RECIPIENT, a ZeroMQ
identity (bytevector)."
  (zmq-send-msg-parts-bytevector (kernel-socket kernel)
                                 (message-parts message
                                                (kernel-key kernel)
                                                #:recipient recipient)))

(define* (relay-message socket kernel name request)
  "Relay REQUEST, a message, over SOCKET, with recipient NAME (a bytevector
representing a ZeroMQ identity), and return its reply.  Send replies to
KERNEL."
  (let ((parts (message-parts request (kernel-key kernel)
                              #:recipient name)))
    (zmq-send-msg-parts-bytevector socket parts))

  (let loop ()
    (let* ((parts  (zmq-get-msg-parts-bytevector socket))
           (reply  (parts->message parts))
           (sender (message-sender request)))
      (match (message-type reply)
        ("execute_reply"
         (send-message kernel reply
                       #:recipient sender)
         (loop))
        ((or "execute_result" "error")
         (send-message kernel reply #:kernel-socket kernel-iopub
                       #:recipient sender)
         (loop))
        ("execute_input"
         (send-message kernel reply #:kernel-socket kernel-iopub
                       #:recipient sender)
         (loop))
        ("stream"
         (send-message kernel reply #:kernel-socket kernel-iopub
                       #:recipient sender)
         (loop))
        ("status"
         (let ((content (json-string->scm (message-content reply))))
Ludovic Courtès's avatar
Ludovic Courtès committed
401
           (match (assoc-ref content "execution_state")
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
             ("idle" reply)
             (_      (loop)))))
        (_
         reply)))))

(define (pub kernel message status)
  (let ((content `(("execution_state" . ,status))))
    (send-message kernel (reply message "status"
                                  (scm->json-string content))
                  #:kernel-socket kernel-iopub)))

(define (pub-busy kernel message)
  (pub kernel message "busy"))

(define (pub-idle kernel message)
  (pub kernel message "idle"))

;;
;; Reply.
;;

(define (reply-html kernel message html count)
  "Reply to MESSAGE with HTML."
Ludovic Courtès's avatar
Ludovic Courtès committed
425
426
427
  (let ((code (assoc-ref (json-string->scm (message-content message))
                         "code"))
	(empty-object '())
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
	(counter      (+ count 1))                ;execution counter

        (send (lambda (socket type content)
                (send-message kernel
                              (reply message type
                                     (scm->json-string content))
                              #:kernel-socket socket))))

    (send kernel-iopub
          "execute_input" `(("code"            . ,code)
                            ("execution_count" . ,counter)))
    (send kernel-iopub
          "execute_result" `(("data"     . (("text/html" . ,html)))
                             ("metadata" . ,empty-object)
                             ("execution_count" . ,counter)))
    (send kernel-shell
          "execute_reply" `(("status"           . "ok")
                            ("execution_count"  . ,counter)
                            ("payload"          . [])
                            ("user_expressions" . ,empty-object)))
    counter))