kernels.scm 13.2 KB
Newer Older
1
;;; Guix-kernel -- Guix kernel for Jupyter
2
;;; Copyright (C) 2018 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
21
  #:use-module (guix build utils)
  #:use-module (ice-9 rdelim)
22
  #:use-module (ice-9 match)
23
24
  #:use-module (simple-zmq)
  #:use-module (json)
25
  #:use-module (rnrs bytevectors)
26
  #:use-module (srfi srfi-1)
27
  #:use-module (srfi srfi-9)
28
  #:use-module (srfi srfi-26)
29
  #:export (find-kernel-by-name
30
31
32
33
34
35
            run-kernel

            kernel
            kernel?
            kernel-name
            kernel-pid
36
            kernel-key
37
38
39
40
            kernel-control
            kernel-shell
            kernel-standard-input
            kernel-heartbeat
41
42
            kernel-iosub
            kernel-iopub                          ;alias
43
            kernel-sockets
44

45
46
47
48
49
50
51
52
            read-message
            send-message
            relay-message
            pub-busy
            pub-idle

            reply-html

53
            close-kernel))
54

55
56
57
58
59
60
61
;;; Commentary:
;;;
;;; This module implements Jupyter "kernels" as defined at
;;; <https://jupyter-client.readthedocs.io/en/latest/kernels.html>.
;;;
;;; Code:

62
63
64
65
;;
;; Kernel execution.
;;

66
;; Type of a Jupyter kernel.
67
(define-record-type <kernel>
68
  (%kernel name pid key control shell stdin heartbeat iosub)
69
70
71
  kernel?
  (name        kernel-name)                       ;string
  (pid         kernel-pid)                        ;integer
72
  (key         kernel-key)                        ;bytevector
73
74
75
76
77
78
  (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

79
80
81
(define-syntax kernel-iopub (identifier-syntax kernel-iosub))

(define* (kernel name pid #:key key control shell
82
                 standard-input heartbeat iosub)
83
84
85
  (%kernel name pid key
           control shell standard-input heartbeat iosub))

86
87
88
89
90
91
92
93
94
95
(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)))

96
97
(define (close-kernel kernel)
  "Close all the open connections of KERNEL."
98
  (for-each zmq-close-socket (kernel-sockets kernel)))
99

100
101
102
103
104
105
106
107
108
109
(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"))))))
110

111
112
113
114
115
116
117
118
119
120
(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))
121
122
123
124
125

;;
;; Running procedure.
;;

126
127
128
129
130
(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."
131
132
133
134
135
136
137
  (let* ((scm `(("transport"        . ,type)
                ("ip"               . ,ip)
                ("signature_scheme" . "hmac-sha256")
                ("key"              . ,key)
                ("control_port"     . ,control)
                ("shell_port"       . ,shell)
                ("stdin_port"       . ,stdin)
138
                ("hb_port"          . ,heartbeat)
139
140
                ("iopub_port"       . ,iosub)))
         (json (scm->json-string scm))
141
142
143
144
145
146
147
148
         (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))))
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

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

166
167
168
169
170
171
172
173
(define (kernel-arguments kernel-file connection-file)
  "Return the argument list read from KERNEL-FILE, substituting references to
'connection-file' with CONNECTION-FILE."
  (let ((table (call-with-input-file kernel-file json->scm)))
    (map (match-lambda
           ("{connection_file}" connection-file)
           (x x))
         (hash-ref table "argv"))))
174

175
176
177
178
179
180
181
(define search-path->list
  (let ((not-colon (char-set-complement (char-set #\:))))
    (match-lambda
      (#f '())
      ((? string? str)
       (string-tokenize str not-colon)))))

182
183
184
185
186
187
188
189
190
191
192
193
194
(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))))
195

196
197
198
199
200
201
  (let ((pid (primitive-fork)))
    (if (zero? pid)
        (match arguments
          ((command . _)
           (apply execl command arguments)))
        pid)))
202

203
204
205
206
207
208
209
210
211
212
213
214
215
216
(define (run-kernel context name uuid key)
  (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)))

217
218
219
220
221
222
         (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))
223

224
         (pid    (exec-kernel name connection-file))
225

226
227
228
229
230
         (addr   "tcp://127.0.0.1:")
         (addr-p (lambda (port)
                   (string-append addr
                                  (number->string port))))

231
         (kernel (kernel name pid
232
                         #:key key
233
234
235
236
237
                         #:control socket-control
                         #:shell socket-shell
                         #:standard-input socket-stdin
                         #:heartbeat socket-heartbeat
                         #:iosub socket-iosub)))
238
239
    
    (zmq-set-socket-option socket-iosub ZMQ_SUBSCRIBE "")
240
241
    (zmq-set-socket-option socket-shell ZMQ_IDENTITY (utf8->string uuid))

242
243
244
245
246
247
248
249
    ;; 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))
250
251
252
253
254
255
256
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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364


;;
;; Communicating with a kernel.
;;

(define (read-message kernel)
  "Read a message for KERNEL--i.e., a message sent by Jupyter--and return
it or #f if nothing is available."
  ;; FIXME Use 'zmq_poll'.
  (define (waiting-data socket next)
    (catch 'zmq-error
      (λ _
        (zmq-get-msg-parts-bytevector socket))
      (λ stuff
        (cond
         ((equal? EAGAIN (cadr stuff))
          (and next (waiting-data next socket)))
         (else #f)))))

  (and=> (waiting-data (kernel-shell kernel)
                       (kernel-control kernel))
         parts->message))

(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))))
           (match (hash-ref content "execution_state")
             ("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."
  (let ((code (hash-ref (json-string->scm (message-content message))
                        "code"))
	(empty-object (make-hash-table 1))
	(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))