##// END OF EJS Templates
Updating CodeMirror to v 2.12....
Updating CodeMirror to v 2.12. For now I am keeping the old codemirror2 directory in here until we finish debugging the new version.

File last commit:

r4495:708c73e4
r4504:981bc0cc
Show More
kernelmanager.py
350 lines | 12.1 KiB | text/x-python | PythonLexer
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 """A kernel manager for multiple kernels."""
Brian E. Granger
Refactoring the notebook app to support the new config system.
r4344 #-----------------------------------------------------------------------------
Brian E. Granger
Updating the notebook to work with the latex master....
r4348 # Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
Brian E. Granger
Refactoring the notebook app to support the new config system.
r4344 # Imports
#-----------------------------------------------------------------------------
Brian Granger
Work on the server side of the html notebook.
r4297 import signal
import sys
Brian Granger
Different clients now share a single zmq session....
r4306 import uuid
Brian Granger
Work on the server side of the html notebook.
r4297
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 import zmq
Brian E. Granger
Adding kernel/notebook associations.
r4494 from tornado import web
from .routers import IOPubStreamRouter, ShellStreamRouter
Brian E. Granger
Notebook app debugging....
r4345 from IPython.config.configurable import LoggingConfigurable
Brian Granger
Work on the server side of the html notebook.
r4297 from IPython.zmq.ipkernel import launch_kernel
Brian E. Granger
Adding kernel/notebook associations.
r4494 from IPython.utils.traitlets import Instance, Dict, List, Unicode
Brian Granger
Work on the server side of the html notebook.
r4297
Brian E. Granger
Refactoring the notebook app to support the new config system.
r4344 #-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
Brian Granger
Work on the server side of the html notebook.
r4297
Brian Granger
Basic server for htmlnotebook working.
r4298 class DuplicateKernelError(Exception):
pass
Brian E. Granger
Notebook app debugging....
r4345 class KernelManager(LoggingConfigurable):
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 """A class for managing multiple kernels."""
context = Instance('zmq.Context')
def _context_default(self):
return zmq.Context.instance()
Brian Granger
Work on the server side of the html notebook.
r4297
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 _kernels = Dict()
Brian Granger
Work on the server side of the html notebook.
r4297
@property
def kernel_ids(self):
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 """Return a list of the kernel ids of the active kernels."""
Brian Granger
Work on the server side of the html notebook.
r4297 return self._kernels.keys()
def __len__(self):
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 """Return the number of running kernels."""
Brian Granger
Work on the server side of the html notebook.
r4297 return len(self.kernel_ids)
def __contains__(self, kernel_id):
if kernel_id in self.kernel_ids:
return True
else:
return False
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 def start_kernel(self, **kwargs):
"""Start a new kernel."""
Brian E. Granger
Adding kernel/notebook associations.
r4494 kernel_id = unicode(uuid.uuid4())
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 (process, shell_port, iopub_port, stdin_port, hb_port) = launch_kernel(**kwargs)
# Store the information for contacting the kernel. This assumes the kernel is
# running on localhost.
Brian Granger
Work on the server side of the html notebook.
r4297 d = dict(
process = process,
stdin_port = stdin_port,
iopub_port = iopub_port,
shell_port = shell_port,
hb_port = hb_port,
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 ip = '127.0.0.1'
Brian Granger
Work on the server side of the html notebook.
r4297 )
Brian Granger
Basic server for htmlnotebook working.
r4298 self._kernels[kernel_id] = d
return kernel_id
Brian Granger
Work on the server side of the html notebook.
r4297
def kill_kernel(self, kernel_id):
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 """Kill a kernel by its kernel uuid.
Parameters
==========
kernel_id : uuid
The id of the kernel to kill.
"""
Brian Granger
Work on the server side of the html notebook.
r4297 kernel_process = self.get_kernel_process(kernel_id)
if kernel_process is not None:
# Attempt to kill the kernel.
try:
kernel_process.kill()
except OSError, e:
# In Windows, we will get an Access Denied error if the process
# has already terminated. Ignore it.
if not (sys.platform == 'win32' and e.winerror == 5):
raise
del self._kernels[kernel_id]
def interrupt_kernel(self, kernel_id):
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 """Interrupt (SIGINT) the kernel by its uuid.
Parameters
==========
kernel_id : uuid
The id of the kernel to interrupt.
"""
Brian Granger
Work on the server side of the html notebook.
r4297 kernel_process = self.get_kernel_process(kernel_id)
if kernel_process is not None:
if sys.platform == 'win32':
from parentpoller import ParentPollerWindows as Poller
Poller.send_interrupt(kernel_process.win32_interrupt_event)
else:
kernel_process.send_signal(signal.SIGINT)
def signal_kernel(self, kernel_id, signum):
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 """ Sends a signal to the kernel by its uuid.
Note that since only SIGTERM is supported on Windows, this function
is only useful on Unix systems.
Parameters
==========
kernel_id : uuid
The id of the kernel to signal.
Brian Granger
Work on the server side of the html notebook.
r4297 """
kernel_process = self.get_kernel_process(kernel_id)
if kernel_process is not None:
kernel_process.send_signal(signum)
def get_kernel_process(self, kernel_id):
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 """Get the process object for a kernel by its uuid.
Parameters
==========
kernel_id : uuid
The id of the kernel.
"""
Brian Granger
Work on the server side of the html notebook.
r4297 d = self._kernels.get(kernel_id)
if d is not None:
return d['process']
else:
raise KeyError("Kernel with id not found: %s" % kernel_id)
def get_kernel_ports(self, kernel_id):
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 """Return a dictionary of ports for a kernel.
Parameters
==========
kernel_id : uuid
The id of the kernel.
Returns
=======
port_dict : dict
A dict of key, value pairs where the keys are the names
(stdin_port,iopub_port,shell_port) and the values are the
integer port numbers for those channels.
"""
Brian Granger
Work on the server side of the html notebook.
r4297 d = self._kernels.get(kernel_id)
if d is not None:
dcopy = d.copy()
dcopy.pop('process')
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 dcopy.pop('ip')
Brian Granger
Work on the server side of the html notebook.
r4297 return dcopy
else:
raise KeyError("Kernel with id not found: %s" % kernel_id)
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 def get_kernel_ip(self, kernel_id):
"""Return ip address for a kernel.
Parameters
==========
kernel_id : uuid
The id of the kernel.
Returns
=======
ip : str
The ip address of the kernel.
"""
Brian Granger
Work on the server side of the html notebook.
r4297 d = self._kernels.get(kernel_id)
if d is not None:
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 return d['ip']
Brian Granger
Work on the server side of the html notebook.
r4297 else:
raise KeyError("Kernel with id not found: %s" % kernel_id)
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 def create_session_manager(self, kernel_id):
"""Create a new session manager for a kernel by its uuid."""
from sessionmanager import SessionManager
return SessionManager(
kernel_id=kernel_id, kernel_manager=self,
Brian E. Granger
Notebook app debugging....
r4345 config=self.config, context=self.context, log=self.log
Brian E. Granger
Refactored htmlnotebook session and kernel manager....
r4343 )
Brian Granger
Work on the server side of the html notebook.
r4297
Brian E. Granger
Adding kernel/notebook associations.
r4494
class RoutingKernelManager(LoggingConfigurable):
"""A KernelManager that handles WebSocket routing and HTTP error handling"""
kernel_argv = List(Unicode)
kernel_manager = Instance(KernelManager)
_routers = Dict()
_session_dict = Dict()
_notebook_mapping = Dict()
#-------------------------------------------------------------------------
# Methods for managing kernels and sessions
#-------------------------------------------------------------------------
@property
def kernel_ids(self):
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 """List the kernel ids."""
Brian E. Granger
Adding kernel/notebook associations.
r4494 return self.kernel_manager.kernel_ids
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 def kernel_for_notebook(self, notebook_id):
"""Return the kernel_id for a notebook_id or None."""
return self._notebook_mapping.get(notebook_id)
def set_kernel_for_notebook(self, notebook_id, kernel_id):
"""Associate a notebook with a kernel."""
if notebook_id is not None:
self._notebook_mapping[notebook_id] = kernel_id
Brian E. Granger
Adding kernel/notebook associations.
r4494 def notebook_for_kernel(self, kernel_id):
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 """Return the notebook_id for a kernel_id or None."""
Brian E. Granger
Adding kernel/notebook associations.
r4494 notebook_ids = [k for k, v in self._notebook_mapping.iteritems() if v == kernel_id]
if len(notebook_ids) == 1:
return notebook_ids[0]
else:
return None
def delete_mapping_for_kernel(self, kernel_id):
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 """Remove the kernel/notebook mapping for kernel_id."""
Brian E. Granger
Adding kernel/notebook associations.
r4494 notebook_id = self.notebook_for_kernel(kernel_id)
if notebook_id is not None:
del self._notebook_mapping[notebook_id]
def start_kernel(self, notebook_id=None):
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 """Start a kernel an return its kernel_id.
Parameters
----------
notebook_id : uuid
The uuid of the notebook to associate the new kernel with. If this
is not None, this kernel will be persistent whenever the notebook
requests a kernel.
"""
Brian E. Granger
Adding kernel/notebook associations.
r4494 self.log.info
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 kernel_id = self.kernel_for_notebook(notebook_id)
Brian E. Granger
Adding kernel/notebook associations.
r4494 if kernel_id is None:
kwargs = dict()
kwargs['extra_arguments'] = self.kernel_argv
kernel_id = self.kernel_manager.start_kernel(**kwargs)
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 self.set_kernel_for_notebook(notebook_id, kernel_id)
self.log.info("Kernel started: %s" % kernel_id)
Brian E. Granger
Adding kernel/notebook associations.
r4494 self.log.debug("Kernel args: %r" % kwargs)
self.start_session_manager(kernel_id)
else:
self.log.info("Using existing kernel: %s" % kernel_id)
return kernel_id
def start_session_manager(self, kernel_id):
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 """Start the ZMQ sockets (a "session") to connect to a kernel."""
Brian E. Granger
Adding kernel/notebook associations.
r4494 sm = self.kernel_manager.create_session_manager(kernel_id)
self._session_dict[kernel_id] = sm
iopub_stream = sm.get_iopub_stream()
shell_stream = sm.get_shell_stream()
iopub_router = IOPubStreamRouter(
zmq_stream=iopub_stream, session=sm.session, config=self.config
)
shell_router = ShellStreamRouter(
zmq_stream=shell_stream, session=sm.session, config=self.config
)
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 self.set_router(kernel_id, 'iopub', iopub_router)
self.set_router(kernel_id, 'shell', shell_router)
Brian E. Granger
Adding kernel/notebook associations.
r4494
def kill_kernel(self, kernel_id):
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 """Kill a kernel and remove its notebook association."""
Brian E. Granger
Adding kernel/notebook associations.
r4494 if kernel_id not in self.kernel_manager:
raise web.HTTPError(404)
try:
sm = self._session_dict.pop(kernel_id)
except KeyError:
raise web.HTTPError(404)
sm.stop()
self.kernel_manager.kill_kernel(kernel_id)
self.delete_mapping_for_kernel(kernel_id)
self.log.info("Kernel killed: %s" % kernel_id)
def interrupt_kernel(self, kernel_id):
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 """Interrupt a kernel."""
Brian E. Granger
Adding kernel/notebook associations.
r4494 if kernel_id not in self.kernel_manager:
raise web.HTTPError(404)
self.kernel_manager.interrupt_kernel(kernel_id)
self.log.debug("Kernel interrupted: %s" % kernel_id)
def restart_kernel(self, kernel_id):
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 """Restart a kernel while keeping clients connected."""
Brian E. Granger
Adding kernel/notebook associations.
r4494 if kernel_id not in self.kernel_manager:
raise web.HTTPError(404)
# Get the notebook_id to preserve the kernel/notebook association
notebook_id = self.notebook_for_kernel(kernel_id)
# Create the new kernel first so we can move the clients over.
new_kernel_id = self.start_kernel()
# Copy the clients over to the new routers.
old_iopub_router = self.get_router(kernel_id, 'iopub')
old_shell_router = self.get_router(kernel_id, 'shell')
new_iopub_router = self.get_router(new_kernel_id, 'iopub')
new_shell_router = self.get_router(new_kernel_id, 'shell')
new_iopub_router.copy_clients(old_iopub_router)
new_shell_router.copy_clients(old_shell_router)
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 # Shut down the old routers
old_shell_router.close()
old_iopub_router.close()
self.delete_router(kernel_id, 'shell')
self.delete_router(kernel_id, 'iopub')
del old_shell_router
del old_iopub_router
Brian E. Granger
Adding kernel/notebook associations.
r4494 # Now shutdown the old session and the kernel.
# TODO: This causes a hard crash in ZMQStream.close, which sets
# self.socket to None to hastily. We will need to fix this in PyZMQ
# itself. For now, we just leave the old kernel running :(
# Maybe this is fixed now, but nothing was changed really.
self.kill_kernel(kernel_id)
# Now save the new kernel/notebook association. We have to save it
# after the old kernel is killed as that will delete the mapping.
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 self.set_kernel_for_notebook(notebook_id, new_kernel_id)
Brian E. Granger
Adding kernel/notebook associations.
r4494
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 self.log.debug("Kernel restarted: %s" % new_kernel_id)
Brian E. Granger
Adding kernel/notebook associations.
r4494 return new_kernel_id
def get_router(self, kernel_id, stream_name):
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 """Return the router for a given kernel_id and stream name."""
Brian E. Granger
Adding kernel/notebook associations.
r4494 router = self._routers[(kernel_id, stream_name)]
return router
Brian E. Granger
Fixed subtle bug in kernel restarting....
r4495 def set_router(self, kernel_id, stream_name, router):
"""Set the router for a given kernel_id and stream_name."""
self._routers[(kernel_id, stream_name)] = router
def delete_router(self, kernel_id, stream_name):
"""Delete a router for a kernel_id and stream_name."""
try:
del self._routers[(kernel_id, stream_name)]
except KeyError:
pass