diff --git a/README.md b/README.md index b89cf2a..d1153d9 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ server on the player's own machine, and a server added by its address connects t | `tools/server_probe.py` | checks a server from outside (status page, UDP HELLO -> WELCOME) | | `tools/xtsw_decode.py` | decodes the requests a server saved with `--dump-requests` | | `tools/event_admin.py` | manages community events on a server | +| `tools/stop_loop.py` | stops a busy server on this machine thousands of times and counts the stops that were lost or did not save (#78) | | `accounts/` | the website accounts service for forza.dyotson.dev/api/ (Django, django-allauth, django-ninja): its own dependencies, image and tests ([`accounts/README.md`](accounts/README.md)) | | `screening/` | the screening worker for community photos, videos and designs (its own Docker image, [`screening/README.md`](screening/README.md)) | | `video/` | the video converter: the game's movie uploads to MP4 with ffmpeg, in a container with no network (its own Docker image, [`video/README.md`](video/README.md)) | diff --git a/docs/configuration.md b/docs/configuration.md index 67c21e5..5993809 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -29,6 +29,7 @@ Options are command line flags of `forza_live_server.py` (`--help` lists them al | `--no-invites` | `FORZA_INVITES=0` | drop every game invite | | `--stall-limit MS` | | log what holds the event loop longer than this, and count it on the status page (default 50; `0`: off) ([what holds the event loop](operating.md#what-holds-the-event-loop)) | | `--stall-stack MS` | | also log where the loop was once it has been held this long (default 250; `0`: never) | +| `--stop-limit S` | | a stop signal the event loop has not taken after this many seconds (the loop is held) breaks into what holds it, so that the saves are made before the kill (default 5; `0`: never; at most 3600) ([stopping the server](operating.md#stopping-the-server)) | | `--server-name HOST` | `FORZA_SERVER_NAMES` | the names players type to reach this server ([signed requests](#signed-requests)) | | `--rebind-legacy` | `FORZA_REBIND_LEGACY=1` | let an XUID bound to a friends key move to the first signed game | | `--raw-key-cutoff UNIX_TIME` | `FORZA_RAW_KEY_CUTOFF` | refuse friends keys sent raw after this time | diff --git a/docs/operating.md b/docs/operating.md index c28de33..0fe7e69 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -720,6 +720,89 @@ token, and let the accounts container reach the HTTP port directly, from an addr `--trusted-proxy` (the routes refuse the tunnel and proxies, as moderation does). Without the token the routes are off and the account page cannot delete. +## Stopping the server + +`docker compose stop` (SIGTERM) and Ctrl+C in a terminal (SIGINT) stop the server the same way. +The signal only asks for the stop: the server ends what it is doing at that moment (a datagram, a +request, a tick of its timers) and then stops, in this order. A Discord status update under way +is not waited for: the saves come first. + +1. `stop: SIGTERM: the server stops` in the log (`SIGINT` for Ctrl+C). +2. The server takes nothing new from here: no new connection on the HTTP port, no datagram on + the UDP port (no player joins), and the requests of the connections already open end where + they are, unanswered. Nothing a player does after the first line can change a store after + its save. +3. The [event loop's watchdog](#what-holds-the-event-loop) is turned off: the saves hold the loop, + on purpose. +4. The saves: the registrations (`live_state.json`), the co-op ledger and friends, then + `notifications.json` and the boards' `scoreboards.json` last, each with its own line + ([scores on disk](#scores-on-disk), [notifications on disk](#notifications-on-disk)). +5. When the Discord status is set up: an update that was under way when the signal came is given + up to 5 s more to end, then the status says the server is offline (with its own line only + when Discord cannot be reached). Then the process ends with exit status 0. + +So a stop ends with the notifications' line and then the boards' (after a second signal, one +more line, below): + + stop: SIGTERM: the server stops + notifications: notifications.json written whole at the stop in 0.14 s: it has every change: 29310 notifications for 3998 players, 5 broadcasts + scoreboards: scoreboards.json written whole at the stop in 0.32 s: it has every change: 412 boards, 50123 rows, 812 unranked rows, 1500 players in the 1000 Club + +A stop signal that comes while the server starts (while it reads its files, or while Python is +still loading its code) is noted: the start reads every file whole, and the server then stops as +above, the first line being `stop: SIGTERM during the start: the server stops now that it is +done`. A start that refuses to run (a file it cannot read) still ends with exit status 1 and its +own line. A volunteer relay (`--relay-only`) has nothing to save: it logs the first line and ends +with exit status 0. + +**A second signal changes nothing.** Once the stop has begun, every further SIGTERM or SIGINT (a +second `docker compose stop`, Ctrl+C pressed again) is noted and ignored until the process ends: +no save is cut short, and the log says so once for each part of the stop it came in, the first +line before the notifications' line, the second after the boards' line (the stop's last line +then). After the first signal of each part the server ignores the others outright, so even a +flood of them does not slow the saves: + + stop: SIGTERM again while the registrations, co-op ledger and friends were written: ignored until they were + stop: SIGTERM again while notifications.json and scoreboards.json were written: ignored until they were + +The exit status stays 0, even for a signal that comes as the process ends. + +The stop takes a fraction of a second, most of it those last two writes (a slow disk can make them +take a few seconds), and on a bad network a few more for the Discord status after them; the +compose file gives it 20 s (`stop_grace_period`). Only a kill ends it earlier: Docker's at the end +of that time, `docker compose kill`, or SIGKILL. A kill costs the boards and the notifications +nothing (their journals have every change) and the other stores what changed since their last +save; and it leaves `scoreboards.json` and `notifications.json` complete only together with their +journals, which matters before a rollback ([scores on disk](#scores-on-disk)). + +A Discord update stuck on the network past its 5 s does not hold the saves, which are made by +then, but the process ends only once the update gives up: past the 20 s Docker kills it (exit +status 137), at no cost to what was saved. Since every signal after the first is ignored, a stop +that does not end is not ended by a second Ctrl+C either: in a terminal, Ctrl+\ (SIGQUIT) or +`kill -9` ends it. + +**A held event loop.** The stop runs on the event loop, so a loop held by a bug (code that runs +on and on: the [watchdog's](#what-holds-the-event-loop) lines say what) takes the signal only +once it is free. Free within 5 s of the signal, it stops then, as above. If not, the stop breaks +into what holds the loop, as versions before this one did for every signal, and runs as above +with every save, exit status 0. The saves take well under a second, so they end long before +Docker's 20 s. The log says so first: + + stop: SIGTERM came 5 s ago and the event loop has not taken it: something holds the loop (the watchdog's lines say what); the stop breaks into it + +What held the loop is cut short where it was. A try that lands where Python only prints errors +(`Exception ignored in ...`, `BreakIn`) is followed by another a tenth of a second later. +Inside a call that cannot be broken into (C code that waits, such as a lock or a library's +call), the stop waits for that call to return and then runs at once. The log says +`stop: the event loop is still held 5 s later: inside a call that cannot be broken into; the +stop waits for it`. If the call has not returned by Docker's kill, nothing can save there (exit +status 137). `--stop-limit S` sets the 5 s (0: never break in; at most 3600). Keep it well under the 20 s, so +that the saves still have their time after it. + +Versions before this one stopped through an exception raised wherever the server was when the +signal came; inside code whose errors Python only prints (`Exception ignored in ...` in the log), +the stop was lost: the server ran on until Docker killed it 20 s later, without the stop's saves. + ## Backups and rollback Everything the server keeps (players, friends, clubs, scores, photos, designs, moderation lists) is in the data folder. Stop the server for a moment so every file is complete, copy the folder, and start it again (the commands are in the [hosting guide](hosting.md#keeping-it-running)). To restore a backup, stop the server, replace the data folder with the backup's, and start it. @@ -796,13 +879,9 @@ does (rolling back, below). The stores that have no journal (the registrations in `live_state.json`, the co-op ledger and friends) are written first, each whatever became of the others (an error in one is logged as `stop: the friends could not be written` with that save's own traceback, and the others and the -boards are still written). While they are written a second stop signal (a second `docker compose -stop`, Ctrl+C) is ignored and logged (`stop: SIGTERM again while the registrations, co-op ledger -and friends were written: ignored until they were`); once they are, a signal ends the stop again, -which costs the boards nothing. The notifications' last write comes between those stores and the -boards: a signal while it runs ends it (`stop: KeyboardInterrupt while notifications.json was -written whole: not written, its journal has every change; the boards are written all the same`, a -warning) and the boards are still written; only a signal after that one cuts theirs short. +boards are still written). The notifications' last write comes between those stores and the +boards. A second stop signal (a second `docker compose stop`, Ctrl+C) during any of them is noted +and ignored, and no write is cut short ([stopping the server](#stopping-the-server)). **A `scoreboards.json` that cannot be read.** When the file is there but cannot be read (a read error, permissions) the boards come from its `.bak` and the journal, as above. When the `.bak` @@ -831,8 +910,13 @@ it held`. What that means for you: -- **Stopping**: one `docker compose stop`, and let it end. The boards are written last, after - everything else the server saves. +- **Stopping**: `docker compose stop`, and let it end. The boards are written last, after + everything else the server saves. A second `docker compose stop` (or Ctrl+C) while it stops is + harmless: it is logged and ignored, and the stop goes on as for one. What ends a stop early is a + kill (`docker compose kill`, or the 20 s running out), which leaves `scoreboards.json` complete + only with its journal: the boards' line at the stop (`scoreboards: ... at the stop`, the last + line, or the one before a line about a signal ignored meanwhile) is there only when the stop + wrote them. - **Backups**: the whole data folder, with the server stopped. A copy of `scoreboards.json` taken while the server runs is not complete without `scoreboards.journal` beside it: by itself it lacks up to a minute of scores. If you must copy from a running server, copy diff --git a/forza_live/server.py b/forza_live/server.py index fcd57b8..62cf374 100644 --- a/forza_live/server.py +++ b/forza_live/server.py @@ -18,13 +18,16 @@ import asyncio import json import logging +import math import os import random import signal import sqlite3 import struct import sys +import threading import time +import _thread import urllib.parse from forza_live.core import auth @@ -2235,32 +2238,464 @@ async def keep_counted(stores=None, every=None): if hasattr(signal, name)) -def hold_stop_signals(): +def signal_name(number): + try: + return signal.Signals(number).name + except ValueError: + return str(number) + + +STOP_LIMIT = 5.0 # s: a stop signal the event loop has not taken by then breaks into it (--stop-limit) +BREAK_RETRY = 0.1 # s: between the tries of the break-in, until the stop runs +BREAK_TOLD = 5.0 # s: the log says so when the tries have not reached the stop by then +STOP_LIMIT_MAX = 3600.0 # s: --stop-limit's largest (far past any container runtime's stop time) + + +def stop_limit(text): + """--stop-limit: seconds, from 0 (never break in) to STOP_LIMIT_MAX; anything else (inf, + nan, a negative number) is refused as the server starts, with this message.""" + try: + seconds = float(text) + except ValueError: + seconds = math.nan + if not 0 <= seconds <= STOP_LIMIT_MAX: # (nan is neither) + raise argparse.ArgumentTypeError("%r: seconds from 0 (never) to %g" % (text, STOP_LIMIT_MAX)) + return seconds + + +class BreakIn(KeyboardInterrupt): + """Raised in the main thread wherever a held event loop is, when a stop signal has waited + for it past StopRequest.limit: it ends what holds the loop, as a stop signal's + KeyboardInterrupt did before #78, and the stop runs. A KeyboardInterrupt, which asyncio + lets through to run() where it catches the others.""" + + +def quiet_break_in(loop, context): + """The loop's exception handler (StopRequest.install): a task a BreakIn ended is no error to + log, its exception is seen in finish(). A connection's task (http_handler, from asyncio's + streams) was logged as "Unhandled exception in client_connected_cb", with a traceback, after + the saves. Anything else as asyncio has it.""" + if isinstance(context.get("exception"), BreakIn): + return + loop.default_exception_handler(context) + + +class StopRequest: + """The stop signals (SIGTERM: `docker stop`; SIGINT: Ctrl+C), taken through the event loop + (#78). A signal only notes itself here and wakes main(), which then ends from its own code: + the tick loop's wait returns, and the stop runs as main() has it. Python's own way, a + KeyboardInterrupt raised in the main thread at whatever it is doing, was lost when that was + a weakref callback, a __del__ or a garbage collector callback (it is only printed there, + "Exception ignored in ..."): the server ran on until the container runtime killed it, and + none of the stop's saves were made. + + install(loop) takes them with a signal.signal handler that only hands the note to the loop + (call_soon_threadsafe): nothing is raised where the signal lands, and every signal after + the first is noted and changes nothing. Not with loop.add_signal_handler: the loop puts + Python's default handlers back as it lets go of them (remove_signal_handler, its close), and + a SIGTERM in that moment, taken by any thread still running, ended the process with -15 + after the saves (a flood of signals: 1 stop in 50). + + The last resort, for a loop held so long that it never takes the note (a bug, Python code + that runs for good): a thread (watch) waits for the stop to begin, and `limit` seconds + after the first signal (counted from the end of the start) it breaks into what holds the + loop, as the signal itself did before: BreakIn raised in the main thread, again every + BREAK_RETRY until the stop runs (raised where Python only prints it, it is lost, and the + next try is not). The stop's steps then run (stop_once) and save everything, before the + container runtime's kill. Never inside them: they begin by turning the break-in off.""" + + def __init__(self): + self.came = [] # the stop signals, in the order they came + self.during_start = False # the first one came before the server was serving + self.serving_at = None # main() sets serving once the start is done (its time here) + self.ended = False # end(): the stop is done, a signal is nothing from here + self.stopping = asyncio.Event() + self.loop = None + self.limit = STOP_LIMIT # s: see the class (main(): --stop-limit); 0: never + self.first = self.first_at = None # the first stop signal, and its time, from the handler + self.at_stop = None # main()'s stop: its steps (an async function), once it serves + self.began = False # stop_once() has begun them: never a break-in from here + self.begun = threading.Event() # (the same, for the watching thread) + self.finished = asyncio.Event() # stop_once() is done with them + self.forcing = False # the watching thread breaks into the loop (its signals: poking) + self.poking = False + self.broken = [] # the tasks a BreakIn ended (their exception: seen, never logged) + self.own_tasks = set() # finish()'s: the stop's own, never cancelled by it + self.watcher = self.wake_fds = None + self.wakeup_set = False # the pipe is the signals' wakeup fd too (signal.set_wakeup_fd) + self.closing = False + + @property + def serving(self): + return self.serving_at is not None + + @serving.setter + def serving(self, on): + self.serving_at = time.monotonic() if on else None + + def install(self, loop): + """The signals are this loop's from here, and the thread that watches for a held loop + is started (it waits for the first signal). Nothing in a thread other than the main + one, where signals cannot be set (none is delivered there either).""" + self.loop = loop + if loop.get_exception_handler() is None: # (someone else's: left as it is) + loop.set_exception_handler(quiet_break_in) + try: + for number in STOP_SIGNALS: + signal.signal(number, self.schedule) + except ValueError: # not the main thread + return self + if self.watcher is None: + self.wake_fds = os.pipe() + os.set_blocking(self.wake_fds[1], False) + if os.name == "posix": # (Windows: the Proactor loop's own, which Ctrl+C needs) + # Python's C handler writes each signal's number there, at once: the thread + # knows of the signal even while the main thread is in a call that does not + # let Python's handler run (it then waits for that call, and says so) + try: + old = signal.set_wakeup_fd(self.wake_fds[1], warn_on_full_buffer=False) + if old != -1: # someone else's: left as it was + signal.set_wakeup_fd(old) + else: + self.wakeup_set = True + except (ValueError, OSError): + pass + self.watcher = threading.Thread(target=self.watch, args=(self.wake_fds[0],), + name="stop-watch", daemon=True) + self.watcher.start() + return self + + def schedule(self, number, frame): + """The handler: it runs in the main thread wherever that is (a weakref callback, a + __del__, the loop's own code), so it only hands the note to the loop, which cannot fail + there, nor raise. After end(), nothing. The watching thread's own signal (poking) is + the break-in: BreakIn raised here, unless the stop has begun or this is the stop's own + code (main(), run(), this class: where it would skip the stop instead of starting + it; the next try comes BREAK_RETRY later).""" + if self.ended: + return + if self.poking: + self.poking = False + if self.forcing and not self.began and (frame is None or frame.f_code not in OWN_CODE): + try: + self.broken.append(asyncio.current_task(self.loop)) + except RuntimeError: # no loop (a test's request) + pass + raise BreakIn("the event loop was held past the stop's limit") + return + self.first_signal(number) + try: + self.loop.call_soon_threadsafe(self.note, number) + except RuntimeError: # the loop is closed: the stop is over + self.came.append(number) + + def first_signal(self, number): + """The handler (and run(), for a signal while the code was read): the first one wakes + the watching thread. A plain write to a pipe: no lock that the code the signal landed + in could hold.""" + if self.first is None: + self.first, self.first_at = number, time.monotonic() + if self.wake_fds is not None: + try: + os.write(self.wake_fds[1], b"!") + except OSError: + pass + + def watch(self, fd): + """The watching thread: from the first stop signal, it waits for the stop to begin, + and breaks into the loop when it has not, `limit` seconds after the signal (or after + the start's end, for a signal during the start: the start reads its files whole).""" + while True: # the first stop signal: its number from Python's C handler, or "!" from ours + try: + byte = os.read(fd, 1) + except OSError: + return + if not byte or self.closing: + return + if byte[0] in STOP_SIGNALS: + if self.first is None: + self.first = byte[0] + break + if byte == b"!": + break + if self.first_at is None: + self.first_at = time.monotonic() + while True: + if self.closing or self.begun.is_set() or not self.limit: + return + if self.serving_at is None: + self.begun.wait(0.1) + continue + left = max(self.first_at, self.serving_at) + self.limit - time.monotonic() + if left <= 0: + break + self.begun.wait(min(left, 1.0)) # (in steps: a limit set some other way stays a wait) + log.warning("stop: %s came %g s ago and the event loop has not taken it: something holds " + "the loop (the watchdog's lines say what); the stop breaks into it", + signal_name(self.first), self.limit) + self.forcing = True + tried = time.monotonic() + told = False + while not self.closing and not self.begun.is_set(): + self.poke() + self.begun.wait(BREAK_RETRY) + if not told and time.monotonic() - tried >= BREAK_TOLD: + told = True + if not self.begun.is_set(): + log.warning("stop: the event loop is still held %g s later: inside a call " + "that cannot be broken into; the stop waits for it", + BREAK_TOLD) + + def poke(self): + """One try of the break-in: the first signal again, to the main thread itself (a call + that waits there, a sleep or a select, then ends with EINTR), its handler told it is + the break-in (poking).""" + self.poking = True + try: + if hasattr(signal, "pthread_kill"): + signal.pthread_kill(threading.main_thread().ident, self.first) + else: # Windows: Python's own flag, seen once the main thread runs Python code + _thread.interrupt_main(self.first) + except (OSError, ValueError, RuntimeError): + pass + + def poked(self): + """For the saves' handler (hold_stop_signals): True for a last try of the break-in + that reached it after the stop had begun, which is not a signal that came.""" + if self.poking: + self.poking = False + return True + return False + + async def stop_once(self): + """main()'s stop (at_stop), once: from main()'s finally, or from run() when a break-in + ended the loop's run outside main()'s own code. A second call waits for the first.""" + if self.began: + await self.finished.wait() + return + self.began = True # first: from here the break-in is nothing + self.begun.set() + self.stopping.set() # main()'s wait ends too, when the stop runs from run(): no tick + try: + if self.at_stop is not None: + await self.at_stop() + finally: + self.finished.set() + + def finish(self, runner): + """run(), after a BreakIn ended the loop's run: the stop, if main() did not get to it + (the BreakIn was raised in another task, main()'s still waits), on a task of its own, + or the end of main()'s, when main() began it first (its wakeup was queued before this + task: a loop freed just as the break-in came). That task is part of the stop: the stop + does not cancel it with the others (end_the_others). A further try of the break-in + before the stop begins ends this run too: once more.""" + loop = runner.get_loop() + while True: + for task in self.broken: + if task is not None and task.done() and not task.cancelled(): + task.exception() # what the BreakIn ended: seen, not logged as an error + del self.broken[:] + if self.finished.is_set(): + return + task = loop.create_task(self.stop_once()) + self.own_tasks.add(task) + try: + loop.run_until_complete(task) + except BreakIn: + continue + + def close(self): + """The watching thread ends (quiet(), at the very end; a test's cleanup).""" + self.closing = True + self.begun.set() + if self.wakeup_set: + self.wakeup_set = False + try: + signal.set_wakeup_fd(-1) + except ValueError: # not the main thread + pass + if self.wake_fds is not None: + fds, self.wake_fds = self.wake_fds, None + try: + os.write(fds[1], b"!") + except OSError: + pass + if self.watcher is not None: + self.watcher.join(1) + for fd in fds: + try: + os.close(fd) + except OSError: + pass + + def note(self, number): + """A stop signal (the loop calls this, never the signal itself).""" + if not self.came: + self.during_start = not self.serving + self.came.append(number) + self.stopping.set() + + async def wait(self, seconds): + """True once a stop was asked for (at once if it was already), False after seconds. + (True after them too when it was asked for meanwhile: a stop that a break-in began + while this wait's time ran out, its end not yet taken by main().)""" + if self.stopping.is_set(): + return True + try: + async with asyncio.timeout(seconds): + await self.stopping.wait() + except TimeoutError: + return self.stopping.is_set() + return True + + async def until_stopped(self, coro): + """coro until it ends by itself or a stop is asked for, which cancels it at the await it + is at (the --relay-only relay: it has nothing to save; the tick's Discord status + update, shielded: the stop's saves never wait for it). Its result or exception, None + when the stop cancelled it.""" + task = asyncio.ensure_future(coro) + stopped = asyncio.ensure_future(self.stopping.wait()) + try: + await asyncio.wait((task, stopped), return_when=asyncio.FIRST_COMPLETED) + finally: + stopped.cancel() + if not task.done(): + task.cancel() + await asyncio.wait((task,)) + if task.cancelled() and self.stopping.is_set(): + return None + return task.result() + + def said(self): + """The log's line for the stop that was asked for, or None (main() ends another way). + (After a break-in the loop may not have noted the signal yet: the handler's first.)""" + first = self.came[0] if self.came else self.first + if first is None: + return None + if self.during_start: + return ("stop: %s during the start: the server stops now that it is done" + % signal_name(first)) + return "stop: %s: the server stops" % signal_name(first) + + def end(self): + """The stop is done (main() once its saves are, run() after main()): from here a stop + signal is nothing at all (a container runtime's second SIGTERM, a second Ctrl+C), and + the handler stays ours, so that no thread can be ended by Python's default action while + the loop closes and its threads are joined (quiet() then).""" + self.ended = True + try: + for number in STOP_SIGNALS: + signal.signal(number, self.schedule) # (the held signals' handler, until now) + except ValueError: # not the main thread + pass + + def quiet(self): + """Every stop signal ignored, to the end of the process: run() calls it last, once the + loop is closed and its threads joined. SIG_IGN rather than a handler of ours: Python + puts the default action back for its own handlers as the interpreter ends, and a signal + then ended the process with that signal's status instead of 0. The main thread blocks + the signals meanwhile: one that comes then is dropped, rather than met in Python's + handler table by SIG_IGN ("Signal 2 ignored due to race condition", printed).""" + blocked = None + try: + if hasattr(signal, "pthread_sigmask"): + blocked = signal.pthread_sigmask(signal.SIG_BLOCK, STOP_SIGNALS) + for number in STOP_SIGNALS: + signal.signal(number, signal.SIG_IGN) + except ValueError: # not the main thread + pass + finally: + if blocked is not None: + signal.pthread_sigmask(signal.SIG_SETMASK, blocked) + + +def end_the_others(stop, keep=()): + """At the stop, before the saves: every task of the loop but this one, keep and the stop's + own (StopRequest.finish: they only wait for this stop to end) is cancelled, the open HTTP + connections' first (each ends at the await it is at, its request not answered), as the + loop's close cancelled them all before #78. They end once the loop runs again, after the + saves: nothing they would have done is left out of them.""" + me = asyncio.current_task() + for task in asyncio.all_tasks(): + if task is not me and task not in keep and task not in stop.own_tasks: + task.cancel() + + +def stop_accepting(listening): + """No new connection on the HTTP port from here, the server object left as it is: its + listening sockets are taken off the loop. Server.close() would do it too, but on Python + 3.13 and later a connection accepted just before it then fails in the accept (an assertion, + silent) and again as the process ends ("Exception ignored ... _SelectorTransport.__del__", + the closed server woken a second time): about one busy stop in 20 on 3.14. Windows' loops + accept another way (no remove_reader): Server.close() there.""" + loop = asyncio.get_running_loop() + try: + for sock in listening.sockets: + loop.remove_reader(sock.fileno()) + except NotImplementedError: + listening.close() + + +DISCORD_WAIT = 5 # s: at the stop, the Discord status update under way, before the offline one +SMALL_STORES = "the registrations, co-op ledger and friends" +JOURNALED_STORES = "notifications.json and scoreboards.json" + + +def hold_stop_signals(skip=None): """From here a stop signal (SIGTERM, SIGINT) is noted and ignored, until - release_stop_signals(held): the stores without a journal are written whole, and a second - `docker stop` or Ctrl+C in the middle would cut them short (#70). None where signals cannot - be set (a thread other than the main one): nothing is held then.""" + release_stop_signals(held): the stop's saves run with it, and a second `docker stop` or + Ctrl+C in the middle would otherwise reach the loop's handler only once they are done, with + nothing in the log (#70, #78). Each signal is noted once, and is then SIG_IGN until the log + has told of it (tell_held): a flood of them costs the saves nothing, not even a handler's call + each. None where signals cannot be set (a thread other than the main one): nothing is held + then. skip: a call that says a signal is not one that came (StopRequest.poked: a last + try of the break-in), which is then nothing at all.""" came, previous = [], {} + + def noted(number, frame): + if skip is not None and skip(): + return + came.append(number) + # the rest of this part of the stop: nothing. Only this signal: one of the others may + # be waiting for its handler in this same round of Python's, which then finds SIG_IGN + # and prints "Signal 15 ignored due to race condition" + signal.signal(number, signal.SIG_IGN) + try: for number in STOP_SIGNALS: - previous[number] = signal.signal(number, lambda number, frame: came.append(number)) + previous[number] = signal.signal(number, noted) except ValueError: - release_stop_signals((came, previous)) + release_stop_signals((came, previous, noted)) return None - return came, previous + return came, previous, noted -def release_stop_signals(held): +def tell_held(held, during=SMALL_STORES): + """The log tells of a signal held while `during` were written, once, and the next one is + noted again.""" + if held is None: + return + came, previous, noted = held + if came: + log.info("stop: %s again while %s were written: ignored until they were", + signal_name(came[0]), during) + del came[:] + for number in previous: + signal.signal(number, noted) + + +def release_stop_signals(held, during=SMALL_STORES): """The handlers as they were before hold_stop_signals(), and the log told of a signal that came meanwhile.""" if held is None: return - came, previous = held + came, previous, _ = held for number, handler in previous.items(): signal.signal(number, handler) if came: - log.info("stop: %s again while the registrations, co-op ledger and friends were written: " - "ignored until they were", signal.Signals(came[0]).name) + log.info("stop: %s again while %s were written: ignored until they were", + signal_name(came[0]), during) + del came[:] def own_error(error, handled): @@ -2284,12 +2719,12 @@ def own_error(error, handled): def save_at_stop(server, held=None): """What the server writes as it stops, the boards last: their last write is megabytes, and - whatever ends it early (a second signal, the stop's time running out) costs the boards - nothing, their journal has every change (#67); so for the notifications' write before them, - and a signal that ends that one still lets the boards be written. The stores before them have no journal: a - stop signal waits until they are written (held: what hold_stop_signals() gave, when the - caller already holds them), and each is written whatever became of the others, so that the - boards' last write is always reached (#70).""" + whatever ends it early (the stop's time running out, a kill) costs the boards nothing, + their journal has every change (#67); so for the notifications' write before them. The + stores before them have no journal. Each is written whatever became of the others, so that + the boards' last write is always reached (#70), and a stop signal waits until all of them + are written (held: what hold_stop_signals() gave, when the caller already holds them): the + signals no longer end the stop at all (#78), they are noted, and the log says so.""" def ledger(): if coop_ledger.LEDGER.dirty: coop_ledger.LEDGER.save() @@ -2300,35 +2735,42 @@ def friends_store(): if held is None: held = hold_stop_signals() - stopping = sys.exc_info()[1] # what ends main(): the signal's KeyboardInterrupt, ... - try: - # the registrations first: a restart now keeps the players (#93) - for what, save in (("registrations", server.save_state), ("co-op ledger", ledger), - ("friends", friends_store)): - try: - save() - except Exception as e: # noqa: BLE001 - the stores after it, and the boards, go on - log.error("stop: the %s could not be written", what, - exc_info=own_error(e, stopping)) - finally: - release_stop_signals(held) - # The stores with a journal, which loses nothing whatever ends the stop: the boards last, - # reached whatever ends the notifications' write (a second signal there ends the stop only - # once the boards are written, or a third one cuts them). + stopping = sys.exc_info()[1] # what ends main() when it is an exception try: - notifications.STORE.stop() # notifications.json gets what only its journal had - except Exception as e: # noqa: BLE001 - the boards are still written - log.error("stop: the notifications could not be written", exc_info=own_error(e, stopping)) - except BaseException as e: - log.warning("stop: %s while notifications.json was written whole: not written, its " - "journal has every change; the boards are written all the same", - type(e).__name__) - raise + try: + # the registrations first: a restart now keeps the players (#93) + for what, save in (("registrations", server.save_state), ("co-op ledger", ledger), + ("friends", friends_store)): + try: + save() + except Exception as e: # noqa: BLE001 - the stores after it, and the boards, go on + log.error("stop: the %s could not be written", what, + exc_info=own_error(e, stopping)) + finally: + tell_held(held, SMALL_STORES) + # The stores with a journal, which loses nothing whatever ends the stop: the boards + # last, reached whatever ends the notifications' write. + try: + notifications.STORE.stop() # notifications.json gets what only its journal had + except Exception as e: # noqa: BLE001 - the boards are still written + log.error("stop: the notifications could not be written", + exc_info=own_error(e, stopping)) + except BaseException as e: # (not a stop signal: those are held) + log.warning("stop: %s while notifications.json was written whole: not written, its " + "journal has every change; the boards are written all the same", + type(e).__name__) + raise + finally: + scores.STORE.stop() # scoreboards.json gets what only its journal had finally: - scores.STORE.stop() # scoreboards.json gets what only its journal had + release_stop_signals(held, JOURNALED_STORES) -async def main(): +async def main(stop=None): + """The server until a stop signal (stop: run()'s StopRequest, already installed; one is + installed on this loop when main() is run some other way).""" + if stop is None: + stop = StopRequest().install(asyncio.get_running_loop()) parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--host", default="0.0.0.0", help="address to listen on") parser.add_argument("--port", type=int, default=int(os.environ.get("FORZA_LIVE_PORT", 21200)), @@ -2395,16 +2837,25 @@ async def main(): parser.add_argument("--stall-stack", type=float, default=watchdog.STACK_MS, metavar="MS", help="also log where the loop was when it is held longer than this: " "milliseconds, default %(default)g; 0: never") + parser.add_argument("--stop-limit", type=stop_limit, default=STOP_LIMIT, metavar="S", + help="a stop signal that the event loop has not taken after this many " + "seconds (something holds the loop) breaks into what holds it, so " + "that the stop's saves are made before the container runtime's " + "kill: default %(default)g; 0: never") parser.add_argument("-v", "--verbose", action="store_true") lsp.add_arguments(parser) world.add_arguments(parser) campaign.add_arguments(parser) challenge.add_arguments(parser) args = parser.parse_args() + stop.limit = args.stop_limit logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, format="%(asctime)s %(message)s") if args.relay_only: # nothing below: no data folder, no HTTP port (relay_node.py) - await relay_node.run(args) + stop.serving = True # nothing to read first: a stop signal ends the relay at once + await stop.until_stopped(relay_node.run(args)) + if stop.said(): + log.info("%s", stop.said()) return limits.configure_proxies(os.environ.get("FORZA_TRUSTED_PROXIES", ""), *args.trusted_proxy) if limits.TRUSTED_PROXIES: @@ -2447,12 +2898,13 @@ async def main(): server.relays.probation_time = max(0.0, args.relay_probation) * 60 server.relays.configure(args.data_dir) log.info("Forza Live listening on UDP %s:%d (epoch %04X)", args.host, args.port, server.epoch) + listening = None # the HTTP port's server, closed first at the stop if args.http_port: server.http_port = args.http_port server.proxy_http_port = args.proxy_http_port server.invites = not args.no_invites - await asyncio.start_server(lambda r, w: http_handler(server, r, w), args.host, args.http_port, - limit=1 << 15) + listening = await asyncio.start_server(lambda r, w: http_handler(server, r, w), args.host, + args.http_port, limit=1 << 15) log.info("title servers and status page on http://%s:%d/", args.host, args.http_port) if watchdog.WATCH.on: log.info("event loop watchdog: logs what holds the loop over %g ms (stacks over %g ms)", @@ -2468,10 +2920,47 @@ def flush_events(): except (OSError, sqlite3.Error): log.warning("community event delivery storage unavailable; retrying later") + updating = loop.create_future() # the Discord status update under way (none yet) + updating.set_result(None) + + async def the_stop(): + """The stop, in this order (docs/operating.md, "Stopping the server"): run once, by + StopRequest.stop_once.""" + held = hold_stop_signals(stop.poked) # until every store is written: noted, and ignored + if stop.said(): + log.info("%s", stop.said()) + # Nothing new from here: no connection on the HTTP port, no datagram (no player joins), + # and the requests of the connections still open end where they are: none of them + # changes a store after its save (the Discord wait below runs the loop again) + for step in (lambda: listening is None or stop_accepting(listening), + transport.close, + lambda: end_the_others(stop, keep=(updating,)), + watchdog.WATCH.stop, # the saves hold the loop, on purpose + counting.cancel, writing.cancel, noting.cancel, + limits.STORED.close, # a count under way ends now: its thread does not + videos.STORED.close): # hold the exit + try: + step() + except Exception: # noqa: BLE001 - nothing before the saves keeps them from being made + log.exception("stop: a step before the saves failed; the saves are made all " + "the same") + try: + save_at_stop(server, held) + finally: + stop.end() # the saves are done: every signal from here is ignored + if not updating.done(): # its edit first, so that the offline one is the last + await asyncio.wait((updating,), timeout=DISCORD_WAIT) + if updating.done() and not updating.cancelled(): + updating.exception() # (never raises: update() catches everything) seen, not logged + if discord_status.enabled(): + discord_status.offline(args.data_dir) + server.events.db.close() + + stop.at_stop = the_stop + stop.serving = True # a stop signal during the start was noted: it stops the server here try: ticks = 0 - while True: - await asyncio.sleep(1) + while not await stop.wait(1): # a stop signal ends this wait, never a tick half way ticks += 1 timed("challenges.tick", server.challenges.tick) if ticks % 2 == 0: @@ -2484,37 +2973,55 @@ def flush_events(): timed("videos.tick", videos.tick) # the video converter's results (videos.collect) timed("events.flush", flush_events) if ticks % 30 == 0 and discord_status.enabled(): - # urllib blocks: off the event loop, and never fatal (it catches everything) - await asyncio.to_thread(discord_status.update, server.status(), args.data_dir) + # urllib blocks: off the event loop, and never fatal (it catches everything). + # A stop does not wait for it: on a bad network it takes tens of seconds (its + # requests' timeouts, a name lookup with none), past the stop's 20 s + updating = asyncio.ensure_future(asyncio.to_thread( + discord_status.update, server.status(), args.data_dir)) + await stop.until_stopped(asyncio.shield(updating)) finally: - watchdog.WATCH.stop() # the stop's saves hold the loop, on purpose - held = hold_stop_signals() # until the stores without a journal are written - counting.cancel() - writing.cancel() - noting.cancel() - limits.STORED.close() # a count under way ends now: its thread does not hold the exit - videos.STORED.close() - save_at_stop(server, held) - if discord_status.enabled(): - discord_status.offline(args.data_dir) - transport.close() - server.events.db.close() + await stop.stop_once() # (a break-in may have begun it from run(): then it waits) -def run(): - """The command line (forza_live_server.py in the repository's root calls this).""" - # SIGTERM (docker stop) ends the server like Ctrl+C; as a container's first process - # it would otherwise be ignored. - signal.signal(signal.SIGTERM, signal.default_int_handler) +def run(came=()): + """The command line (forza_live_server.py in the repository's root calls this, with the stop + signals that came while the server's code was read: they stop it once it has started). + + A stop signal (SIGTERM: `docker stop`; SIGINT: Ctrl+C) is the event loop's (StopRequest): + main() returns once the stop's saves are done, and the exit status is 0. Every signal after + the first is ignored, to the end of the process (noted, and logged, during the saves). As a + container's first process the server would ignore SIGTERM without a handler of its own.""" + stop = StopRequest() try: - asyncio.run(main()) - except KeyboardInterrupt: + with asyncio.Runner() as runner: + try: + stop.install(runner.get_loop()) + for number in came: + stop.first_signal(number) + stop.note(number) + try: + runner.run(main(stop)) + except BreakIn: # a held loop broken into (StopRequest.watch): the stop runs + stop.finish(runner) + finally: + stop.end() # (main() did, but for the relay and the other ways it ends) + # the loop is closed, its threads joined: SIG_IGN to the end (finally) + except KeyboardInterrupt: # not a stop signal any more (those are the loop's): kept as before pass except journal.Unreadable: # scoreboards.json or notifications.json is there and cannot be read, nor its .bak (or # it is damaged and the .bak cannot be read): the log has said so, and the server does # not start without them (docs/operating.md, "Scores on disk", "Notifications on disk") sys.exit(1) + finally: + stop.quiet() + stop.close() + + +# The stop's own code, where a break-in is never raised (StopRequest.schedule): in main() it +# would skip the stop's steps rather than run them +OWN_CODE = frozenset([main.__code__, run.__code__] + [ + f.__code__ for f in vars(StopRequest).values() if hasattr(f, "__code__")]) if __name__ == "__main__": diff --git a/forza_live_server.py b/forza_live_server.py index 98644ad..d754d1b 100644 --- a/forza_live_server.py +++ b/forza_live_server.py @@ -6,7 +6,16 @@ `python3 forza_live_server.py --help` lists every option. """ -from forza_live.server import run - if __name__ == "__main__": - run() + import signal + + # A stop signal while the server's code is still being read is noted, and stops the server + # once it has started (forza_live.server.run, #78): as a container's first process it would + # otherwise be ignored, and a stop right after a start lost. + came = [] + for name in ("SIGTERM", "SIGINT"): + if hasattr(signal, name): + signal.signal(getattr(signal, name), lambda number, frame: came.append(number)) + + from forza_live.server import run + run(came) diff --git a/tests/competition/test_scores_journal.py b/tests/competition/test_scores_journal.py index d186f07..b5e0067 100644 --- a/tests/competition/test_scores_journal.py +++ b/tests/competition/test_scores_journal.py @@ -793,7 +793,7 @@ def test_the_stores_without_a_journal_are_saved_before_the_boards(self): server, ledger = self.server(), mock.Mock(dirty=True) server.friends.store.seen(A_XUID, "DriverA") self.trap(A_XUID, 50.0) - # a second signal while the boards' last write is under way + # the boards' last write ended by an exception (no longer a stop signal: those are held) with mock.patch.object(coop_ledger, "LEDGER", ledger), \ mock.patch.object(scores.STORE, "write", side_effect=KeyboardInterrupt): self.assertRaises(KeyboardInterrupt, srv.save_at_stop, server) @@ -1020,9 +1020,10 @@ def save_state(): again.load() self.assertEqual(again.name(A_XUID), "DriverA") self.assertTrue(os.path.exists(server.state_path)) - self.assertTrue(any("ignored" in line for line in logs.output), logs.output) + self.assertIn("INFO:forza-live:stop: SIGTERM again while the registrations, co-op ledger " + "and friends were written: ignored until they were", logs.output) self.assertEqual(as_a_previous_version_reads_it(self.dir.name), tables()) - # and after them a signal ends the stop again: the boards' journal has every change + # and after the stop's writes the handler is the one from before them again self.assertIs(signal.getsignal(signal.SIGTERM), signal.default_int_handler) def test_the_stop_tells_the_truth_when_the_journal_cannot_take_the_last_change(self): diff --git a/tests/core/test_watchdog.py b/tests/core/test_watchdog.py index 5ca4701..65e95a7 100644 --- a/tests/core/test_watchdog.py +++ b/tests/core/test_watchdog.py @@ -492,10 +492,8 @@ def run_server(self, *flags): stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def end(): - # Python 3.12 can lose a SIGTERM: its KeyboardInterrupt, raised while a weakref - # callback runs, is only "ignored" there (once in a few hundred stops). Once more, - # then kill: a test never waits for good. - for stop in (proc.terminate, proc.terminate, proc.kill): + # the stop, then a kill: a test never waits for good + for stop in (proc.terminate, proc.kill): stop() try: proc.wait(15) diff --git a/tests/server/test_stop.py b/tests/server/test_stop.py new file mode 100644 index 0000000..86cd50d --- /dev/null +++ b/tests/server/test_stop.py @@ -0,0 +1,927 @@ +"""A stop signal is the event loop's (#78): SIGTERM (`docker stop`) and SIGINT (Ctrl+C) only note +themselves (server.StopRequest), and main() ends from its own code with every save of the stop. +They used to raise KeyboardInterrupt wherever the main thread was, and Python only prints an +exception raised in a weakref callback, a __del__ or a garbage collector callback: there the +stop was lost and the server ran on until the container runtime killed it. + +The unit tests raise the signals in this process (signal.raise_signal), the others stop real +servers on this machine. tools/stop_loop.py stops a busy server thousands of times.""" + +import argparse +import asyncio +import gc +import json +import os +import re +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +import unittest +import urllib.error +import urllib.request +import weakref +from unittest import mock + +from forza_live import server as srv +from forza_live.core import relays +from forza_live.social import notifications as notices +from tests.support import ROOT, hello + +PYTHON = getattr(sys, "_base_executable", sys.executable) +POSIX_SIGNALS = unittest.skipIf(sys.platform == "win32", + "a stop signal to another process is POSIX's (Windows: " + "TerminateProcess, or Ctrl+C in the server's own console)") +PLAYER = 0x0009000000000001 + + +class Dropped: + """An object whose weakref callback runs some code: where a signal used to be lost.""" + + +def in_a_weakref_callback(code): + """code() run as Python runs a weakref callback (WeakSet._remove when a task is collected): + what it raises is printed and dropped there, never seen by the code around it.""" + obj = Dropped() + ref = weakref.ref(obj, lambda ref: code()) + with mock.patch("sys.unraisablehook"): # "Exception ignored in ..." without the noise + del obj + gc.collect() + return ref + + +def put_back(test): + """The stop signals' handlers as this process has them, after the test.""" + for number in srv.STOP_SIGNALS: + test.addCleanup(signal.signal, number, signal.getsignal(number)) + + +class StopRequestTest(unittest.IsolatedAsyncioTestCase): + """The request itself, on the test's loop, with the signals raised in this process.""" + + async def asyncSetUp(self): + put_back(self) + self.loop = asyncio.get_running_loop() + + def serving(self, stop): + stop.serving = True # as main() has it once the start is done + return stop + + def installed(self): + stop = srv.StopRequest().install(self.loop) + self.addCleanup(stop.close) + return stop + + async def test_the_old_way_loses_a_signal_in_a_weakref_callback(self): + """Why (#78): with Python's handler the KeyboardInterrupt is raised inside the callback, + and dropped there.""" + signal.signal(signal.SIGINT, signal.default_int_handler) + reached = [] + + def callback(): + signal.raise_signal(signal.SIGINT) + reached.append("after") # not reached: the KeyboardInterrupt ended the callback + try: + in_a_weakref_callback(callback) + except KeyboardInterrupt: + self.fail("the KeyboardInterrupt reached the caller") + self.assertEqual(reached, []) # and nobody knows there was a stop + + async def test_a_signal_is_noted_and_wakes_the_wait(self): + stop = self.serving(self.installed()) + self.assertFalse(await stop.wait(0.01)) + signal.raise_signal(signal.SIGTERM) # nothing raised here + self.assertTrue(await stop.wait(5)) + self.assertTrue(await stop.wait(0)) # and from then on, at once + self.assertEqual(stop.came, [signal.SIGTERM]) + self.assertEqual(stop.said(), "stop: SIGTERM: the server stops") + + async def test_a_signal_in_a_weakref_callback_is_not_lost(self): + stop = self.installed() + reached = [] + + def callback(): + signal.raise_signal(signal.SIGTERM) + reached.append("after") + in_a_weakref_callback(callback) + self.assertEqual(reached, ["after"]) # the callback ran on: nothing was raised in it + self.assertTrue(await stop.wait(5)) + self.assertEqual(stop.came, [signal.SIGTERM]) + + async def test_the_handler_only_schedules_the_note(self): + """A signal.signal handler that only hands the note to the loop, on every system (the + loop's add_signal_handler is not used: Windows' loops have none, and elsewhere the loop + puts Python's default handlers back as it lets go of them).""" + stop = self.installed() + for number in srv.STOP_SIGNALS: + self.assertEqual(signal.getsignal(number), stop.schedule) + reached = [] + + def callback(): + signal.raise_signal(signal.SIGINT) + reached.append("after") + in_a_weakref_callback(callback) + self.assertEqual(reached, ["after"]) + self.assertEqual(stop.came, []) # the loop notes it, not the handler + self.assertTrue(await stop.wait(5)) + self.assertEqual(stop.came, [signal.SIGINT]) + + async def test_more_signals_change_nothing(self): + stop = self.serving(self.installed()) + for number in (signal.SIGTERM, signal.SIGINT, signal.SIGTERM): + signal.raise_signal(number) + self.assertTrue(await stop.wait(5)) + await asyncio.sleep(0.05) # the loop has read them all + self.assertEqual(stop.came, [signal.SIGTERM, signal.SIGINT, signal.SIGTERM]) + self.assertEqual(stop.said(), "stop: SIGTERM: the server stops") + + async def test_a_signal_during_the_start_waits_for_it(self): + stop = self.installed() + signal.raise_signal(signal.SIGTERM) + await asyncio.sleep(0.05) # the start's next await: noted, nothing else + self.assertTrue(stop.stopping.is_set()) + stop.serving = True # main(): the start is done + self.assertTrue(await stop.wait(1)) + self.assertEqual(stop.said(), "stop: SIGTERM during the start: the server stops now " + "that it is done") + + async def test_the_relay_is_cancelled_at_its_await(self): + stop = self.installed() + steps = [] + + async def relay(): + try: + while True: + steps.append("tick") + await asyncio.sleep(0.01) + finally: + steps.append("closed") + self.loop.call_later(0.05, signal.raise_signal, signal.SIGTERM) + self.assertIsNone(await asyncio.wait_for(stop.until_stopped(relay()), 5)) + self.assertEqual(steps[-1], "closed") + + async def refused(): # a relay that ends by itself (its command line) ends main() so + raise ValueError("--relay-only needs ...") + with self.assertRaises(ValueError): + await srv.StopRequest().until_stopped(refused()) + + async def test_after_the_stop_a_signal_is_ignored(self): + """To the end of the process, with SIG_IGN: the interpreter's end puts the default + action back for Python's own handlers, and a signal then ended the process with its + status instead of 0 (a third signal 20 ms into a stop of the busy server, 179 times in + 700).""" + stop = self.installed() + stop.end() # main(), after the saves + signal.raise_signal(signal.SIGINT) # nothing happens + signal.raise_signal(signal.SIGTERM) + await asyncio.sleep(0.05) + self.assertEqual(stop.came, []) + self.assertFalse(stop.stopping.is_set()) + stop.end() # (run() again, after main()) + stop.quiet() # run(), last + stop.close() + for number in srv.STOP_SIGNALS: + self.assertEqual(signal.getsignal(number), signal.SIG_IGN) + signal.raise_signal(signal.SIGINT) + signal.raise_signal(signal.SIGTERM) + self.assertEqual(stop.came, []) + + +class EndTest(unittest.TestCase): + def setUp(self): + put_back(self) + + def test_python_s_default_action_is_never_put_back(self): + """From install() to quiet() the handler is ours, then SIG_IGN: never SIG_DFL, nor + Python's default_int_handler, not even for a moment (the loop's close put them back + when the loop had the signals, and a SIGTERM then, taken by a thread still running, + ended a stop of a flood of signals with -15 after its saves).""" + seen = [] + real = signal.signal + + def setting(number, handler): + seen.append(handler) + return real(number, handler) + loop = asyncio.new_event_loop() + with mock.patch.object(signal, "signal", setting): + try: + stop = srv.StopRequest().install(loop) + self.addCleanup(stop.close) + held = srv.hold_stop_signals() + srv.release_stop_signals(held) + stop.end() + finally: + loop.close() + stop.quiet() + self.assertTrue(seen) + self.assertNotIn(signal.SIG_DFL, seen) + self.assertNotIn(signal.default_int_handler, seen) + for number in srv.STOP_SIGNALS: + self.assertEqual(signal.getsignal(number), signal.SIG_IGN) + + +class StopAcceptingTest(unittest.IsolatedAsyncioTestCase): + async def test_no_new_connection_is_served_and_the_open_ones_go_on(self): + served = [] + + async def handler(reader, writer): + served.append(await reader.readline()) + writer.write(b"ok\n") + await writer.drain() + writer.close() + listening = await asyncio.start_server(handler, "127.0.0.1", 0) + self.addCleanup(listening.close) + port = listening.sockets[0].getsockname()[1] + reader, writer = await asyncio.open_connection("127.0.0.1", port) + self.addCleanup(writer.close) + await asyncio.sleep(0.05) # accepted + srv.stop_accepting(listening) + writer.write(b"open before\n") + self.assertEqual(await asyncio.wait_for(reader.readline(), 5), b"ok\n") + try: + late = socket.create_connection(("127.0.0.1", port), timeout=2) # the backlog + except OSError: # Windows: Server.close(), the port refuses it + pass + else: + self.addCleanup(late.close) + late.sendall(b"opened after\n") + await asyncio.sleep(0.2) + self.assertEqual(served, [b"open before\n"]) + + +class HeldTest(unittest.TestCase): + """During the stop's saves the signals are held: noted, and the log says so.""" + + def setUp(self): + put_back(self) + + def test_held_signals_are_told_once_and_never_raised(self): + signal.signal(signal.SIGTERM, signal.default_int_handler) # the worst handler outside + held = srv.hold_stop_signals() + signal.raise_signal(signal.SIGTERM) + in_a_weakref_callback(lambda: signal.raise_signal(signal.SIGTERM)) + with self.assertLogs("forza-live", "INFO") as logs: + srv.tell_held(held, srv.SMALL_STORES) + signal.raise_signal(signal.SIGINT) + with self.assertLogs("forza-live", "INFO") as more: + srv.release_stop_signals(held, srv.JOURNALED_STORES) + self.assertEqual(logs.output, [ + "INFO:forza-live:stop: SIGTERM again while the registrations, co-op ledger and " + "friends were written: ignored until they were"]) + self.assertEqual(more.output, [ + "INFO:forza-live:stop: SIGINT again while notifications.json and scoreboards.json " + "were written: ignored until they were"]) + self.assertIs(signal.getsignal(signal.SIGTERM), signal.default_int_handler) + + @unittest.skipUnless(hasattr(signal, "pthread_sigmask"), "POSIX") + def test_two_signals_handled_in_one_round(self): + """SIGINT and SIGTERM waiting together: Python runs their handlers in one round, and the + first one's SIG_IGN must not be the second one's (it printed "Signal 15 ignored due to + race condition", with a traceback, in 5 of 79 busy three-signal stops).""" + held = srv.hold_stop_signals() + self.addCleanup(srv.release_stop_signals, held) + printed = [] + with mock.patch("sys.unraisablehook", printed.append): + signal.pthread_sigmask(signal.SIG_BLOCK, srv.STOP_SIGNALS) + try: + signal.raise_signal(signal.SIGINT) + signal.raise_signal(signal.SIGTERM) + finally: + signal.pthread_sigmask(signal.SIG_UNBLOCK, srv.STOP_SIGNALS) # both, at once + self.assertEqual(printed, []) + self.assertEqual(held[0], [signal.SIGINT, signal.SIGTERM]) + + def test_a_flood_costs_the_saves_nothing(self): + """Once a held signal is noted it is SIG_IGN until the log has told of it: a flood of + them is not a handler's call each (a flood of thousands a second starved the boards' + write past the stop's 20 s).""" + signal.signal(signal.SIGTERM, signal.default_int_handler) + held = srv.hold_stop_signals() + noted = signal.getsignal(signal.SIGTERM) + signal.raise_signal(signal.SIGINT) + self.assertEqual(signal.getsignal(signal.SIGINT), signal.SIG_IGN) + for _ in range(2000): + signal.raise_signal(signal.SIGINT) # ignored by the system itself + signal.raise_signal(signal.SIGTERM) # noted once, then ignored too + self.assertEqual(signal.getsignal(signal.SIGTERM), signal.SIG_IGN) + self.assertEqual(held[0], [signal.SIGINT, signal.SIGTERM]) + with self.assertLogs("forza-live", "INFO") as logs: + srv.tell_held(held, srv.SMALL_STORES) + self.assertEqual(len(logs.output), 1) + for number in srv.STOP_SIGNALS: # the next part notes them again + self.assertIs(signal.getsignal(number), noted) + for _ in range(2000): + signal.raise_signal(signal.SIGTERM) + with self.assertLogs("forza-live", "INFO") as more: + srv.release_stop_signals(held, srv.JOURNALED_STORES) + self.assertEqual(more.output, [ + "INFO:forza-live:stop: SIGTERM again while notifications.json and scoreboards.json " + "were written: ignored until they were"]) + self.assertIs(signal.getsignal(signal.SIGTERM), signal.default_int_handler) + + +class BreakInTest(unittest.TestCase): + """The last resort (StopRequest.watch): a loop held past the stop's limit, so that it never + takes the signal's note, is broken into, and the stop runs; run() as the server has it, + with a main() of the test's.""" + + def setUp(self): + put_back(self) + + def run_held(self, hold, at_stop=None, limit=0.3): + steps = [] + + async def stopping(): + steps.append("stop") + if at_stop is not None: + at_stop() + steps.append("saved") + + async def main(stop): + stop.limit = limit + stop.at_stop = stopping + stop.serving = True + + async def holder(): + await asyncio.sleep(0.05) + signal.raise_signal(signal.SIGTERM) # noted: the loop is held before it takes it + hold() + steps.append("free") + asyncio.get_running_loop().create_task(holder()) + try: + while not await stop.wait(1): + pass + finally: + await stop.stop_once() + with mock.patch.object(srv, "main", main): + began = time.monotonic() + srv.run() + return steps, time.monotonic() - began + + @staticmethod + def spin(seconds): + end = time.monotonic() + seconds + while time.monotonic() < end: + pass + + def test_a_loop_free_before_the_limit_takes_the_signal_itself(self): + with self.assertNoLogs("forza-live", "WARNING"): + steps, took = self.run_held(lambda: self.spin(0.1)) + self.assertEqual(steps, ["free", "stop", "saved"]) + + def test_a_loop_held_past_the_limit_is_broken_into(self): + with self.assertLogs("forza-live", "WARNING") as logs: + steps, took = self.run_held(lambda: self.spin(30)) + self.assertEqual(steps, ["stop", "saved"]) # the hold never ended by itself + self.assertLess(took, 5) + self.assertRegex(logs.output[0], r"stop: SIGTERM came 0\.3 s ago and the event loop has " + r"not taken it: .* the stop breaks into it") + + def test_a_try_where_python_only_prints_it_is_followed_by_another(self): + """The loop held inside weakref callbacks first: a BreakIn raised there ends the + callback and is dropped ("Exception ignored"); the next try, 0.1 s later, is not.""" + printed = [] + + def hold(): + end = time.monotonic() + 1.0 + while time.monotonic() < end: + obj = Dropped() + ref = weakref.ref(obj, lambda ref: self.spin(0.25)) + del obj # the callback runs here + self.spin(30) + with mock.patch("sys.unraisablehook", printed.append), \ + self.assertLogs("forza-live", "WARNING"): + steps, took = self.run_held(hold) + self.assertEqual(steps, ["stop", "saved"]) + self.assertTrue(any(isinstance(p.exc_value, srv.BreakIn) for p in printed), printed) + self.assertLess(took, 5) + + def test_never_raised_in_the_stop_s_own_code(self): + """A try of the break-in that lands in main()'s own frame (its finally, before the stop + has begun) or once the stop has begun is nothing: there it would skip the stop.""" + stop = srv.StopRequest() + stop.forcing = True + coro = srv.main(stop) + self.addCleanup(coro.close) + stop.poking = True + self.assertIsNone(stop.schedule(signal.SIGTERM, coro.cr_frame)) + self.assertFalse(stop.poking) + stop.poking = True + with self.assertRaises(srv.BreakIn): + stop.schedule(signal.SIGTERM, sys._getframe()) + stop.poking, stop.began = True, True + self.assertIsNone(stop.schedule(signal.SIGTERM, sys._getframe())) + self.assertEqual(stop.came, []) # none of them was a signal that came + + def test_a_limit_that_is_not_seconds_is_refused(self): + """--stop-limit inf crashed the watching thread (OverflowError in its wait) once a + signal came: inf, nan, a negative number or past STOP_LIMIT_MAX are refused at the + command line.""" + for text in ("inf", "-inf", "nan", "-1", "1e300", "3601", "five"): + with self.assertRaises(argparse.ArgumentTypeError, msg=text): + srv.stop_limit(text) + self.assertEqual(srv.stop_limit("0"), 0) + self.assertEqual(srv.stop_limit("2.5"), 2.5) + refused = subprocess.run([PYTHON, os.path.join(ROOT, "forza_live_server.py"), + "--stop-limit", "inf"], cwd=ROOT, capture_output=True, + text=True, stdin=subprocess.DEVNULL, timeout=60) + self.assertEqual(refused.returncode, 2) + self.assertIn("argument --stop-limit: 'inf': seconds from 0 (never) to 3600", + refused.stderr) + + def test_never_inside_the_stop(self): + """Once the stop has begun, it is never broken into, however long it holds the loop.""" + with self.assertLogs("forza-live", "WARNING"): + steps, took = self.run_held(lambda: self.spin(30), at_stop=lambda: self.spin(1.0)) + self.assertEqual(steps, ["stop", "saved"]) + self.assertGreater(took, 1.0) + + +def free_port(kind=socket.SOCK_DGRAM): + s = socket.socket(socket.AF_INET, kind) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +# A server whose start is stopped: a SIGTERM to itself while its boards are read, or while the +# server's own code is still being imported (before run() has a handler). +DURING_LOAD = """ +import os, signal, sys, time +sys.path.insert(0, os.getcwd()) +from forza_live.competition import scores +real = scores.Store.load +def load(self): + if not self.loaded: + os.kill(os.getpid(), signal.SIGTERM) # docker stop, while the boards are read + time.sleep(0.2) + return real(self) +scores.Store.load = load +from forza_live.server import run +sys.argv = ["forza_live_server.py"] + sys.argv[1:] +run() +""" +DURING_IMPORT = """ +import importlib.abc, os, runpy, signal, sys +class Stop(importlib.abc.MetaPathFinder): + def find_spec(self, name, path=None, target=None): + if name == "forza_live.server": + os.kill(os.getpid(), signal.SIGTERM) # docker stop, while the code is read + return None +sys.meta_path.insert(0, Stop()) +sys.argv = sys.argv[1:] +runpy.run_path(sys.argv[0], run_name="__main__") +""" +# A server with a Discord status whose update takes 3 s (a slow network: it can take tens of +# seconds), its ticks 100 times faster (the update every 0.3 s instead of 30 s), and a line +# when its HTTP port takes no new connection. +SLOW_DISCORD = """ +import logging, os, sys, time +sys.path.insert(0, os.getcwd()) +from forza_live import server as srv +from forza_live.social import discord_status +log = logging.getLogger("forza-live") +def update(status, data_dir, now=None): + log.info("test: the status update starts") + time.sleep(3) + log.info("test: the status update ends") +discord_status.enabled = lambda: True +discord_status.update = update +discord_status.offline = lambda data_dir: log.info("test: the status says offline") +real_wait = srv.StopRequest.wait +async def wait(self, seconds): + return await real_wait(self, seconds / 100) +srv.StopRequest.wait = wait +real_stop_accepting = srv.stop_accepting +def stop_accepting(listening): + real_stop_accepting(listening) + log.info("test: no new connection") +srv.stop_accepting = stop_accepting +sys.argv = ["forza_live_server.py"] + sys.argv[1:] +srv.run() +""" +# A server whose loop is held, from the moment a file appears, by a pure-Python loop, a sleep or +# a C call that signals do not end (a pthread mutex another thread holds): KIND SECONDS FILE. +# edge, chain: held until just before the stop's limit (5 ms, 20 ms), then by a callback of +# 0.1 s, 0.3 s: the signal's note has run and main()'s wakeup waits behind that callback, which +# the break-in lands in. task: the same as chain, but what holds the loop 0.3 s is a connection's +# task (asyncio.start_server's, as http_handler is), woken as the hold ends +HELD = """ +import asyncio, ctypes, logging, os, socket, sys, threading, time +sys.path.insert(0, os.getcwd()) +from forza_live import server as srv +log = logging.getLogger("forza-live") +KIND, SECONDS, TRIGGER = sys.argv[1], float(sys.argv[2]), sys.argv[3] +def c_hold(seconds): + libc = ctypes.CDLL(None) + mutex = ctypes.create_string_buffer(64) + held = threading.Event() + def owner(): + libc.pthread_mutex_lock(mutex) + held.set() + time.sleep(seconds) + libc.pthread_mutex_unlock(mutex) + threading.Thread(target=owner, daemon=True).start() + held.wait() + libc.pthread_mutex_lock(mutex) # (the GIL let go of: the other threads run) + libc.pthread_mutex_unlock(mutex) +def spin(seconds): + end = time.monotonic() + seconds + while time.monotonic() < end: + pass +def hold(stop): + log.info("test: the loop is held") + if KIND in ("edge", "chain", "task"): # free just before the limit, then held again + while stop.first_at is None: + pass + before, again = (0.005, 0.1) if KIND == "edge" else (0.02, 0.3) + spin(stop.first_at + stop.limit - before - time.monotonic()) + if KIND == "task": + go.set() # (the connection's task: its wakeup queued before main()'s) + else: + asyncio.get_running_loop().call_soon(spin, again) + elif KIND == "python": + end = time.monotonic() + SECONDS + while time.monotonic() < end: + pass + elif KIND == "sleep": + time.sleep(SECONDS) + else: + c_hold(SECONDS) + log.info("test: the loop is free") +go = asyncio.Event() +async def connection(reader, writer): + await go.wait() + spin(0.3) + writer.close() +async def trigger(stop): + if KIND == "task": + listening = await asyncio.start_server(connection, "127.0.0.1", 0) + client = socket.create_connection(listening.sockets[0].getsockname()[:2]) + while not os.path.exists(TRIGGER): + await asyncio.sleep(0.01) + hold(stop) +real_main = srv.main +async def main(stop): + asyncio.get_running_loop().create_task(trigger(stop)) + await real_main(stop) +srv.main = main +sys.argv = ["forza_live_server.py"] + sys.argv[4:] +srv.run() +""" +# A server whose HTTP port cannot be taken off the loop at the stop (a closed socket's fd -1). +FAILED_STEP = """ +import os, sys +sys.path.insert(0, os.getcwd()) +from forza_live import server as srv +def stop_accepting(listening): + raise ValueError("Invalid file descriptor: -1") +srv.stop_accepting = stop_accepting +sys.argv = ["forza_live_server.py"] + sys.argv[1:] +srv.run() +""" + + +@POSIX_SIGNALS +class RealStopTest(unittest.TestCase): + """Real servers on this machine, stopped as a container runtime and a terminal stop them.""" + + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.data = os.path.join(self.temp.name, "data") + old = notices.DATA_DIR + self.addCleanup(notices.configure, old) + notices.configure(self.data) # a notification only in the journal: the stop writes + notices.STORE.load() # notifications.json whole, and says so + notices.send(PLAYER, notices.NEWS, {"Message": "before the stop"}) + notices.configure(old) + + def start(self, *flags, head=None, data=True): + http = free_port(socket.SOCK_STREAM) + args = ["--host", "127.0.0.1", "--port", str(free_port())] + if data: + args += ["--http-port", str(http), "--data-dir", self.data] + log = open(os.path.join(self.temp.name, "server.log"), "w+") + self.addCleanup(log.close) + proc = subprocess.Popen((head or [PYTHON, os.path.join(ROOT, "forza_live_server.py")]) + + args + list(flags), cwd=ROOT, stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT) + self.addCleanup(lambda: proc.poll() is None and (proc.kill(), proc.wait())) + return proc, log, http + + def ready(self, proc, http): + deadline = time.monotonic() + 30 + while True: + try: + return json.loads(urllib.request.urlopen( + "http://127.0.0.1:%d/status" % http, timeout=2).read()) + except (urllib.error.URLError, OSError, ValueError): + if proc.poll() is not None or time.monotonic() > deadline: + raise RuntimeError("the server did not start") + time.sleep(0.05) + + def ended(self, proc, log): + """The exit status and the log, once the process has ended (20 s: the public server's + time to stop).""" + try: + proc.wait(20) + except subprocess.TimeoutExpired: + self.fail("the stop was lost: the server still runs") + log.seek(0) + return proc.returncode, log.read().splitlines() + + def assert_stopped_cleanly(self, status, lines, first="stop: SIGTERM: the server stops"): + text = "\n".join(lines) + self.assertEqual(status, 0, text) + self.assertNotIn("Traceback", text) + self.assertNotIn("Exception ignored", text) + self.assertNotIn("Task was destroyed", text) + said = [line.split(" ", 2)[2] for line in lines] + self.assertIn(first, said) + stop = said.index(first) + # the last lines: the notifications', then the boards' (then, when signals came while + # they were written, the line that says so) + if " again while notifications.json and scoreboards.json were written" in said[-1]: + said = said[:-1] + self.assertRegex(said[-2], r"^notifications: notifications\.json written whole at the " + r"stop in [\d.]+ s: it has every change: 1 notification ") + self.assertRegex(said[-1], r"^scoreboards: .*at the stop") + self.assertLess(stop, len(said) - 2) + with open(os.path.join(self.data, "notifications.json")) as f: + self.assertIn("before the stop", f.read()) + self.assertTrue(os.path.exists(os.path.join(self.data, srv.STATE_FILE))) + return said[stop:] + + def busy(self, http, stop): + """Connections opened and dropped: tasks die, their weak references are cleaned up.""" + while not stop.is_set(): + try: + c = socket.create_connection(("127.0.0.1", http), timeout=2) + c.sendall(b"GET /sta") + c.close() + except OSError: + time.sleep(0.01) + + def test_sigterm_while_busy(self): + proc, log, http = self.start() + self.ready(proc, http) + stop = threading.Event() + loader = threading.Thread(target=self.busy, args=(http, stop)) + loader.start() + self.addCleanup(loader.join) + self.addCleanup(stop.set) + time.sleep(0.3) + proc.send_signal(signal.SIGTERM) + status, lines = self.ended(proc, log) + stop.set() + self.assertEqual(self.assert_stopped_cleanly(status, lines)[1:], [ + line.split(" ", 2)[2] for line in lines[-2:]]) # nothing between but the saves + + def test_ctrl_c(self): + proc, log, http = self.start() + self.ready(proc, http) + proc.send_signal(signal.SIGINT) + self.assert_stopped_cleanly(*self.ended(proc, log), first="stop: SIGINT: the server stops") + + def test_three_signals_change_nothing(self): + """docker stop, then again and again while it stops: the stop and its saves as for one, + and a line in the log for the signals it held.""" + proc, log, http = self.start() + self.ready(proc, http) + for number in (signal.SIGTERM, signal.SIGTERM, signal.SIGINT): + proc.send_signal(number) + time.sleep(0.01) # the last one as the process ends, often (its status stays 0) + said = self.assert_stopped_cleanly(*self.ended(proc, log)) + self.assertTrue(all(line.startswith(("stop: ", "notifications: ", "scoreboards: ")) + for line in said), said) + + def test_a_signal_while_the_stores_are_read(self): + """The boards are read whole, the server starts and then stops, with every save.""" + proc, log, _ = self.start(head=[PYTHON, "-c", DURING_LOAD]) + self.assert_stopped_cleanly(*self.ended(proc, log), first="stop: SIGTERM during the " + "start: the server stops now that it is done") + + def test_a_signal_while_the_code_is_read(self): + proc, log, _ = self.start(head=[PYTHON, "-c", DURING_IMPORT, + os.path.join(ROOT, "forza_live_server.py")]) + self.assert_stopped_cleanly(*self.ended(proc, log), first="stop: SIGTERM during the " + "start: the server stops now that it is done") + + def test_the_saves_do_not_wait_for_the_discord_status(self): + """A stop while the tick waits for the Discord status update: the saves at once, then + the update's end, then the offline status (the last edit). They used to come once the + update was done, and an update past the stop's 20 s cost them all.""" + proc, log, http = self.start(head=[PYTHON, "-c", SLOW_DISCORD]) + deadline = time.monotonic() + 30 + while "test: the status update starts" not in (log.seek(0) or log.read()): + self.assertLess(time.monotonic(), deadline, "no status update") + self.assertIsNone(proc.poll()) + time.sleep(0.02) + proc.send_signal(signal.SIGTERM) + status, lines = self.ended(proc, log) + text = "\n".join(lines) + self.assertEqual(status, 0, text) + self.assertNotIn("Traceback", text) + said = [line.split(" ", 2)[2] for line in lines] + order = [said.index(line) for line in ( + "stop: SIGTERM: the server stops", "test: no new connection", + "test: the status update ends", "test: the status says offline")] + self.assertEqual(order, sorted(order), text) + saves = [i for i, line in enumerate(said) if line.startswith( + ("notifications: notifications.json written whole at the stop", "scoreboards: ")) + and "at the stop" in line] + self.assertEqual(len(saves), 2, text) + self.assertTrue(order[1] < saves[0] < saves[1] < order[2], text) + self.assertEqual(said.index("test: the status says offline"), len(said) - 1, text) + + def held(self, kind, seconds, *flags): + """A server whose loop is held (HELD), and a SIGTERM 0.5 s into the hold.""" + trigger = os.path.join(self.temp.name, "hold") + proc, log, http = self.start(*flags, head=[PYTHON, "-c", HELD, kind, str(seconds), + trigger]) + self.ready(proc, http) + open(trigger, "w").close() + deadline = time.monotonic() + 30 + while "test: the loop is held" not in (log.seek(0) or log.read()): + self.assertLess(time.monotonic(), deadline, "not held") + time.sleep(0.01) + time.sleep(0.5) + proc.send_signal(signal.SIGTERM) + return proc, log + + def test_a_loop_held_3_s_stops_once_it_is_free(self): + """Under the stop's limit (5 s): the loop takes the signal itself, once it is free.""" + proc, log = self.held("python", 3) + status, lines = self.ended(proc, log) + self.assert_stopped_cleanly(status, lines) + said = [line.split(" ", 2)[2] for line in lines] + self.assertLess(said.index("test: the loop is free"), + said.index("stop: SIGTERM: the server stops"), said) + self.assertFalse(any("breaks into" in line for line in said), said) + + def test_a_loop_held_past_the_limit_is_broken_into_and_saves(self): + """A loop held by Python code past --stop-limit: broken into, the stop and every save, + exit status 0, long before the container runtime's kill.""" + began = time.monotonic() + proc, log = self.held("python", 60, "--stop-limit", "1") + said = self.assert_stopped_cleanly(*self.ended(proc, log)) + self.assertLess(time.monotonic() - began, 15) + log.seek(0) + lines = [line.split(" ", 2)[2] for line in log.read().splitlines()] + self.assertNotIn("test: the loop is free", lines) # it was broken into + told = [i for i, line in enumerate(lines) if line.startswith( + "stop: SIGTERM came 1 s ago and the event loop has not taken it")] + self.assertEqual(len(told), 1, lines) + self.assertLess(told[0], lines.index("stop: SIGTERM: the server stops")) + self.assertEqual(said[0], "stop: SIGTERM: the server stops") + + def assert_broken_into_at_the_limit(self, kind): + proc, log = self.held(kind, 0, "--stop-limit", "1") + status, lines = self.ended(proc, log) + self.assert_stopped_cleanly(status, lines) + said = [line.split(" ", 2)[2] for line in lines] + self.assertTrue(any(line.endswith("the stop breaks into it") for line in said), said) + + def test_a_loop_free_at_the_limit_then_held_by_a_callback(self): + """The loop frees itself as the break-in comes, and the break-in lands in the next + callback: main()'s stop runs first (its wakeup was queued before run()'s own task for + the stop), and that task is part of the stop, not cancelled with the others (it was: + a CancelledError out of run(), exit status 1, after every save).""" + self.assert_broken_into_at_the_limit("edge") + + def test_a_loop_free_before_the_limit_then_held_again(self): + self.assert_broken_into_at_the_limit("chain") + + def test_a_connection_s_task_broken_into(self): + """The break-in lands in a connection's task (http_handler's, from asyncio's streams): + the task the BreakIn ended is no error to log (asyncio logged it, "Unhandled exception + in client_connected_cb" and a traceback, after the saves).""" + self.assert_broken_into_at_the_limit("task") + + def test_a_loop_held_in_a_sleep_is_broken_into(self): + proc, log = self.held("sleep", 60, "--stop-limit", "1") + self.assert_stopped_cleanly(*self.ended(proc, log)) + + @unittest.skipUnless(sys.platform.startswith("linux"), "a pthread mutex through ctypes") + def test_a_call_that_cannot_be_broken_into_ends_before_the_kill(self): + """A C call that signals do not end: the stop waits for it, and is broken into as soon + as it returns, with every save.""" + proc, log = self.held("c", 4, "--stop-limit", "1") + status, lines = self.ended(proc, log) + self.assert_stopped_cleanly(status, lines) + said = [line.split(" ", 2)[2] for line in lines] + self.assertTrue(any(line.endswith("the stop breaks into it") for line in said), said) + self.assertNotIn("test: the loop is free", said) # broken into as the call returned + + @unittest.skipUnless(sys.platform.startswith("linux"), "a pthread mutex through ctypes") + def test_a_call_that_cannot_be_broken_into_past_the_kill(self): + """Not ended by the container runtime's kill (here at 8 s): nothing can save there. The + log says what the stop waited for; exit status -9, no save made.""" + proc, log = self.held("c", 60, "--stop-limit", "1") + try: + proc.wait(8) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + self.assertEqual(proc.returncode, -signal.SIGKILL) + log.seek(0) + text = log.read() + self.assertIn("the stop breaks into it", text) + self.assertIn("stop: the event loop is still held 5 s later: inside a call that cannot " + "be broken into; the stop waits for it", text) + self.assertNotIn("stop: SIGTERM: the server stops", text) + self.assertFalse(os.path.exists(os.path.join(self.data, "notifications.json"))) + + def test_nothing_new_is_taken_after_the_saves(self): + """During the wait for a Discord status update after the saves, no datagram is answered + (no player joins) and a connection opened before the stop gets no answer: nothing + changes a store after its save.""" + proc, log, http = self.start(head=[PYTHON, "-c", SLOW_DISCORD]) + udp = int(proc.args[proc.args.index("--port") + 1]) + self.ready(proc, http) + before = socket.create_connection(("127.0.0.1", http), timeout=5) + self.addCleanup(before.close) + request = b"GET /status HTTP/1.1\r\nHost: x\r\nConnection: keep-alive\r\n\r\n" + before.sendall(request) + self.assertTrue(before.recv(65536).startswith(b"HTTP/1.1 200")) + deadline = time.monotonic() + 30 + while "test: the status update starts" not in (log.seek(0) or log.read()): + self.assertLess(time.monotonic(), deadline, "no status update") + time.sleep(0.02) + proc.send_signal(signal.SIGTERM) + while not re.search(r"scoreboards: .*at the stop", log.seek(0) or log.read()): + self.assertLess(time.monotonic(), deadline, "no saves") + time.sleep(0.01) + game = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.addCleanup(game.close) + game.settimeout(0.5) + game.sendto(hello(1, PLAYER, "Late"), ("127.0.0.1", udp)) + try: + answer = game.recv(2048) + except OSError: # nothing, or the port's refusal + answer = b"" + self.assertEqual(answer, b"") + try: + before.sendall(request) + late = before.recv(65536) + except OSError: + late = b"" + self.assertEqual(late, b"") + status, lines = self.ended(proc, log) + text = "\n".join(lines) + self.assertEqual(status, 0, text) + self.assertNotIn("Traceback", text) + self.assertNotIn("join", text) + self.assertIn("test: the status update ends", text) # the wait was under way meanwhile + said = [line.split(" ", 2)[2] for line in lines] + self.assertGreater(said.index("test: the status update ends"), + [i for i, line in enumerate(said) if line.startswith("scoreboards: ")][0]) + + def test_a_step_before_the_saves_that_fails_does_not_skip_them(self): + proc, log, http = self.start(head=[PYTHON, "-c", FAILED_STEP]) + self.ready(proc, http) + proc.send_signal(signal.SIGTERM) + status, lines = self.ended(proc, log) + text = "\n".join(lines) + self.assertEqual(status, 0, text) + self.assertIn("stop: a step before the saves failed; the saves are made all the same", + text) + self.assertIn("ValueError: Invalid file descriptor: -1", text) + self.assertRegex(lines[-2], r"notifications: notifications\.json written whole at the " + r"stop") + self.assertRegex(lines[-1], r"scoreboards: .*at the stop") + + def test_a_relay(self): + relay_port = free_port() + secret = relays.add_relay(os.path.join(self.temp.name, "main"), "local-1", "Local", + "127.0.0.1:%d" % relay_port, "Here") + proc, log, _ = self.start("--relay-only", "--relay-of", "127.0.0.1:%d" % free_port(), + "--relay-id", "local-1", "--relay-secret-file", secret, + data=False) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + log.seek(0) + if "relay local-1 on UDP" in log.read(): + break + time.sleep(0.05) + proc.send_signal(signal.SIGTERM) + status, lines = self.ended(proc, log) + self.assertEqual(status, 0, lines) + self.assertTrue(lines[-1].endswith("stop: SIGTERM: the server stops"), lines) + self.assertNotIn("Traceback", "\n".join(lines)) + + def test_a_start_refused_still_exits_1(self): + os.mkdir(os.path.join(self.data, "scoreboards.json")) # cannot be read + proc, log, _ = self.start() + status, lines = self.ended(proc, log) + self.assertEqual(status, 1) + self.assertRegex(lines[-1], r"scoreboards\.json cannot be read .* not started") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/social/test_notifications_journal.py b/tests/social/test_notifications_journal.py index 8501ef7..8b9829c 100644 --- a/tests/social/test_notifications_journal.py +++ b/tests/social/test_notifications_journal.py @@ -650,10 +650,10 @@ def test_the_server_writes_it_before_the_boards_whatever_happens_to_it(self): boards.assert_called_once_with() self.assertIn("stop: the notifications could not be written", logs.output[0]) - def test_a_second_signal_during_its_write_still_lets_the_boards_be_written(self): - """docker stop twice: the second signal comes while notifications.json is written - whole at the stop (the stop signals are no longer held then). That write ends, the - journal has every change, and the boards' stop still runs before the stop ends.""" + def test_a_second_and_third_signal_during_the_writes_change_nothing(self): + """docker stop again while notifications.json is written whole at the stop, and once + more while the boards are (#78: the signals are held for the whole stop). Neither write + is cut short, and the log says the signals were ignored.""" old = scores.DATA_DIR self.addCleanup(scores.configure, old) scores.configure(self.dir.name, "main-1") @@ -664,18 +664,28 @@ def test_a_second_signal_during_its_write_still_lets_the_boards_be_written(self) def dump(*args): signal.raise_signal(signal.SIGTERM) # docker stop again, in the middle of it return real(*args) - previous = signal.signal(signal.SIGTERM, signal.default_int_handler) # as run() has it - self.addCleanup(signal.signal, signal.SIGTERM, previous) + boards_stop = scores.STORE.stop + + def boards(): + signal.raise_signal(signal.SIGINT) # and Ctrl+C while the boards are written + return boards_stop() + for number in srv.STOP_SIGNALS: # the worst handler there could be outside the stop + self.addCleanup(signal.signal, number, signal.signal(number, signal.default_int_handler)) with mock.patch.object(notices, "dump", dump), \ - mock.patch.object(scores.STORE, "stop", wraps=scores.STORE.stop) as boards, \ + mock.patch.object(scores.STORE, "stop", side_effect=boards) as stopped, \ self.assertLogs("forza-live", "INFO") as logs: - self.assertRaises(KeyboardInterrupt, srv.save_at_stop, self.server()) - boards.assert_called_once_with() - self.assertTrue(any("KeyboardInterrupt while notifications.json was written whole" in - line and line.startswith("WARNING") for line in logs.output), - logs.output) - self.assertFalse(os.path.exists(self.path("notifications.json"))) - self.restart() # nothing lost: the journal had it + try: + srv.save_at_stop(self.server()) + except KeyboardInterrupt: + self.fail("a signal cut the stop's writes short") + stopped.assert_called_once_with() + self.assertIn("INFO:forza-live:stop: SIGTERM again while notifications.json and " + "scoreboards.json were written: ignored until they were", logs.output) + self.assertFalse(any(line.startswith("WARNING") for line in logs.output), logs.output) + with open(self.path("notifications.json")) as f: + self.assertIn("only in the journal", f.read()) # written whole: alone it is complete + self.assertIs(signal.getsignal(signal.SIGTERM), signal.default_int_handler) + self.restart() self.assertEqual([n["id"] for n in notices.pending(A)], [nid]) def test_rolling_back_without_the_fold(self): diff --git a/tools/stop_loop.py b/tools/stop_loop.py new file mode 100644 index 0000000..053fbc4 --- /dev/null +++ b/tools/stop_loop.py @@ -0,0 +1,308 @@ +#!/usr/bin/env python3 +"""Stop a busy server over and over, and count the stops that were lost (#78). + +Usage: stop_loop.py RUNS [--repo DIR] [--python EXE] [--signals SIGTERM[,SIGINT...]] [--gap S] + [--gc-threshold N] [--slow-discord S] [--held SHARE] [--diag] + [--out FILE.jsonl] + +Each run starts the server (forza_live_server.py of --repo, this repository by default) on +127.0.0.1 with free ports and a temporary data folder, waits for /status, and puts it under load: +HTTP connections opened and closed as fast as one thread can (a third answered, a third dropped +after half a request, a third dropped at once) and junk UDP datagrams, so tasks die and their weak +references are cleaned up all the time. --gc-threshold N runs the server with +gc.set_threshold(N), the garbage collector at work far more often. --slow-discord S turns on a +Discord status (nothing sent) whose update takes S seconds, with the server's ticks 100 times +faster (an update every 0.3 s instead of 30 s): most signals then come while the tick waits for +it, and the stop's saves must not wait for it. --held SHARE: in that share of the runs the +signal comes while a task holds the loop with Python code, 2-4 s (the loop takes the signal +once free) or 8-40 s (the stop breaks into it after its 5 s limit). At a random moment the run +sends the signal(s), --gap seconds apart, and waits 20 s (the public server's stop_grace_period) +for the process to end. + +A stop is LOST when the process still runs after those 20 s; it is killed then (with --diag it is +asked for the stacks of all its threads first: faulthandler, in its log). Each run also checks +the stop's saves: every data folder starts with a notification that only notifications.journal +has, so a stop that saves writes notifications.json whole (its line in the log) and +live_state.json, and logs the boards' line, after the notifications' one and with nothing but +an "again" line after it. Logs with a traceback, an "Exception ignored" or a "Task was +destroyed" are counted too. The time of a stop is from the first signal to the process's end. + +Prints each run that went wrong and a summary; --out adds a JSON line per run to FILE.jsonl. +Use nice and keep it to batches: each run is about 2 cores for a second or two. +""" +import argparse +import json +import os +import random +import shutil +import signal +import socket +import statistics +import subprocess +import sys +import tempfile +import threading +import time +import urllib.request + +STOP_TIMEOUT = 20.0 +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +# the server run as forza_live_server.py runs it, with what --gc-threshold, --slow-discord, +# --held and --diag add +WRAPPER = ("import gc, faulthandler, runpy, signal, sys\n" + "if {gc}: gc.set_threshold({gc})\n" + "if {slow}:\n" + " import time\n" + " from forza_live import server\n" + " from forza_live.social import discord_status\n" + " discord_status.enabled = lambda: True\n" + " discord_status.update = lambda *a, **k: time.sleep({slow})\n" + " discord_status.offline = lambda data_dir: None\n" + " real_wait = server.StopRequest.wait\n" + " async def wait(self, seconds):\n" + " return await real_wait(self, seconds / 100)\n" + " server.StopRequest.wait = wait\n" + "if {held}:\n" + " import asyncio, os, time\n" + " from forza_live import server\n" + " real_main = server.main\n" + " async def hold():\n" + " while not os.path.exists({trigger!r}):\n" + " await asyncio.sleep(0.01)\n" + " server.log.info('test: the loop is held')\n" + " end = time.monotonic() + {held}\n" + " while time.monotonic() < end:\n" + " pass\n" + " server.log.info('test: the loop is free')\n" + " async def main(stop):\n" + " asyncio.get_running_loop().create_task(hold())\n" + " await real_main(stop)\n" + " server.main = main\n" + "if {diag}: faulthandler.register(signal.SIGUSR1, all_threads=True)\n" + "sys.argv = sys.argv[1:]\n" + "runpy.run_path(sys.argv[0], run_name='__main__')\n") +SEED = ("import sys; sys.path.insert(0, sys.argv[1]); from forza_live.social import " + "notifications as n; n.configure(sys.argv[2]); n.STORE.load(); " + "n.send(0x0009000000000001, n.NEWS, {'Message': 'before the stop'})") + + +def free(kind): + s = socket.socket(socket.AF_INET, kind) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +def load(http, udp, stop): + junk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + n = 0 + while not stop.is_set(): + n += 1 + try: + c = socket.create_connection(("127.0.0.1", http), timeout=2) + if n % 3 == 0: + c.sendall(b"GET /status HTTP/1.0\r\nHost: x\r\n\r\n") + c.recv(65536) + elif n % 3 == 1: + c.sendall(b"GET /sta") + c.close() + except OSError: + time.sleep(0.005) + if n % 4 == 0: + try: + junk.sendto(os.urandom(random.randint(1, 64)), ("127.0.0.1", udp)) + except OSError: + pass + junk.close() + + +def stamp(line): + """The time of a log line ("2026-11-15 13:13:44,695 ..."), or None.""" + try: + return time.mktime(time.strptime(line[:19], "%Y-%m-%d %H:%M:%S")) + int(line[20:23]) / 1000 + except (ValueError, IndexError): + return None + + +def one(args, signals, template): + with tempfile.TemporaryDirectory() as top: + data = os.path.join(top, "data") + shutil.copytree(template, data) + http, udp = free(socket.SOCK_STREAM), free(socket.SOCK_DGRAM) + log_path = os.path.join(top, "server.log") + trigger = os.path.join(top, "hold") + held = 0.0 + if random.random() < args.held: # under the stop's limit, or far past it + held = random.uniform(2, 4) if random.random() < 0.5 else random.uniform(8, 40) + wrapper = WRAPPER.format(gc=args.gc_threshold, diag=args.diag, slow=args.slow_discord, + held=held, trigger=trigger) + with open(log_path, "w") as log: + proc = subprocess.Popen( + [args.python, "-c", wrapper, os.path.join(args.repo, "forza_live_server.py"), + "--host", "127.0.0.1", "--port", str(udp), "--http-port", str(http), + "--data-dir", data], + cwd=args.repo, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT) + deadline = time.monotonic() + 30 + started = False + while time.monotonic() < deadline and proc.poll() is None: + try: + urllib.request.urlopen("http://127.0.0.1:%d/status" % http, timeout=2).read() + started = True + break + except OSError: + time.sleep(0.02) + stop = threading.Event() + loader = threading.Thread(target=load, args=(http, udp, stop), daemon=True) + loader.start() + time.sleep(random.uniform(0.2, 1.2)) + if held and started: + open(trigger, "w").close() + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + with open(log_path, errors="replace") as f: + if "test: the loop is held" in f.read(): + break + time.sleep(0.01) + time.sleep(random.uniform(0.2, 1.0)) + sent, sent_at = time.monotonic(), time.time() + for i, name in enumerate(signals): + if i: + time.sleep(args.gap) + try: + proc.send_signal(getattr(signal, name)) + except ProcessLookupError: + pass + # a blocking wait, timed to the moment the process ends (wait(timeout) polls, with + # sleeps of up to 50 ms) + waiter = threading.Thread(target=proc.wait, daemon=True) + waiter.start() + waiter.join(STOP_TIMEOUT) + lost = waiter.is_alive() + if lost: + if args.diag: + proc.send_signal(signal.SIGUSR1) + time.sleep(1.0) + proc.kill() + waiter.join() + took, ended_at = time.monotonic() - sent, time.time() + stop.set() + loader.join() + with open(log_path, errors="replace") as f: + text = f.read() + state = os.path.exists(os.path.join(data, "live_state.json")) + whole = os.path.exists(os.path.join(data, "notifications.json")) + lines = text.splitlines() + saved = (state and whole + and any("notifications: notifications.json written whole at the stop" in line + for line in lines) + and any("scoreboards:" in line and "at the stop" in line for line in lines)) + # the log's clock: from the signal to the stop's first line (a version without one: its first + # save line), then to its last save line, then to the process's end (the loop's close, the + # connections still open, the exit) + phases = None + stamps = [stamp(line) for line in lines if " stop: " in line or "at the stop" in line] + if stamps and None not in stamps: + phases = [round(stamps[0] - sent_at, 4), round(stamps[-1] - stamps[0], 4), + round(ended_at - stamps[-1], 4)] + # the saves' lines: one notifications line, then one boards line, nothing after them but + # an "again" line + said = [line for line in lines if " notifications: " in line and "at the stop" in line + or " scoreboards: " in line and "at the stop" in line] + order = (len(said) == 2 and " notifications: " in said[0] and " scoreboards: " in said[1] + and all(" again while " in line for line in lines[lines.index(said[1]) + 1:])) + broke = "the stop breaks into it" in text + bad = (lost or not saved or proc.returncode != 0 or "Traceback" in text + or "Exception ignored" in text or "Task was destroyed" in text or not order + or (held and broke != (held > 5))) + return {"started": started, "lost": lost, "rc": proc.returncode, "took": round(took, 4), + "saved": saved, "traceback": "Traceback" in text, + "ignored": "Exception ignored" in text, "destroyed": "Task was destroyed" in text, + "order": order, "held": round(held, 2), "broke": broke, + "last": lines[-2:], "phases": phases, + "again": sum(" again while " in line for line in lines), + "tail": text[-4000:] if bad else ""} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("runs", type=int) + parser.add_argument("--repo", default=ROOT, help="the server's folder (default: this one)") + parser.add_argument("--python", default=sys.executable, help="the Python that runs it") + parser.add_argument("--signals", default="SIGTERM", help="sent in this order (default SIGTERM)") + parser.add_argument("--gap", type=float, default=0.0, help="seconds between the signals") + parser.add_argument("--gc-threshold", type=int, default=0, metavar="N", + help="gc.set_threshold(N) in the server (default: Python's)") + parser.add_argument("--slow-discord", type=float, default=0.0, metavar="S", + help="a Discord status update that takes S seconds, every 0.3 s") + parser.add_argument("--held", type=float, default=0.0, metavar="SHARE", + help="in this share of the runs (0-1) the signal comes while the " + "server's loop is held by Python code: 2-4 s (it takes the " + "signal once free) or 8-40 s (past the stop's 5 s limit: broken " + "into)") + parser.add_argument("--diag", action="store_true", + help="the stacks of a lost stop's threads in its log, before the kill") + parser.add_argument("--out", help="a JSON line per run, added to this file") + args = parser.parse_args() + signals = args.signals.split(",") + version = subprocess.run([args.python, "-c", "import platform; print(platform.python_version())"], + capture_output=True, text=True).stdout.strip() + template = tempfile.mkdtemp() + out = open(args.out, "a") if args.out else None + results = [] + try: + subprocess.run([args.python, "-c", SEED, args.repo, template], check=True, + capture_output=True) + for i in range(args.runs): + r = one(args, signals, template) + results.append(r) + if out: + out.write(json.dumps(dict(r, python=version, signals=args.signals, + gc=args.gc_threshold, + slow_discord=args.slow_discord)) + "\n") + out.flush() + if r["tail"]: + print("run %d: lost=%s rc=%s saved=%s took=%.2f s\n%s" % ( + i, r["lost"], r["rc"], r["saved"], r["took"], r["tail"]), flush=True) + finally: + shutil.rmtree(template, ignore_errors=True) + if out: + out.close() + took = sorted(r["took"] for r in results if not r["lost"]) + print("Python %s, %d runs, %s%s: lost %d, without the stop's saves %d, exit status not 0 %d, " + "a traceback %d, 'Exception ignored' %d, not started %d" % ( + version, len(results), args.signals, + (", gc threshold %d" % args.gc_threshold if args.gc_threshold else "") + + (", Discord update %g s" % args.slow_discord if args.slow_discord else ""), + sum(r["lost"] for r in results), sum(not r["saved"] for r in results), + sum(r["rc"] != 0 for r in results), sum(r["traceback"] for r in results), + sum(r["ignored"] for r in results), sum(not r["started"] for r in results))) + print("'Task was destroyed' %d, the saves' lines out of order %d" % ( + sum(r["destroyed"] for r in results), sum(not r["order"] for r in results))) + held = [r for r in results if r["held"]] + if held: + print("held loops: %d (%d under the limit, %d past it), broken into %d, wrong way %d, " + "slowest of them %.2f s" % ( + len(held), sum(r["held"] <= 5 for r in held), sum(r["held"] > 5 for r in held), + sum(r["broke"] for r in held), + sum(r["broke"] != (r["held"] > 5) for r in held), + max(r["took"] for r in held))) + if len(signals) > 1: + print("the log said a signal was ignored during the saves in %d runs (%d lines)" % ( + sum(r["again"] > 0 for r in results), sum(r["again"] for r in results))) + phases = [r["phases"] for r in results if r["phases"]] + if phases: + print("of which (the log's millisecond clock), median / max: signal to the stop's first " + "line %s, its saves %s, the end after them %s" % tuple( + "%.3f / %.3f s" % (statistics.median(p[k] for p in phases), + max(p[k] for p in phases)) for k in range(3))) + if took: + print("stop time, first signal to exit: median %.3f s, 99th percentile %.3f s, " + "max %.3f s" % (statistics.median(took), + took[min(len(took) - 1, int(len(took) * 0.99))], took[-1])) + return 1 if any(r["lost"] or not r["saved"] or r["rc"] != 0 or not r["order"] + for r in results) else 0 + + +if __name__ == "__main__": + sys.exit(main())