Skip to content

Commit b733e64

Browse files
authored
fix: Exit 0 on SIGTERM while serving (#430)
* fix: Exit 0 on SIGTERM while serving * fix: Bound shutdown when an RPC handler is blocked * fix: Keep output flushing from blocking forced exit
1 parent 5391577 commit b733e64

2 files changed

Lines changed: 237 additions & 1 deletion

File tree

‎cloudquery/sdk/serve/plugin.py‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44
import logging
55
import os
66
import shutil
7+
import signal
78
import subprocess
89
import tarfile
10+
import threading
11+
import time
912
from concurrent import futures
1013
from pathlib import Path
1114

@@ -24,6 +27,9 @@
2427
from cloudquery.sdk.schema import table
2528

2629
_IS_WINDOWS = sys.platform == "win32"
30+
_STOP_GRACE_SECONDS = 5
31+
_FORCED_EXIT_DELAY_SECONDS = 5
32+
_FORCED_EXIT_FLUSH_TIMEOUT_SECONDS = 1
2733

2834
try:
2935
import colorama
@@ -401,7 +407,41 @@ def _serve(self, args):
401407
self._server.add_insecure_port(args.address)
402408
logger.info("Starting server", address=args.address)
403409
self._server.start()
410+
self._stop_on_termination_signals()
404411
self._server.wait_for_termination()
405412

413+
def _stop_on_termination_signals(self):
414+
if threading.current_thread() is not threading.main_thread():
415+
return
416+
self._termination_requested = False
417+
for signum in (signal.SIGTERM, signal.SIGINT):
418+
signal.signal(signum, self._on_termination_signal)
419+
420+
def _on_termination_signal(self, signum, frame):
421+
if self._termination_requested:
422+
_exit_now()
423+
self._termination_requested = True
424+
threading.Thread(target=self._stop_then_force_exit, daemon=True).start()
425+
426+
def _stop_then_force_exit(self):
427+
self.stop().wait()
428+
time.sleep(_FORCED_EXIT_DELAY_SECONDS)
429+
_exit_now()
430+
406431
def stop(self):
407-
self._server.stop(5)
432+
return self._server.stop(_STOP_GRACE_SECONDS)
433+
434+
435+
def _exit_now():
436+
flusher = threading.Thread(target=_flush_output_streams, daemon=True)
437+
flusher.start()
438+
flusher.join(_FORCED_EXIT_FLUSH_TIMEOUT_SECONDS)
439+
os._exit(0)
440+
441+
442+
def _flush_output_streams():
443+
for stream in (sys.stdout, sys.stderr):
444+
try:
445+
stream.flush()
446+
except Exception:
447+
pass

‎tests/serve/signals.py‎

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
import signal
2+
import socket
3+
import subprocess
4+
import sys
5+
import textwrap
6+
import time
7+
8+
import grpc
9+
import pytest
10+
11+
from cloudquery.plugin_v3 import plugin_pb2, plugin_pb2_grpc
12+
13+
SERVE_PLUGIN = """
14+
from cloudquery.sdk import serve
15+
from cloudquery.sdk.plugin import Plugin
16+
17+
serve.PluginCommand(Plugin("test", "v0.0.1")).run(["serve", "--address", "127.0.0.1:0"])
18+
"""
19+
20+
SERVE_PLUGIN_WITH_BLOCKED_INIT = """
21+
import sys, threading
22+
from cloudquery.sdk import serve
23+
from cloudquery.sdk.plugin import Plugin
24+
25+
class BlockedInitPlugin(Plugin):
26+
def init(self, spec, no_connection=False):
27+
threading.Event().wait()
28+
29+
serve.PluginCommand(BlockedInitPlugin("test", "v0.0.1")).run(["serve", "--address", sys.argv[1]])
30+
"""
31+
32+
SERVE_PLUGIN_WITH_INIT_FLOODING_STDOUT = """
33+
import sys
34+
from cloudquery.sdk import serve
35+
from cloudquery.sdk.plugin import Plugin
36+
37+
class FloodingInitPlugin(Plugin):
38+
def init(self, spec, no_connection=False):
39+
while True:
40+
sys.stdout.write("x" * 1024)
41+
42+
serve.PluginCommand(FloodingInitPlugin("test", "v0.0.1")).run(["serve", "--address", sys.argv[1]])
43+
"""
44+
45+
SERVE_PLUGIN_WITH_INIT_BLOCKED_ON_BUFFERED_STDOUT = """
46+
import sys, threading
47+
from cloudquery.sdk import serve
48+
from cloudquery.sdk.plugin import Plugin
49+
50+
class BufferedInitPlugin(Plugin):
51+
def init(self, spec, no_connection=False):
52+
sys.stdout.write("buffered and never flushed")
53+
threading.Event().wait()
54+
55+
serve.PluginCommand(BufferedInitPlugin("test", "v0.0.1")).run(["serve", "--address", sys.argv[1]])
56+
"""
57+
58+
SIGTERM_DURING_LOCK_RESTORE = """
59+
import os, signal, sys, threading
60+
from cloudquery.sdk import serve
61+
from cloudquery.sdk.plugin import Plugin
62+
63+
def signal_handler(sig, frame):
64+
sys.exit(0)
65+
66+
signal.signal(signal.SIGTERM, signal_handler)
67+
68+
_orig = threading.Condition._acquire_restore
69+
_fired = threading.Event()
70+
71+
def _acquire_restore(self, x):
72+
if threading.current_thread() is threading.main_thread() and not _fired.is_set():
73+
_fired.set()
74+
os.kill(os.getpid(), signal.SIGTERM)
75+
return _orig(self, x)
76+
77+
threading.Timer(1.0, lambda: setattr(threading.Condition, "_acquire_restore", _acquire_restore)).start()
78+
79+
serve.PluginCommand(Plugin("test", "v0.0.1")).run(["serve", "--address", "127.0.0.1:0"])
80+
"""
81+
82+
83+
def start_plugin(tmp_path, source, *args):
84+
script = tmp_path / "plugin_main.py"
85+
script.write_text(textwrap.dedent(source))
86+
return subprocess.Popen(
87+
[sys.executable, str(script), *args],
88+
stdout=subprocess.PIPE,
89+
stderr=subprocess.STDOUT,
90+
text=True,
91+
)
92+
93+
94+
def wait_until_serving(process):
95+
for line in process.stdout:
96+
if "Starting server" in line:
97+
time.sleep(0.5)
98+
return
99+
pytest.fail("plugin exited before it started serving")
100+
101+
102+
def test_sigterm_during_lock_restore_exits_zero(tmp_path):
103+
process = start_plugin(tmp_path, SIGTERM_DURING_LOCK_RESTORE)
104+
output, _ = process.communicate(timeout=30)
105+
assert process.returncode == 0, output
106+
107+
108+
@pytest.mark.parametrize("signum", [signal.SIGTERM, signal.SIGINT])
109+
def test_signal_while_serving_exits_zero(tmp_path, signum):
110+
process = start_plugin(tmp_path, SERVE_PLUGIN)
111+
wait_until_serving(process)
112+
process.send_signal(signum)
113+
output, _ = process.communicate(timeout=30)
114+
assert process.returncode == 0, output
115+
116+
117+
def free_address():
118+
with socket.socket() as sock:
119+
sock.bind(("127.0.0.1", 0))
120+
return "127.0.0.1:%d" % sock.getsockname()[1]
121+
122+
123+
def start_plugin_with_blocked_init(tmp_path, source=SERVE_PLUGIN_WITH_BLOCKED_INIT):
124+
address = free_address()
125+
process = start_plugin(tmp_path, source, address)
126+
wait_until_serving(process)
127+
channel = grpc.insecure_channel(address)
128+
init_call = plugin_pb2_grpc.PluginStub(channel).Init.future(
129+
plugin_pb2.Init.Request(spec=b"")
130+
)
131+
time.sleep(0.5)
132+
return process, channel, init_call
133+
134+
135+
def test_sigterm_with_blocked_handler_exits_zero_within_bound(tmp_path):
136+
process, channel, init_call = start_plugin_with_blocked_init(tmp_path)
137+
try:
138+
process.send_signal(signal.SIGTERM)
139+
output, _ = process.communicate(timeout=20)
140+
assert process.returncode == 0, output
141+
finally:
142+
init_call.cancel()
143+
channel.close()
144+
process.kill()
145+
146+
147+
def test_second_signal_with_blocked_handler_exits_zero_immediately(tmp_path):
148+
process, channel, init_call = start_plugin_with_blocked_init(tmp_path)
149+
try:
150+
process.send_signal(signal.SIGTERM)
151+
time.sleep(0.5)
152+
process.send_signal(signal.SIGINT)
153+
output, _ = process.communicate(timeout=3)
154+
assert process.returncode == 0, output
155+
finally:
156+
init_call.cancel()
157+
channel.close()
158+
process.kill()
159+
160+
161+
def send_termination_signals(process, second_signal):
162+
process.send_signal(signal.SIGTERM)
163+
if second_signal:
164+
time.sleep(0.5)
165+
process.send_signal(signal.SIGINT)
166+
return 3
167+
return 20
168+
169+
170+
@pytest.mark.parametrize("second_signal", [False, True])
171+
def test_forced_exit_with_full_stdout_pipe_exits_zero(tmp_path, second_signal):
172+
process, channel, init_call = start_plugin_with_blocked_init(
173+
tmp_path, SERVE_PLUGIN_WITH_INIT_FLOODING_STDOUT
174+
)
175+
try:
176+
timeout = send_termination_signals(process, second_signal)
177+
assert process.wait(timeout=timeout) == 0
178+
finally:
179+
init_call.cancel()
180+
channel.close()
181+
process.kill()
182+
183+
184+
@pytest.mark.parametrize("second_signal", [False, True])
185+
def test_forced_exit_with_closed_stdout_pipe_exits_zero(tmp_path, second_signal):
186+
process, channel, init_call = start_plugin_with_blocked_init(
187+
tmp_path, SERVE_PLUGIN_WITH_INIT_BLOCKED_ON_BUFFERED_STDOUT
188+
)
189+
try:
190+
process.stdout.close()
191+
timeout = send_termination_signals(process, second_signal)
192+
assert process.wait(timeout=timeout) == 0
193+
finally:
194+
init_call.cancel()
195+
channel.close()
196+
process.kill()

0 commit comments

Comments
 (0)