Debian Codegraph @

tests/test_restarter.py

raw
1 """Tests for the KernelManager"""
2
3 # Copyright (c) Jupyter Development Team.
4 # Distributed under the terms of the Modified BSD License.
5 import asyncio
6 import json
7 import os
8 import sys
9 from concurrent.futures import Future
10
11 import pytest
12 from jupyter_core import paths
13 from traitlets.config.loader import Config
14 from traitlets.log import get_logger
15
16 from jupyter_client.ioloop import AsyncIOLoopKernelManager, IOLoopKernelManager
17
18 pjoin = os.path.join
19
20
21 def _install_kernel(name="problemtest", extra_env=None):
22 if extra_env is None:
23 extra_env = {}
24 kernel_dir = pjoin(paths.jupyter_data_dir(), "kernels", name)
25 os.makedirs(kernel_dir)
26 with open(pjoin(kernel_dir, "kernel.json"), "w") as f:
27 f.write(
28 json.dumps(
29 {
30 "argv": [
31 sys.executable,
32 "-m",
33 "tests.problemkernel",
34 "-f",
35 "{connection_file}",
36 ],
37 "display_name": "Problematic Test Kernel",
38 "env": {"TEST_VARS": "${TEST_VARS}:test_var_2", **extra_env},
39 }
40 )
41 )
42 return name
43
44
45 @pytest.fixture
46 def install_kernel():
47 return _install_kernel("problemtest")
48
49
50 @pytest.fixture
51 def install_fail_kernel():
52 return _install_kernel("problemtest-fail", extra_env={"FAIL_ON_START": "1"})
53
54
55 @pytest.fixture
56 def install_slow_fail_kernel():
57 return _install_kernel(
58 "problemtest-slow", extra_env={"STARTUP_DELAY": "5", "FAIL_ON_START": "1"}
59 )
60
61
62 @pytest.fixture(params=["tcp", "ipc"])
63 def transport(request):
64 if sys.platform == "win32" and request.param == "ipc": #
65 pytest.skip("Transport 'ipc' not supported on Windows.")
66 return request.param
67
68
69 @pytest.fixture
70 def config(transport):
71 c = Config()
72 c.KernelManager.transport = transport
73 if transport == "ipc":
74 c.KernelManager.ip = "test"
75 return c
76
77
78 @pytest.fixture
79 def debug_logging():
80 get_logger().setLevel("DEBUG")
81
82
83 win_skip = pytest.mark.skipif(
84 os.name == "nt",
85 reason='"RuntimeError: Cannot run the event loop while another loop is running" error on Windows',
86 )
87
88
89 @win_skip
90 async def test_restart_check(config, install_kernel, debug_logging):
91 """Test that the kernel is restarted and recovers"""
92 # If this test fails, run it with --log-cli-level=DEBUG to inspect
93 N_restarts = 1
94 config.KernelRestarter.restart_limit = N_restarts
95 config.KernelRestarter.debug = True
96 km = IOLoopKernelManager(kernel_name=install_kernel, config=config)
97
98 cbs = 0
99 restarts: list = [Future() for i in range(N_restarts)]
100
101 def cb():
102 nonlocal cbs
103 if cbs >= N_restarts:
104 raise RuntimeError("Kernel restarted more than %d times!" % N_restarts)
105 restarts[cbs].set_result(True)
106 cbs += 1
107
108 try:
109 km.start_kernel()
110 km.add_restart_callback(cb, "restart")
111 except BaseException:
112 if km.has_kernel:
113 km.shutdown_kernel()
114 raise
115
116 try:
117 for i in range(N_restarts + 1):
118 kc = km.client()
119 kc.start_channels()
120 kc.wait_for_ready(timeout=60)
121 kc.stop_channels()
122 if i < N_restarts:
123 # Kill without cleanup to simulate crash:
124 assert km.provisioner is not None
125 await km.provisioner.kill()
126 restarts[i].result()
127 # Wait for kill + restart
128 max_wait = 10.0
129 waited = 0.0
130 while waited < max_wait and km.is_alive():
131 await asyncio.sleep(0.1)
132 waited += 0.1
133 while waited < max_wait and not km.is_alive():
134 await asyncio.sleep(0.1)
135 waited += 0.1
136
137 assert cbs == N_restarts
138 assert km.is_alive()
139
140 finally:
141 km.shutdown_kernel(now=True)
142 assert km.context.closed
143
144
145 @win_skip
146 async def test_restarter_gives_up(config, install_fail_kernel, debug_logging):
147 """Test that the restarter gives up after reaching the restart limit"""
148 # If this test fails, run it with --log-cli-level=DEBUG to inspect
149 N_restarts = 1
150 config.KernelRestarter.restart_limit = N_restarts
151 config.KernelRestarter.debug = True
152 km = IOLoopKernelManager(kernel_name=install_fail_kernel, config=config)
153
154 cbs = 0
155 restarts: list = [Future() for i in range(N_restarts)]
156
157 def cb():
158 nonlocal cbs
159 if cbs >= N_restarts:
160 raise RuntimeError("Kernel restarted more than %d times!" % N_restarts)
161 restarts[cbs].set_result(True)
162 cbs += 1
163
164 died: Future = Future()
165
166 def on_death():
167 died.set_result(True)
168
169 try:
170 km.start_kernel()
171 km.add_restart_callback(cb, "restart")
172 km.add_restart_callback(on_death, "dead")
173 except BaseException:
174 if km.has_kernel:
175 km.shutdown_kernel()
176 raise
177
178 try:
179 for i in range(N_restarts):
180 restarts[i].result()
181
182 assert died.result()
183 assert cbs == N_restarts
184
185 finally:
186 km.shutdown_kernel(now=True)
187 assert km.context.closed
188
189
190 async def test_async_restart_check(config, install_kernel, debug_logging):
191 """Test that the kernel is restarted and recovers"""
192 # If this test fails, run it with --log-cli-level=DEBUG to inspect
193 N_restarts = 1
194 config.KernelRestarter.restart_limit = N_restarts
195 config.KernelRestarter.debug = True
196 km = AsyncIOLoopKernelManager(kernel_name=install_kernel, config=config)
197
198 cbs = 0
199 restarts: list = [asyncio.Future() for i in range(N_restarts)]
200
201 def cb():
202 nonlocal cbs
203 if cbs >= N_restarts:
204 raise RuntimeError("Kernel restarted more than %d times!" % N_restarts)
205 restarts[cbs].set_result(True)
206 cbs += 1
207
208 try:
209 await km.start_kernel()
210 km.add_restart_callback(cb, "restart")
211 except BaseException:
212 if km.has_kernel:
213 await km.shutdown_kernel()
214 raise
215
216 try:
217 for i in range(N_restarts + 1):
218 kc = km.client()
219 kc.start_channels()
220 await kc.wait_for_ready(timeout=60)
221 kc.stop_channels()
222 if i < N_restarts:
223 # Kill without cleanup to simulate crash:
224 assert km.provisioner is not None
225 await km.provisioner.kill()
226 await restarts[i]
227 # Wait for kill + restart
228 max_wait = 10.0
229 waited = 0.0
230 while waited < max_wait and await km.is_alive():
231 await asyncio.sleep(0.1)
232 waited += 0.1
233 while waited < max_wait and not await km.is_alive():
234 await asyncio.sleep(0.1)
235 waited += 0.1
236
237 assert cbs == N_restarts
238 assert await km.is_alive()
239
240 finally:
241 await km.shutdown_kernel(now=True)
242 assert km.context.closed
243
244
245 async def test_async_restarter_gives_up(config, install_slow_fail_kernel, debug_logging):
246 """Test that the restarter gives up after reaching the restart limit"""
247 # If this test fails, run it with --log-cli-level=DEBUG to inspect
248 N_restarts = 2
249 config.KernelRestarter.restart_limit = N_restarts
250 config.KernelRestarter.debug = True
251 config.KernelRestarter.stable_start_time = 30.0
252 km = AsyncIOLoopKernelManager(kernel_name=install_slow_fail_kernel, config=config)
253
254 cbs = 0
255 restarts: list = [asyncio.Future() for i in range(N_restarts)]
256
257 def cb():
258 nonlocal cbs
259 if cbs >= N_restarts:
260 raise RuntimeError("Kernel restarted more than %d times!" % N_restarts)
261 restarts[cbs].set_result(True)
262 cbs += 1
263
264 died: asyncio.Future = asyncio.Future()
265
266 def on_death():
267 died.set_result(True)
268
269 try:
270 await km.start_kernel()
271 km.add_restart_callback(cb, "restart")
272 km.add_restart_callback(on_death, "dead")
273 except BaseException:
274 if km.has_kernel:
275 await km.shutdown_kernel()
276 raise
277
278 try:
279 await asyncio.gather(*restarts)
280
281 assert await died
282 assert cbs == N_restarts
283
284 finally:
285 await km.shutdown_kernel(now=True)
286 assert km.context.closed