Debian Codegraph @

R/kernel.r

raw symbols SCIP
1 #' @include execution.r help.r comm_manager.r logging.r utils.r
2 PROTOCOL_VER = '5.3'
3
4 Kernel <- setRefClass(
5 'Kernel',
6 fields = list(
7 connection_info = 'list',
8 zmqctx = 'externalptr',
9 sockets = 'list',
10 executor = 'Executor',
11 comm_manager = 'CommManager'),
12 methods = list(
13
14 hb_reply = function() {
15 data <- zmq.msg.recv(sockets$hb, unserialize = FALSE)
16 zmq.msg.send(data, sockets$hb, serialize = FALSE)
17 },
18
19 sign_msg = function(msg_lst) {
20 "Sign messages"
21
22 concat <- unlist(msg_lst)
23 hmac(connection_info$key, concat, 'sha256')
24 },
25
26 wire_to_msg = function(parts) {
27 "Deserialize a message"
28
29 i <- 1
30 while (!identical(parts[[i]], charToRaw('<IDS|MSG>'))) {
31 i <- i + 1
32 }
33 if (!identical(connection_info$key, '')) {
34 signature <- rawToChar(parts[[i + 1]])
35 expected_signature <- sign_msg(parts[(i + 2):(i + 5)])
36 stopifnot(identical(signature, expected_signature))
37 }
38
39 # Convert the four key parts of the message to strings and parse the JSON
40 header <- fromRawJSON(parts[[i + 2]])
41 parent_header <- fromRawJSON(parts[[i + 3]])
42 metadata <- fromRawJSON(parts[[i + 4]])
43 content <- fromRawJSON(parts[[i + 5]])
44
45 # ZMQ routing bits
46 if (i > 1) {
47 identities <- parts[1:(i - 1)]
48 } else {
49 identities <- NULL
50 }
51
52 list(
53 header = header,
54 parent_header = parent_header,
55 metadata = metadata,
56 content = content,
57 identities = identities)
58 },
59
60 msg_to_wire = function(msg) {
61 "Serialize a message"
62
63 bodyparts <- list(
64 charToRaw(toJSON(msg$header, auto_unbox = TRUE)),
65 charToRaw(toJSON(msg$parent_header, auto_unbox = TRUE)),
66 charToRaw(toJSON(msg$metadata, auto_unbox = TRUE)),
67 charToRaw(toJSON(msg$content, auto_unbox = TRUE)))
68
69 signature <- sign_msg(bodyparts)
70 c(
71 msg$identities,
72 list(charToRaw('<IDS|MSG>')),
73 list(charToRaw(signature)),
74 bodyparts)
75 },
76
77 new_reply = function(msg_type, parent_msg) {
78 "Prepare a reply"
79
80 header <- list(
81 msg_id = UUIDgenerate(),
82 session = parent_msg$header$session,
83 username = parent_msg$header$username,
84 # ISO 8601, 6 is the maximum number decimal digits supported by R
85 date = strftime(as.POSIXlt(Sys.time(), 'UTC'), '%Y-%m-%dT%H:%M:%OS6Z'),
86 msg_type = msg_type,
87 version = PROTOCOL_VER)
88
89 list(
90 header = header,
91 parent_header = parent_msg$header,
92 identities = parent_msg$identities,
93 # Ensure this is {} in JSON, not []
94 metadata = namedlist())
95 },
96
97 send_response = function(msg_type, parent_msg, socket_name, content) {
98 "Send a response"
99
100 msg <- new_reply(msg_type, parent_msg)
101 if (grepl('_reply$', msg_type) && is.null(content$status)) {
102 content$status <- 'ok'
103 }
104 msg$content <- content
105 socket <- sockets[[socket_name]]
106 zmq.send.multipart(socket, msg_to_wire(msg), serialize = FALSE)
107 log_debug('Sending msg %s.%s', socket_name, msg$header$msg_type)
108 },
109
110 handle_shell = function() {
111 "React to a shell message coming in"
112
113 parts <- zmq.recv.multipart(sockets$shell, unserialize = FALSE)
114 msg <- wire_to_msg(parts)
115
116 # protocol 5.0: send busy/idle around all of these
117 send_response('status', msg, 'iopub', list(
118 execution_state = 'busy'))
119
120 switch(
121 msg$header$msg_type,
122 comm_info_request = comm_manager$on_comm_info_request(msg),
123 comm_open = comm_manager$on_comm_open(msg),
124 comm_msg = comm_manager$on_comm_msg(msg),
125 comm_close = comm_manager$on_comm_close(msg),
126 execute_request = executor$execute(msg),
127 kernel_info_request = kernel_info(msg),
128 history_request = history(msg),
129 complete_request = complete(msg),
130 is_complete_request = is_complete(msg),
131 inspect_request = inspect(msg),
132 shutdown_request = shutdown(msg),
133 log_debug(c('Got unhandled msg_type:', msg$header$msg_type)))
134
135 send_response('status', msg, 'iopub', list(
136 execution_state = 'idle'))
137 },
138
139 abort_shell_msg = function() {
140 "Send an abort message for an incoming shell request"
141 # See https://github.com/ipython/ipykernel/blob/1d97cb2a04149387a0d2dbea1b3d0af691d8df6c/ipykernel/kernelbase.py#L623
142
143 parts <- zmq.recv.multipart(sockets$shell, unserialize = FALSE)
144 msg <- wire_to_msg(parts)
145 log_debug('Aborting msg of type %s', msg$header$msg_type)
146 reply_type <- paste0(unlist(strsplit(msg$header$msg_type, '_'))[1], '_reply')
147 reply_content <- list(status = 'aborted')
148 send_response(reply_type, msg, 'shell', reply_content)
149 log_debug('Aborted msg')
150 },
151
152 abort_queued_messages = function() {
153 "Abort all already queued shell messages after an error"
154
155 log_debug('abort loop: aborted all outstanding msg')
156 while (TRUE) {
157 log_debug('abort loop: before poll')
158 ret <- zmq.poll(
159 c(sockets$shell), # only shell channel
160 c(ZMQ.PO()$POLLIN), # type
161 0) # zero timeout, only what's already there
162 log_debug('abort loop: after poll')
163 if (bitwAnd(zmq.poll.get.revents(1), ZMQ.PO()$POLLIN)) {
164 log_debug('abort loop: found msg')
165 abort_shell_msg()
166 } else {
167 # no more messages...
168 log_debug('abort loop: breaking')
169 break
170 }
171 }
172 log_debug('abort loop: end')
173
174 },
175
176 handle_stdin = function() {
177 "React to a stdin message coming in"
178
179 # wait for 'input_reply' response message
180 while (TRUE) {
181 log_debug('stdin loop: beginning')
182 zmq.poll(c(sockets$stdin), # only stdin channel
183 c(ZMQ.PO()$POLLIN)) # type
184
185 if (bitwAnd(zmq.poll.get.revents(1), ZMQ.PO()$POLLIN)) {
186 log_debug('stdin loop: found msg')
187 parts <- zmq.recv.multipart(sockets$stdin, unserialize = FALSE)
188 msg <- wire_to_msg(parts)
189 return(msg$content$value)
190 } else {
191 # else shouldn't be possible
192 log_error('stdin loop: zmq.poll returned but no message found?')
193 }
194 }
195 },
196
197 is_complete = function(request) {
198 "Checks whether the code in the rest is complete"
199
200 code <- request$content$code
201 message <- tryCatch({
202 parse_all(code)
203 # the code compiles, so we are complete (either no code at all / only
204 # comments or syntactically correct code)
205 'complete'
206 }, error = function(e) e$message)
207
208 # One of 'complete', 'incomplete', 'invalid', 'unknown'
209 status <- if (message == 'complete') {
210 # syntactical complete code
211 'complete'
212 } else if (grepl(gettext('unexpected end of input', domain = 'R'), message, fixed = TRUE)) {
213 # missing closing parenthesis
214 'incomplete'
215 } else if (grepl(gettextf('unexpected %s', 'INCOMPLETE_STRING', domain = 'R'), message, fixed = TRUE)) {
216 # missing closing quotes
217 'incomplete'
218 } else {
219 # all else
220 'invalid'
221 }
222
223 content <- list(status = status)
224 if (status == 'incomplete') {
225 # we don't try to guess the indention level and just return zero indention
226 # That's fine because R has braces... :-)
227 # TODO: do some guessing?
228 content <- c(content, indent = '')
229 }
230
231 send_response('is_complete_reply', request, 'shell', content)
232 },
233
234 complete = function(request) {
235 # 5.0 protocol:
236 code <- request$content$code
237 cursor_pos <- request$content$cursor_pos
238
239 comps <- completions(code, cursor_pos)
240 send_response('complete_reply', request, 'shell', list(
241 matches = as.list(comps$comps), # make single strings not explode into letters
242 metadata = namedlist(),
243 cursor_start = comps$start,
244 cursor_end = comps$end))
245 },
246
247 inspect = function(request) {
248 # 5.0 protocol:
249 code <- request$content$code
250 cursor_pos <- request$content$cursor_pos
251
252 title_templates <- list(
253 'text/plain' = '# %s:\n',
254 'text/html' = '<h1>%s:</h1>\n')
255 # Function to add a section to content.
256 add_new_section <- function(data, section_name, new_data) {
257 for (mime in names(title_templates)) {
258 new_content <- new_data[[mime]]
259 if (is.null(new_content)) next
260 title <- sprintf(title_templates[[mime]], section_name)
261 # use paste0 since sprintf cannot deal with format strings > 8192 bytes
262 data[[mime]] <- paste0(data[[mime]], title, new_content, '\n', sep = '\n')
263 }
264 return(data)
265 }
266
267 # Get token under the `cursor_pos`.
268 # Since `.guessTokenFromLine()` does not check the characters after `cursor_pos`
269 # check them by a loop. Use get since R CMD check does not like :::
270 token <- ''
271 for (i in seq(cursor_pos, nchar(code))) {
272 token_candidate <- get('.guessTokenFromLine', asNamespace('utils'))(code, i)
273 if (nchar(token_candidate) == 0) break
274 token <- token_candidate
275 }
276
277 data <- namedlist()
278 if (nchar(token) != 0) {
279 # In many cases `get(token)` works, but it does not
280 # in the cases such as `token` is a numeric constant or a reserved word.
281 # Therefore `eval()` is used here.
282 obj <- tryCatch(eval(parse(text = token), envir = .GlobalEnv), error = function(e) NULL)
283 class_data <- if (!is.null(obj)) IRdisplay::prepare_mimebundle(class(obj))$data
284 print_data <- if (!is.null(obj)) IRdisplay::prepare_mimebundle(obj)$data
285
286 # `help(token)` is not used here because it does not works
287 # in the cases `token` is in `pkg::topic`or `pkg:::topic` form.
288 help_data <- tryCatch({
289 help_obj <- eval(parse(text = paste0('?', token)))
290 IRdisplay::prepare_mimebundle(help_obj)$data
291 }, error = function(e) NULL)
292
293 # only show help if we have a function
294 if ('function' %in% class(obj) && !is.null(help_data)) {
295 data <- help_data
296 } else {# any of those that are NULL are automatically skipped
297 data <- add_new_section(data, 'Class attribute', class_data)
298 data <- add_new_section(data, 'Printed form', print_data)
299 data <- add_new_section(data, 'Help document', help_data)
300 }
301 }
302 found <- length(data) != 0
303 send_response('inspect_reply', request, 'shell', list(
304 found = found,
305 data = data,
306 metadata = namedlist()))
307 },
308
309 history = function(request) {
310 send_response('history_reply', request, 'shell', list(history = list()))
311 },
312
313 kernel_info = function(request) {
314 rversion <- paste0(version$major, '.', version$minor)
315 send_response('kernel_info_reply', request, 'shell', list(
316 protocol_version = PROTOCOL_VER,
317 implementation = 'IRkernel',
318 implementation_version = as.character(packageVersion('IRkernel')),
319 language_info = list(
320 name = 'R',
321 codemirror_mode = 'r',
322 pygments_lexer = 'r',
323 mimetype = 'text/x-r-source',
324 file_extension = '.r',
325 version = rversion),
326 banner = version$version.string))
327 },
328
329 handle_control = function() {
330 log_debug('Control: beginning')
331 parts <- zmq.recv.multipart(sockets$control, unserialize = FALSE)
332 msg <- wire_to_msg(parts)
333 log_debug('Control: recv msg of type %s', msg$header$msg_type)
334 if (msg$header$msg_type == 'shutdown_request') {
335 log_debug('Control: shutdown...')
336 shutdown(msg)
337 } else {
338 log_debug(paste('Unhandled control message, msg_type:', msg$header$msg_type))
339 }
340 },
341
342 shutdown = function(request) {
343 send_response('shutdown_reply', request, 'control', list(
344 restart = request$content$restart))
345 # Always call the base quit() during shutdown since execution shadows it.
346 backup_env$base_quit('no') # bound during startup in .onLoad
347 },
348
349 initialize = function(connection_file) {
350 if (is.character(connection_file)) connection_file <- file(connection_file)
351 connection_info <<- fromJSON(connection_file)
352 stopifnot(connection_info$transport %in% c('tcp', 'ipc'))
353
354 url <- paste0(connection_info$transport, '://', connection_info$ip)
355 url_with_port <- function(port_name) {
356 sep <- switch(connection_info$transport, tcp = ':', ipc = '-')
357 paste0(url, sep, connection_info[[port_name]])
358 }
359
360 # ZMQ Socket setup
361 zmqctx <<- zmq.ctx.new()
362 sockets <<- list(
363 hb = zmq.socket(zmqctx, ZMQ.ST()$REP),
364 iopub = zmq.socket(zmqctx, ZMQ.ST()$PUB),
365 control = zmq.socket(zmqctx, ZMQ.ST()$ROUTER),
366 stdin = zmq.socket(zmqctx, ZMQ.ST()$ROUTER),
367 shell = zmq.socket(zmqctx, ZMQ.ST()$ROUTER))
368
369 # Enable handover: https://github.com/IRkernel/IRkernel/issues/508
370 for (router in sockets[c('control', 'stdin', 'shell')]) {
371 zmq.setsockopt(router, ZMQ.SO()$ROUTER_HANDOVER, 1L)
372 }
373
374 zmq.bind(sockets$hb, url_with_port('hb_port'))
375 zmq.bind(sockets$iopub, url_with_port('iopub_port'))
376 zmq.bind(sockets$control, url_with_port('control_port'))
377 zmq.bind(sockets$stdin, url_with_port('stdin_port'))
378 zmq.bind(sockets$shell, url_with_port('shell_port'))
379
380 executor <<- Executor$new(
381 send_response = .self$send_response,
382 handle_stdin = .self$handle_stdin,
383 abort_queued_messages = .self$abort_queued_messages)
384
385 comm_manager <<- CommManager$new(send_response = .self$send_response)
386 runtime_env$comm_manager <- comm_manager
387 },
388
389 run = function() {
390 options(jupyter.in_kernel = TRUE)
391
392 while (TRUE) {
393 log_debug('main loop: beginning')
394 r <- tryCatch(
395 zmq.poll(
396 c(sockets$hb, sockets$shell, sockets$control),
397 rep(ZMQ.PO()$POLLIN, 3),
398 MC = ZMQ.MC(check.eintr = TRUE)),
399 interrupt = function(e) list(0L, 'SIGINT'))
400 log_debug('main loop: after poll. ZMQ code: %s; Errno: %s', r[[1L]], r[[2L]])
401 if (identical(r[[2L]], 'SIGINT')) {
402 log_info('main loop: keyboard interrupt caught')
403 next
404 }
405
406 # It's important that these messages are handled one by one in each
407 # look. The problem is that during the handler, a new zmq.poll could be
408 # done (and is done in case of errors in a execution request) and this
409 # invalidates the zmq.poll.get.revents call leading to "funny" results
410 # with found control message even if there are no control messages. So
411 # the easiest seems to be to handle this in a big if .. else if .. else
412 # clause...
413 # https://github.com/IRkernel/IRkernel/pull/266
414 if (bitwAnd(zmq.poll.get.revents(1), ZMQ.PO()$POLLIN)) {
415 log_debug('main loop: hb')
416 hb_reply()
417 } else if (bitwAnd(zmq.poll.get.revents(2), ZMQ.PO()$POLLIN)) {
418 log_debug('main loop: shell')
419 handle_shell()
420 } else if (bitwAnd(zmq.poll.get.revents(3), ZMQ.PO()$POLLIN)) {
421 log_debug('main loop: control')
422 handle_control()
423 } else {
424 # else shouldn't be possible
425 log_debug('main loop: zmq.poll returned but no message found?')
426 }
427 }
428 log_debug('main loop: end')
429 })
430 )