| 1 |
"""A minimal application base mixin for all ZMQ based IPython frontends. |
| 2 |
|
| 3 |
This is not a complete console app, as subprocess will not be able to receive |
| 4 |
input, there is no real readline support, among other limitations. This is a |
| 5 |
refactoring of what used to be the IPython/qt/console/qtconsoleapp.py |
| 6 |
""" |
| 7 |
|
| 8 |
# Copyright (c) Jupyter Development Team. |
| 9 |
# Distributed under the terms of the Modified BSD License. |
| 10 |
import atexit |
| 11 |
import os |
| 12 |
import signal |
| 13 |
import sys |
| 14 |
import typing as t |
| 15 |
import uuid |
| 16 |
import warnings |
| 17 |
|
| 18 |
from jupyter_core.application import base_aliases, base_flags |
| 19 |
from traitlets import CBool, CUnicode, Dict, List, Type, Unicode |
| 20 |
from traitlets.config.application import boolean_flag |
| 21 |
|
| 22 |
from . import KernelManager, connect, find_connection_file, tunnel_to_kernel |
| 23 |
from .blocking import BlockingKernelClient |
| 24 |
from .connect import KernelConnectionInfo |
| 25 |
from .kernelspec import NoSuchKernel |
| 26 |
from .localinterfaces import localhost |
| 27 |
from .restarter import KernelRestarter |
| 28 |
from .session import Session |
| 29 |
from .utils import _filefind |
| 30 |
|
| 31 |
ConnectionFileMixin = connect.ConnectionFileMixin |
| 32 |
|
| 33 |
# ----------------------------------------------------------------------------- |
| 34 |
# Aliases and Flags |
| 35 |
# ----------------------------------------------------------------------------- |
| 36 |
|
| 37 |
flags: dict = {} |
| 38 |
flags.update(base_flags) |
| 39 |
# the flags that are specific to the frontend |
| 40 |
# these must be scrubbed before being passed to the kernel, |
| 41 |
# or it will raise an error on unrecognized flags |
| 42 |
app_flags: dict = { |
| 43 |
"existing": ( |
| 44 |
{"JupyterConsoleApp": {"existing": "kernel*.json"}}, |
| 45 |
"Connect to an existing kernel. If no argument specified, guess most recent", |
| 46 |
), |
| 47 |
} |
| 48 |
app_flags.update( |
| 49 |
boolean_flag( |
| 50 |
"confirm-exit", |
| 51 |
"JupyterConsoleApp.confirm_exit", |
| 52 |
"""Set to display confirmation dialog on exit. You can always use 'exit' or |
| 53 |
'quit', to force a direct exit without any confirmation. This can also |
| 54 |
be set in the config file by setting |
| 55 |
`c.JupyterConsoleApp.confirm_exit`. |
| 56 |
""", |
| 57 |
"""Don't prompt the user when exiting. This will terminate the kernel |
| 58 |
if it is owned by the frontend, and leave it alive if it is external. |
| 59 |
This can also be set in the config file by setting |
| 60 |
`c.JupyterConsoleApp.confirm_exit`. |
| 61 |
""", |
| 62 |
) |
| 63 |
) |
| 64 |
flags.update(app_flags) |
| 65 |
|
| 66 |
aliases: dict = {} |
| 67 |
aliases.update(base_aliases) |
| 68 |
|
| 69 |
# also scrub aliases from the frontend |
| 70 |
app_aliases: dict = { |
| 71 |
"ip": "JupyterConsoleApp.ip", |
| 72 |
"transport": "JupyterConsoleApp.transport", |
| 73 |
"hb": "JupyterConsoleApp.hb_port", |
| 74 |
"shell": "JupyterConsoleApp.shell_port", |
| 75 |
"iopub": "JupyterConsoleApp.iopub_port", |
| 76 |
"stdin": "JupyterConsoleApp.stdin_port", |
| 77 |
"control": "JupyterConsoleApp.control_port", |
| 78 |
"existing": "JupyterConsoleApp.existing", |
| 79 |
"f": "JupyterConsoleApp.connection_file", |
| 80 |
"kernel": "JupyterConsoleApp.kernel_name", |
| 81 |
"ssh": "JupyterConsoleApp.sshserver", |
| 82 |
"sshkey": "JupyterConsoleApp.sshkey", |
| 83 |
} |
| 84 |
aliases.update(app_aliases) |
| 85 |
|
| 86 |
# ----------------------------------------------------------------------------- |
| 87 |
# Classes |
| 88 |
# ----------------------------------------------------------------------------- |
| 89 |
|
| 90 |
classes: t.List[t.Type[t.Any]] = [KernelManager, KernelRestarter, Session] |
| 91 |
|
| 92 |
|
| 93 |
class JupyterConsoleApp(ConnectionFileMixin): |
| 94 |
"""The base Jupyter console application.""" |
| 95 |
|
| 96 |
name: t.Union[str, Unicode] = "jupyter-console-mixin" |
| 97 |
|
| 98 |
description: t.Union[str, Unicode] = """ |
| 99 |
The Jupyter Console Mixin. |
| 100 |
|
| 101 |
This class contains the common portions of console client (QtConsole, |
| 102 |
ZMQ-based terminal console, etc). It is not a full console, in that |
| 103 |
launched terminal subprocesses will not be able to accept input. |
| 104 |
|
| 105 |
The Console using this mixing supports various extra features beyond |
| 106 |
the single-process Terminal IPython shell, such as connecting to |
| 107 |
existing kernel, via: |
| 108 |
|
| 109 |
jupyter console <appname> --existing |
| 110 |
|
| 111 |
as well as tunnel via SSH |
| 112 |
|
| 113 |
""" |
| 114 |
|
| 115 |
classes = classes |
| 116 |
flags = Dict(flags) |
| 117 |
aliases = Dict(aliases) |
| 118 |
kernel_manager_class = Type( |
| 119 |
default_value=KernelManager, |
| 120 |
config=True, |
| 121 |
help="The kernel manager class to use.", |
| 122 |
) |
| 123 |
kernel_client_class = BlockingKernelClient |
| 124 |
|
| 125 |
kernel_argv = List(Unicode()) |
| 126 |
|
| 127 |
# connection info: |
| 128 |
|
| 129 |
sshserver = Unicode("", config=True, help="""The SSH server to use to connect to the kernel.""") |
| 130 |
sshkey = Unicode( |
| 131 |
"", |
| 132 |
config=True, |
| 133 |
help="""Path to the ssh key to use for logging in to the ssh server.""", |
| 134 |
) |
| 135 |
|
| 136 |
def _connection_file_default(self) -> str: |
| 137 |
return "kernel-%i.json" % os.getpid() |
| 138 |
|
| 139 |
existing = CUnicode("", config=True, help="""Connect to an already running kernel""") |
| 140 |
|
| 141 |
kernel_name = Unicode( |
| 142 |
"python", config=True, help="""The name of the default kernel to start.""" |
| 143 |
) |
| 144 |
|
| 145 |
confirm_exit = CBool( |
| 146 |
True, |
| 147 |
config=True, |
| 148 |
help=""" |
| 149 |
Set to display confirmation dialog on exit. You can always use 'exit' or 'quit', |
| 150 |
to force a direct exit without any confirmation.""", |
| 151 |
) |
| 152 |
|
| 153 |
def build_kernel_argv(self, argv: object = None) -> None: |
| 154 |
"""build argv to be passed to kernel subprocess |
| 155 |
|
| 156 |
Override in subclasses if any args should be passed to the kernel |
| 157 |
""" |
| 158 |
self.kernel_argv = self.extra_args # type:ignore[attr-defined] |
| 159 |
|
| 160 |
def init_connection_file(self) -> None: |
| 161 |
"""find the connection file, and load the info if found. |
| 162 |
|
| 163 |
The current working directory and the current profile's security |
| 164 |
directory will be searched for the file if it is not given by |
| 165 |
absolute path. |
| 166 |
|
| 167 |
When attempting to connect to an existing kernel and the `--existing` |
| 168 |
argument does not match an existing file, it will be interpreted as a |
| 169 |
fileglob, and the matching file in the current profile's security dir |
| 170 |
with the latest access time will be used. |
| 171 |
|
| 172 |
After this method is called, self.connection_file contains the *full path* |
| 173 |
to the connection file, never just its name. |
| 174 |
""" |
| 175 |
runtime_dir = self.runtime_dir # type:ignore[attr-defined] |
| 176 |
if self.existing: |
| 177 |
try: |
| 178 |
cf = find_connection_file(self.existing, [".", runtime_dir]) |
| 179 |
except Exception: |
| 180 |
self.log.critical( |
| 181 |
"Could not find existing kernel connection file %s", self.existing |
| 182 |
) |
| 183 |
self.exit(1) # type:ignore[attr-defined] |
| 184 |
self.log.debug("Connecting to existing kernel: %s", cf) |
| 185 |
self.connection_file = cf |
| 186 |
else: |
| 187 |
# not existing, check if we are going to write the file |
| 188 |
# and ensure that self.connection_file is a full path, not just the shortname |
| 189 |
try: |
| 190 |
cf = find_connection_file(self.connection_file, [runtime_dir]) |
| 191 |
except Exception: |
| 192 |
# file might not exist |
| 193 |
if self.connection_file == os.path.basename(self.connection_file): |
| 194 |
# just shortname, put it in security dir |
| 195 |
cf = os.path.join(runtime_dir, self.connection_file) |
| 196 |
else: |
| 197 |
cf = self.connection_file |
| 198 |
self.connection_file = cf |
| 199 |
try: |
| 200 |
self.connection_file = _filefind(self.connection_file, [".", runtime_dir]) |
| 201 |
except OSError: |
| 202 |
self.log.debug("Connection File not found: %s", self.connection_file) |
| 203 |
return |
| 204 |
|
| 205 |
# should load_connection_file only be used for existing? |
| 206 |
# as it is now, this allows reusing ports if an existing |
| 207 |
# file is requested |
| 208 |
try: |
| 209 |
self.load_connection_file() |
| 210 |
except Exception: |
| 211 |
self.log.error( |
| 212 |
"Failed to load connection file: %r", |
| 213 |
self.connection_file, |
| 214 |
exc_info=True, |
| 215 |
) |
| 216 |
self.exit(1) # type:ignore[attr-defined] |
| 217 |
|
| 218 |
def init_ssh(self) -> None: |
| 219 |
"""set up ssh tunnels, if needed.""" |
| 220 |
if not self.existing or (not self.sshserver and not self.sshkey): |
| 221 |
return |
| 222 |
self.load_connection_file() |
| 223 |
|
| 224 |
transport = self.transport |
| 225 |
ip = self.ip |
| 226 |
|
| 227 |
if transport != "tcp": |
| 228 |
self.log.error("Can only use ssh tunnels with TCP sockets, not %s", transport) |
| 229 |
sys.exit(-1) |
| 230 |
|
| 231 |
if self.sshkey and not self.sshserver: |
| 232 |
# specifying just the key implies that we are connecting directly |
| 233 |
self.sshserver = ip |
| 234 |
ip = localhost() |
| 235 |
|
| 236 |
# build connection dict for tunnels: |
| 237 |
info: KernelConnectionInfo = { |
| 238 |
"ip": ip, |
| 239 |
"shell_port": self.shell_port, |
| 240 |
"iopub_port": self.iopub_port, |
| 241 |
"stdin_port": self.stdin_port, |
| 242 |
"hb_port": self.hb_port, |
| 243 |
"control_port": self.control_port, |
| 244 |
} |
| 245 |
|
| 246 |
self.log.info("Forwarding connections to %s via %s", ip, self.sshserver) |
| 247 |
|
| 248 |
# tunnels return a new set of ports, which will be on localhost: |
| 249 |
self.ip = localhost() |
| 250 |
try: |
| 251 |
newports = tunnel_to_kernel(info, self.sshserver, self.sshkey) |
| 252 |
except: # noqa |
| 253 |
# even catch KeyboardInterrupt |
| 254 |
self.log.error("Could not setup tunnels", exc_info=True) |
| 255 |
self.exit(1) # type:ignore[attr-defined] |
| 256 |
|
| 257 |
( |
| 258 |
self.shell_port, |
| 259 |
self.iopub_port, |
| 260 |
self.stdin_port, |
| 261 |
self.hb_port, |
| 262 |
self.control_port, |
| 263 |
) = newports |
| 264 |
|
| 265 |
cf = self.connection_file |
| 266 |
root, ext = os.path.splitext(cf) |
| 267 |
self.connection_file = root + "-ssh" + ext |
| 268 |
self.write_connection_file() # write the new connection file |
| 269 |
self.log.info("To connect another client via this tunnel, use:") |
| 270 |
self.log.info("--existing %s", os.path.basename(self.connection_file)) |
| 271 |
|
| 272 |
def _new_connection_file(self) -> str: |
| 273 |
cf = "" |
| 274 |
while not cf: |
| 275 |
# we don't need a 128b id to distinguish kernels, use more readable |
| 276 |
# 48b node segment (12 hex chars). Users running more than 32k simultaneous |
| 277 |
# kernels can subclass. |
| 278 |
ident = str(uuid.uuid4()).split("-")[-1] |
| 279 |
runtime_dir = self.runtime_dir # type:ignore[attr-defined] |
| 280 |
cf = os.path.join(runtime_dir, "kernel-%s.json" % ident) |
| 281 |
# only keep if it's actually new. Protect against unlikely collision |
| 282 |
# in 48b random search space |
| 283 |
cf = cf if not os.path.exists(cf) else "" |
| 284 |
return cf |
| 285 |
|
| 286 |
def init_kernel_manager(self) -> None: |
| 287 |
"""Initialize the kernel manager.""" |
| 288 |
# Don't let Qt or ZMQ swallow KeyboardInterupts. |
| 289 |
if self.existing: |
| 290 |
self.kernel_manager = None |
| 291 |
return |
| 292 |
signal.signal(signal.SIGINT, signal.SIG_DFL) |
| 293 |
|
| 294 |
# Create a KernelManager and start a kernel. |
| 295 |
try: |
| 296 |
self.kernel_manager = self.kernel_manager_class( |
| 297 |
ip=self.ip, |
| 298 |
session=self.session, |
| 299 |
transport=self.transport, |
| 300 |
shell_port=self.shell_port, |
| 301 |
iopub_port=self.iopub_port, |
| 302 |
stdin_port=self.stdin_port, |
| 303 |
hb_port=self.hb_port, |
| 304 |
control_port=self.control_port, |
| 305 |
connection_file=self.connection_file, |
| 306 |
kernel_name=self.kernel_name, |
| 307 |
parent=self, |
| 308 |
data_dir=self.data_dir, |
| 309 |
) |
| 310 |
# access kernel_spec to ensure the NoSuchKernel error is raised |
| 311 |
# if it's going to be |
| 312 |
kernel_spec = self.kernel_manager.kernel_spec # noqa: F841 |
| 313 |
except NoSuchKernel: |
| 314 |
self.log.critical("Could not find kernel %r", self.kernel_name) |
| 315 |
self.exit(1) # type:ignore[attr-defined] |
| 316 |
|
| 317 |
self.kernel_manager = t.cast(KernelManager, self.kernel_manager) |
| 318 |
self.kernel_manager.client_factory = self.kernel_client_class |
| 319 |
kwargs = {} |
| 320 |
kwargs["extra_arguments"] = self.kernel_argv |
| 321 |
self.kernel_manager.start_kernel(**kwargs) |
| 322 |
atexit.register(self.kernel_manager.cleanup_ipc_files) |
| 323 |
|
| 324 |
if self.sshserver: |
| 325 |
# ssh, write new connection file |
| 326 |
self.kernel_manager.write_connection_file() |
| 327 |
|
| 328 |
# in case KM defaults / ssh writing changes things: |
| 329 |
km = self.kernel_manager |
| 330 |
self.shell_port = km.shell_port |
| 331 |
self.iopub_port = km.iopub_port |
| 332 |
self.stdin_port = km.stdin_port |
| 333 |
self.hb_port = km.hb_port |
| 334 |
self.control_port = km.control_port |
| 335 |
self.connection_file = km.connection_file |
| 336 |
|
| 337 |
atexit.register(self.kernel_manager.cleanup_connection_file) |
| 338 |
|
| 339 |
def init_kernel_client(self) -> None: |
| 340 |
"""Initialize the kernel client.""" |
| 341 |
if self.kernel_manager is not None: |
| 342 |
self.kernel_client = self.kernel_manager.client() |
| 343 |
else: |
| 344 |
self.kernel_client = self.kernel_client_class( |
| 345 |
session=self.session, |
| 346 |
ip=self.ip, |
| 347 |
transport=self.transport, |
| 348 |
shell_port=self.shell_port, |
| 349 |
iopub_port=self.iopub_port, |
| 350 |
stdin_port=self.stdin_port, |
| 351 |
hb_port=self.hb_port, |
| 352 |
control_port=self.control_port, |
| 353 |
connection_file=self.connection_file, |
| 354 |
parent=self, |
| 355 |
) |
| 356 |
|
| 357 |
self.kernel_client.start_channels() |
| 358 |
|
| 359 |
def initialize(self, argv: object = None) -> None: |
| 360 |
""" |
| 361 |
Classes which mix this class in should call: |
| 362 |
JupyterConsoleApp.initialize(self,argv) |
| 363 |
""" |
| 364 |
if getattr(self, "_dispatching", False): |
| 365 |
return |
| 366 |
self.init_connection_file() |
| 367 |
self.init_ssh() |
| 368 |
self.init_kernel_manager() |
| 369 |
self.init_kernel_client() |
| 370 |
|
| 371 |
|
| 372 |
class IPythonConsoleApp(JupyterConsoleApp): |
| 373 |
"""An app to manage an ipython console.""" |
| 374 |
|
| 375 |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: |
| 376 |
"""Initialize the app.""" |
| 377 |
warnings.warn("IPythonConsoleApp is deprecated. Use JupyterConsoleApp", stacklevel=2) |
| 378 |
super().__init__(*args, **kwargs) |