"""Independent bounded cleanup and owned process signal lifecycle.""" from contextlib import contextmanager import json import signal from threading import Event, Lock, Thread import time from services.local_s2s.components import start_components @contextmanager def termination_signals(stop): previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)} try: for sig in previous: signal.signal(sig, lambda *_: stop.set()) yield finally: for sig, handler in previous.items(): signal.signal(sig, handler) def bounded_call(action, timeout): finished, result = Event(), [] def run(): try: action() result.append(0) except BaseException: result.append(1) finally: finished.set() Thread(target=run, daemon=True).start() return result[0] if finished.wait(timeout) else 2 def cleanup(runtime, guard, thread, stop, *, timeout=2, emit=print): stop.set() counters = {} # Cancel owned provider I/O before joining workers which may be awaiting it. # Every operation is independent; one failure cannot skip later cleanup. for name, action in ( ('gateway_shutdown', guard.shutdown), ('gateway_close', guard.server_close), ('runtime_stop', runtime.stop if runtime is not None else lambda: None), ('gateway_join', lambda: thread.join(timeout)), ): counters[name] = bounded_call(action, timeout) counters['gateway_alive'] = int(thread.is_alive()) emit(json.dumps(dict(stage='close', cleanup=counters, request_counts=dict(guard.counts))), flush=True) return any(counters.values()) def run_owned(build, key, request_timeout, *, startup_timeout=90, cleanup_timeout=2, emit=print): stop, constructed, finished, abandoned, lock = Event(), Event(), Event(), Event(), Lock() runtime = None result = {} with termination_signals(stop): guard, thread = start_components(key, request_timeout) def drive(): nonlocal runtime if stop.is_set(): return 1 def construct(): try: value = build(stop) with lock: if not abandoned.is_set(): result['runtime'] = value else: bounded_call(value.stop, cleanup_timeout) except BaseException: result['failed'] = True finally: constructed.set() Thread(target=construct, daemon=True).start() deadline = time.monotonic() + startup_timeout while not constructed.wait(.01): if stop.is_set() or time.monotonic() >= deadline: with lock: abandoned.set() emit(json.dumps(dict(status='failed', category='LOCAL_ENGINE_STARTUP_DEADLINE')), flush=True) return 1 runtime = result.get('runtime') if runtime is None or stop.is_set(): emit(json.dumps(dict(status='failed', category='LOCAL_ENGINE_STARTUP_OR_RUNTIME_FAILURE')), flush=True) return 1 emit(json.dumps(dict(stage='startup', request_counts=dict(guard.counts))), flush=True) def serve(): try: runtime.start() runtime.wait() except BaseException: result['failed'] = True finally: finished.set() Thread(target=serve, daemon=True).start() while not finished.wait(.02) and not stop.is_set(): pass return int(bool(result.get('failed'))) try: outcome = drive() finally: # Fetch a construction result which raced the deadline before abandoning it. with lock: abandoned.set() runtime = runtime or result.get('runtime') cleanup_failed = cleanup(runtime, guard, thread, stop, timeout=cleanup_timeout, emit=emit) return int(outcome or cleanup_failed)