jupyter_server.services.kernels package#

Subpackages#

Submodules#

Tornado handlers for kernels.

Preliminary documentation at ipython/ipython

class jupyter_server.services.kernels.handlers.KernelActionHandler(application, request, **kwargs)#

Bases: KernelsAPIHandler

A kernel action API handler.

post(kernel_id, action)#

Interrupt or restart a kernel.

class jupyter_server.services.kernels.handlers.KernelHandler(application, request, **kwargs)#

Bases: KernelsAPIHandler

A kernel API handler.

delete(kernel_id)#

Remove a kernel.

get(kernel_id)#

Get a kernel model.

class jupyter_server.services.kernels.handlers.KernelsAPIHandler(application, request, **kwargs)#

Bases: APIHandler

A kernels API handler.

auth_resource = 'kernels'#
class jupyter_server.services.kernels.handlers.MainKernelHandler(application, request, **kwargs)#

Bases: KernelsAPIHandler

The root kernel handler.

get()#

Get the list of running kernels.

post()#

Start a kernel.

A MultiKernelManager for use in the Jupyter server

  • raises HTTPErrors

  • creates REST API models

class jupyter_server.services.kernels.kernelmanager.AsyncMappingKernelManager(**kwargs: Any)#

Bases: MappingKernelManager, AsyncMultiKernelManager

An asynchronous mapping kernel manager.

class jupyter_server.services.kernels.kernelmanager.MappingKernelManager(**kwargs: Any)#

Bases: MultiKernelManager

A KernelManager that handles - File mapping - HTTP error handling - Kernel message filtering

allow_tracebacks#

Whether to send tracebacks to clients on exceptions.

allowed_message_types#

White list of allowed kernel message types. When the list is empty, all message types are allowed.

buffer_offline_messages#

Whether messages from kernels whose frontends have disconnected should be buffered in-memory.

When True (default), messages are buffered and replayed on reconnect, avoiding lost messages due to interrupted connectivity.

Disable if long-running kernels will produce too much output while no frontends are connected.

cull_busy#

Whether to consider culling kernels which are busy. Only effective if cull_idle_timeout > 0.

cull_connected#

Whether to consider culling kernels which have one or more connections. Only effective if cull_idle_timeout > 0.

cull_idle_timeout#

Timeout (in seconds) after which a kernel is considered idle and ready to be culled. Values of 0 or lower disable culling. Very short timeouts may result in kernels being culled for users with poor network connections.

cull_interval#

The interval (in seconds) on which to check for idle kernels exceeding the cull timeout value.

cull_interval_default = 300#
async cull_kernel_if_idle(kernel_id)#

Cull a kernel if it is idle.

async cull_kernels()#

Handle culling kernels.

cwd_for_path(path, **kwargs)#

Turn API path into absolute OS path.

get_buffer(kernel_id, session_key)#

Get the buffer for a given kernel

Parameters:
  • kernel_id (str) – The id of the kernel to stop buffering.

  • session_key (str, optional) – The session_key, if any, that should get the buffer. If the session_key matches the current buffered session_key, the buffer will be returned.

initialize_culler()#

Start idle culler if ‘cull_idle_timeout’ is greater than zero.

Regardless of that value, set flag that we’ve been here.

kernel_argv#

An instance of a Python list.

kernel_info_timeout#

Timeout for giving up on a kernel (in seconds).

On starting and restarting kernels, we check whether the kernel is running and responsive by sending kernel_info_requests. This sets the timeout in seconds for how long the kernel can take before being presumed dead. This affects the MappingKernelManager (which handles kernel restarts) and the ZMQChannelsHandler (which handles the startup).

kernel_model(kernel_id)#

Return a JSON-safe dict representing a kernel

For use in representing kernels in the JSON APIs.

last_kernel_activity#

The last activity on any kernel, including shutting down a kernel

list_kernels()#

Returns a list of kernel_id’s of kernels running.

notify_connect(kernel_id)#

Notice a new connection to a kernel

notify_disconnect(kernel_id)#

Notice a disconnection from a kernel

ports_changed(kernel_id)#

Used by ZMQChannelsHandler to determine how to coordinate nudge and replays.

Ports are captured when starting a kernel (via MappingKernelManager). Ports are considered changed (following restarts) if the referenced KernelManager is using a set of ports different from those captured at startup. If changes are detected, the captured set is updated and a value of True is returned.

NOTE: Use is exclusive to ZMQChannelsHandler because this object is a singleton instance while ZMQChannelsHandler instances are per WebSocket connection that can vary per kernel lifetime.

async restart_kernel(kernel_id, now=False)#

Restart a kernel by kernel_id

root_dir#

A trait for unicode strings.

async shutdown_kernel(kernel_id, now=False, restart=False)#

Shutdown a kernel by kernel_id

start_buffering(kernel_id, session_key, channels)#

Start buffering messages for a kernel

Parameters:
  • kernel_id (str) – The id of the kernel to stop buffering.

  • session_key (str) – The session_key, if any, that should get the buffer. If the session_key matches the current buffered session_key, the buffer will be returned.

  • channels (dict({'channel': ZMQStream})) – The zmq channels whose messages should be buffered.

