kernels.scm 14.6 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-26)
30
  #:export (find-kernel-by-name
31
32
            run-kernel

33
34
35
36
37
38
            kernel-specs?
            kernel-specs-arguments
            kernel-specs-display-name
            kernel-specs-language
            json->kernel-specs

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

52
53
54
55
56
57
58
59
            read-message
            send-message
            relay-message
            pub-busy
            pub-idle

            reply-html

60
            close-kernel))
61

62
63
64
65
66
67
68
;;; Commentary:
;;;
;;; This module implements Jupyter "kernels" as defined at
;;; <https://jupyter-client.readthedocs.io/en/latest/kernels.html>.
;;;
;;; Code:

69
70
71
72
;;
;; Kernel execution.
;;

73
;; Type of a Jupyter kernel.
74
(define-record-type <kernel>
75
  (%kernel name pid key control shell stdin heartbeat iosub)
76
77
78
  kernel?
  (name        kernel-name)                       ;string
  (pid         kernel-pid)                        ;integer
79
  (key         kernel-key)                        ;bytevector
80
81
82
83
84
85
  (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

86
87
(define-syntax kernel-iopub (identifier-syntax kernel-iosub))

88
89
90
91
92
93
94
95
96
97
;; 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))

98
(define* (kernel name pid #:key key control shell
99
                 standard-input heartbeat iosub)
100
101
102
  (%kernel name pid key
           control shell standard-input heartbeat iosub))

103
104
105
106
107
108
109
110
111
112
(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)))

113
114
(define (close-kernel kernel)
  "Close all the open connections of KERNEL."
115
  (for-each zmq-close-socket (kernel-sockets kernel)))
116

117
118
119
120
121
122
123
124
125
126
(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"))))))
127

128
129
130
131
132
133
134
135
136
137
(define* (find-kernel-by-name kernel
                              #:optional (path (jupyter-kernel-path)))
  "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))
138
139
140
141
142

;;
;; Running procedure.
;;

143
144
145
146
147
(define* (new-connection-file type ip key
                              #:key control shell heartbeat stdin iosub)
  "Return the file name of a new JSON \"connection file\" for the given IP
and TYPE (e.g., \"tcp\"), with the given notebook KEY, and the specified
sockets."
148
149
150
151
152
153
154
  (let* ((scm `(("transport"        . ,type)
                ("ip"               . ,ip)
                ("signature_scheme" . "hmac-sha256")
                ("key"              . ,key)
                ("control_port"     . ,control)
                ("shell_port"       . ,shell)
                ("stdin_port"       . ,stdin)
155
                ("hb_port"          . ,heartbeat)
156
157
                ("iopub_port"       . ,iosub)))
         (json (scm->json-string scm))
158
159
160
161
162
163
164
165
         (file (string-append "/tmp/guix-kernel/conn/"
                              (number->string (string-hash json))
                              ".json")))
    (mkdir-p (dirname file))
    (call-with-output-file file
      (lambda (port)
        (scm->json scm port #:pretty #t)
        file))))
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182

(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))))))

183
184
185
(define (kernel-arguments kernel-file connection-file)
  "Return the argument list read from KERNEL-FILE, substituting references to
'connection-file' with CONNECTION-FILE."
186
  (let ((specs (call-with-input-file kernel-file json->kernel-specs)))
187
188
189
    (map (match-lambda
           ("{connection_file}" connection-file)
           (x x))
190
         (kernel-specs-arguments specs))))
191

192
193
194
195
196
197
198
(define search-path->list
  (let ((not-colon (char-set-complement (char-set #\:))))
    (match-lambda
      (#f '())
      ((? string? str)
       (string-tokenize str not-colon)))))

199
200
201
202
203
204
205
206
207
208
209
210
211
(define (exec-kernel kernel connection-file)
  "Execute KERNEL as a separate process, passing it CONNECTION-FILE, and
return its PID."
  (define arguments
    (cond ((string=? 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")))
             (list ipython "kernel" "--quiet" "-f" connection-file)))
          (else
           (kernel-arguments (find-kernel-by-name kernel)
                             connection-file))))
212

213
214
215
216
217
218
  (let ((pid (primitive-fork)))
    (if (zero? pid)
        (match arguments
          ((command . _)
           (apply execl command arguments)))
        pid)))
219

220
(define* (run-kernel context name key #:key identity)
221
222
223
224
225
226
227
228
229
230
231
232
233
  (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))

         (++ (lambda (port) (+ port 1)))
         (port-control   (test-bind socket-control   1024))
         (port-shell     (test-bind socket-shell     (++ port-control)))
         (port-stdin     (test-bind socket-stdin     (++ port-shell)))
         (port-heartbeat (test-bind socket-heartbeat (++ port-stdin)))
         (port-iosub     (test-bind socket-iosub     (++ port-heartbeat)))

234
235
236
237
238
239
         (connection-file (new-connection-file "tcp" "127.0.0.1" key
                                               #:control port-control
                                               #:shell port-shell
                                               #:heartbeat port-heartbeat
                                               #:stdin port-stdin
                                               #:iosub port-iosub))
240

241
         (pid    (exec-kernel name connection-file))
242

243
244
245
246
247
         (addr   "tcp://127.0.0.1:")
         (addr-p (lambda (port)
                   (string-append addr
                                  (number->string port))))

248
         (kernel (kernel name pid
249
                         #:key key
250
251
252
253
254
                         #:control socket-control
                         #:shell socket-shell
                         #:standard-input socket-stdin
                         #:heartbeat socket-heartbeat
                         #:iosub socket-iosub)))
255

256
    (zmq-set-socket-option socket-iosub ZMQ_SUBSCRIBE "")
257
258
259
260
261
262
263

    ;; <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)))
264

265
266
267
268
269
270
271
272
    ;; Sub socket connection.
    (zmq-connect socket-control   (addr-p port-control))
    (zmq-connect socket-shell     (addr-p port-shell))
    (zmq-connect socket-stdin     (addr-p port-stdin))
    (zmq-connect socket-heartbeat (addr-p port-heartbeat))
    (zmq-connect socket-iosub     (addr-p port-iosub))

    kernel))
273
274
275
276
277
278


;;
;; Communicating with a kernel.
;;

279
(define* (read-message kernel #:optional (timeout -1))
280
281
282
283
284
285
286
  "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."
287
288
289
290
291
292
293
294
295
296
297
298
299
300
  (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 ...)
       (let ((socket (poll-item-socket item)))
301
302
303
304
305
306
         ;; Heartbeat messages are raw "bytestrings" that should be echoed
         ;; back right away.
         (if (eq? socket (kernel-heartbeat kernel))
             (zmq-get-msg-bytevector socket)
             (parts->message
              (zmq-get-msg-parts-bytevector socket))))))))
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

(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
351
           (match (assoc-ref content "execution_state")
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
             ("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
375
376
377
  (let ((code (assoc-ref (json-string->scm (message-content message))
                         "code"))
	(empty-object '())
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
	(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))