##// END OF EJS Templates
Allow passing extra arguments to iptest through for nose
Allow passing extra arguments to iptest through for nose

File last commit:

r12591:5d0418a8
r12638:10e40f56
Show More
manager.py
378 lines | 12.9 KiB | text/x-python | PythonLexer
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 """Base class to manage a running kernel"""
Brian Granger
Work on the kernel manager.
r2606
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 #-----------------------------------------------------------------------------
MinRK
split KernelManager into KernelManager + KernelClient
r10285 # Copyright (C) 2013 The IPython Development Team
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 #
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
MinRK
mv IPython.zmq to IPython.kernel.zmq
r9372 from __future__ import absolute_import
MinRK
move zmq.KernelManagers into IPython.kernel
r9370 # Standard library imports
epatters
Implemented kernel interrupts for Windows.
r3027 import signal
epatters
Adding some temporary hacks to work around (Py)ZMQ bugs on Windows.
r2995 import sys
epatters
Added a flush method to the SubSocketChannel. The Qt console frontend now uses this method to ensure that output has been processed before it writes a new prompt.
r2614 import time
Brian Granger
Work on the kernel manager.
r2606
import zmq
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
MinRK
move zmq.KernelManagers into IPython.kernel
r9370 # Local imports
MinRK
split KernelManager into KernelManager + KernelClient
r10285 from IPython.config.configurable import LoggingConfigurable
MinRK
add `KernelManager.client()`
r10300 from IPython.utils.importstring import import_item
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 from IPython.utils.localinterfaces import is_local_ip, local_ips
MinRK
use connection files instead of ports to connect to kernels...
r4958 from IPython.utils.traitlets import (
MinRK
add `KernelManager.client()`
r10300 Any, Instance, Unicode, List, Bool, Type, DottedObjectName
MinRK
use connection files instead of ports to connect to kernels...
r4958 )
MinRK
move utils.kernel (formerly entry_point and lib.kernel) to kernel.util
r9353 from IPython.kernel import (
MinRK
s/make_kernel_cmd/make_ipkernel_cmd/
r9350 make_ipkernel_cmd,
MinRK
allow custom kernel_cmd in KernelManager
r9348 launch_kernel,
)
MinRK
split KernelManager into KernelManager + KernelClient
r10285 from .connect import ConnectionFileMixin
MinRK
define and test IPython.kernel public API
r9376 from .zmq.session import Session
MinRK
update imports with new layout
r10284 from .managerabc import (
Brian Granger
Creating an ABC for kernel managers and channels.
r9121 KernelManagerABC
)
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 #-----------------------------------------------------------------------------
# Main kernel manager class
#-----------------------------------------------------------------------------
MinRK
split KernelManager into KernelManager + KernelClient
r10285 class KernelManager(LoggingConfigurable, ConnectionFileMixin):
"""Manages a single kernel in a subprocess on this host.
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
split KernelManager into KernelManager + KernelClient
r10285 This version starts kernels with Popen.
epatters
Cleaned up KernelManager interface and clarified documentation.
r2631 """
MinRK
split KernelManager into KernelManager + KernelClient
r10285
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 # The PyZMQ Context to use for communication with the kernel.
MinRK
finish plumbing config to Session objects...
r4015 context = Instance(zmq.Context)
def _context_default(self):
return zmq.Context.instance()
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
# The Session to use for communication with the kernel.
MinRK
finish plumbing config to Session objects...
r4015 session = Instance(Session)
epatters
Refactor kernel managers in preparation for the EmbeddedKernel.
r8408 def _session_default(self):
MinRK
use `parent=self` throughout IPython...
r11064 return Session(parent=self)
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
MinRK
add `KernelManager.client()`
r10300 # the class to create with our `client` method
MinRK
make BlockingKernelClient the default Client...
r10384 client_class = DottedObjectName('IPython.kernel.blocking.BlockingKernelClient')
MinRK
add `KernelManager.client()`
r10300 client_factory = Type()
def _client_class_changed(self, name, old, new):
self.client_factory = import_item(str(new))
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 # The kernel process with which the KernelManager is communicating.
MinRK
allow custom kernel_cmd in KernelManager
r9348 # generally a Popen instance
MinRK
relocate redundantly-named kernel files...
r10283 kernel = Any()
MinRK
allow custom kernel_cmd in KernelManager
r9348 kernel_cmd = List(Unicode, config=True,
help="""The Popen Command to launch the kernel.
MinRK
relocate redundantly-named kernel files...
r10283 Override this if you have a custom
MinRK
allow custom kernel_cmd in KernelManager
r9348 """
)
Brian Granger
Refactoring kernel restarting.
r10282
MinRK
allow custom kernel_cmd in KernelManager
r9348 def _kernel_cmd_changed(self, name, old, new):
self.ipython_kernel = False
ipython_kernel = Bool(True)
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730
MinRK
split KernelManager into KernelManager + KernelClient
r10285 # Protected traits
MinRK
add control channel...
r10296 _launch_args = Any()
_control_socket = Any()
MinRK
improve default ipc file locations...
r9175
MinRK
KM.client creates a client with a shared Session
r10309 _restarter = Any()
Brian Granger
Refactoring kernel restarting.
r10282 autorestart = Bool(False, config=True,
help="""Should we autorestart the kernel if it dies."""
)
MinRK
improve default ipc file locations...
r9175 def __del__(self):
MinRK
add control channel...
r10296 self._close_control_socket()
Brian E. Granger
Putting connection file cleanup back in __del__.
r9154 self.cleanup_connection_file()
Brian E. Granger
Removing connection/ipc file cleanup from KernelManager.__del__.
r9152
epatters
* The SVG payload matplotlib backend now works....
r2758 #--------------------------------------------------------------------------
Brian Granger
Refactoring kernel restarting.
r10282 # Kernel restarter
#--------------------------------------------------------------------------
def start_restarter(self):
pass
def stop_restarter(self):
pass
MinRK
expose restart callbacks via KernelManager
r10313 def add_restart_callback(self, callback, event='restart'):
"""register a callback to be called when a kernel is restarted"""
if self._restarter is None:
return
self._restarter.add_callback(callback, event)
def remove_restart_callback(self, callback, event='restart'):
"""unregister a callback to be called when a kernel is restarted"""
if self._restarter is None:
return
self._restarter.remove_callback(callback, event)
Brian Granger
Refactoring kernel restarting.
r10282 #--------------------------------------------------------------------------
MinRK
add `KernelManager.client()`
r10300 # create a Client connected to our Kernel
#--------------------------------------------------------------------------
def client(self, **kwargs):
"""Create a client configured to connect to our kernel"""
if self.client_factory is None:
self.client_factory = import_item(self.client_class)
kw = {}
kw.update(self.get_connection_info())
MinRK
KM.client creates a client with a shared Session
r10309 kw.update(dict(
connection_file=self.connection_file,
session=self.session,
MinRK
use `parent=self` throughout IPython...
r11064 parent=self,
MinRK
KM.client creates a client with a shared Session
r10309 ))
MinRK
add `KernelManager.client()`
r10300
# add kwargs last, for manual overrides
kw.update(kwargs)
return self.client_factory(**kw)
#--------------------------------------------------------------------------
Brian E. Granger
Final cleanup of kernelmanager...
r9151 # Kernel management
Brian Granger
Creating an ABC for kernel managers and channels.
r9121 #--------------------------------------------------------------------------
Brian Granger
Refactoring kernel restarting.
r10282
MinRK
allow custom kernel_cmd in KernelManager
r9348 def format_kernel_cmd(self, **kw):
"""format templated args (e.g. {connection_file})"""
if self.kernel_cmd:
cmd = self.kernel_cmd
else:
MinRK
s/make_kernel_cmd/make_ipkernel_cmd/
r9350 cmd = make_ipkernel_cmd(
MinRK
mv IPython.zmq to IPython.kernel.zmq
r9372 'from IPython.kernel.zmq.kernelapp import main; main()',
MinRK
allow custom kernel_cmd in KernelManager
r9348 **kw
)
ns = dict(connection_file=self.connection_file)
ns.update(self._launch_args)
return [ c.format(**ns) for c in cmd ]
MinRK
relocate redundantly-named kernel files...
r10283
MinRK
allow KM._launch_kernel to be overridden in subclasses
r9349 def _launch_kernel(self, kernel_cmd, **kw):
"""actually launch the kernel
MinRK
relocate redundantly-named kernel files...
r10283
MinRK
allow KM._launch_kernel to be overridden in subclasses
r9349 override in a subclass to launch kernel subprocesses differently
"""
return launch_kernel(kernel_cmd, **kw)
MinRK
relocate redundantly-named kernel files...
r10283
MinRK
add `KernelManager.client()`
r10300 # Control socket used for polite kernel shutdown
MinRK
add control channel...
r10296 def _connect_control_socket(self):
if self._control_socket is None:
self._control_socket = self.connect_control()
MinRK
add `KernelManager.client()`
r10300 self._control_socket.linger = 100
MinRK
add control channel...
r10296
def _close_control_socket(self):
if self._control_socket is None:
return
self._control_socket.close()
self._control_socket = None
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 def start_kernel(self, **kw):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Starts a kernel on this host in a separate process.
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 If random ports (port=0) are being used, this method must be called
before the channels are created.
epatters
* The SVG payload matplotlib backend now works....
r2758
Parameters:
-----------
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 **kw : optional
MinRK
move IPython.zmq.entry_point to IPython.utils.kernel
r9352 keyword arguments that are passed down to build the kernel_cmd
and launching the kernel (e.g. Popen kwargs).
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 """
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 if self.transport == 'tcp' and not is_local_ip(self.ip):
MinRK
Possible fix for GH-169
r3144 raise RuntimeError("Can only launch a kernel on a local interface. "
epatters
* Implemented a proper main() function for kernel.py that reads command line input....
r2667 "Make sure that the '*_address' attributes are "
MinRK
Possible fix for GH-169
r3144 "configured properly. "
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 "Currently valid addresses are: %s" % local_ips()
MinRK
Possible fix for GH-169
r3144 )
MinRK
relocate redundantly-named kernel files...
r10283
MinRK
use connection files instead of ports to connect to kernels...
r4958 # write connection file / get default ports
self.write_connection_file()
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
allow custom kernel_cmd in KernelManager
r9348 # save kwargs for use in restart
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 self._launch_args = kw.copy()
MinRK
allow custom kernel_cmd in KernelManager
r9348 # build the Popen cmd
kernel_cmd = self.format_kernel_cmd(**kw)
# launch the kernel subprocess
MinRK
allow KM._launch_kernel to be overridden in subclasses
r9349 self.kernel = self._launch_kernel(kernel_cmd,
ipython_kernel=self.ipython_kernel,
**kw)
Brian Granger
Refactoring kernel restarting.
r10282 self.start_restarter()
MinRK
add control channel...
r10296 self._connect_control_socket()
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686
MinRK
split KernelManager into KernelManager + KernelClient
r10285 def _send_shutdown_request(self, restart=False):
"""TODO: send a shutdown request via control channel"""
MinRK
add control channel...
r10296 content = dict(restart=restart)
msg = self.session.msg("shutdown_request", content=content)
self.session.send(self._control_socket, msg)
MinRK
split KernelManager into KernelManager + KernelClient
r10285
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 def shutdown_kernel(self, now=False, restart=False):
MinRK
relocate redundantly-named kernel files...
r10283 """Attempts to the stop the kernel process cleanly.
Brian E. Granger
More kernelmanager docstring cleanup.
r9129
This attempts to shutdown the kernels cleanly by:
1. Sending it a shutdown message over the shell channel.
2. If that fails, the kernel is shutdown forcibly by sending it
a signal.
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 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.
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961 """
Brian Granger
Refactoring kernel restarting.
r10282 # Stop monitoring for restarting while we shutdown.
self.stop_restarter()
# FIXME: Shutdown does not work on Windows due to ZMQ errors!
if sys.platform == 'win32':
self._kill_kernel()
return
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 if now:
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961 if self.has_kernel:
Brian E. Granger
Make KernelManager.kill_kernel private....
r9130 self._kill_kernel()
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 else:
# Don't send any additional kernel kill messages immediately, to give
# the kernel a chance to properly execute shutdown actions. Wait for at
# most 1s, checking every 0.1s.
MinRK
split KernelManager into KernelManager + KernelClient
r10285 self._send_shutdown_request(restart=restart)
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 for i in range(10):
Brian E. Granger
Made is_alive a method of KernelManager and MultiKernelManager....
r10275 if self.is_alive():
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 time.sleep(0.1)
else:
break
else:
# OK, we've waited long enough.
if self.has_kernel:
Brian E. Granger
Make KernelManager.kill_kernel private....
r9130 self._kill_kernel()
Bernardo B. Marques
remove all trailling spaces
r4872
Brian E. Granger
Fixing bug in connection file cleanup....
r9117 if not restart:
self.cleanup_connection_file()
Brian E. Granger
Final cleanup of kernelmanager...
r9151 self.cleanup_ipc_files()
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 else:
self.cleanup_ipc_files()
MinRK
use connection files instead of ports to connect to kernels...
r4958
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 def restart_kernel(self, now=False, **kw):
"""Restarts a kernel with the arguments that were used to launch it.
Bernardo B. Marques
remove all trailling spaces
r4872
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 If the old kernel was launched with random ports, the same ports will be
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 used for the new kernel. The same connection file is used again.
Fernando Perez
Added kernel shutdown support: messaging spec, zmq and client code ready....
r2972
Parameters
----------
Fernando Perez
Rename 'instant_death' to 'now' as per code review.
r3030 now : bool, optional
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 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.
Fernando Perez
Added kernel shutdown support: messaging spec, zmq and client code ready....
r2972
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 In all cases the kernel is restarted, the only difference is whether
it is given a chance to perform a clean shutdown or not.
**kw : optional
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 Any options specified here will overwrite those used to launch the
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 kernel.
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 """
if self._launch_args is None:
raise RuntimeError("Cannot restart the kernel. "
"No previous call to 'start_kernel'.")
else:
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 # Stop currently running kernel.
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 self.shutdown_kernel(now=now, restart=True)
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784
# Start new kernel.
self._launch_args.update(kw)
epatters
* Fixed heartbeat thread not stopping cleanly....
r2915 self.start_kernel(**self._launch_args)
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851
epatters
Adding some temporary hacks to work around (Py)ZMQ bugs on Windows.
r2995 # FIXME: Messages get dropped in Windows due to probable ZMQ bug
# unless there is some delay here.
if sys.platform == 'win32':
time.sleep(0.2)
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686 @property
def has_kernel(self):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Has a kernel been started that we are managing."""
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 return self.kernel is not None
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686
Brian E. Granger
Make KernelManager.kill_kernel private....
r9130 def _kill_kernel(self):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Kill the running kernel.
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 This is a private method, callers should use shutdown_kernel(now=True).
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487 """
Brian Granger
Fixed inconsistent usage of has_kernel in KernelManager.
r3026 if self.has_kernel:
epatters
Integrated the heart beat pausing/unpausing logic with the (Qt)KernelManager.
r3032
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487 # Signal the kernel to terminate (sends SIGKILL on Unix and calls
# TerminateProcess() on Win32).
epatters
Safe kernel killing in Windows.
r3034 try:
self.kernel.kill()
Matthias BUSSONNIER
conform to pep 3110...
r7787 except OSError as e:
epatters
Safe kernel killing in Windows.
r3034 # In Windows, we will get an Access Denied error if the process
# has already terminated. Ignore it.
epatters
Handle Unix ESRCH errors gracefully in kill_kernel.
r3827 if sys.platform == 'win32':
if e.winerror != 5:
raise
# On Unix, we may get an ESRCH error if the process has already
# terminated. Ignore it.
else:
from errno import ESRCH
if e.errno != ESRCH:
raise
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
# Block until the kernel terminates.
self.kernel.wait()
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 self.kernel = None
epatters
Added 'start_listening' and 'stop_listening' methods to the kernel manager.
r2639 else:
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686 raise RuntimeError("Cannot kill kernel. No kernel is running!")
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
epatters
Implemented kernel interrupts for Windows.
r3027 def interrupt_kernel(self):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Interrupts the kernel by sending it a signal.
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
Unlike ``signal_kernel``, this operation is well supported on all
platforms.
epatters
Implemented kernel interrupts for Windows.
r3027 """
if self.has_kernel:
if sys.platform == 'win32':
Thomas Kluyver
Correct import for kernelmanager on Windows
r9487 from .zmq.parentpoller import ParentPollerWindows as Poller
epatters
Implemented kernel interrupts for Windows.
r3027 Poller.send_interrupt(self.kernel.win32_interrupt_event)
else:
self.kernel.send_signal(signal.SIGINT)
else:
raise RuntimeError("Cannot interrupt kernel. No kernel is running!")
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 def signal_kernel(self, signum):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Sends a signal to the kernel.
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
Note that since only SIGTERM is supported on Windows, this function is
only useful on Unix systems.
epatters
Implemented kernel interrupts for Windows.
r3027 """
Brian Granger
Fixed inconsistent usage of has_kernel in KernelManager.
r3026 if self.has_kernel:
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 self.kernel.send_signal(signum)
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686 else:
raise RuntimeError("Cannot signal kernel. No kernel is running!")
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 def is_alive(self):
"""Is the kernel process still running?"""
Brian Granger
Fixed inconsistent usage of has_kernel in KernelManager.
r3026 if self.has_kernel:
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 if self.kernel.poll() is None:
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 return True
else:
return False
else:
MinRK
split KernelManager into KernelManager + KernelClient
r10285 # we don't have a kernel
return False
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699
Brian Granger
Creating an ABC for kernel managers and channels.
r9121 #-----------------------------------------------------------------------------
# ABC Registration
#-----------------------------------------------------------------------------
Brian Granger
Added heartbeat support.
r2910
Brian Granger
Creating an ABC for kernel managers and channels.
r9121 KernelManagerABC.register(KernelManager)
MinRK
split KernelManager into KernelManager + KernelClient
r10285