async start_kernel(*, kernel_id=None, path=None, **kwargs)#

Start a kernel for a session and return its kernel_id.

Parameters:
  • kernel_id (uuid (str)) – The uuid to associate the new kernel with. If this is not None, this kernel will be persistent whenever it is requested.

  • path (API path) – The API path (unicode, ‘/’ delimited) for the cwd. Will be transformed to an OS path relative to root_dir.

  • kernel_name (str) – The name identifying which kernel spec to launch. This is ignored if an existing kernel is returned, but it may be checked in the future.

Return type:

str

start_watching_activity(kernel_id)#

Start watching IOPub messages on a kernel for activity.

  • update last_activity on every message

  • record execution_state from status messages

stop_buffering(kernel_id)#

Stop buffering kernel messages

Parameters:

kernel_id (str) – The id of the kernel to stop buffering.

stop_watching_activity(kernel_id)#

Stop watching IOPub messages on a kernel for activity.

traceback_replacement_message#

Message to print when allow_tracebacks is False, and an exception occurs

class jupyter_server.services.kernels.kernelmanager.ServerKernelManager(*args, **kwargs)#

Bases: AsyncIOLoopKernelManager

A server-specific kernel manager.

property core_event_schema_paths: list[Path]#
emit(schema_id, data)#

Emit an event from the kernel manager.

event_logger#

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

execution_state#

The current execution state of the kernel

extra_event_schema_paths: List[str]#

A list of pathlib.Path objects pointing at to register with the kernel manager’s eventlogger.

async interrupt_kernel(*args, **kwargs)#

Interrupts the kernel by sending it a signal.

Unlike signal_kernel, this operation is well supported on all platforms.

last_activity#

The last activity on the kernel

reason#

The reason for the last failure against the kernel

async restart_kernel(*args, **kwargs)#

Restarts a kernel with the arguments that were used to launch it.

Parameters:
  • now (bool, optional) –

    If True, the kernel is forcefully restarted immediately, without having a chance to do any cleanup action. Otherwise the kernel is given 1s to clean up before a forceful restart is issued.

    In all cases the kernel is restarted, the only difference is whether it is given a chance to perform a clean shutdown or not.

  • newports (bool, optional) – If the old kernel was launched with random ports, this flag decides whether the same ports and connection file will be used again. If False, the same ports and connection file are used. This is the default. If True, new random port numbers are chosen and a new connection file is written. It is still possible that the newly chosen random port numbers happen to be the same as the old ones.

  • **kw (optional) – Any options specified here will overwrite those used to launch the kernel.

async shutdown_kernel(*args, **kwargs)#

Attempts to stop the kernel process cleanly.

This attempts to shutdown the kernels cleanly by:

  1. Sending it a shutdown message over the control channel.

  2. If that fails, the kernel is shutdown forcibly by sending it a signal.

Parameters:
  • now (bool) – Should the kernel be forcible killed now. This skips the first, nice shutdown attempt.

  • restart (bool) – Will this kernel be restarted after it is shutdown. When this is True, connection files will not be cleaned up.

async start_kernel(*args, **kwargs)#

Starts a kernel on this host in a separate process.

If random ports (port=0) are being used, this method must be called before the channels are created.

Parameters:

**kw (optional) – keyword arguments that are passed down to build the kernel_cmd and launching the kernel (e.g. Popen kwargs).

jupyter_server.services.kernels.kernelmanager.emit_kernel_action_event(success_msg='')#

Decorate kernel action methods to begin emitting jupyter kernel action events.

Parameters:
  • success_msg (str) – A formattable string that’s passed to the message field of the emitted event when the action succeeds. You can include the kernel_id, kernel_name, or action in the message using a formatted string argument, e.g. “{kernel_id} succeeded to {action}.”

  • error_msg (str) – A formattable string that’s passed to the message field of the emitted event when the action fails. You can include the kernel_id, kernel_name, or action in the message using a formatted string argument, e.g. “{kernel_id} failed to {action}.”

Return type:

Callable[..., Any]

Tornado handlers for WebSocket <-> ZMQ sockets.

class jupyter_server.services.kernels.websocket.KernelWebsocketHandler(application, request, **kwargs)#

Bases: WebSocketMixin, WebSocketHandler, JupyterHandler

The kernels websocket should connect

auth_resource = 'kernels'#
get(kernel_id)#

Handle a get request for a kernel.

get_compression_options()#

Get the socket connection options.

property kernel_websocket_connection_class#

The kernel websocket connection class.

on_close()#

Handle a socket closure.

on_message(ws_message)#

Get a kernel message from the websocket and turn it into a ZMQ message.

async open(kernel_id)#

Open a kernel websocket.

async pre_get()#

Handle a pre_get.

select_subprotocol(subprotocols)#

Select the sub protocol for the socket.

set_default_headers()#

Undo the set_default_headers in JupyterHandler

which doesn’t make sense for websockets

Module contents#