Debian Codegraph @

jupyter_client/restarter.py

raw
1 """A basic kernel monitor with autorestarting.
2
3 This watches a kernel's state using KernelManager.is_alive and auto
4 restarts the kernel if it dies.
5
6 It is an incomplete base class, and must be subclassed.
7 """
8
9 # Copyright (c) Jupyter Development Team.
10 # Distributed under the terms of the Modified BSD License.
11 from __future__ import annotations
12
13 import time
14 import typing as t
15
16 from traitlets import Bool, Dict, Float, Instance, Integer, default
17 from traitlets.config.configurable import LoggingConfigurable
18
19
20 class KernelRestarter(LoggingConfigurable):
21 """Monitor and autorestart a kernel."""
22
23 kernel_manager = Instance("jupyter_client.KernelManager")
24
25 debug = Bool(
26 False,
27 config=True,
28 help="""Whether to include every poll event in debugging output.
29
30 Has to be set explicitly, because there will be *a lot* of output.
31 """,
32 )
33
34 time_to_dead = Float(3.0, config=True, help="""Kernel heartbeat interval in seconds.""")
35
36 stable_start_time = Float(
37 10.0,
38 config=True,
39 help="""The time in seconds to consider the kernel to have completed a stable start up.""",
40 )
41
42 restart_limit = Integer(
43 5,
44 config=True,
45 help="""The number of consecutive autorestarts before the kernel is presumed dead.""",
46 )
47
48 random_ports_until_alive = Bool(
49 True,
50 config=True,
51 help="""Whether to choose new random ports when restarting before the kernel is alive.""",
52 )
53 _restarting = Bool(False)
54 _restart_count = Integer(0)
55 _initial_startup = Bool(True)
56 _last_dead = Float()
57
58 @default("_last_dead")
59 def _default_last_dead(self) -> float:
60 return time.time()
61
62 callbacks = Dict()
63
64 def _callbacks_default(self) -> dict[str, list]:
65 return {"restart": [], "dead": []}
66
67 def start(self) -> None:
68 """Start the polling of the kernel."""
69 msg = "Must be implemented in a subclass"
70 raise NotImplementedError(msg)
71
72 def stop(self) -> None:
73 """Stop the kernel polling."""
74 msg = "Must be implemented in a subclass"
75 raise NotImplementedError(msg)
76
77 def add_callback(self, f: t.Callable[..., t.Any], event: str = "restart") -> None:
78 """register a callback to fire on a particular event
79
80 Possible values for event:
81
82 'restart' (default): kernel has died, and will be restarted.
83 'dead': restart has failed, kernel will be left dead.
84
85 """
86 self.callbacks[event].append(f)
87
88 def remove_callback(self, f: t.Callable[..., t.Any], event: str = "restart") -> None:
89 """unregister a callback to fire on a particular event
90
91 Possible values for event:
92
93 'restart' (default): kernel has died, and will be restarted.
94 'dead': restart has failed, kernel will be left dead.
95
96 """
97 try:
98 self.callbacks[event].remove(f)
99 except ValueError:
100 pass
101
102 def _fire_callbacks(self, event: t.Any) -> None:
103 """fire our callbacks for a particular event"""
104 for callback in self.callbacks[event]:
105 try:
106 callback()
107 except Exception:
108 self.log.error(
109 "KernelRestarter: %s callback %r failed",
110 event,
111 callback,
112 exc_info=True,
113 )
114
115 def poll(self) -> None:
116 if self.debug:
117 self.log.debug("Polling kernel...")
118 if self.kernel_manager.shutting_down:
119 self.log.debug("Kernel shutdown in progress...")
120 return
121 now = time.time()
122 if not self.kernel_manager.is_alive():
123 self._last_dead = now
124 if self._restarting:
125 self._restart_count += 1
126 else:
127 self._restart_count = 1
128
129 if self._restart_count > self.restart_limit:
130 self.log.warning("KernelRestarter: restart failed")
131 self._fire_callbacks("dead")
132 self._restarting = False
133 self._restart_count = 0
134 self.stop()
135 else:
136 newports = self.random_ports_until_alive and self._initial_startup
137 self.log.info(
138 "KernelRestarter: restarting kernel (%i/%i), %s random ports",
139 self._restart_count,
140 self.restart_limit,
141 "new" if newports else "keep",
142 )
143 self._fire_callbacks("restart")
144 self.kernel_manager.restart_kernel(now=True, newports=newports)
145 self._restarting = True
146 else:
147 # Since `is_alive` only tests that the kernel process is alive, it does not
148 # indicate that the kernel has successfully completed startup. To solve this
149 # correctly, we would need to wait for a kernel info reply, but it is not
150 # necessarily appropriate to start a kernel client + channels in the
151 # restarter. Therefore, we use "has been alive continuously for X time" as a
152 # heuristic for a stable start up.
153 # See https://github.com/jupyter/jupyter_client/pull/717 for details.
154 stable_start_time = self.stable_start_time
155 if self.kernel_manager.provisioner:
156 stable_start_time = self.kernel_manager.provisioner.get_stable_start_time(
157 recommended=stable_start_time
158 )
159 if self._initial_startup and now - self._last_dead >= stable_start_time:
160 self._initial_startup = False
161 if self._restarting and now - self._last_dead >= stable_start_time:
162 self.log.debug("KernelRestarter: restart apparently succeeded")
163 self._restarting = False