| 1 |
"""Test kernel for signalling subprocesses""" |
| 2 |
|
| 3 |
# Copyright (c) Jupyter Development Team. |
| 4 |
# Distributed under the terms of the Modified BSD License. |
| 5 |
import os |
| 6 |
import signal |
| 7 |
import time |
| 8 |
from subprocess import PIPE, Popen |
| 9 |
|
| 10 |
from ipykernel.displayhook import ZMQDisplayHook |
| 11 |
from ipykernel.kernelapp import IPKernelApp |
| 12 |
from ipykernel.kernelbase import Kernel |
| 13 |
|
| 14 |
|
| 15 |
class SignalTestKernel(Kernel): |
| 16 |
"""Kernel for testing subprocess signaling""" |
| 17 |
|
| 18 |
implementation = "signaltest" |
| 19 |
implementation_version = "0.0" |
| 20 |
banner = "" |
| 21 |
|
| 22 |
def __init__(self, **kwargs): |
| 23 |
kwargs.pop("user_ns", None) |
| 24 |
super().__init__(**kwargs) |
| 25 |
self.children = [] |
| 26 |
|
| 27 |
if os.environ.get("NO_SIGTERM_REPLY", None) == "1": |
| 28 |
signal.signal(signal.SIGTERM, signal.SIG_IGN) |
| 29 |
|
| 30 |
async def shutdown_request(self, stream, ident, parent): |
| 31 |
if os.environ.get("NO_SHUTDOWN_REPLY") != "1": |
| 32 |
await super().shutdown_request(stream, ident, parent) |
| 33 |
|
| 34 |
def do_execute( |
| 35 |
self, code, silent, store_history=True, user_expressions=None, allow_stdin=False |
| 36 |
): |
| 37 |
code = code.strip() |
| 38 |
reply: dict = { |
| 39 |
"status": "ok", |
| 40 |
"user_expressions": {}, |
| 41 |
} |
| 42 |
if code == "start": |
| 43 |
child = Popen(["bash", "-i", "-c", "sleep 30"], stderr=PIPE) # noqa |
| 44 |
self.children.append(child) |
| 45 |
reply["user_expressions"]["pid"] = self.children[-1].pid |
| 46 |
elif code == "check": |
| 47 |
reply["user_expressions"]["poll"] = [child.poll() for child in self.children] |
| 48 |
elif code == "env": |
| 49 |
reply["user_expressions"]["env"] = os.getenv("TEST_VARS", "") |
| 50 |
elif code == "sleep": |
| 51 |
try: |
| 52 |
time.sleep(10) |
| 53 |
except KeyboardInterrupt: |
| 54 |
reply["user_expressions"]["interrupted"] = True |
| 55 |
else: |
| 56 |
reply["user_expressions"]["interrupted"] = False |
| 57 |
else: |
| 58 |
reply["status"] = "error" |
| 59 |
reply["ename"] = "Error" |
| 60 |
reply["evalue"] = code |
| 61 |
reply["traceback"] = ["no such command: %s" % code] |
| 62 |
return reply |
| 63 |
|
| 64 |
|
| 65 |
class SignalTestApp(IPKernelApp): |
| 66 |
kernel_class = SignalTestKernel # type:ignore[assignment] |
| 67 |
|
| 68 |
def init_io(self): |
| 69 |
# Overridden to disable stdout/stderr capture |
| 70 |
self.displayhook = ZMQDisplayHook(self.session, self.iopub_socket) |
| 71 |
|
| 72 |
|
| 73 |
if __name__ == "__main__": |
| 74 |
# make startup artificially slow, |
| 75 |
# so that we exercise client logic for slow-starting kernels |
| 76 |
time.sleep(2) |
| 77 |
SignalTestApp.launch_instance() |