From fb2117df9221634527e5de4df3707a4cec138a01 Mon Sep 17 00:00:00 2001 From: Mateo Rossi Date: Tue, 27 Oct 2026 13:30:00 +1100 Subject: [PATCH 1/9] test(gated): expect a stalled list download to say how far it got Exercise a stalled HTTPS list body after 4096 of 65536 bytes and a TLS handshake that never answers after TCP connect. The failed fetch line should append phase, received body bytes, and the response Content-Length after its existing fields. Today both cases report only curl=28 reason=timeout. CTest accepts this run only when both cases fail in that current way. --- CMakeLists.txt | 7 +- tests/test_ticket_fetch_progress.py | 194 ++++++++++++++++++++++++++++ 2 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 tests/test_ticket_fetch_progress.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c87aa31..e65c439 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -153,6 +153,11 @@ set_tests_properties(hub_tls PROPERTIES TIMEOUT 60) add_test(NAME tls_failure_reasons COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_tls_failure_reasons.py $ $) set_tests_properties(tls_failure_reasons PROPERTIES TIMEOUT 120) +add_test(NAME ticket_fetch_progress COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/tests/test_ticket_fetch_progress.py $) +# The next commit removes PASS_REGULAR_EXPRESSION when the log says how far the download got. +set_tests_properties(ticket_fetch_progress PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "result: stalled list downloads do not say how far they got") add_test(NAME device_tls COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_device_tls.py $) set_tests_properties(device_tls PROPERTIES TIMEOUT 40) @@ -238,5 +243,5 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") endif() add_test(NAME status_deadline COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_status_deadline.py $ $) -set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons http_distribution offline_reports protocol_compat status_deadline +set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons ticket_fetch_progress http_distribution offline_reports protocol_compat status_deadline PROPERTIES RESOURCE_LOCK status_ports) diff --git a/tests/test_ticket_fetch_progress.py b/tests/test_ticket_fetch_progress.py new file mode 100644 index 0000000..47fb142 --- /dev/null +++ b/tests/test_ticket_fetch_progress.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Describe the progress fields expected on stalled ticket fetches.""" +import os +from pathlib import Path +import socket +import ssl +import subprocess +import sys +import tempfile +import threading + + +SOURCE = Path(__file__).resolve().parents[1] +OLD_LIST = b'GP-999999999999\n' +CASES = ('body_stall', 'handshake_stall') + + +class SetupError(Exception): + pass + + +class StalledHub: + def __init__(self, certs, case): + self.case = case + self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + self.context.load_cert_chain(str(certs / 'hub/chain.pem'), + str(certs / 'hub/key.pem')) + self.context.load_verify_locations(cafile=str(certs / 'hub/ca.pem')) + self.context.verify_mode = ssl.CERT_REQUIRED + self.listener = socket.socket() + try: + self.listener.bind(('127.0.0.1', 8444)) + self.listener.listen(1) + self.listener.settimeout(.1) + except BaseException: + self.listener.close() + raise + self.finished = threading.Event() + self.accepted = False + self.request = b'' + self.error = None + self.thread = threading.Thread(target=self.serve, daemon=True) + self.thread.start() + + def serve(self): + try: + while not self.finished.is_set(): + try: + peer, _ = self.listener.accept() + break + except socket.timeout: + continue + else: + return + with peer: + self.accepted = True + if self.case == 'body_stall': + peer.settimeout(2) + with self.context.wrap_socket(peer, server_side=True) as tls: + while b'\r\n\r\n' not in self.request: + part = tls.recv(4096) + if not part: + raise SetupError('gate closed before sending the HTTP request') + self.request += part + if len(self.request) > 65536: + raise SetupError('gate sent an oversized HTTP request') + digest = b'0' * 64 + tls.sendall(b'HTTP/1.1 200 OK\r\nContent-Length: 65536\r\n' + b'ETag: "' + digest + b'"\r\n' + b'X-Content-SHA256: ' + digest + b'\r\n\r\n' + + b'x' * 4096) + self.finished.wait() + else: + self.finished.wait() + except BaseException as exc: + self.error = exc + + def close(self): + self.finished.set() + self.thread.join(timeout=3) + self.listener.close() + if self.thread.is_alive(): + raise SetupError(f'{self.case}: fake hub did not stop') + if self.error is not None: + raise SetupError(f'{self.case}: fake hub failed: {self.error}') + if not self.accepted: + raise SetupError(f'{self.case}: fake hub saw no TCP connection') + if self.case == 'body_stall' and not self.request.startswith(b'GET /tickets HTTP/1.1\r\n'): + raise SetupError(f'{self.case}: expected GET /tickets, saw {self.request!r}') + + +def fields(line): + result = [] + for token in line.split(): + if '=' not in token: + return None + key, value = token.split('=', 1) + if not key or any(key == name for name, _ in result): + return None + result.append((key, value)) + if ('level', 'WARN') not in result or sum(key == 'level' for key, _ in result) != 1: + return None + return [(key, value) for key, value in result if key not in ('time', 'level')] + + +def classify(case, result, timed_out, local): + lines = [line for line in result.stderr.splitlines() + if 'event=ticket_fetch state=failed' in line] + if timed_out: + return 'unexpected', f'gate did not exit within 5 seconds; stderr={result.stderr!r}', lines + contents = local.read_bytes() + if contents != OLD_LIST: + return 'unexpected', f'local list changed to {contents!r}', lines + if result.returncode != 0: + return 'unexpected', f'gate exited with status {result.returncode}; stderr={result.stderr!r}', lines + if len(lines) != 1: + return 'unexpected', f'expected one failed fetch line, saw {len(lines)}; stderr={result.stderr!r}', lines + observed = fields(lines[0]) + base = [('event', 'ticket_fetch'), ('state', 'failed'), ('http', '200' if case == 'body_stall' else '0'), + ('curl', '28'), ('reason', 'timeout')] + progress = ([('phase', 'body'), ('received', '4096'), ('expected', '65536')] + if case == 'body_stall' else + [('phase', 'tls'), ('received', '0'), ('expected', 'unknown')]) + if observed == base + progress: + return 'pass', 'saw the expected ordered fields', lines + if observed == base: + return 'fails as today', 'saw only the current ordered fields', lines + return 'unexpected', f'saw fields {observed!r}', lines + + +def run_case(binary, certs, work, case): + local = work / f'{case}.txt' + local.write_bytes(OLD_LIST) + env = {key: value for key, value in os.environ.items() + if not key.startswith('GATEPOST_')} + role = certs / 'gate1' + env.update(GATEPOST_TLS_CA=str(role / 'ca.pem'), + GATEPOST_TLS_CERT=str(role / 'chain.pem'), + GATEPOST_TLS_KEY=str(role / 'key.pem')) + while True: + with socket.socket() as unused: + unused.bind(('127.0.0.1', 0)) + hub_port = unused.getsockname()[1] + if hub_port != 8444: + break + hub = StalledHub(certs, case) + timed_out = False + try: + try: + result = subprocess.run([binary, '--gate-id', 'gate1', '--hub', + f'127.0.0.1:{hub_port}', str(local)], + env=env, input='', text=True, capture_output=True, + timeout=5) + except subprocess.TimeoutExpired as exc: + timed_out = True + result = subprocess.CompletedProcess(exc.cmd, -1, '', + (exc.stderr or b'').decode(errors='replace') + if isinstance(exc.stderr, bytes) else exc.stderr or '') + finally: + hub.close() + return classify(case, result, timed_out, local) + + +def main(binary): + outcomes = [] + with tempfile.TemporaryDirectory() as temporary: + work = Path(temporary) + certs = work / 'certs' + subprocess.run(['sh', str(SOURCE / 'lab/device-certs.sh'), str(certs)], + check=True, capture_output=True, timeout=10) + for case in CASES: + status, detail, lines = run_case(binary, certs, work, case) + outcomes.append(status) + print(f'case {case}: {status}: {detail}', flush=True) + for line in lines: + print(f' {line}', flush=True) + if all(status == 'fails as today' for status in outcomes): + print('result: stalled list downloads do not say how far they got') + return 1 + if all(status == 'pass' for status in outcomes): + print('result: stalled list downloads say how far they got') + return 0 + print('result: mixed') + return 1 + + +if __name__ == '__main__': + try: + if len(sys.argv) != 2: + raise SetupError('usage: test_ticket_fetch_progress.py ') + sys.exit(main(os.path.abspath(sys.argv[1]))) + except (SetupError, OSError, subprocess.SubprocessError, ssl.SSLError) as exc: + print(f'error: {exc}', flush=True) + sys.exit(2) From bc5dc08816878c7e508a372d11ceb2f4875db718 Mon Sep 17 00:00:00 2001 From: Mateo Rossi Date: Tue, 27 Oct 2026 15:30:00 +1100 Subject: [PATCH 2/9] fix(gated): log the phase and bytes of a failed list download A stalled body, a stalled handshake, and an unreachable hub could all log curl=28 reason=timeout. The failure line now reports how far the attempt got and how many body bytes of how many arrived. The phase comes from curl's connection count, the status line and end of headers seen, and bytes handed to the write callback. A phase change is logged like a reason change. The two exact log-line checks in test_gated_tls.py now include the new fields. --- CMakeLists.txt | 4 +- README.md | 2 +- README.zh-CN.md | 2 +- docs/runbooks/renew-device-certificate.md | 4 +- .../renew-device-certificate.zh-CN.md | 4 +- gated/ticket_sync.c | 91 +++++++++++++++++-- lab/README.md | 4 +- lab/README.zh-CN.md | 4 +- tests/test_gated_tls.py | 5 +- 9 files changed, 100 insertions(+), 20 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e65c439..b74a4ab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -155,9 +155,7 @@ add_test(NAME tls_failure_reasons COMMAND ${Python3_EXECUTABLE} set_tests_properties(tls_failure_reasons PROPERTIES TIMEOUT 120) add_test(NAME ticket_fetch_progress COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_ticket_fetch_progress.py $) -# The next commit removes PASS_REGULAR_EXPRESSION when the log says how far the download got. -set_tests_properties(ticket_fetch_progress PROPERTIES TIMEOUT 60 - PASS_REGULAR_EXPRESSION "result: stalled list downloads do not say how far they got") +set_tests_properties(ticket_fetch_progress PROPERTIES TIMEOUT 60) add_test(NAME device_tls COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_device_tls.py $) set_tests_properties(device_tls PROPERTIES TIMEOUT 40) diff --git a/README.md b/README.md index 91d9569..1ae138c 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ Ticket work logs `event=ticket_sync` for build start, completion or failure and The data-centre probe logs `event=dc_dns` when resolution becomes `resolved`, `stale`, `failed`, or `recovered`. A stale address is usable for at most 30 seconds; `reason=stale_expired` means the grace period ended, and `reason=never_resolved` that the name has not resolved since the hub started. `resolved` is the first successful lookup, `recovered` one after a failure. It logs `event=dc_link state=connected` or `state=failed` only when the connection state changes, and `state=connected address=... previous=...` when it stays connected but moves to another address; this TCP probe uses port 8443 with device TLS configured, or 8080 otherwise. `GATEPOST_DC_HOST` sets the host that both the probe and the sync connect to (default `api.elsworne.example`); the sync always checks the certificate as `api.elsworne.example`. A failed probe startup or socket close uses `event=operation_failed`. Mail submission logs `event=mail_alert gate=... state=failed` once when an incident cannot be submitted, and `state=sent` after submission and durable state update. Persistent alert-state file failures and their recovery use `event=mail_state state=failed` and `state=recovered`. Alert initialization failures use `event=operation_failed`. -In the test builds, without device TLS, the hub serves `/tickets`, `/status` and `/metrics` over HTTP on port 8081. When device TLS and `GATEPOST_STATUS` are configured, port 8081 serves `/status` and `/metrics` but answers `GET /tickets` with 404; port 8444 serves the list and the other routes over TLS 1.3 at the same bind address. Port 8444 requires a venue CA-signed gate certificate and accepts only `Host: hub.venue.lan` or `Host: hub.venue.lan:8444`. With device TLS configured, a gate fetches `https://hub.venue.lan:8444/tickets` on startup and periodically, connecting to the `--hub` host while verifying the hub certificate as `hub.venue.lan` and presenting its own certificate. In the test builds, without device TLS, it fetches over 8081: with `--hub 10.77.20.10:7000`, it asks for `http://10.77.20.10:8081/tickets` and sends `Host: 10.77.20.10:8081`. Set `GATEPOST_TICKETS_URL` to override the URL; production builds accept only `https://` and `file://` overrides, while the `http://` override warning appears only in test builds. The hub answers only Host values listed in `GATEPOST_STATUS_HOSTS` (default `hub.venue.lan`, `hub.venue.lan:8081`, `127.0.0.1:8081` and `localhost:8081`) and returns 400 to any other. For plaintext gates reaching the hub by address, add `
:8081` to `GATEPOST_STATUS_HOSTS`; the variable replaces the default list, so keep the names you still use. A gate logs `event=ticket_fetch state=failed http= curl= reason=` when fetching starts failing or the reason changes, suppresses repeats of the same reason, and logs `event=ticket_fetch state=recovered` once when it works again. The gate retains used-ticket state when installing a new list. With device TLS configured, the hub syncs its binary data-centre copy over port 8443 using its certificate, with range requests and SHA-256 verification before installation. +In the test builds, without device TLS, the hub serves `/tickets`, `/status` and `/metrics` over HTTP on port 8081. When device TLS and `GATEPOST_STATUS` are configured, port 8081 serves `/status` and `/metrics` but answers `GET /tickets` with 404; port 8444 serves the list and the other routes over TLS 1.3 at the same bind address. Port 8444 requires a venue CA-signed gate certificate and accepts only `Host: hub.venue.lan` or `Host: hub.venue.lan:8444`. With device TLS configured, a gate fetches `https://hub.venue.lan:8444/tickets` on startup and periodically, connecting to the `--hub` host while verifying the hub certificate as `hub.venue.lan` and presenting its own certificate. In the test builds, without device TLS, it fetches over 8081: with `--hub 10.77.20.10:7000`, it asks for `http://10.77.20.10:8081/tickets` and sends `Host: 10.77.20.10:8081`. Set `GATEPOST_TICKETS_URL` to override the URL; production builds accept only `https://` and `file://` overrides, while the `http://` override warning appears only in test builds. The hub answers only Host values listed in `GATEPOST_STATUS_HOSTS` (default `hub.venue.lan`, `hub.venue.lan:8081`, `127.0.0.1:8081` and `localhost:8081`) and returns 400 to any other. For plaintext gates reaching the hub by address, add `
:8081` to `GATEPOST_STATUS_HOSTS`; the variable replaces the default list, so keep the names you still use. A gate logs `event=ticket_fetch state=failed http= curl= reason= phase= received= expected=` when fetching starts failing or the reason or phase changes. It suppresses repeats with the same reason and phase even if the byte counts differ, and logs `event=ticket_fetch state=recovered` once when it works again. The gate retains used-ticket state when installing a new list. With device TLS configured, the hub syncs its binary data-centre copy over port 8443 using its certificate, with range requests and SHA-256 verification before installation. The hub also serves `/metrics` on its staff-side status listener, separate from the gate RPC port. In the lab it binds `10.77.20.10:8081`, and only staff-subnet or loopback clients may read metrics. See [metric names and labels](docs/operations/metrics.md). The hub sends `X-Content-SHA256` with each ticket list; a gate verifies the bytes and prepares its ETag metadata before replacing the old list. diff --git a/README.zh-CN.md b/README.zh-CN.md index 599bf22..731f467 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -93,7 +93,7 @@ time=1775170804235739 level=INFO event=hub_link gate=south state=online 数据中心探测的地址解析状态变为 `resolved`、`stale`、`failed` 或 `recovered` 时写入 `event=dc_dns`。旧地址最多沿用 30 秒;`reason=stale_expired` 表示宽限期结束,`reason=never_resolved` 表示 hub 启动以来这个名字还没解析成功过。`resolved` 是第一次解析成功,`recovered` 是失败之后再次成功。连接状态变化时写入 `event=dc_link state=connected` 或 `state=failed`;连接一直正常、只是换到另一个地址时,写入 `state=connected address=... previous=...`。这项 TCP 探测在配置设备 TLS 时使用 8443 端口,否则使用 8080 端口。`GATEPOST_DC_HOST` 指定探测和同步连接的主机,默认是 `api.elsworne.example`;同步始终按 `api.elsworne.example` 验证证书。探测启动或关闭套接字失败时写入 `event=operation_failed`。 邮件发送失败时,每次故障只写一次 `event=mail_alert gate=... state=failed`;发送并持久化成功后写入 `state=sent`。告警状态文件持续失败及其恢复分别写入 `event=mail_state state=failed` 和 `state=recovered`。告警初始化失败写入 `event=operation_failed`。 -测试构建未配置设备 TLS 时,Hub 在 8081 端口通过 HTTP 提供 `/tickets`、`/status` 和 `/metrics`。配置设备 TLS 和 `GATEPOST_STATUS` 后,8081 只提供 `/status` 和 `/metrics`,对 `GET /tickets` 返回 404;同一绑定地址的 8444 端口通过 TLS 1.3 提供票单和其他接口。8444 要求客户端出示场馆 CA 签发的闸机证书,只接受 `Host: hub.venue.lan` 或 `Host: hub.venue.lan:8444`。配置设备 TLS 后,闸机在启动时及之后定期请求 `https://hub.venue.lan:8444/tickets`,实际连接 `--hub` 指定的主机,按 `hub.venue.lan` 验证 hub 证书,并出示自己的设备证书。测试构建未配置设备 TLS 时仍使用 8081:以 `--hub 10.77.20.10:7000` 启动时,请求 `http://10.77.20.10:8081/tickets`,发送 `Host: 10.77.20.10:8081`。可用 `GATEPOST_TICKETS_URL` 覆盖地址;生产构建只接受 `https://` 和 `file://`,`http://` 覆盖地址的警告只在测试构建中出现。Hub 只接受 `GATEPOST_STATUS_HOSTS` 中列出的 Host(默认是 `hub.venue.lan`、`hub.venue.lan:8081`、`127.0.0.1:8081` 和 `localhost:8081`),其他一律回 400。明文闸机按地址连接 hub 时,要把 `<地址>:8081` 加进 `GATEPOST_STATUS_HOSTS`;这个变量会整个替换默认列表,仍要用的名字也要写上。闸机取票开始失败、或失败期间原因有变化时,记录 `event=ticket_fetch state=failed http=<状态码> curl=<错误码> reason=<原因>`;原因不变不重复记录;恢复时记录一次 `event=ticket_fetch state=recovered`。闸机安装新票单时保留已使用状态。配置设备 TLS 后,Hub 使用自己的证书通过 8443 端口分段同步数据中心的二进制票单,安装前验证 SHA-256。 +测试构建未配置设备 TLS 时,Hub 在 8081 端口通过 HTTP 提供 `/tickets`、`/status` 和 `/metrics`。配置设备 TLS 和 `GATEPOST_STATUS` 后,8081 只提供 `/status` 和 `/metrics`,对 `GET /tickets` 返回 404;同一绑定地址的 8444 端口通过 TLS 1.3 提供票单和其他接口。8444 要求客户端出示场馆 CA 签发的闸机证书,只接受 `Host: hub.venue.lan` 或 `Host: hub.venue.lan:8444`。配置设备 TLS 后,闸机在启动时及之后定期请求 `https://hub.venue.lan:8444/tickets`,实际连接 `--hub` 指定的主机,按 `hub.venue.lan` 验证 hub 证书,并出示自己的设备证书。测试构建未配置设备 TLS 时仍使用 8081:以 `--hub 10.77.20.10:7000` 启动时,请求 `http://10.77.20.10:8081/tickets`,发送 `Host: 10.77.20.10:8081`。可用 `GATEPOST_TICKETS_URL` 覆盖地址;生产构建只接受 `https://` 和 `file://`,`http://` 覆盖地址的警告只在测试构建中出现。Hub 只接受 `GATEPOST_STATUS_HOSTS` 中列出的 Host(默认是 `hub.venue.lan`、`hub.venue.lan:8081`、`127.0.0.1:8081` 和 `localhost:8081`),其他一律回 400。明文闸机按地址连接 hub 时,要把 `<地址>:8081` 加进 `GATEPOST_STATUS_HOSTS`;这个变量会整个替换默认列表,仍要用的名字也要写上。闸机取票开始失败,或连续失败期间原因或阶段发生变化时,记录 `event=ticket_fetch state=failed http=<状态码> curl=<错误码> reason=<原因> phase=<阶段> received=<字节数> expected=<字节数|unknown>`;原因和阶段都相同的失败不重复记录,即使字节数不同也是如此;恢复后记录一次 `event=ticket_fetch state=recovered`。闸机安装新票单时保留已使用状态。配置设备 TLS 后,Hub 使用自己的证书通过 8443 端口分段同步数据中心的二进制票单,安装前验证 SHA-256。 Hub 还在员工网络一侧的状态服务上提供 `/metrics`,与闸机 RPC 端口分开。实验环境将其绑定到 `10.77.20.10:8081`;只有员工网段或本机能读取指标。指标名称和标签见[运维指标](docs/operations/metrics.zh-CN.md)。Hub 随票单发送 `X-Content-SHA256`;闸机验证文件内容,并在替换旧票单之前准备 ETag 元数据。 diff --git a/docs/runbooks/renew-device-certificate.md b/docs/runbooks/renew-device-certificate.md index ea0cdb9..fe429b5 100644 --- a/docs/runbooks/renew-device-certificate.md +++ b/docs/runbooks/renew-device-certificate.md @@ -8,9 +8,9 @@ This procedure follows the current venue lab. Run shell commands from the reposi Check a device certificate ahead of time with `openssl x509 -in /chain.pem -noout -enddate -checkend 604800` from the TLS directory. Read its `notAfter=` value; exit status 1 means it expires within seven days. In the lab, `sh lab/keys.sh` refuses a retained set containing a certificate that expires within seven days. Nothing runs this check on a schedule. If a certificate expires while a program is running, the failure appears only when a connection is attempted. At startup, each program logs `level=ERROR event=tls_certificate state=expired` or `level=ERROR event=tls_certificate state=not_yet_valid` once, then keeps running. -For an expired **hub** certificate, each gate reports `level=WARN event=hub_link gate=gate1 state=offline reason=certificate_expired` and `level=WARN event=ticket_fetch state=failed http=0 curl=60 reason=tls_certificate` (substitute its gate ID). The hub reports `level=ERROR event=tls_certificate state=expired`, `level=WARN event=tls_handshake state=failed reason=rejected_by_peer peer=10.77.10.11` and `level=WARN event=status_client state=handshake_failed reason=rejected_by_peer peer=10.77.10.11` (one of each per gate), plus `level=ERROR event=dc_sync state=failed reason=connection`. +For an expired **hub** certificate, each gate reports `level=WARN event=hub_link gate=gate1 state=offline reason=certificate_expired` and `level=WARN event=ticket_fetch state=failed http=0 curl=60 reason=tls_certificate phase=tls received=0 expected=unknown` (substitute its gate ID). The hub reports `level=ERROR event=tls_certificate state=expired`, `level=WARN event=tls_handshake state=failed reason=rejected_by_peer peer=10.77.10.11` and `level=WARN event=status_client state=handshake_failed reason=rejected_by_peer peer=10.77.10.11` (one of each per gate), plus `level=ERROR event=dc_sync state=failed reason=connection`. -For an expired **gate1** certificate, the hub reports `level=WARN event=tls_handshake state=failed reason=certificate_expired peer=10.77.10.11` and `level=WARN event=status_client state=handshake_failed reason=certificate_expired peer=10.77.10.11`. Gate1 reports `level=ERROR event=tls_certificate state=expired`, `level=WARN event=hub_link gate=gate1 state=offline reason=rejected_by_peer` and `level=WARN event=ticket_fetch state=failed http=0 curl=56 reason=connection`. With TLS 1.3, a gate whose certificate the hub rejects learns this only on its first request after the handshake: the next scan or link check. +For an expired **gate1** certificate, the hub reports `level=WARN event=tls_handshake state=failed reason=certificate_expired peer=10.77.10.11` and `level=WARN event=status_client state=handshake_failed reason=certificate_expired peer=10.77.10.11`. Gate1 reports `level=ERROR event=tls_certificate state=expired`, `level=WARN event=hub_link gate=gate1 state=offline reason=rejected_by_peer` and `level=WARN event=ticket_fetch state=failed http=0 curl=56 reason=connection phase=headers received=0 expected=unknown`. With TLS 1.3, a gate whose certificate the hub rejects learns this only on its first request after the handshake: the next scan or link check. That is why its ticket_fetch line shows `phase=headers`, not `phase=tls`. The side logging `certificate_expired` rejected the other side's certificate. Each failure log line appears once per peer until the reason changes or a handshake from that peer succeeds, while `gatepost_tls_handshake_failures_total{listener="gate",reason=""} ` and the `listener="status"` series keep rising on repeated failures. See [operations metrics](../operations/metrics.md). Gates continue admitting tickets offline while the link is down. diff --git a/docs/runbooks/renew-device-certificate.zh-CN.md b/docs/runbooks/renew-device-certificate.zh-CN.md index 78449bd..1668faa 100644 --- a/docs/runbooks/renew-device-certificate.zh-CN.md +++ b/docs/runbooks/renew-device-certificate.zh-CN.md @@ -8,9 +8,9 @@ 要提前检查证书,在 TLS 目录运行 `openssl x509 -in /chain.pem -noout -enddate -checkend 604800`;查看输出的 `notAfter=`,退出码为 1 表示证书将在七天内到期。实验脚本 `sh lab/keys.sh` 遇到七天内到期的现有证书集会拒绝继续运行。目前没有定时检查。程序运行期间证书过期,要等到连接尝试失败才会发现。程序启动时,若自己的证书已过期或尚未生效,只记一次 `level=ERROR event=tls_certificate state=expired` 或 `level=ERROR event=tls_certificate state=not_yet_valid`,之后仍继续运行。 -若过期的是 **hub 证书**,每台闸机会记录 `level=WARN event=hub_link gate=gate1 state=offline reason=certificate_expired` 和 `level=WARN event=ticket_fetch state=failed http=0 curl=60 reason=tls_certificate`(其他闸机换成自己的编号)。hub 自身记录 `level=ERROR event=tls_certificate state=expired`、`level=WARN event=tls_handshake state=failed reason=rejected_by_peer peer=10.77.10.11`、`level=WARN event=status_client state=handshake_failed reason=rejected_by_peer peer=10.77.10.11`(后两类每台闸机各一条),还有 `level=ERROR event=dc_sync state=failed reason=connection`。 +若过期的是 **hub 证书**,每台闸机会记录 `level=WARN event=hub_link gate=gate1 state=offline reason=certificate_expired` 和 `level=WARN event=ticket_fetch state=failed http=0 curl=60 reason=tls_certificate phase=tls received=0 expected=unknown`(其他闸机换成自己的编号)。hub 自身记录 `level=ERROR event=tls_certificate state=expired`、`level=WARN event=tls_handshake state=failed reason=rejected_by_peer peer=10.77.10.11`、`level=WARN event=status_client state=handshake_failed reason=rejected_by_peer peer=10.77.10.11`(后两类每台闸机各一条),还有 `level=ERROR event=dc_sync state=failed reason=connection`。 -若过期的是 **gate1 证书**,hub 记录 `level=WARN event=tls_handshake state=failed reason=certificate_expired peer=10.77.10.11` 和 `level=WARN event=status_client state=handshake_failed reason=certificate_expired peer=10.77.10.11`。gate1 记录 `level=ERROR event=tls_certificate state=expired`、`level=WARN event=hub_link gate=gate1 state=offline reason=rejected_by_peer` 和 `level=WARN event=ticket_fetch state=failed http=0 curl=56 reason=connection`。在 TLS 1.3 下,hub 拒绝闸机证书后,闸机要到握手后的首次请求才得知,也就是下一次扫码或链路检查。 +若过期的是 **gate1 证书**,hub 记录 `level=WARN event=tls_handshake state=failed reason=certificate_expired peer=10.77.10.11` 和 `level=WARN event=status_client state=handshake_failed reason=certificate_expired peer=10.77.10.11`。gate1 记录 `level=ERROR event=tls_certificate state=expired`、`level=WARN event=hub_link gate=gate1 state=offline reason=rejected_by_peer` 和 `level=WARN event=ticket_fetch state=failed http=0 curl=56 reason=connection phase=headers received=0 expected=unknown`。在 TLS 1.3 下,hub 拒绝闸机证书后,闸机要到握手后的首次请求才得知,也就是下一次扫码或链路检查,所以取票失败行显示 `phase=headers`,而不是 `tls`。 判断哪边证书过期,就看哪边记了 `certificate_expired`:记这条原因的一方拒绝了对端证书。同一个对端的失败日志,在原因变化或这个对端握手成功一次之前只记一次,但反复握手失败仍会使 `gatepost_tls_handshake_failures_total{listener="gate",reason=""} ` 和 `listener="status"` 对应计数持续增加;见[运维指标](../operations/metrics.zh-CN.md)。链路中断期间,闸机仍可离线验票放行。 diff --git a/gated/ticket_sync.c b/gated/ticket_sync.c index 26ad4d3..a14d811 100644 --- a/gated/ticket_sync.c +++ b/gated/ticket_sync.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -19,9 +20,14 @@ typedef struct { FILE *file; char etag[100]; char digest[65]; + bool status_line; + bool headers_done; + long long content_length; + size_t received; } fetch; static size_t body_write(char *data, size_t size, size_t count, void *context) { fetch *state = context; + state->received += size * count; return fwrite(data, size, count, state->file) * size; } static size_t header_read(char *data, size_t size, size_t count, void *context) { @@ -30,7 +36,38 @@ static size_t header_read(char *data, size_t size, size_t count, void *context) const char *start = NULL; char *destination = NULL; size_t capacity = 0; - if (length > 6 && strncasecmp(data, "ETag:", 5) == 0) { + if (length >= 5 && memcmp(data, "HTTP/", 5) == 0) { + state->status_line = true; + state->headers_done = false; + state->content_length = -1; + state->received = 0; + } else if ((length == 2 && memcmp(data, "\r\n", 2) == 0) || (length == 1 && data[0] == '\n')) { + state->headers_done = true; + } else if (length >= 15 && strncasecmp(data, "Content-Length:", 15) == 0) { + const char *digit = data + 15; + const char *end = data + length; + long long value = 0; + bool valid = false; + state->content_length = -1; + while (digit < end && (*digit == ' ' || *digit == '\t')) + ++digit; + while (digit < end && *digit >= '0' && *digit <= '9') { + int next = *digit - '0'; + if (value > (LLONG_MAX - next) / 10) + return length; + value = value * 10 + next; + valid = true; + ++digit; + } + while (digit < end && (*digit == ' ' || *digit == '\t')) + ++digit; + if (digit < end && *digit == '\r') + ++digit; + if (digit < end && *digit == '\n') + ++digit; + if (valid && digit == end) + state->content_length = value; + } else if (length > 6 && strncasecmp(data, "ETag:", 5) == 0) { start = data + 5; destination = state->etag; capacity = sizeof state->etag; @@ -86,6 +123,9 @@ static int digest_matches(const char *path, const char *expected) { static long last_http_status; static CURLcode last_curl_result; static const char *last_failure_reason; +static const char *last_phase; +static size_t last_received; +static long long last_expected; static int fetch_tickets(const char *url, const char *path, const gate_ticket_tls *tls) { char temporary[512], meta_path[512], meta_temp[512], backup[512], etag[100] = {0}; @@ -137,7 +177,7 @@ static int fetch_tickets(const char *url, const char *path, const gate_ticket_tl unlink(temporary); return -1; } - fetch state = {.file = file}; + fetch state = {.file = file, .content_length = -1}; struct curl_slist *headers = NULL; struct curl_slist *connect_to = NULL; char conditional[160]; @@ -176,10 +216,32 @@ static int fetch_tickets(const char *url, const char *path, const gate_ticket_tl } CURLcode result = curl_easy_perform(curl); long status = 0; - curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status); + if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status) != CURLE_OK) + status = 0; last_http_status = status; last_curl_result = result; last_failure_reason = gate_curl_failure_reason(result, status); + last_received = state.received; + last_expected = state.content_length; + if (result == CURLE_OK) { + last_phase = "complete"; + } else { + long connections = 0; + if (curl_easy_getinfo(curl, CURLINFO_NUM_CONNECTS, &connections) == CURLE_OK && + connections == 0) { + last_phase = "connect"; + } else if (!state.status_line) { + curl_off_t appconnect_time = 0; + if (strncasecmp(url, "https://", 8) == 0 && + curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME_T, &appconnect_time) == CURLE_OK && + appconnect_time == 0) + last_phase = "tls"; + else + last_phase = "headers"; + } else { + last_phase = state.headers_done ? "body" : "headers"; + } + } if (result != CURLE_OK || (status != 200 && status != 304)) goto fail; if (status == 304) { @@ -278,17 +340,32 @@ static int fetch_tickets(const char *url, const char *path, const gate_ticket_tl int gate_fetch_tickets(const char *url, const char *path, const gate_ticket_tls *tls) { static bool failing; static const char *logged_failure_reason; + static const char *logged_phase; last_http_status = 0; last_curl_result = CURLE_OK; last_failure_reason = "install"; + last_phase = "setup"; + last_received = 0; + last_expected = -1; int result = fetch_tickets(url, path, tls); if (result < 0 && (!failing || !logged_failure_reason || - strcmp(logged_failure_reason, last_failure_reason) != 0)) - gate_log("WARN", "ticket_fetch", "state=failed http=%ld curl=%d reason=%s", - last_http_status, (int)last_curl_result, last_failure_reason); - else if (result >= 0 && failing) + strcmp(logged_failure_reason, last_failure_reason) != 0 || + strcmp(logged_phase, last_phase) != 0)) { + if (last_expected < 0) + gate_log("WARN", "ticket_fetch", + "state=failed http=%ld curl=%d reason=%s phase=%s received=%zu " + "expected=unknown", + last_http_status, (int)last_curl_result, last_failure_reason, last_phase, + last_received); + else + gate_log("WARN", "ticket_fetch", + "state=failed http=%ld curl=%d reason=%s phase=%s received=%zu expected=%lld", + last_http_status, (int)last_curl_result, last_failure_reason, last_phase, + last_received, last_expected); + } else if (result >= 0 && failing) gate_log("INFO", "ticket_fetch", "state=recovered"); failing = result < 0; logged_failure_reason = failing ? last_failure_reason : NULL; + logged_phase = failing ? last_phase : NULL; return result; } diff --git a/lab/README.md b/lab/README.md index 9dc4de0..df21adf 100644 --- a/lab/README.md +++ b/lab/README.md @@ -150,7 +150,7 @@ The data-centre stub serves a binary list with `ETag` and byte ranges on plainte Without device TLS, the hub's C HTTP listener on port 8081 serves `/status`, `/metrics` and `/tickets`. With device TLS configured, port 8081 serves `/status` and `/metrics` but answers `GET /tickets` with 404; port 8444 serves the list and the other paths over TLS to venue CA-signed gate certificates. `GATEPOST_STATUS_HOSTS` is a comma-separated list of accepted Host values; the default includes the venue name and local loopback addresses. `/tickets` supports `ETag`, `If-None-Match` with 304, and single open-ended byte ranges. Gates fetch the list on startup and every 20 seconds, install it with `fsync` and `rename`, and carry used-ticket state across a reload. Right after the lab starts, the hub may not be answering yet, so a gate's first fetch can time out and log `event=ticket_fetch state=failed`; the next fetch, 20 seconds later, succeeds and logs `state=recovered`. Run `sh lab/http-status.sh` for request validation. The lab's gates use `--hub 10.77.20.10:7000`, so `lab/compose.yaml` adds `10.77.20.10:8081` to the hub's `GATEPOST_STATUS_HOSTS` next to the default names. After the lab starts, run `sh lab/http-sync-install.sh`: it reads the served ETag from gate1 over TLS on port 8444, waits until both gates hold that ETag, and fails if either does not. -The gate logs a `ticket_fetch` failure when fetching starts failing or the reason changes, and logs `state=recovered` after a successful fetch. Read `http` and `curl` alongside the reason: +The gate logs a `ticket_fetch` failure when fetching starts failing or the reason or phase changes, and logs `state=recovered` after a successful fetch. Read `http` and `curl` alongside the reason: | `reason` | What to check on call | | --- | --- | @@ -164,6 +164,8 @@ The gate logs a `ticket_fetch` failure when fetching starts failing or the reaso | `install` | Check the downloaded list, digest and local write path. | | `other` | Use the curl code to investigate an unclassified transfer error. | +Read `phase` to locate the failure: `setup` means the gate failed before sending the request; `connect` means no TCP connection was made; `tls` means TCP connected but the TLS handshake did not finish; and `headers` means the connection (and TLS handshake, if used) was up but the response headers did not all arrive. With TLS 1.3, `curl=56 reason=connection phase=headers` can also mean the hub rejected the gate certificate after the handshake; check the hub's `tls_handshake ... reason=` line. `body` means the headers arrived and the body transfer failed; when `received` is below `expected`, it stopped after that many body bytes. `complete` means the download finished, leaving the HTTP status or local installation as the cause. `received` counts body bytes handed to the gate, while `expected` is the Content-Length; `expected=unknown` means no valid Content-Length arrived. + Production builds accept only `https://` and `file://` `GATEPOST_TICKETS_URL` overrides. In test builds with device TLS configured, an `http://` override logs `event=ticket_source state=plaintext reason=url_override` at startup. ## UDP measurement and offline admissions diff --git a/lab/README.zh-CN.md b/lab/README.zh-CN.md index 63cedac..0fa8307 100644 --- a/lab/README.zh-CN.md +++ b/lab/README.zh-CN.md @@ -142,7 +142,7 @@ hub 从有 frame 的 `HELLO` 消息获取闸机身份,不依靠来源 IP。若 未配置设备 TLS 时,hub 的 C HTTP 服务在 8081 端口提供 `/status`、`/metrics` 和 `/tickets`。配置设备 TLS 后,8081 提供 `/status` 和 `/metrics`,但对 `GET /tickets` 返回 404;8444 端口通过 TLS 向持有场馆 CA 签发的闸机证书的客户端提供票单和其他接口。`GATEPOST_STATUS_HOSTS` 是允许的 Host 值列表,以逗号分隔;默认包含场馆名称和本机回环地址。`/tickets` 支持 `ETag`、`If-None-Match` 返回 304,以及单个开放式字节范围。闸机在启动时及此后每 20 秒获取票单,通过 `fsync` 和 `rename` 安装,并在重载时保留已用票状态。实验刚启动时,hub 可能还没开始应答,闸机第一轮取票会超时,记下 `event=ticket_fetch state=failed`;20 秒后的下一轮取票成功,记下 `state=recovered`。运行 `sh lab/http-status.sh` 检查请求校验。实验环境的闸机使用 `--hub 10.77.20.10:7000`,所以 `lab/compose.yaml` 在 hub 的 `GATEPOST_STATUS_HOSTS` 里,除默认名字外还加上 `10.77.20.10:8081`。实验环境启动后运行 `sh lab/http-sync-install.sh`:它从 gate1 通过 8444 上的 TLS 读取 hub 发出的 ETag,等待两台闸机都持有该 ETag,任何一台没有就以失败退出。 -闸机取票开始失败、或失败期间原因有变化时记录 `ticket_fetch` 日志,成功获取票单后记录 `state=recovered`。值班时结合 `http` 和 `curl` 字段判断: +闸机取票开始失败,或连续失败期间原因或阶段发生变化时记录 `ticket_fetch` 日志;成功获取票单后记录 `state=recovered`。值班时结合 `http` 和 `curl` 字段判断: | `reason` | 值班时检查什么 | | --- | --- | @@ -156,6 +156,8 @@ hub 从有 frame 的 `HELLO` 消息获取闸机身份,不依靠来源 IP。若 | `install` | 检查下载的票单、摘要和本地写入路径。 | | `other` | 根据 curl 错误码调查未分类的传输错误。 | +`phase` 表示失败发生在哪一步:`setup` 是请求尚未发出就失败;`connect` 是未建立 TCP 连接;`tls` 是 TCP 已连接,但 TLS 握手未完成;`headers` 是连接已建立(用 TLS 时握手也已完成),但响应头没有收齐;在 TLS 1.3 下,`curl=56 reason=connection phase=headers` 也可能是 hub 在握手后拒绝了闸机证书,这时去看 hub 的 `tls_handshake ... reason=` 那一行。`body` 表示响应头已收齐,正文传输中断;若 `received` 小于 `expected`,说明正文收到 `received` 字节后就断了。`complete` 表示下载已结束,失败原因在 HTTP 状态或本地安装。`received` 是闸机收到的正文字节数,`expected` 来自 Content-Length;`expected=unknown` 表示没有收到有效的 Content-Length。 + 生产构建的 `GATEPOST_TICKETS_URL` 覆盖地址只接受 `https://` 和 `file://`。测试构建配置设备 TLS 时,若覆盖为 `http://` 地址,闸机启动时会记录 `event=ticket_source state=plaintext reason=url_override`。 ## UDP 测量与离线放行 diff --git a/tests/test_gated_tls.py b/tests/test_gated_tls.py index 79b326b..a817894 100644 --- a/tests/test_gated_tls.py +++ b/tests/test_gated_tls.py @@ -336,9 +336,10 @@ def test_ticket_fetch_logs_reason_change_without_repeats(self): env = self.environment() env.pop('GATEPOST_TICKETS_URL') gate = self.start_gate(1, env) - connect = b'event=ticket_fetch state=failed http=0 curl=7 reason=connect\n' + connect = (b'event=ticket_fetch state=failed http=0 curl=7 reason=connect ' + b'phase=connect received=0 expected=unknown\n') certificate = (b'event=ticket_fetch state=failed http=0 curl=60 ' - b'reason=tls_certificate\n') + b'reason=tls_certificate phase=tls received=0 expected=unknown\n') gate.wait_for_log(connect) # The next fetch is 20 seconds after startup; leave 8444 closed for that retry. time.sleep(22) From 7ec232e7e57ff9f684ffcc31902c8a7426252d3d Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Tue, 27 Oct 2026 16:30:00 +1100 Subject: [PATCH 3/9] test(gate-hub): show an aborted ticket reply is counted as 200 Serve a large ticket list, shrink the client's receive buffer, read only the response headers, then reset the connection during the body. The complete download should add one tickets/200 count, and the aborted download should add one tickets/incomplete count. Today both are counted as 200. CTest accepts this run only when it fails that way. --- CMakeLists.txt | 7 +- tests/test_ticket_reply_count.py | 196 +++++++++++++++++++++++++++++++ 2 files changed, 202 insertions(+), 1 deletion(-) create mode 100644 tests/test_ticket_reply_count.py diff --git a/CMakeLists.txt b/CMakeLists.txt index b74a4ab..52a0c08 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -210,6 +210,11 @@ add_test(NAME mail_alert COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_mail_alert.py $) add_test(NAME http_distribution COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_http.py $ $) +add_test(NAME ticket_reply_count COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/tests/test_ticket_reply_count.py $) +# The next commit removes PASS_REGULAR_EXPRESSION when only completed ticket replies count as 200. +set_tests_properties(ticket_reply_count PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "result: an aborted ticket reply is counted as 200") add_test(NAME http_sync_integrity COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_http_sync.py $) add_test(NAME protocol_compat COMMAND ${Python3_EXECUTABLE} @@ -241,5 +246,5 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") endif() add_test(NAME status_deadline COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_status_deadline.py $ $) -set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons ticket_fetch_progress http_distribution offline_reports protocol_compat status_deadline +set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons ticket_fetch_progress http_distribution ticket_reply_count offline_reports protocol_compat status_deadline PROPERTIES RESOURCE_LOCK status_ports) diff --git a/tests/test_ticket_reply_count.py b/tests/test_ticket_reply_count.py new file mode 100644 index 0000000..74e4fe0 --- /dev/null +++ b/tests/test_ticket_reply_count.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Count a reset ticket download separately from a complete one.""" +import os +from pathlib import Path +import re +import socket +import struct +import subprocess +import sys +import tempfile +import time + + +SOURCE = Path(__file__).resolve().parents[1] +ADDRESS = ('127.0.0.1', 8081) +TICKETS = b'GET /tickets HTTP/1.1\r\nHost: 127.0.0.1:8081\r\n\r\n' +METRICS = b'GET /metrics HTTP/1.1\r\nHost: 127.0.0.1:8081\r\n\r\n' +SERIES = re.compile(r'gatepost_http_requests_total\{route="tickets",status="([^"]+)"\} (\d+)') +LIST_SIZE = 200000 + + +class SetupError(Exception): + pass + + +def free_port(): + with socket.socket() as peer: + peer.bind(('127.0.0.1', 0)) + return peer.getsockname()[1] + + +def read_reply(request): + with socket.create_connection(ADDRESS, timeout=5) as peer: + peer.settimeout(10) + peer.sendall(request) + response = bytearray() + while block := peer.recv(65536): + response.extend(block) + if b'\r\n\r\n' not in response: + raise SetupError('HTTP reply has no complete headers') + return bytes(response).split(b'\r\n\r\n', 1) + + +def content_length(head): + if not head.startswith(b'HTTP/1.1 200 '): + raise SetupError(f'expected HTTP 200, saw {head.splitlines()[:1]!r}') + fields = [line.split(b':', 1)[1].strip() for line in head.split(b'\r\n')[1:] + if line.lower().startswith(b'content-length:')] + if len(fields) != 1 or not fields[0].isdigit(): + raise SetupError(f'expected one numeric Content-Length, saw {fields!r}') + return int(fields[0]) + + +def ticket_counts(): + head, body = read_reply(METRICS) + if content_length(head) != len(body): + raise SetupError('incomplete metrics reply') + counts = {} + for line in body.decode('utf-8').splitlines(): + match = SERIES.fullmatch(line) + if match: + status, value = match.groups() + if status in counts: + raise SetupError(f'duplicate tickets series for {status}') + counts[status] = int(value) + if not counts: + raise SetupError('metrics reply has no tickets series') + return counts + + +def abort_download(expected_length): + with socket.socket() as peer: + peer.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096) + peer.settimeout(10) + peer.connect(ADDRESS) + peer.sendall(TICKETS) + received = bytearray() + while b'\r\n\r\n' not in received: + block = peer.recv(4096) + if not block: + raise SetupError('ticket reply ended before its headers') + received.extend(block) + if len(received) > 65536: + raise SetupError('ticket reply headers are too large') + head, body = bytes(received).split(b'\r\n\r\n', 1) + if content_length(head) != expected_length: + raise SetupError('aborted reply has a different Content-Length') + time.sleep(.5) + peer.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0)) + if len(body) >= expected_length // 4: + raise SetupError(f'aborted client received too much body: {len(body)} bytes') + return len(body) + + +def deltas(before, after): + return {status: after.get(status, 0) - before.get(status, 0) + for status in sorted(before.keys() | after.keys())} + + +def classify(changes, incomplete_exists, alive): + if not alive: + return 'unexpected' + other = any(value != 0 for status, value in changes.items() + if status not in ('200', 'incomplete')) + if not other and changes.get('200') == 1 and incomplete_exists and changes.get('incomplete') == 1: + return 'pass' + if not other and changes.get('200') == 2 and not incomplete_exists: + return 'fails as today' + return 'unexpected' + + +def main(binary): + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + tickets = work / 'tickets.txt' + subprocess.run([sys.executable, str(SOURCE / 'tools/gen_tickets.py'), + str(LIST_SIZE), str(tickets)], check=True, timeout=20) + keys = work / 'keys' + keys.mkdir() + environment = {key: value for key, value in os.environ.items() + if not key.startswith('GATEPOST_')} + environment.update(GATEPOST_STATUS='1', GATEPOST_MAC_KEY_DIR=str(keys), + GATEPOST_REPORT_FILE=str(work / 'reports'), + GATEPOST_OFFLINE_FILE=str(work / 'offline')) + hub = subprocess.Popen([binary, str(tickets), str(free_port()), 'pool'], + env=environment, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE) + try: + for _ in range(100): + if hub.poll() is not None: + raise SetupError(f'hub did not start with {LIST_SIZE} tickets: exit {hub.returncode}') + try: + with socket.create_connection(ADDRESS, timeout=.1): + break + except OSError: + time.sleep(.02) + else: + raise SetupError(f'HTTP listener did not start with {LIST_SIZE} tickets') + + before = ticket_counts() + head, body = read_reply(TICKETS) + length = content_length(head) + if len(body) != length or length < 2_000_000: + raise SetupError(f'complete download has {len(body)} of {length} bytes') + aborted_bytes = abort_download(length) + + deadline = time.monotonic() + 5 + after = before + poll_error = None + while True: + try: + after = ticket_counts() + except (SetupError, OSError) as exc: + if hub.poll() is None: + raise + poll_error = f'metrics unavailable after hub exit: {exc}' + break + changes = deltas(before, after) + if sum(changes.values()) >= 2 or time.monotonic() >= deadline: + break + time.sleep(.05) + changes = deltas(before, after) + alive = hub.poll() is None + outcome = classify(changes, 'incomplete' in after, alive) + print(f'list size: {LIST_SIZE} tickets ({tickets.stat().st_size} bytes)') + print(f'Content-Length: {length}') + print(f'aborted client body bytes: {aborted_bytes}') + print(f'tickets deltas: {changes}') + print(f'case: {outcome}: hub_alive={alive}' + + (f'; {poll_error}' if poll_error else '')) + if outcome == 'fails as today': + print('result: an aborted ticket reply is counted as 200') + return 1 + if outcome == 'pass': + print('result: an aborted ticket reply is counted as incomplete') + return 0 + print('result: mixed') + return 1 + finally: + if hub.poll() is None: + hub.terminate() + try: + hub.communicate(timeout=3) + except subprocess.TimeoutExpired: + hub.kill() + hub.communicate(timeout=3) + + +if __name__ == '__main__': + try: + if len(sys.argv) != 2: + raise SetupError('usage: test_ticket_reply_count.py ') + sys.exit(main(os.path.abspath(sys.argv[1]))) + except (SetupError, OSError, subprocess.SubprocessError) as exc: + print(f'error: {exc}', flush=True) + sys.exit(2) From 7bf0dec2428eb3596f208239ddf3f7f51b60dd8e Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Wed, 28 Oct 2026 09:30:00 +1100 Subject: [PATCH 4/9] fix(gate-hub): count only completed ticket replies A body write that failed part-way still counted as 200, so aborted transfers never appeared in the ticket request metric. Count those replies, and replies whose headers could not be written, once as status="incomplete" on the tickets route. The header-write path is not covered by the test: headers are too small to make that write fail reliably. --- CMakeLists.txt | 4 +--- docs/operations/metrics.md | 2 +- docs/operations/metrics.zh-CN.md | 2 +- gate-hub/prometheus.c | 14 +++++++++++++- gate-hub/prometheus.h | 1 + gate-hub/status.c | 7 ++++++- 6 files changed, 23 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 52a0c08..d77875c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -212,9 +212,7 @@ add_test(NAME http_distribution COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_http.py $ $) add_test(NAME ticket_reply_count COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_ticket_reply_count.py $) -# The next commit removes PASS_REGULAR_EXPRESSION when only completed ticket replies count as 200. -set_tests_properties(ticket_reply_count PROPERTIES TIMEOUT 60 - PASS_REGULAR_EXPRESSION "result: an aborted ticket reply is counted as 200") +set_tests_properties(ticket_reply_count PROPERTIES TIMEOUT 60) add_test(NAME http_sync_integrity COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_http_sync.py $) add_test(NAME protocol_compat COMMAND ${Python3_EXECUTABLE} diff --git a/docs/operations/metrics.md b/docs/operations/metrics.md index ad8346b..daecbb1 100644 --- a/docs/operations/metrics.md +++ b/docs/operations/metrics.md @@ -14,6 +14,6 @@ The hub exposes Prometheus text format 0.0.4 at `GET /metrics` on its staff-side | `gatepost_dc_sync_attempts_total` | Counter | `outcome` (`success`, `error`) | Completed background data-centre synchronization runs. | | `gatepost_worker_queue_depth` | Gauge | None | Gate RPC connections waiting for one of the pool workers. | | `gatepost_tls_handshake_failures_total` | Counter | `listener` (`gate`, `status`), `reason` | Every failed TLS handshake, including repeated failures suppressed in logs. Reasons: `certificate_expired` (expired peer certificate), `certificate_not_yet_valid` (not yet valid), `certificate_untrusted` (unknown or untrusted issuer or self-signed chain), `certificate_invalid` (other certificate verification or gate identity error), `no_certificate` (peer supplied none), `rejected_by_peer` (peer sent a fatal alert), `protocol` (other TLS error), `timeout` (handshake deadline). No peer label; all 16 fixed series are rendered, including zeros. | -| `gatepost_http_requests_total` | Counter | `route` (`tickets`, `health`, `other`), `status` | HTTP requests on the status listener, by route and response code. The `/metrics` route is excluded. `/status` uses `health`, so dashboards can exclude it from ticket traffic. | +| `gatepost_http_requests_total` | Counter | `route` (`tickets`, `health`, `other`), `status` | HTTP requests on the status listener, by route and response code, or `incomplete` when the client did not receive a `/tickets` reply in full. Only `route="tickets"` has the `incomplete` status; each `/tickets` request is counted once. The `/metrics` route is excluded. `/status` uses `health`, so dashboards can exclude it from ticket traffic. | The gate's list response carries both an ETag and `X-Content-SHA256`; the gate checks the downloaded bytes before installing. Each list and ETag metadata replacement is prepared in temporary files, with rollback on a metadata rename failure. After a restart, the gate hashes the installed list and compares it with the SHA-256 encoded in the saved ETag. A mismatch drops the ETag and logs `event=ticket_etag state=dropped reason=list_mismatch`; the next request downloads the full list. This also recovers from a power loss between the two renames. diff --git a/docs/operations/metrics.zh-CN.md b/docs/operations/metrics.zh-CN.md index d76dce3..db08050 100644 --- a/docs/operations/metrics.zh-CN.md +++ b/docs/operations/metrics.zh-CN.md @@ -14,6 +14,6 @@ Hub 在员工网络一侧的 8081 端口通过 `GET /metrics` 提供 Prometheus | `gatepost_dc_sync_attempts_total` | Counter | `outcome`(`success`、`error`) | 后台数据中心同步完成的次数及结果。 | | `gatepost_worker_queue_depth` | Gauge | 无 | 等待线程池处理的闸机 RPC 连接数。 | | `gatepost_tls_handshake_failures_total` | Counter | `listener`(`gate`、`status`)、`reason` | 每次 TLS 握手失败都计数,包括日志中被合并的重复失败。`certificate_expired` 为对端证书过期,`certificate_not_yet_valid` 为尚未生效,`certificate_untrusted` 为签发者未知、不受信任或自签链,`certificate_invalid` 为其他证书验证或闸机身份错误,`no_certificate` 为未提交证书,`rejected_by_peer` 为对端发送致命告警,`protocol` 为其他 TLS 错误,`timeout` 为握手超时。没有 peer 标签;固定的 16 条序列全部输出,未发生的值为零。 | -| `gatepost_http_requests_total` | Counter | `route`(`tickets`、`health`、`other`)、`status` | 状态服务按路径和响应状态统计 HTTP 请求。`/metrics` 不计入;`/status` 标为 `health`,仪表盘可以从票务流量中排除。 | +| `gatepost_http_requests_total` | Counter | `route`(`tickets`、`health`、`other`)、`status` | 状态服务按路径和响应状态统计 HTTP 请求。`status` 通常是响应码;客户端未完整收到 `/tickets` 响应时记为 `incomplete`,且这个值仅用于 `route="tickets"`。每次 `/tickets` 请求只计一次。`/metrics` 不计入;`/status` 标为 `health`,仪表盘可以从票务流量中排除。 | Hub 的票单响应同时携带 ETag 与 `X-Content-SHA256`;闸机安装前会核对下载内容。新票单和 ETag 元数据先写入临时文件;若元数据重命名失败,闸机会恢复旧票单。重启后,闸机会计算已安装票单的 SHA-256,并与已保存 ETag 中的摘要比较。两者不符时会丢弃 ETag,记录 `event=ticket_etag state=dropped reason=list_mismatch`,下一次请求便重新下载完整票单。即使两次重命名之间断电,也能这样恢复。 diff --git a/gate-hub/prometheus.c b/gate-hub/prometheus.c index 118efb6..cdd1751 100644 --- a/gate-hub/prometheus.c +++ b/gate-hub/prometheus.c @@ -36,6 +36,7 @@ static struct { unsigned long long sync_ok, sync_error; unsigned long long http_tickets[HTTP_STATUSES], http_health[HTTP_STATUSES]; unsigned long long http_other[HTTP_STATUSES]; + unsigned long long http_tickets_incomplete; unsigned long long tls_failures[2][TLS_REASONS]; } data = {.lock = PTHREAD_MUTEX_INITIALIZER}; @@ -144,6 +145,12 @@ void prometheus_http(const char *route, int status) { ++counts[status_index(status)]; (void)pthread_mutex_unlock(&data.lock); } +void prometheus_http_tickets_incomplete(void) { + if (pthread_mutex_lock(&data.lock) != 0) + return; + ++data.http_tickets_incomplete; + (void)pthread_mutex_unlock(&data.lock); +} void prometheus_tls_failure(int status_listener, const char *reason) { if (pthread_mutex_lock(&data.lock) != 0) return; @@ -233,10 +240,15 @@ int prometheus_render(const char *version, double age, char **body, size_t *leng static const int statuses[] = {200, 206, 304, 400, 403, 404, 405, 416, 503, 500}; const unsigned long long *routes[] = {data.http_tickets, data.http_health, data.http_other}; const char *names[] = {"tickets", "health", "other"}; - for (size_t i = 0; i < 3; ++i) + for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < HTTP_STATUSES; ++j) fprintf(out, "gatepost_http_requests_total{route=\"%s\",status=\"%d\"} %llu\n", names[i], statuses[j], routes[i][j]); + if (i == 0) + fprintf(out, + "gatepost_http_requests_total{route=\"tickets\",status=\"incomplete\"} %llu\n", + data.http_tickets_incomplete); + } fprintf(out, "# HELP gatepost_tls_handshake_failures_total Failed hub TLS handshakes.\n" "# TYPE gatepost_tls_handshake_failures_total counter\n"); for (size_t listener = 0; listener < 2; ++listener) diff --git a/gate-hub/prometheus.h b/gate-hub/prometheus.h index ee5f254..72e02ee 100644 --- a/gate-hub/prometheus.h +++ b/gate-hub/prometheus.h @@ -8,6 +8,7 @@ void prometheus_stats(const char *gate); void prometheus_queue(size_t depth); void prometheus_sync(int success); void prometheus_http(const char *route, int status); +void prometheus_http_tickets_incomplete(void); void prometheus_tls_failure(int status_listener, const char *reason); int prometheus_render(const char *version, double list_age_seconds, char **body, size_t *length); #endif diff --git a/gate-hub/status.c b/gate-hub/status.c index 5e34505..d20687c 100644 --- a/gate-hub/status.c +++ b/gate-hub/status.c @@ -231,6 +231,7 @@ static void serve_tickets(int fd, SSL *tls, const char *matching, const char *ra struct tm utc; if (now == (time_t)-1 || !gmtime_r(&now, &utc) || !strftime(date, sizeof date, "%a, %d %b %Y %H:%M:%S GMT", &utc)) { + prometheus_http_tickets_incomplete(); fclose(file); return; } @@ -241,6 +242,7 @@ static void serve_tickets(int fd, SSL *tls, const char *matching, const char *ra range ? "206 Partial Content" : "200 OK", date, (long long)(st.st_size - start), extra); if (n <= 0 || (size_t)n >= sizeof header || write_full(fd, tls, header, (size_t)n) != 0 || fseeko(file, start, SEEK_SET) != 0) { + prometheus_http_tickets_incomplete(); fclose(file); return; } @@ -251,7 +253,10 @@ static void serve_tickets(int fd, SSL *tls, const char *matching, const char *ra break; if (count == 0 && !ferror(file)) connection_reply_complete = true; - prometheus_http("tickets", range ? 206 : 200); + if (connection_reply_complete) + prometheus_http("tickets", range ? 206 : 200); + else + prometheus_http_tickets_incomplete(); fclose(file); } static bool metrics_peer_allowed(const struct sockaddr_in *peer) { From 15b289ceeb8021fe64127e9a4ba49a58fe0b4e5b Mon Sep 17 00:00:00 2001 From: Mateo Rossi Date: Wed, 28 Oct 2026 11:30:00 +1100 Subject: [PATCH 5/9] feat(gated,gate-hub): report each gate's installed list version in its heartbeat The hub could not tell which list each gate had installed. List age based on file time also kept growing through 304 confirmations. Keep the verified SHA-256 and monotonic confirmation time at each gate. Send the installed version and time since confirmation in CONFIG, then compare it with the list the hub currently serves. Gates reporting no version have unknown status, which is not an error. A gate retries an empty CONFIG on the same connection for a hub not yet upgraded. The hub trusts the reported list state as sent: CONFIG has no MAC, so whoever holds a gate's certificate can report a false state for that gate. Co-authored-by: Ben Carter --- CMakeLists.txt | 5 +- docs/operations/metrics.md | 4 +- docs/operations/metrics.zh-CN.md | 4 +- docs/protocol/gate-protocol.md | 2 +- docs/protocol/gate-protocol.zh-CN.md | 2 +- gate-hub/main.c | 68 +++++-- gate-hub/prometheus.c | 57 +++++- gate-hub/prometheus.h | 3 + gated/hub.c | 32 ++- gated/ticket_sync.c | 35 ++++ gated/ticket_sync.h | 3 + lab/README.md | 2 +- lab/README.zh-CN.md | 2 +- tests/test_gate_list_version.py | 290 +++++++++++++++++++++++++++ tests/test_gate_mac.py | 7 +- tests/test_gated_tls.py | 7 +- tests/test_protocol_compat.py | 2 +- 17 files changed, 498 insertions(+), 27 deletions(-) create mode 100644 tests/test_gate_list_version.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d77875c..a090789 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -217,6 +217,9 @@ add_test(NAME http_sync_integrity COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_http_sync.py $) add_test(NAME protocol_compat COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_protocol_compat.py $) +add_test(NAME gate_list_version COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/tests/test_gate_list_version.py $ $) +set_tests_properties(gate_list_version PROPERTIES TIMEOUT 90) add_test(NAME protocol_probe_timeout COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_probe_timeout.py $) @@ -244,5 +247,5 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") endif() add_test(NAME status_deadline COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_status_deadline.py $ $) -set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons ticket_fetch_progress http_distribution ticket_reply_count offline_reports protocol_compat status_deadline +set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons ticket_fetch_progress http_distribution ticket_reply_count offline_reports protocol_compat gate_list_version status_deadline PROPERTIES RESOURCE_LOCK status_ports) diff --git a/docs/operations/metrics.md b/docs/operations/metrics.md index daecbb1..90142c4 100644 --- a/docs/operations/metrics.md +++ b/docs/operations/metrics.md @@ -1,6 +1,6 @@ # Hub metrics -The hub exposes Prometheus text format 0.0.4 at `GET /metrics` on its staff-side status listener, port 8081. When device TLS is configured, port 8444 serves the same routes on the same bind address to clients with venue CA-signed gate certificates. In the venue lab, `GATEPOST_STATUS_BIND=10.77.20.10` binds this listener to the staff network, while gate RPC uses port 7000. The metrics route accepts loopback and sources matching `GATEPOST_STAFF_PREFIX=10.77.20.`. Without device TLS, gates may fetch `/tickets` on port 8081. With device TLS, port 8081 answers `GET /tickets` with 404, and gates fetch the list on port 8444 using their certificates; their subnet cannot read `/metrics`. On a hub with device TLS, a rising `gatepost_http_requests_total{route="tickets",status="404"}` means some client still fetches the list from 8081, usually a gate without device TLS or one whose `GATEPOST_TICKETS_URL` is an `http://` address. Keep the status listener on a staff-only interface and set the prefix to that network in a deployment. The hub uses a bounded in-process C collector; it adds no dependency. At most 64 distinct gate labels are retained, and invalid label characters become `_`. +The hub exposes Prometheus text format 0.0.4 at `GET /metrics` on its staff-side status listener, port 8081. When device TLS is configured, port 8444 serves the same routes on the same bind address to clients with venue CA-signed gate certificates. In the venue lab, `GATEPOST_STATUS_BIND=10.77.20.10` binds this listener to the staff network, while gate RPC uses port 7000. The metrics route accepts loopback and sources matching `GATEPOST_STAFF_PREFIX=10.77.20.`. Without device TLS, gates may fetch `/tickets` on port 8081. With device TLS, port 8081 answers `GET /tickets` with 404, and gates fetch the list on port 8444 using their certificates; their subnet cannot read `/metrics`. On a hub with device TLS, a rising `gatepost_http_requests_total{route="tickets",status="404"}` means some client still fetches the list from 8081, usually a gate without device TLS or one whose `GATEPOST_TICKETS_URL` is an `http://` address. Keep the status listener on a staff-only interface and set the prefix to that network in a deployment. The hub uses a bounded in-process C collector; it adds no dependency. At most 64 distinct gate labels are retained, and invalid label characters become `_`. A new gate beyond the limit has no list series: its list report is not recorded. Existing scan and connection metrics keep their overflow behavior. A gate reporting no version has `unknown` list status; this is not an error. | Name | Type | Labels | Meaning | | --- | --- | --- | --- | @@ -9,6 +9,8 @@ The hub exposes Prometheus text format 0.0.4 at `GET /metrics` on its staff-side | `gatepost_connected_gates` | Gauge | `gate` | 1 while that gate has an identified open RPC connection, otherwise 0. Connections not yet identified appear as `unknown`. | | `gatepost_connected_gates_count` | Gauge | None | Number of gates with an open identified RPC connection. | | `gatepost_last_stats_age_seconds` | Gauge | `gate` | Seconds since the last text `STATS` or framed CONFIG from that gate; absent until first report. | +| `gatepost_gate_list_status` | Gauge | `gate`, `status` (`current`, `stale`, `unknown`) | Three series per retained gate, exactly one equal to 1. `current` means the last reported SHA-256 matches the list the hub serves now; `stale` means another list or `list=none`; `unknown` means no valid version report, including empty or invalid CONFIG and text-line gates. | +| `gatepost_gate_list_confirmed_age_seconds` | Gauge | `gate` | The gate's reported confirmation age plus whole seconds since the report; absent if no age was reported or the list state is unknown. | | `gatepost_ticket_list_info` | Gauge | `version` | Always 1 for the active hub list. Version is its SHA-256 in hex. | | `gatepost_ticket_list_age_seconds` | Gauge | None | Seconds since the active list file's modification time. | | `gatepost_dc_sync_attempts_total` | Counter | `outcome` (`success`, `error`) | Completed background data-centre synchronization runs. | diff --git a/docs/operations/metrics.zh-CN.md b/docs/operations/metrics.zh-CN.md index db08050..b5622ef 100644 --- a/docs/operations/metrics.zh-CN.md +++ b/docs/operations/metrics.zh-CN.md @@ -1,6 +1,6 @@ # Hub 指标 -Hub 在员工网络一侧的 8081 端口通过 `GET /metrics` 提供 Prometheus 0.0.4 文本格式。配置设备 TLS 后,同一绑定地址的 8444 端口向持有场馆 CA 签发的闸机证书的客户端提供相同接口。场馆实验中,`GATEPOST_STATUS_BIND=10.77.20.10` 将状态服务绑定在员工网络,闸机 RPC 使用 7000 端口。指标接口允许本机及符合 `GATEPOST_STAFF_PREFIX=10.77.20.` 的来源访问。未配置设备 TLS 时,闸机可通过 8081 获取 `/tickets`。配置设备 TLS 后,8081 对 `GET /tickets` 返回 404,闸机须持证书从 8444 获取票单;在这样的 hub 上,`gatepost_http_requests_total{route="tickets",status="404"}` 如果还在涨,说明仍有客户端从 8081 取票单,通常是没配设备 TLS 的闸机,或者 `GATEPOST_TICKETS_URL` 设成了 `http://` 地址的闸机;闸机网段不能读取 `/metrics`。实际部署时,应把状态服务绑定在仅供员工使用的接口,并把前缀设为该网络。Hub 使用容量有上限的 C 语言进程内采集器,不增加依赖。最多保留 64 个不同的闸机标签;标签中的非法字符会替换为 `_`。 +Hub 在员工网络一侧的 8081 端口通过 `GET /metrics` 提供 Prometheus 0.0.4 文本格式。配置设备 TLS 后,同一绑定地址的 8444 端口向持有场馆 CA 签发的闸机证书的客户端提供相同接口。场馆实验中,`GATEPOST_STATUS_BIND=10.77.20.10` 将状态服务绑定在员工网络,闸机 RPC 使用 7000 端口。指标接口允许本机及符合 `GATEPOST_STAFF_PREFIX=10.77.20.` 的来源访问。未配置设备 TLS 时,闸机可通过 8081 获取 `/tickets`。配置设备 TLS 后,8081 对 `GET /tickets` 返回 404,闸机须持证书从 8444 获取票单;在这样的 hub 上,`gatepost_http_requests_total{route="tickets",status="404"}` 如果还在涨,说明仍有客户端从 8081 取票单,通常是没配设备 TLS 的闸机,或者 `GATEPOST_TICKETS_URL` 设成了 `http://` 地址的闸机;闸机网段不能读取 `/metrics`。实际部署时,应把状态服务绑定在仅供员工使用的接口,并把前缀设为该网络。Hub 使用容量有上限的 C 语言进程内采集器,不增加依赖。最多保留 64 个不同的闸机标签;标签中的非法字符会替换为 `_`。超过上限的新闸机不会留下票单状态记录,也没有该闸机的票单指标序列;原有扫描和连接指标仍按既有方式处理超额闸机。闸机未报告版本时显示 `unknown`,这不表示发生错误。 | 名称 | 类型 | 标签 | 含义 | | --- | --- | --- | --- | @@ -9,6 +9,8 @@ Hub 在员工网络一侧的 8081 端口通过 `GET /metrics` 提供 Prometheus | `gatepost_connected_gates` | Gauge | `gate` | 已确认身份的闸机 RPC 连接打开时为 1,否则为 0。尚未确认身份的连接记作 `unknown`。 | | `gatepost_connected_gates_count` | Gauge | 无 | 当前已确认身份且保持 RPC 连接的闸机数。 | | `gatepost_last_stats_age_seconds` | Gauge | `gate` | 距该闸机最近一次文本 `STATS` 或帧格式 CONFIG 的秒数;首次收到之前不显示。 | +| `gatepost_gate_list_status` | Gauge | `gate`、`status`(`current`、`stale`、`unknown`) | 每个保留的闸机固定输出三条序列,恰有一条为 1。最近报告的 SHA-256 与 hub 当前提供的票单一致时为 `current`;报告其他版本或 `list=none` 时为 `stale`;没有有效版本报告(包括空 CONFIG、无效 CONFIG 和文本行闸机)时为 `unknown`。 | +| `gatepost_gate_list_confirmed_age_seconds` | Gauge | `gate` | 闸机报告的确认时间加上报告后经过的整秒数;未报告确认时间或票单状态未知时不显示。 | | `gatepost_ticket_list_info` | Gauge | `version` | 当前 Hub 票单的值恒为 1;版本号是十六进制 SHA-256。 | | `gatepost_ticket_list_age_seconds` | Gauge | 无 | 当前票单文件自修改以来的秒数。 | | `gatepost_dc_sync_attempts_total` | Counter | `outcome`(`success`、`error`) | 后台数据中心同步完成的次数及结果。 | diff --git a/docs/protocol/gate-protocol.md b/docs/protocol/gate-protocol.md index faf2127..8dd0a80 100644 --- a/docs/protocol/gate-protocol.md +++ b/docs/protocol/gate-protocol.md @@ -15,7 +15,7 @@ With `GATEPOST_TLS_CA`, `GATEPOST_TLS_CERT` and `GATEPOST_TLS_KEY` configured, t | 8 | 4 | payload length, 0–4096 | | 12 | 4 | request ID, echoed in response | -Types: `1 LOOKUP` → `2 LOOKUP_REPLY`, `3 SCAN` → `4 SCAN_REPLY`, `5 CONFIG` → `6 CONFIG_REPLY`, `7 HELLO` → `8 HELLO_REPLY`, `9 REPORT` → `10 REPORT_REPLY`, and `127 ERROR`. LOOKUP and SCAN payloads are barcode bytes, without NUL. Replies carry `FOUND`, `MISSING`, `ACCEPT`, or `REJECT`. CONFIG has no request payload and replies with `scans=N tickets=N`. HELLO carries the gate ID and refreshes the hub link monitor. REPORT carries ` `; the scan ID is a durable 128-bit random value encoded as 32 lowercase hex digits. The hub fsyncs a report log before replying `RECORDED`. A repeated scan ID with identical data receives the same reply without a second record; a changed payload under that ID receives ERROR. The hub compares offline admissions by barcode across gate IDs and exposes the duplicate count in `/status`. Scan decisions and reports use TCP; UDP is used only for the venue reliability measurement. Unknown types receive ERROR with the same request ID. Malformed magic, reserved bits, or excessive length closes the connection. +Types: `1 LOOKUP` → `2 LOOKUP_REPLY`, `3 SCAN` → `4 SCAN_REPLY`, `5 CONFIG` → `6 CONFIG_REPLY`, `7 HELLO` → `8 HELLO_REPLY`, `9 REPORT` → `10 REPORT_REPLY`, and `127 ERROR`. LOOKUP and SCAN payloads are barcode bytes, without NUL. Replies carry `FOUND`, `MISSING`, `ACCEPT`, or `REJECT`. CONFIG carries `list=<64 lowercase SHA-256 hex> confirmed_age=` after a successful list fetch, `list=<64 lowercase SHA-256 hex>` for an installed list not yet confirmed since start, or `list=none` when no verified list is installed. The optional age is a decimal integer from 0 to 31536000. An empty CONFIG payload remains accepted for gates not yet upgraded. The reply remains `scans=N tickets=N`; an invalid payload gets that reply and a warning, with the gate's list state unknown. If a hub not yet upgraded answers a non-empty CONFIG with ERROR, the gate retries one empty CONFIG on the same connection. HELLO carries the gate ID and refreshes the hub link monitor. REPORT carries ` `; the scan ID is a durable 128-bit random value encoded as 32 lowercase hex digits. The hub fsyncs a report log before replying `RECORDED`. A repeated scan ID with identical data receives the same reply without a second record; a changed payload under that ID receives ERROR. The hub compares offline admissions by barcode across gate IDs and exposes the duplicate count in `/status`. Scan decisions and reports use TCP; UDP is used only for the venue reliability measurement. Unknown types receive ERROR with the same request ID. Malformed magic, reserved bits, or excessive length closes the connection. Connection state: connect → read header → validate length/version → read payload → dispatch → send matching response → repeat; EOF closes. The gate applies a 300 ms overall deadline to each scan RPC. The hub caches the last eight requests and replies per connection. A retry with the same ID and identical type and payload gets its cached reply; reusing an ID with different content gets ERROR. Reconnecting starts a new cache. Durable offline reports use their own scan IDs. diff --git a/docs/protocol/gate-protocol.zh-CN.md b/docs/protocol/gate-protocol.zh-CN.md index f69db8c..b77f05d 100644 --- a/docs/protocol/gate-protocol.zh-CN.md +++ b/docs/protocol/gate-protocol.zh-CN.md @@ -15,7 +15,7 @@ | 8 | 4 | payload length,0–4096 | | 12 | 4 | request ID,响应原样返回 | -类型:`1 LOOKUP` → `2 LOOKUP_REPLY`、`3 SCAN` → `4 SCAN_REPLY`、`5 CONFIG` → `6 CONFIG_REPLY`、`7 HELLO` → `8 HELLO_REPLY`、`9 REPORT` → `10 REPORT_REPLY`、`127 ERROR`。LOOKUP 和 SCAN 的 payload 是无 NUL 的 barcode 字节;响应是 `FOUND`、`MISSING`、`ACCEPT` 或 `REJECT`。CONFIG 的请求为空,响应是 `scans=N tickets=N`。HELLO 携带闸机 ID,并刷新 hub 的连接监视状态。REPORT 携带 ` `;scan ID 是持久化的 128-bit 随机值,以 32 个小写十六进制字符表示。hub 在回复 `RECORDED` 前对报告日志执行 fsync。同一 scan ID 的相同数据再次发送时得到相同回复,不产生第二条记录;该 ID 携带不同内容时收到 ERROR。hub 比较不同闸机 ID 对同一条码的离线放行,并在 `/status` 显示重复数量。扫描决定和报告使用 TCP;UDP 仅用于场馆网络的可靠性交付测量。未知类型收到相同 request ID 的 ERROR。magic、保留位或长度非法时关闭连接。 +类型:`1 LOOKUP` → `2 LOOKUP_REPLY`、`3 SCAN` → `4 SCAN_REPLY`、`5 CONFIG` → `6 CONFIG_REPLY`、`7 HELLO` → `8 HELLO_REPLY`、`9 REPORT` → `10 REPORT_REPLY`、`127 ERROR`。LOOKUP 和 SCAN 的 payload 是无 NUL 的 barcode 字节;响应是 `FOUND`、`MISSING`、`ACCEPT` 或 `REJECT`。CONFIG 在取票单成功后携带 `list=<64 位小写 SHA-256 十六进制值> confirmed_age=<整秒数>`;票单已安装但本次启动后尚未确认时只携带 `list=<64 位小写 SHA-256 十六进制值>`;没有已验证的票单时携带 `list=none`。可选的确认时间为 0 到 31536000 的十进制整数。尚未升级的闸机仍可发送空 CONFIG。响应始终为 `scans=N tickets=N`;payload 无效时,hub 仍正常响应并记录警告,将该闸机的票单状态记为未知。若尚未升级的 hub 对非空 CONFIG 回复 ERROR,闸机会在同一连接上补发一次空 CONFIG。HELLO 携带闸机 ID,并刷新 hub 的连接监视状态。REPORT 携带 ` `;scan ID 是持久化的 128-bit 随机值,以 32 个小写十六进制字符表示。hub 在回复 `RECORDED` 前对报告日志执行 fsync。同一 scan ID 的相同数据再次发送时得到相同回复,不产生第二条记录;该 ID 携带不同内容时收到 ERROR。hub 比较不同闸机 ID 对同一条码的离线放行,并在 `/status` 显示重复数量。扫描决定和报告使用 TCP;UDP 仅用于场馆网络的可靠性交付测量。未知类型收到相同 request ID 的 ERROR。magic、保留位或长度非法时关闭连接。 连接状态:connect → 读取 header → 校验长度和版本 → 读取 payload → 执行 → 发送匹配响应 → 重复;EOF 后关闭。闸机对每次扫描 RPC 使用总计 300 ms 的截止时间。hub 为每条连接缓存最近八个请求及响应。同一 ID 与相同类型、payload 的重试得到缓存响应;相同 ID 携带不同内容时收到 ERROR。重连会清空缓存。离线报告使用独立且持久的 scan ID。 diff --git a/gate-hub/main.c b/gate-hub/main.c index 000222e..a9ffa69 100644 --- a/gate-hub/main.c +++ b/gate-hub/main.c @@ -265,6 +265,7 @@ static void serve_line(hub *owner, int fd, const struct sockaddr_in *address) { memcpy(gate, line + 6, strlen(line + 6) + 1); prometheus_connection(gate, 1); prometheus_stats(gate); + (void)prometheus_gate_list(gate, NULL, 0, 0, 1); } if (getenv("GATEPOST_ALERTS") && line[5] == ' ' && gate_watch_seen(&owner->watch, line + 6) != 0) @@ -304,6 +305,44 @@ static void reply_text(gate_message *reply, uint8_t type, const char *text) { memcpy(reply->payload, text, reply->length); } +/* CONFIG is text but its frame payload is not NUL terminated. */ +static int parse_gate_list(const gate_message *request, char hex[65], int *has_age, unsigned *age) { + const unsigned char *payload = request->payload; + size_t length = request->length; + *has_age = 0; + *age = 0; + if (length < 9 || memcmp(payload, "list=", 5) != 0) + return 0; + if (length == 9 && memcmp(payload + 5, "none", 4) == 0) { + memcpy(hex, "none", 5); + return 1; + } + if (length < 69) + return 0; + for (size_t i = 5; i < 69; ++i) + if (!((payload[i] >= '0' && payload[i] <= '9') || (payload[i] >= 'a' && payload[i] <= 'f'))) + return 0; + memcpy(hex, payload + 5, 64); + hex[64] = 0; + if (length == 69) + return 1; + static const char suffix[] = " confirmed_age="; + if (length <= 69 + sizeof suffix - 1 || memcmp(payload + 69, suffix, sizeof suffix - 1) != 0) + return 0; + unsigned value = 0; + for (size_t i = 69 + sizeof suffix - 1; i < length; ++i) { + if (payload[i] < '0' || payload[i] > '9') + return 0; + unsigned digit = (unsigned)(payload[i] - '0'); + if (value > (31536000U - digit) / 10) + return 0; + value = value * 10 + digit; + } + *has_age = 1; + *age = value; + return 1; +} + static int lowercase_hex(const char *text, size_t length) { if (strlen(text) != length) return 0; @@ -594,19 +633,22 @@ static void serve_binary(hub *owner, int fd, SSL *tls, const char *peer_gate, reply_text(&reply, GATE_LOOKUP_REPLY, found ? "FOUND" : "MISSING"); } } else if (request.type == GATE_CONFIG) { - if (request.length != 0) - reply_text(&reply, GATE_ERROR, "CONFIG payload must be empty"); - else { - unsigned scans, tickets; - char status[64]; - if (metrics_snapshot(&owner->metrics, NULL, &scans, &tickets) != 0) - break; - int length = snprintf(status, sizeof status, "scans=%u tickets=%u", scans, tickets); - if (length < 0 || (size_t)length >= sizeof status) - break; - reply_text(&reply, GATE_CONFIG_REPLY, status); - prometheus_stats(gate); - } + char hex[65]; + int has_age = 0; + unsigned age = 0; + int valid = !request.length || parse_gate_list(&request, hex, &has_age, &age); + if (prometheus_gate_list(gate, valid && request.length ? hex : NULL, has_age, age, + valid)) + gate_log("WARN", "gate_list", "state=invalid gate=%s", gate); + unsigned scans, tickets; + char status[64]; + if (metrics_snapshot(&owner->metrics, NULL, &scans, &tickets) != 0) + break; + int length = snprintf(status, sizeof status, "scans=%u tickets=%u", scans, tickets); + if (length < 0 || (size_t)length >= sizeof status) + break; + reply_text(&reply, GATE_CONFIG_REPLY, status); + prometheus_stats(gate); } else if (request.type == GATE_REPORT) { char id[33], gate_id[64], barcode[GATE_BARCODE_MAX + 1]; request_diagnostic diagnostic = {.gate = "unknown", diff --git a/gate-hub/prometheus.c b/gate-hub/prometheus.c index cdd1751..6567ab3 100644 --- a/gate-hub/prometheus.c +++ b/gate-hub/prometheus.c @@ -27,6 +27,12 @@ typedef struct { double duration_sum; unsigned connected; time_t last_stats; + char list_hex[65]; + unsigned confirmed_age; + time_t list_reported_at; + int list_state; /* 0 unknown, 1 none, 2 installed */ + int list_has_age; + int invalid_logged; } gate_record; static struct { pthread_mutex_t lock; @@ -40,7 +46,7 @@ static struct { unsigned long long tls_failures[2][TLS_REASONS]; } data = {.lock = PTHREAD_MUTEX_INITIALIZER}; -static gate_record *get_gate(const char *name) { +static gate_record *find_gate(const char *name, int fold_when_full) { if (!name || !*name) name = "unknown"; char safe[64]; @@ -57,12 +63,14 @@ static gate_record *get_gate(const char *name) { if (strcmp(data.gates[i].name, safe) == 0) return &data.gates[i]; if (data.count == GATES) - return &data.gates[0]; + return fold_when_full ? &data.gates[0] : NULL; gate_record *gate = &data.gates[data.count++]; memcpy(gate->name, safe, n + 1); return gate; } +static gate_record *get_gate(const char *name) { return find_gate(name, 1); } + void prometheus_scan(const char *name, const char *result, double seconds) { if (pthread_mutex_lock(&data.lock) != 0) return; @@ -97,6 +105,27 @@ void prometheus_stats(const char *name) { get_gate(name)->last_stats = time(NULL); (void)pthread_mutex_unlock(&data.lock); } +int prometheus_gate_list(const char *name, const char *hex, int has_age, unsigned age, int valid) { + if (pthread_mutex_lock(&data.lock) != 0) + return 0; + gate_record *gate = find_gate(name, 0); + int warn = 0; + if (gate) { + if (!valid) { + warn = !gate->invalid_logged; + gate->invalid_logged = 1; + } else + gate->invalid_logged = 0; + gate->list_state = hex ? (strcmp(hex, "none") == 0 ? 1 : 2) : 0; + gate->list_has_age = gate->list_state == 2 && has_age; + gate->confirmed_age = age; + gate->list_reported_at = time(NULL); + if (gate->list_state == 2) + memcpy(gate->list_hex, hex, sizeof gate->list_hex); + } + (void)pthread_mutex_unlock(&data.lock); + return warn; +} void prometheus_queue(size_t depth) { if (pthread_mutex_lock(&data.lock) != 0) return; @@ -214,6 +243,30 @@ int prometheus_render(const char *version, double age, char **body, size_t *leng if (data.gates[i].last_stats) fprintf(out, "gatepost_last_stats_age_seconds{gate=\"%s\"} %.0f\n", data.gates[i].name, difftime(now, data.gates[i].last_stats)); + fprintf(out, "# HELP gatepost_gate_list_status Gate list relative to the active hub list.\n" + "# TYPE gatepost_gate_list_status gauge\n"); + for (size_t i = 0; i < data.count; ++i) { + gate_record *gate = &data.gates[i]; + int current = gate->list_state == 2 && strcmp(gate->list_hex, version) == 0; + int stale = gate->list_state != 0 && !current; + fprintf(out, + "gatepost_gate_list_status{gate=\"%s\",status=\"current\"} %d\n" + "gatepost_gate_list_status{gate=\"%s\",status=\"stale\"} %d\n" + "gatepost_gate_list_status{gate=\"%s\",status=\"unknown\"} %d\n", + gate->name, current, gate->name, stale, gate->name, !current && !stale); + } + fprintf( + out, + "# HELP gatepost_gate_list_confirmed_age_seconds Seconds since gate list confirmation.\n" + "# TYPE gatepost_gate_list_confirmed_age_seconds gauge\n"); + for (size_t i = 0; i < data.count; ++i) { + gate_record *gate = &data.gates[i]; + if (gate->list_state == 2 && gate->list_has_age) { + double elapsed = difftime(now, gate->list_reported_at); + fprintf(out, "gatepost_gate_list_confirmed_age_seconds{gate=\"%s\"} %.0f\n", gate->name, + gate->confirmed_age + (elapsed > 0 ? elapsed : 0)); + } + } fprintf(out, "# HELP gatepost_ticket_list_info Active hub list SHA-256.\n" "# TYPE gatepost_ticket_list_info gauge\n" diff --git a/gate-hub/prometheus.h b/gate-hub/prometheus.h index 72e02ee..a3dfba4 100644 --- a/gate-hub/prometheus.h +++ b/gate-hub/prometheus.h @@ -5,6 +5,9 @@ void prometheus_scan(const char *gate, const char *result, double seconds); void prometheus_connection(const char *gate, int delta); void prometheus_stats(const char *gate); +/* hex is NULL for an empty or invalid report, "none" for no installed list. + Returns 1 only when an invalid report needs its once-per-gate warning. */ +int prometheus_gate_list(const char *gate, const char *hex, int has_age, unsigned age, int valid); void prometheus_queue(size_t depth); void prometheus_sync(int success); void prometheus_http(const char *route, int status); diff --git a/gated/hub.c b/gated/hub.c index 43eeabd..8b5366c 100644 --- a/gated/hub.c +++ b/gated/hub.c @@ -3,6 +3,7 @@ #include "hub.h" #include "log.h" #include "protocol_io.h" +#include "ticket_sync.h" #include "tickets.h" #include "tls.h" #include "tls_verify_reason.h" @@ -454,6 +455,7 @@ int hub_scan(hub_endpoint *endpoint, const char *barcode) { } int hub_link_check(hub_endpoint *endpoint, const char *gate_id) { + static int legacy_hub_logged; size_t length = strlen(gate_id); if (!length || length > 63) return 0; @@ -472,8 +474,34 @@ int hub_link_check(hub_endpoint *endpoint, const char *gate_id) { reply.type == GATE_HELLO_REPLY; if (okay) { gate_message config = {.version = GATE_WIRE_VERSION, .type = GATE_CONFIG, .request_id = 2}; - okay = one_rpc(endpoint, &connection, &reader, &config, &reply, deadline) == 0 && - reply.type == GATE_CONFIG_REPLY && reply.length >= 6 && + char hex[65]; + unsigned age = 0; + int state = gate_ticket_list_status(hex, &age); + int payload_length; + if (state == 2) + payload_length = snprintf((char *)config.payload, sizeof config.payload, + "list=%s confirmed_age=%u", hex, age); + else if (state == 1) + payload_length = + snprintf((char *)config.payload, sizeof config.payload, "list=%s", hex); + else + payload_length = snprintf((char *)config.payload, sizeof config.payload, "list=none"); + if (payload_length < 0 || (size_t)payload_length >= sizeof config.payload) { + connection_close(&connection); + return 0; + } + config.length = (uint16_t)payload_length; + okay = one_rpc(endpoint, &connection, &reader, &config, &reply, deadline) == 0; + if (okay && reply.type == GATE_ERROR) { + if (!legacy_hub_logged) { + gate_log("WARN", "hub_config", "state=legacy_hub"); + legacy_hub_logged = 1; + } + config.request_id = 3; + config.length = 0; + okay = one_rpc(endpoint, &connection, &reader, &config, &reply, deadline) == 0; + } + okay = okay && reply.type == GATE_CONFIG_REPLY && reply.length >= 6 && memcmp(reply.payload, "scans=", 6) == 0; } connection_close(&connection); diff --git a/gated/ticket_sync.c b/gated/ticket_sync.c index a14d811..d1c4988 100644 --- a/gated/ticket_sync.c +++ b/gated/ticket_sync.c @@ -14,8 +14,31 @@ #include #include #include +#include #include +static char installed_hex[65]; +static struct timespec confirmed_at; +static bool confirmed; + +int gate_ticket_list_status(char hex[65], unsigned *confirmed_age) { + memcpy(hex, installed_hex, sizeof installed_hex); + if (!installed_hex[0]) + return 0; + if (!confirmed) + return 1; + struct timespec now; + if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) + return 1; + time_t seconds = now.tv_sec - confirmed_at.tv_sec; + if (now.tv_nsec < confirmed_at.tv_nsec) + --seconds; + *confirmed_age = seconds > 0 ? (seconds > 31536000 ? 31536000 : (unsigned)seconds) : 0; + return 2; +} + +static void confirm_list(void) { confirmed = clock_gettime(CLOCK_MONOTONIC, &confirmed_at) == 0; } + typedef struct { FILE *file; char etag[100]; @@ -152,7 +175,15 @@ static int fetch_tickets(const char *url, const char *path, const gate_ticket_tl etag[0] = 0; if (unlink(meta_path) != 0 && errno != ENOENT) gate_log_errno("ticket_etag_unlink"); + installed_hex[0] = 0; + confirmed = false; + } else if (strcmp(installed_hex, expected) != 0) { + memcpy(installed_hex, expected, sizeof installed_hex); + confirmed = false; } + } else { + installed_hex[0] = 0; + confirmed = false; } int fd = mkstemp(temporary); if (fd < 0) @@ -250,6 +281,8 @@ static int fetch_tickets(const char *url, const char *path, const gate_ticket_tl curl_slist_free_all(headers); curl_slist_free_all(connect_to); curl_easy_cleanup(curl); + if (installed_hex[0]) + confirm_list(); return 0; } if (!state.etag[0] || strlen(state.digest) != 64 || strlen(state.etag) != 66 || @@ -325,6 +358,8 @@ static int fetch_tickets(const char *url, const char *path, const gate_ticket_tl curl_slist_free_all(headers); curl_slist_free_all(connect_to); curl_easy_cleanup(curl); + memcpy(installed_hex, state.digest, sizeof installed_hex); + confirm_list(); return bad ? -1 : 1; tls_config_fail: last_failure_reason = "tls_config"; diff --git a/gated/ticket_sync.h b/gated/ticket_sync.h index d25483f..a067968 100644 --- a/gated/ticket_sync.h +++ b/gated/ticket_sync.h @@ -8,4 +8,7 @@ typedef struct { } gate_ticket_tls; int gate_fetch_tickets(const char *url, const char *path, const gate_ticket_tls *tls); +/* Returns 0 for no verified list, 1 for an unconfirmed list, or 2 for a + list confirmed since this process started. */ +int gate_ticket_list_status(char hex[65], unsigned *confirmed_age); #endif diff --git a/lab/README.md b/lab/README.md index df21adf..25e0202 100644 --- a/lab/README.md +++ b/lab/README.md @@ -31,7 +31,7 @@ after TLS application-data hub->gate1: 8 after connection duration ms: 3.6 ``` -The gate's periodic framed `HELLO` and `CONFIG` requests check reachability and drive `LED NET`; scans use the same hub endpoint. A hub that does not answer is abandoned within the 300 ms scan deadline, and local admission continues. +The gate's periodic framed `HELLO` and `CONFIG` requests check reachability and drive `LED NET`; CONFIG also reports the installed list version and its confirmation age when available. Scans use the same hub endpoint. A hub that does not answer is abandoned within the 300 ms scan deadline, and local admission continues. With the lab running, `sh lab/device-tls.sh` checks that the staff laptop receives no ticket list from plaintext port 8081 or from TLS port 8444 without a client certificate, and that a capture of a gate scan does not reveal the gate id or ticket id. Both checks now pass. Check 2 requires payload in both directions and at least one FIN or RST in the same TCP stream. diff --git a/lab/README.zh-CN.md b/lab/README.zh-CN.md index 0fa8307..ac4916f 100644 --- a/lab/README.zh-CN.md +++ b/lab/README.zh-CN.md @@ -31,7 +31,7 @@ after TLS application-data hub->gate1: 8 after connection duration ms: 3.6 ``` -闸机周期性发送有 frame 的 `HELLO` 和 `CONFIG` 检查 hub 链路并驱动 `LED NET`;扫描使用同一个 hub 地址。若 hub 不应答,闸机在 300 ms 扫描期限内放弃等待,继续本地判断。 +闸机周期性发送帧格式的 `HELLO` 和 `CONFIG` 检查 hub 链路并驱动 `LED NET`;CONFIG 还会报告已安装票单的版本,以及可用时的确认时间。扫描使用同一个 hub 地址。若 hub 不应答,闸机在 300 ms 扫描期限内放弃等待,继续本地判断。 实验环境启动后,运行 `sh lab/device-tls.sh`,检查工作人员笔记本无法从明文 8081 或不带客户端证书的 TLS 8444 读取票单,以及闸机扫码的抓包中看不到闸机编号和票号。现在两项检查都应通过。检查 2 要求同一条 TCP 流的两个方向都有负载,且至少出现一个 FIN 或 RST。 diff --git a/tests/test_gate_list_version.py b/tests/test_gate_list_version.py new file mode 100644 index 0000000..0e0a399 --- /dev/null +++ b/tests/test_gate_list_version.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +"""Exercise gate list heartbeats, compatibility, and the bounded metric table.""" +import hashlib +import os +from pathlib import Path +import select +import socket +import struct +import subprocess +import sys +import tempfile +import threading +import time + +GATED, HUB = sys.argv[1:] +STATUS = ('127.0.0.1', 8081) + + +def free_port(): + with socket.socket() as peer: + peer.bind(('127.0.0.1', 0)) + return peer.getsockname()[1] + + +def exact(peer, count): + data = b'' + while len(data) < count: + block = peer.recv(count - len(data)) + assert block, f'framed reply ended with {count - len(data)} bytes missing' + data += block + return data + + +def receive(peer): + header = exact(peer, 16) + assert header[:4] == b'GTP1', f'bad frame magic: {header!r}' + version, kind, reserved, length, number = struct.unpack('!BBHII', header[4:]) + assert reserved == 0 and length <= 4096, f'bad frame header: {header!r}' + return version, kind, number, exact(peer, length) + + +def send(peer, version, kind, number, payload=b''): + peer.sendall(b'GTP1' + struct.pack('!BBHII', version, kind, 0, len(payload), number) + payload) + + +def rpc(peer, version, kind, number, payload=b''): + send(peer, version, kind, number, payload) + answer = receive(peer) + assert answer[0] == version and answer[2] == number, f'wrong reply header: {answer!r}' + return answer[1], answer[3] + + +def raw_gate(port, gate_id, version=2, payload=b''): + with socket.create_connection(('127.0.0.1', port), timeout=2) as peer: + peer.settimeout(2) + kind, body = rpc(peer, version, 7, 1, gate_id.encode()) + assert (kind, body) == (8, b'OK'), f'HELLO failed for {gate_id}: {(kind, body)!r}' + kind, body = rpc(peer, version, 5, 2, payload) + assert kind == 6 and body.startswith(b'scans='), f'CONFIG failed for {gate_id}: {(kind, body)!r}' + kind, body = rpc(peer, version, 5, 3, payload) + assert kind == 6 and body.startswith(b'scans='), f'connection closed after CONFIG for {gate_id}' + + +def metrics(): + with socket.create_connection(STATUS, timeout=2) as peer: + peer.settimeout(2) + peer.sendall(b'GET /metrics HTTP/1.1\r\nHost: hub.venue.lan\r\n\r\n') + body = bytearray() + while block := peer.recv(65536): + body.extend(block) + header, data = bytes(body).split(b'\r\n\r\n', 1) + assert header.startswith(b'HTTP/1.1 200'), f'metrics HTTP failure: {header[:120]!r}' + return data.decode() + + +def value(data, gate, status): + line = f'gatepost_gate_list_status{{gate="{gate}",status="{status}"}} ' + matches = [entry[len(line):] for entry in data.splitlines() if entry.startswith(line)] + assert len(matches) == 1, f'missing or duplicate {status} series for {gate}' + return int(matches[0]) + + +def has_status(data, gate, status): + line = f'gatepost_gate_list_status{{gate="{gate}",status="{status}"}} 1' + return line in data.splitlines() + + +def age(data, gate): + line = f'gatepost_gate_list_confirmed_age_seconds{{gate="{gate}"}} ' + matches = [entry[len(line):] for entry in data.splitlines() if entry.startswith(line)] + assert len(matches) <= 1, f'duplicate confirmation age for {gate}' + return float(matches[0]) if matches else None + + +def until(check, timeout, message): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if check(): + return + time.sleep(.2) + raise AssertionError(message) + + +def start_hub(source, port): + env = dict(os.environ, GATEPOST_STATUS='1') + hub = subprocess.Popen([HUB, str(source), str(port), 'pool'], env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + until(lambda: hub.poll() is None and status_ready(), 4, 'hub status listener did not start') + return hub + + +def status_ready(): + try: + with socket.create_connection(STATUS, timeout=.1): + return True + except OSError: + return False + + +def fake_hub(listener, stop, seen, scans): + listener.settimeout(.2) + while not stop.is_set(): + try: + peer, _ = listener.accept() + except socket.timeout: + continue + except OSError: + break + with peer: + peer.settimeout(1) + try: + while not stop.is_set(): + version, kind, number, payload = receive(peer) + if kind == 7: + reply_kind, body = 8, b'OK' + elif kind == 5: + seen.append(payload) + reply_kind, body = (127, b'CONFIG payload must be empty') if payload else (6, b'scans=0 tickets=0') + elif kind == 3: + scans.append(payload) + reply_kind, body = 4, b'ACCEPT' + else: + reply_kind, body = 127, b'unknown' + send(peer, version, reply_kind, number, body) + except (OSError, AssertionError): + pass + + +with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / 'hub.txt' + source.write_text('GP-000000000001\n') + gate_file = root / 'gate.txt' + gate_file.write_text('GP-999999999999\n') + port = free_port() + hub = start_hub(source, port) + gate = None + try: + gate = subprocess.Popen([GATED, '--hub', f'127.0.0.1:{port}', '--gate-id', 'fresh', + str(gate_file)], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + env=dict(os.environ, GATEPOST_OFFLINE_FILE=str(root / 'gate.offline'))) + until(lambda: has_status(metrics(), 'fresh', 'current'), 6, + 'fresh gate did not report the installed hub list') + assert age(metrics(), 'fresh') is not None and age(metrics(), 'fresh') < 25, \ + 'fresh gate confirmation age is absent or too old' + preinstalled = root / 'preinstalled.txt' + preinstalled.write_bytes(source.read_bytes()) + (root / 'preinstalled.txt.etag').write_text( + f'"{hashlib.sha256(preinstalled.read_bytes()).hexdigest()}"\n') + other = subprocess.Popen([GATED, '--hub', f'127.0.0.1:{port}', '--gate-id', 'preinstalled', + str(preinstalled)], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + env=dict(os.environ, GATEPOST_OFFLINE_FILE=str(root / 'pre.offline'))) + try: + until(lambda: has_status(metrics(), 'preinstalled', 'current'), 6, + 'a matching 304 did not confirm the preinstalled list') + assert age(metrics(), 'preinstalled') is not None and age(metrics(), 'preinstalled') < 25, \ + 'preinstalled list has no recent confirmation age after 304' + counts = [line for line in metrics().splitlines() if line.startswith( + 'gatepost_http_requests_total{route="tickets",status="304"} ')] + assert len(counts) == 1 and int(counts[0].split()[-1]) >= 1, \ + 'hub did not serve a 304 for the preinstalled list' + finally: + other.terminate() + other.communicate(timeout=5) + source.write_text('GP-000000000002\n') + data = metrics() + assert value(data, 'fresh', 'stale') == 1, 'gate did not become stale after hub list changed' + until(lambda: has_status(metrics(), 'fresh', 'current'), 25, + 'gate did not fetch the changed list within 25 seconds') + assert age(metrics(), 'fresh') is not None and age(metrics(), 'fresh') < 25, \ + 'confirmation age was not refreshed after the new list was installed' + + for version in (2, 1): + name = f'oldframe{version}' + raw_gate(port, name, version) + data = metrics() + assert value(data, name, 'unknown') == 1 and age(data, name) is None, \ + f'empty CONFIG from version {version} should have unknown list state' + with socket.create_connection(('127.0.0.1', port), timeout=2) as peer: + peer.sendall(b'STATS oldline\n') + assert peer.recv(128).startswith(b'scans='), 'text-line STATS failed' + data = metrics() + assert value(data, 'oldline', 'unknown') == 1 and age(data, 'oldline') is None, \ + 'text-line gate should have unknown list state' + raw_gate(port, 'invalid', payload=b'list=xyz') + data = metrics() + assert value(data, 'invalid', 'unknown') == 1 and age(data, 'invalid') is None, \ + 'invalid CONFIG should leave an unknown list state without age' + for name, payload in ( + ('upperhex', b'list=' + b'A' * 64), + ('oldage', b'list=' + b'a' * 64 + b' confirmed_age=31536001'), + ('trailing', b'list=' + b'a' * 64 + b' extra'), + ): + raw_gate(port, name, payload=payload) + assert value(metrics(), name, 'unknown') == 1, \ + f'malformed list payload was accepted for {name}' + raw_gate(port, 'no_list', payload=b'list=none') + data = metrics() + assert value(data, 'no_list', 'stale') == 1 and age(data, 'no_list') is None, \ + 'list=none should be stale without a confirmation age' + finally: + if gate: + gate.terminate() + gate.communicate(timeout=5) + hub.terminate() + _, logs = hub.communicate(timeout=5) + assert logs.count(b'event=gate_list state=invalid gate=invalid') == 1, \ + f'invalid CONFIG warning should appear once for two requests: {logs!r}' + + with socket.socket() as listener: + listener.bind(('127.0.0.1', 0)) + listener.listen(4) + stop = threading.Event() + seen = [] + scans = [] + worker = threading.Thread(target=fake_hub, args=(listener, stop, seen, scans), daemon=True) + worker.start() + gate_file.write_text('GP-999999999999\n') + installed = hashlib.sha256(gate_file.read_bytes()).hexdigest() + (root / 'gate.txt.etag').write_text(f'"{installed}"\n') + gate = subprocess.Popen([GATED, '--hub', f'127.0.0.1:{listener.getsockname()[1]}', + '--gate-id', 'legacy', str(gate_file)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=dict(os.environ, + GATEPOST_TICKETS_URL=f'http://127.0.0.1:{free_port()}/tickets', + GATEPOST_OFFLINE_FILE=str(root / 'legacy.offline'))) + try: + until(lambda: len(seen) >= 6, 6, 'legacy hub did not receive several CONFIG requests') + gate.stdin.write(b'GP-999999999999\n') + gate.stdin.flush() + until(lambda: b'GP-999999999999' in scans, 6, 'legacy hub did not receive the scan') + ready, _, _ = select.select([gate.stdout], [], [], 6) + assert ready and gate.stdout.readline() == b'ACCEPT\n', \ + 'legacy gate did not finish the accepted scan' + finally: + gate.terminate() + _, logs = gate.communicate(timeout=5) + stop.set() + listener.close() + worker.join(timeout=2) + assert sum(bool(payload) for payload in seen) >= 3 and seen.count(b'') >= 3, \ + f'gate did not retry empty CONFIG on each legacy heartbeat: {seen!r}' + assert all(payload == f'list={installed}'.encode() for payload in seen if payload), \ + f'verified startup list should be reported without confirmation age: {seen!r}' + assert b'event=hub_link gate=legacy state=online' in logs, 'legacy hub link did not become online' + assert b'event=hub_link gate=legacy state=offline' not in logs, 'legacy hub link became offline' + assert logs.count(b'event=hub_config state=legacy_hub') == 1, \ + f'legacy hub warning should appear once: {logs!r}' + + source.write_text('GP-000000000003\n') + port = free_port() + hub = start_hub(source, port) + try: + version = hashlib.sha256(source.read_bytes()).hexdigest().encode() + names = ['gate0', 'unknown'] + [f'gate{i}' for i in range(1, 63)] + assert len(names) == 64 and len(set(names)) == 64 + for name in names: + raw_gate(port, name, payload=b'list=' + version) + before = metrics() + assert value(before, 'gate0', 'current') == 1, 'first gate lost its current list state' + raw_gate(port, 'gate64', payload=b'list=' + b'b' * 64) + after = metrics() + assert value(after, 'gate0', 'current') == 1, 'overflow gate changed the first gate list state' + assert 'gatepost_gate_list_status{gate="gate64"' not in after, \ + 'overflow gate unexpectedly acquired a list status series' + finally: + hub.terminate() + hub.communicate(timeout=5) diff --git a/tests/test_gate_mac.py b/tests/test_gate_mac.py index 55de3cb..811fdc7 100644 --- a/tests/test_gate_mac.py +++ b/tests/test_gate_mac.py @@ -71,7 +71,12 @@ def serve(self): assert payload == GATE.encode() reply = b'OK' elif kind == 5: - assert payload == b'' + match = re.fullmatch( + rb'list=(none|[0-9a-f]{64}( confirmed_age=(0|[1-9][0-9]{0,7}))?)', + payload) + assert match is not None + if match.group(3) is not None: + assert int(match.group(3)) <= 31536000 reply = b'scans=0' elif kind == 3: self.scans.put(payload.decode('ascii')) diff --git a/tests/test_gated_tls.py b/tests/test_gated_tls.py index a817894..933b8c4 100644 --- a/tests/test_gated_tls.py +++ b/tests/test_gated_tls.py @@ -591,7 +591,12 @@ def receive(tls, size): if kind == 7: self.assertEqual(payload, b'gate1') elif kind == 5: - self.assertEqual(payload, b'') + match = re.fullmatch( + rb'list=(none|[0-9a-f]{64}( confirmed_age=(0|[1-9][0-9]{0,7}))?)', + payload) + self.assertIsNotNone(match) + if match.group(3) is not None: + self.assertLessEqual(int(match.group(3)), 31536000) reply = {7: b'OK', 3: b'ACCEPT', 5: b'scans=0'}[kind] tls.sendall(header.pack(b'GTP1', 2, kind + 1, 0, len(reply), request) + reply) diff --git a/tests/test_protocol_compat.py b/tests/test_protocol_compat.py index fa769e5..484539a 100644 --- a/tests/test_protocol_compat.py +++ b/tests/test_protocol_compat.py @@ -54,7 +54,7 @@ def rpc(peer, kind, number, payload=b''): kind, body = rpc(peer, 3, 41, b'GP-000000000003') assert kind == 127 and b'reused' in body kind, body = rpc(peer, 5, 43, b'x') - assert kind == 127 and b'empty' in body + assert kind == 6 and body.startswith(b'scans='), (kind, body) with socket.create_connection(('127.0.0.1', port), timeout=2) as peer: peer.sendall(b'SCAN GP-000000000002\n') assert peer.recv(32) == b'REJECT\n' From f529926fff40e03014b0359a370fdf8406c5c3d3 Mon Sep 17 00:00:00 2001 From: Wang Hao Date: Wed, 28 Oct 2026 15:00:00 +1100 Subject: [PATCH 6/9] feat(monitoring): provision Prometheus and Grafana for the venue lab On-call staff could only read raw /metrics. Provision a dashboard for the existing hub series: incomplete ticket replies, TLS handshake failures, and per-gate list status. Use a separate Compose file so the venue lab and its drills need no Grafana password. Pin both images by tag and digest. Keep the earlier sync-metrics regression test for the existing sync accounting fix, and check dashboard metrics against the hub. Co-authored-by: Yuki Tanaka --- CMakeLists.txt | 6 +- README.md | 2 +- README.zh-CN.md | 2 +- docs/operations/metrics.md | 2 + docs/operations/metrics.zh-CN.md | 2 + docs/operations/monitoring.md | 37 ++ docs/operations/monitoring.zh-CN.md | 37 ++ lab/README.md | 2 + lab/README.zh-CN.md | 2 + lab/monitoring-check.sh | 144 +++++ lab/monitoring.yaml | 32 ++ lab/monitoring/grafana/dashboards.yml | 10 + lab/monitoring/grafana/datasource.yml | 9 + lab/monitoring/grafana/venue-entrance.json | 597 +++++++++++++++++++++ lab/monitoring/prometheus.yml | 7 + tests/test_monitoring_config.py | 72 +++ tests/test_sync_metrics.py | 85 +++ 17 files changed, 1045 insertions(+), 3 deletions(-) create mode 100644 docs/operations/monitoring.md create mode 100644 docs/operations/monitoring.zh-CN.md create mode 100644 lab/monitoring-check.sh create mode 100644 lab/monitoring.yaml create mode 100644 lab/monitoring/grafana/dashboards.yml create mode 100644 lab/monitoring/grafana/datasource.yml create mode 100644 lab/monitoring/grafana/venue-entrance.json create mode 100644 lab/monitoring/prometheus.yml create mode 100644 tests/test_monitoring_config.py create mode 100644 tests/test_sync_metrics.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a090789..2f10cf9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -192,6 +192,10 @@ add_test(NAME hub_link_logs COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_hub_link_logs.py $) add_test(NAME metrics_failure COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_metrics_failure.py $) +add_test(NAME sync_metrics COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/tests/test_sync_metrics.py $) +add_test(NAME monitoring_config COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/tests/test_monitoring_config.py $) add_test(NAME hub_shutdown COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_hub_shutdown.py $) if(CMAKE_SYSTEM_NAME STREQUAL "Linux") @@ -247,5 +251,5 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") endif() add_test(NAME status_deadline COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_status_deadline.py $ $) -set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons ticket_fetch_progress http_distribution ticket_reply_count offline_reports protocol_compat gate_list_version status_deadline +set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons ticket_fetch_progress http_distribution ticket_reply_count offline_reports protocol_compat gate_list_version status_deadline sync_metrics monitoring_config PROPERTIES RESOURCE_LOCK status_ports) diff --git a/README.md b/README.md index 1ae138c..168e9bc 100644 --- a/README.md +++ b/README.md @@ -105,5 +105,5 @@ After a restart, a gate drops a saved ETag if it no longer matches the installed ## Documents -See [scanner supervision](docs/debugging/scanner-supervision.md), [lock order](docs/concurrency/lock-order.md), the [simulator protocol](docs/device/simulator-protocol.md), [Gate 3 crash investigation](docs/debugging/gate3-crash.md) and [team](docs/team.md). +See [venue monitoring](docs/operations/monitoring.md), [scanner supervision](docs/debugging/scanner-supervision.md), [lock order](docs/concurrency/lock-order.md), the [simulator protocol](docs/device/simulator-protocol.md), [Gate 3 crash investigation](docs/debugging/gate3-crash.md) and [team](docs/team.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 731f467..82a38a8 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -103,5 +103,5 @@ Hub 还在员工网络一侧的状态服务上提供 `/metrics`,与闸机 RPC ## 文档 -另见[扫描器进程监管](docs/debugging/scanner-supervision.zh-CN.md)、[锁的获取顺序](docs/concurrency/lock-order.zh-CN.md)、[模拟器协议](docs/device/simulator-protocol.zh-CN.md)、[三号闸机崩溃排查](docs/debugging/gate3-crash.zh-CN.md)和[团队成员](docs/team.zh-CN.md)。 +另见[场馆监控](docs/operations/monitoring.zh-CN.md)、[扫描器进程监管](docs/debugging/scanner-supervision.zh-CN.md)、[锁的获取顺序](docs/concurrency/lock-order.zh-CN.md)、[模拟器协议](docs/device/simulator-protocol.zh-CN.md)、[三号闸机崩溃排查](docs/debugging/gate3-crash.zh-CN.md)和[团队成员](docs/team.zh-CN.md)。 diff --git a/docs/operations/metrics.md b/docs/operations/metrics.md index 90142c4..aeeb29f 100644 --- a/docs/operations/metrics.md +++ b/docs/operations/metrics.md @@ -1,5 +1,7 @@ # Hub metrics +For the provisioned graphs and on-call interpretation, see [venue monitoring](monitoring.md). + The hub exposes Prometheus text format 0.0.4 at `GET /metrics` on its staff-side status listener, port 8081. When device TLS is configured, port 8444 serves the same routes on the same bind address to clients with venue CA-signed gate certificates. In the venue lab, `GATEPOST_STATUS_BIND=10.77.20.10` binds this listener to the staff network, while gate RPC uses port 7000. The metrics route accepts loopback and sources matching `GATEPOST_STAFF_PREFIX=10.77.20.`. Without device TLS, gates may fetch `/tickets` on port 8081. With device TLS, port 8081 answers `GET /tickets` with 404, and gates fetch the list on port 8444 using their certificates; their subnet cannot read `/metrics`. On a hub with device TLS, a rising `gatepost_http_requests_total{route="tickets",status="404"}` means some client still fetches the list from 8081, usually a gate without device TLS or one whose `GATEPOST_TICKETS_URL` is an `http://` address. Keep the status listener on a staff-only interface and set the prefix to that network in a deployment. The hub uses a bounded in-process C collector; it adds no dependency. At most 64 distinct gate labels are retained, and invalid label characters become `_`. A new gate beyond the limit has no list series: its list report is not recorded. Existing scan and connection metrics keep their overflow behavior. A gate reporting no version has `unknown` list status; this is not an error. | Name | Type | Labels | Meaning | diff --git a/docs/operations/metrics.zh-CN.md b/docs/operations/metrics.zh-CN.md index b5622ef..ce4fad4 100644 --- a/docs/operations/metrics.zh-CN.md +++ b/docs/operations/metrics.zh-CN.md @@ -1,5 +1,7 @@ # Hub 指标 +图表及值班解读见[场馆监控](monitoring.zh-CN.md)。 + Hub 在员工网络一侧的 8081 端口通过 `GET /metrics` 提供 Prometheus 0.0.4 文本格式。配置设备 TLS 后,同一绑定地址的 8444 端口向持有场馆 CA 签发的闸机证书的客户端提供相同接口。场馆实验中,`GATEPOST_STATUS_BIND=10.77.20.10` 将状态服务绑定在员工网络,闸机 RPC 使用 7000 端口。指标接口允许本机及符合 `GATEPOST_STAFF_PREFIX=10.77.20.` 的来源访问。未配置设备 TLS 时,闸机可通过 8081 获取 `/tickets`。配置设备 TLS 后,8081 对 `GET /tickets` 返回 404,闸机须持证书从 8444 获取票单;在这样的 hub 上,`gatepost_http_requests_total{route="tickets",status="404"}` 如果还在涨,说明仍有客户端从 8081 取票单,通常是没配设备 TLS 的闸机,或者 `GATEPOST_TICKETS_URL` 设成了 `http://` 地址的闸机;闸机网段不能读取 `/metrics`。实际部署时,应把状态服务绑定在仅供员工使用的接口,并把前缀设为该网络。Hub 使用容量有上限的 C 语言进程内采集器,不增加依赖。最多保留 64 个不同的闸机标签;标签中的非法字符会替换为 `_`。超过上限的新闸机不会留下票单状态记录,也没有该闸机的票单指标序列;原有扫描和连接指标仍按既有方式处理超额闸机。闸机未报告版本时显示 `unknown`,这不表示发生错误。 | 名称 | 类型 | 标签 | 含义 | diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md new file mode 100644 index 0000000..c11271d --- /dev/null +++ b/docs/operations/monitoring.md @@ -0,0 +1,37 @@ +English | [简体中文](monitoring.zh-CN.md) + +# Venue entrance monitoring + +Start the venue lab as described in [the lab guide](../../lab/README.md). Monitoring is optional. Set a Grafana administrator password, then start the two extra services from the repository root: + +```sh +export GATEPOST_GRAFANA_ADMIN_PASSWORD="$(openssl rand -hex 24)" +docker compose -f lab/compose.yaml -f lab/monitoring.yaml up -d --wait prometheus grafana +``` + +Open Grafana at `http://127.0.0.1:28080` and sign in as `admin` with that password. Prometheus is at `http://127.0.0.1:28090`. Both ports bind only to the local machine. To stop monitoring and remove its anonymous data volumes while keeping the venue running: + +```sh +docker compose -f lab/compose.yaml -f lab/monitoring.yaml rm -sfv prometheus grafana +``` + +The password is needed only for commands that include `lab/monitoring.yaml`. The default lab and its drills run without it. With the venue already running, `sh lab/monitoring-check.sh` starts the two services, checks every dashboard query and Grafana provisioning, then removes only those services and their anonymous volumes. If either monitoring service is already running, the check exits without removing anything; stop monitoring with the command above and run it again. The check generates a temporary random password if none was set. + +The **Venue entrance** dashboard reads the hub's staff-side `/metrics` route. Prometheus scrapes `10.77.20.10:8081` every five seconds. Every panel is limited to the `gate-hub` scrape job. + +| Row | Panel | On-call reading | +| --- | --- | --- | +| Traffic | Scans per second by gate and result | Compare accept, used-ticket rejection, unknown-ticket rejection and error rates by gate. | +| Errors | Ticket HTTP errors | `/tickets` replies other than 200, 206 or 304, grouped by status. `incomplete` means the hub could not hand the whole reply to the kernel; a reply the kernel accepted in full counts as 200 or 206 even if the gate never received it. A rising `404` means a gate is fetching from 8081 on a TLS hub. | +| Errors | TLS handshake failures | Check the listener and reason to distinguish gate RPC from the status listener. | +| Errors | Rejections by result | Compare `reject_used` and `reject_unknown` by gate. | +| Errors | Data-centre sync runs | Compare successful and failed synchronization runs in the last minute. | +| Latency | Decision latency p50, p95 and p99 | Compare the gate decision percentiles with the 300 ms scan deadline. | +| Gate lists | Gate list status | One row per gate: 2 means green `current`, 1 means red `stale`, and 0 means orange `unknown`. `stale` means the gate reports a different list from the one the hub serves; `unknown` means it reports no valid version and is not an error by itself. | +| Gate lists | Seconds since list confirmation | Read the gate's reported confirmation age together with seconds since its last heartbeat. A disconnected gate's last report may be old. | +| Saturation | Gates heard from in the last 30 s | Counts gates whose last STATS or CONFIG heartbeat was less than 30 seconds ago. `gatepost_connected_gates` counts connections open at that moment and is usually 0 because gates use short connections. | +| Saturation | Seconds since last heartbeat | Time since each gate's last STATS or CONFIG report. Rising age calls for a connection check. | +| Saturation | Worker queue depth | Gate connections waiting for a hub worker. | +| Saturation | Hub list version | The active hub ticket list's SHA-256 version. | + +CONFIG does not carry a MAC, so list status is the gate's reported state. Read it alongside connection and heartbeat age before acting on a stale value. diff --git a/docs/operations/monitoring.zh-CN.md b/docs/operations/monitoring.zh-CN.md new file mode 100644 index 0000000..f54bd7e --- /dev/null +++ b/docs/operations/monitoring.zh-CN.md @@ -0,0 +1,37 @@ +[English](monitoring.md) | 简体中文 + +# 场馆入口监控 + +先按[实验环境说明](../../lab/README.zh-CN.md)启动场馆。监控服务可单独启用。在仓库根目录设置 Grafana 管理员密码,再启动两个服务: + +```sh +export GATEPOST_GRAFANA_ADMIN_PASSWORD="$(openssl rand -hex 24)" +docker compose -f lab/compose.yaml -f lab/monitoring.yaml up -d --wait prometheus grafana +``` + +在 `http://127.0.0.1:28080` 打开 Grafana,用 `admin` 和刚设置的密码登录。Prometheus 位于 `http://127.0.0.1:28090`。两个端口都只绑定本机。停止监控并删除其匿名数据卷,同时保留正在运行的场馆服务: + +```sh +docker compose -f lab/compose.yaml -f lab/monitoring.yaml rm -sfv prometheus grafana +``` + +只有包含 `lab/monitoring.yaml` 的命令才需要这个密码;原有实验和演练无需设置。场馆运行期间可执行 `sh lab/monitoring-check.sh`:脚本启动监控服务,逐一检查看板查询和 Grafana 配置,最后只移除这两个服务及其匿名卷。如果任一监控服务已在运行,检查会直接退出,不移除任何服务;先用上面的命令停止监控,再重新运行检查。未设置密码时,脚本会临时生成一个随机密码。 + +**Venue entrance** 看板读取 hub 员工网络一侧的 `/metrics`。Prometheus 每五秒抓取 `10.77.20.10:8081`,所有面板都限定 `gate-hub` 抓取任务。 + +| 分组 | 面板 | 值班时怎么读 | +| --- | --- | --- | +| Traffic | Scans per second by gate and result | 按闸机比较放行、重复票拒绝、未知票拒绝和错误的每秒次数。 | +| Errors | Ticket HTTP errors | 按状态显示 `/tickets` 除 200、206、304 外的响应。`incomplete` 表示 hub 没能把响应全部交给内核;响应一旦全部交给内核,即使闸机最终没有收到,也计为 200 或 206。`404` 持续增长,说明有闸机向启用 TLS 的 hub 的 8081 端口取票。 | +| Errors | TLS handshake failures | 根据监听端口和原因,区分闸机 RPC 与状态服务的握手失败。 | +| Errors | Rejections by result | 按闸机比较 `reject_used` 和 `reject_unknown`。 | +| Errors | Data-centre sync runs | 比较最近一分钟成功和失败的数据中心同步次数。 | +| Latency | Decision latency p50、p95、p99 | 对照 300 毫秒扫码期限观察决策延迟。 | +| Gate lists | Gate list status | 每台闸机一行:2 为绿色 `current`,1 为红色 `stale`,0 为橙色 `unknown`。`stale` 表示闸机报告的票单与 hub 当前提供的不一致;`unknown` 表示没有报告有效版本,本身不算故障。 | +| Gate lists | Seconds since list confirmation | 结合距上次心跳的秒数判断确认时间。闸机断线后,最后一次报告可能已经过时。 | +| Saturation | Gates heard from in the last 30 s | 统计上次 STATS 或 CONFIG 心跳距今不到 30 秒的闸机数。`gatepost_connected_gates` 统计该时刻仍保持连接的数量;闸机使用短连接,所以这个值通常为 0。 | +| Saturation | Seconds since last heartbeat | 距每台闸机上次 STATS 或 CONFIG 报告的时间;持续增长时检查连接。 | +| Saturation | Worker queue depth | 等待 hub 工作线程处理的闸机连接数。 | +| Saturation | Hub list version | Hub 当前票单的 SHA-256 版本。 | + +CONFIG 不携带 MAC,因此票单状态以闸机上报为准。处理 `stale` 时,应同时查看连接状态和心跳间隔。 diff --git a/lab/README.md b/lab/README.md index 25e0202..b28c2c9 100644 --- a/lab/README.md +++ b/lab/README.md @@ -2,6 +2,8 @@ English | [简体中文](README.zh-CN.md) # Venue lab +For optional Prometheus and Grafana services, see [venue monitoring](../docs/operations/monitoring.md). With the venue already running, `sh lab/monitoring-check.sh` verifies the provisioned dashboard and removes only the monitoring services afterward. + The lab runs four gates, including north1 and north2 at the north entrance. From the repository root, build the image with `./scripts/dev.sh build-image`, then run `sh lab/keys.sh` before starting the lab. It builds and runs `ticket_sign` inside `gatepost-build:current`, creating a test key pair, the `season1` public keyring and 100 signed tickets for `event7` in `lab/keys/generated/`, with file permissions `0600`. Re-running keeps the key pair; use `sh lab/keys.sh --rotate` to replace it. Stop the lab before regenerating files, then recreate its containers. Git and image builds exclude this directory. Real tickets are signed by the data centre; these keys are only for the lab. For ticket signatures, gates mount the public keyring and signed list, and the hub mounts the list. `keys.sh` also creates a separate 32-byte MAC key for each gate in `hub/.hex` and `gate/.hex` under the generated directory (0600, preserved unless `--rotate` is used); the hub mounts all gate keys read-only, while each gate mounts only its own. diff --git a/lab/README.zh-CN.md b/lab/README.zh-CN.md index ac4916f..57b35a3 100644 --- a/lab/README.zh-CN.md +++ b/lab/README.zh-CN.md @@ -2,6 +2,8 @@ # 场馆实验环境 +需要启用 Prometheus 和 Grafana 时,参见[场馆监控说明](../docs/operations/monitoring.zh-CN.md)。场馆运行期间执行 `sh lab/monitoring-check.sh`,可检查预置看板;脚本结束后只移除监控服务。 + 实验环境运行四台闸机,其中 north1 和 north2 位于北入口。 在仓库根目录运行 `./scripts/dev.sh build-image`,启动实验前必须先运行 `sh lab/keys.sh`。它在 `gatepost-build:current` 镜像中构建并运行 `ticket_sign`,将测试密钥对、`season1` 公钥文件和 `event7` 的 100 张签名票组成的票单写入 `lab/keys/generated/`,文件权限均为 `0600`。重复运行保留原密钥对;需要轮换时运行 `sh lab/keys.sh --rotate`。重新生成前先停止实验,完成后重新创建容器。Git 和镜像构建均排除该目录。真实条码由数据中心签发,这些密钥仅用于实验。签名所需的文件中,闸机挂载公钥文件和签名票单,hub 挂载票单。`keys.sh` 还为每台闸机生成独立的 32 字节 MAC 密钥,在生成目录的 `hub/.hex` 和 `gate/.hex` 各存一份(权限 0600,除非指定 `--rotate`,否则保留已有密钥);hub 以只读方式挂载全部闸机密钥,每台闸机只挂载自己的密钥。 diff --git a/lab/monitoring-check.sh b/lab/monitoring-check.sh new file mode 100644 index 0000000..73e85f2 --- /dev/null +++ b/lab/monitoring-check.sh @@ -0,0 +1,144 @@ +#!/bin/sh +# Check a running venue lab without stopping its existing services. +set -u +cd "$(dirname "$0")/.." || exit 2 + +monitor_started=0 +result='environment mismatch' +code=2 +compose_monitor() { + docker compose -f lab/compose.yaml -f lab/monitoring.yaml "$@" +} +finish() { + if [ "$monitor_started" -eq 1 ]; then + compose_monitor rm -sfv prometheus grafana >/dev/null 2>&1 || { + result='failed (monitoring cleanup)' + code=1 + } + fi + printf 'result: %s\n' "$result" + exit "$code" +} +trap finish 0 +trap 'result=failed; code=1; exit 1' 1 2 3 15 +fail() { + result='failed' + code=1 + printf '%s\n' "$1" >&2 + exit 1 +} +mismatch() { + printf '%s\n' "$1" >&2 + exit 2 +} + +for tool in docker python3 openssl; do + command -v "$tool" >/dev/null 2>&1 || mismatch "missing $tool" +done +monitor_running=$(GATEPOST_GRAFANA_ADMIN_PASSWORD="${GATEPOST_GRAFANA_ADMIN_PASSWORD:-unused-for-ps}" \ + compose_monitor ps --status running --services 2>/dev/null) || + mismatch 'monitoring status is unavailable' +if printf '%s\n' "$monitor_running" | grep -Eq '^(prometheus|grafana)$'; then + mismatch 'monitoring is already running; stop it with docker compose -f lab/compose.yaml -f lab/monitoring.yaml rm -sfv prometheus grafana, then run the check again' +fi +running=$(docker compose -f lab/compose.yaml ps --status running --services 2>/dev/null) || + mismatch 'venue lab is unavailable' +for service in hub gate1 gate2; do + printf '%s\n' "$running" | grep -qx "$service" || mismatch "venue $service is not running" +done +if [ -z "${GATEPOST_GRAFANA_ADMIN_PASSWORD:-}" ]; then + GATEPOST_GRAFANA_ADMIN_PASSWORD=$(openssl rand -hex 24) || mismatch 'cannot generate password' + printf '%s\n' 'Generated a temporary Grafana administrator password for this check.' +fi +export GATEPOST_GRAFANA_ADMIN_PASSWORD +monitor_started=1 +compose_monitor up -d --wait prometheus grafana >/dev/null || fail 'monitoring services did not start' + +python3 - <<'PY' || fail 'Prometheus did not report gate-hub up' +import json +import time +import urllib.request + +url = 'http://127.0.0.1:28090/api/v1/targets' +deadline = time.monotonic() + 90 +while time.monotonic() < deadline: + try: + with urllib.request.urlopen(url, timeout=3) as response: + targets = json.load(response)['data']['activeTargets'] + if any(t['labels'].get('job') == 'gate-hub' and t['health'] == 'up' + for t in targets): + break + except (OSError, KeyError, ValueError): + pass + time.sleep(2) +else: + raise SystemExit(1) +PY + +# Spread distinct scans over several five-second scrapes for rate panels. +for line in 11 12 13 14; do + compose_monitor exec -T gate1 sh -c 'sed -n "${1}p" /tickets/tickets.txt > /proc/1/fd/0' sh "$line" >/dev/null || + fail 'could not send gate1 scan' + compose_monitor exec -T gate2 sh -c 'sed -n "${1}p" /tickets/tickets.txt > /proc/1/fd/0' sh "$line" >/dev/null || + fail 'could not send gate2 scan' + sleep 6 +done + +python3 - <<'PY' || fail 'dashboard queries or Grafana provisioning failed' +import json +import os +from pathlib import Path +import time +import urllib.parse +import urllib.request + +dashboard = json.loads(Path('lab/monitoring/grafana/venue-entrance.json').read_text()) +queries = [(p['title'], t['expr']) for p in dashboard['panels'] + for t in p.get('targets', [])] +assert queries +assert all('job="gate-hub"' in query for _, query in queries) +base = 'http://127.0.0.1:28090/api/v1/query?' +deadline = time.monotonic() + 75 +pending = [] +while time.monotonic() < deadline: + pending = [] + for title, query in queries: + try: + url = base + urllib.parse.urlencode({'query': query}) + with urllib.request.urlopen(url, timeout=5) as response: + answer = json.load(response) + series = answer['data']['result'] + if answer['status'] != 'success' or not series: + pending.append(title) + except (OSError, KeyError, ValueError): + pending.append(title) + try: + scan_url = base + urllib.parse.urlencode( + {'query': 'gatepost_scans_total{job="gate-hub"}'}) + with urllib.request.urlopen(scan_url, timeout=5) as response: + scans = json.load(response)['data']['result'] + if not any(float(item['value'][1]) > 0 for item in scans): + pending.append('scan counters') + except (OSError, KeyError, ValueError): + pending.append('scan counters') + if not pending: + break + time.sleep(2) +else: + raise SystemExit('queries with no series: ' + ', '.join(pending)) + +credentials = ('admin:' + os.environ['GATEPOST_GRAFANA_ADMIN_PASSWORD']).encode() +import base64 +headers = {'Authorization': 'Basic ' + base64.b64encode(credentials).decode()} +for path, check in ( + ('/api/datasources/uid/venue-prometheus', + lambda data: data['uid'] == 'venue-prometheus' and + data['url'] == 'http://10.77.20.50:9090'), + ('/api/dashboards/uid/venue-entrance', + lambda data: data['dashboard']['title'] == 'Venue entrance')): + request = urllib.request.Request('http://127.0.0.1:28080' + path, headers=headers) + with urllib.request.urlopen(request, timeout=8) as response: + assert check(json.load(response)), path +PY +result='ok' +code=0 diff --git a/lab/monitoring.yaml b/lab/monitoring.yaml new file mode 100644 index 0000000..4f419ea --- /dev/null +++ b/lab/monitoring.yaml @@ -0,0 +1,32 @@ +services: + prometheus: + image: prom/prometheus:v3.13.5@sha256:aafa9d694e6a883c02db516d9f6e5b84e14195f49a2a6456a4cca815edda72b9 + volumes: + - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - /prometheus + ports: ["127.0.0.1:28090:9090"] + healthcheck: + test: ["CMD", "wget", "-qO-", "http://localhost:9090/-/ready"] + interval: 5s + timeout: 3s + retries: 12 + networks: + venue: {ipv4_address: 10.77.20.50} + grafana: + image: grafana/grafana:13.2.4@sha256:dbbc38ea21103cefb50396340cd88afec779c7e070b0a7bf5a75b4ce46651d3f + depends_on: + prometheus: {condition: service_healthy} + environment: + GF_SECURITY_ADMIN_PASSWORD: ${GATEPOST_GRAFANA_ADMIN_PASSWORD:?set GATEPOST_GRAFANA_ADMIN_PASSWORD} + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_ANALYTICS_REPORTING_ENABLED: "false" + GF_ANALYTICS_CHECK_FOR_UPDATES: "false" + GF_PLUGINS_CHECK_FOR_UPDATES: "false" + volumes: + - ./monitoring/grafana/datasource.yml:/etc/grafana/provisioning/datasources/venue.yml:ro + - ./monitoring/grafana/dashboards.yml:/etc/grafana/provisioning/dashboards/venue.yml:ro + - ./monitoring/grafana/venue-entrance.json:/etc/grafana/dashboards/venue-entrance.json:ro + - /var/lib/grafana + ports: ["127.0.0.1:28080:3000"] + networks: + venue: {ipv4_address: 10.77.20.51} diff --git a/lab/monitoring/grafana/dashboards.yml b/lab/monitoring/grafana/dashboards.yml new file mode 100644 index 0000000..f58e8fe --- /dev/null +++ b/lab/monitoring/grafana/dashboards.yml @@ -0,0 +1,10 @@ +apiVersion: 1 +providers: + - name: Venue + orgId: 1 + folder: Venue + type: file + disableDeletion: true + editable: false + options: + path: /etc/grafana/dashboards diff --git a/lab/monitoring/grafana/datasource.yml b/lab/monitoring/grafana/datasource.yml new file mode 100644 index 0000000..63276a5 --- /dev/null +++ b/lab/monitoring/grafana/datasource.yml @@ -0,0 +1,9 @@ +apiVersion: 1 +datasources: + - name: Venue Prometheus + uid: venue-prometheus + type: prometheus + access: proxy + url: http://10.77.20.50:9090 + isDefault: true + editable: false diff --git a/lab/monitoring/grafana/venue-entrance.json b/lab/monitoring/grafana/venue-entrance.json new file mode 100644 index 0000000..652a925 --- /dev/null +++ b/lab/monitoring/grafana/venue-entrance.json @@ -0,0 +1,597 @@ +{ + "id": null, + "uid": "venue-entrance", + "title": "Venue entrance", + "tags": [ + "gatepost", + "venue" + ], + "schemaVersion": 41, + "version": 1, + "refresh": "5s", + "timezone": "browser", + "time": { + "from": "now-5m", + "to": "now" + }, + "panels": [ + { + "id": 1, + "type": "row", + "title": "Traffic", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + } + }, + { + "id": 2, + "type": "timeseries", + "title": "Scans per second by gate and result", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 1 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (gate, result) (rate(gatepost_scans_total{job=\"gate-hub\"}[20s]))", + "legendFormat": "{{gate}} {{result}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 3, + "type": "row", + "title": "Errors", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 9 + } + }, + { + "id": 4, + "type": "timeseries", + "title": "Ticket HTTP errors", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 10 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (status) (rate(gatepost_http_requests_total{job=\"gate-hub\",route=\"tickets\",status!=\"incomplete\",status!~\"200|206|304\"}[20s]))", + "legendFormat": "{{status}}" + }, + { + "refId": "B", + "expr": "sum by (status) (rate(gatepost_http_requests_total{job=\"gate-hub\",route=\"tickets\",status=\"incomplete\"}[20s]))", + "legendFormat": "{{status}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 5, + "type": "timeseries", + "title": "TLS handshake failures", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 10 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (listener, reason) (rate(gatepost_tls_handshake_failures_total{job=\"gate-hub\"}[20s]))", + "legendFormat": "{{listener}} {{reason}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 6, + "type": "timeseries", + "title": "Rejections by result", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 18 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (gate, result) (rate(gatepost_scans_total{job=\"gate-hub\",result=~\"reject_.*\"}[20s]))", + "legendFormat": "{{gate}} {{result}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 7, + "type": "timeseries", + "title": "Data-centre sync runs", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 18 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (outcome) (increase(gatepost_dc_sync_attempts_total{job=\"gate-hub\"}[1m]))", + "legendFormat": "{{outcome}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 8, + "type": "row", + "title": "Latency", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 26 + } + }, + { + "id": 9, + "type": "timeseries", + "title": "Decision latency p50", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 27 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.50, sum by (gate, le) (rate(gatepost_decision_seconds_bucket{job=\"gate-hub\"}[20s])))", + "legendFormat": "{{gate}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 10, + "type": "timeseries", + "title": "Decision latency p95", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 27 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.95, sum by (gate, le) (rate(gatepost_decision_seconds_bucket{job=\"gate-hub\"}[20s])))", + "legendFormat": "{{gate}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 11, + "type": "timeseries", + "title": "Decision latency p99", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 35 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.99, sum by (gate, le) (rate(gatepost_decision_seconds_bucket{job=\"gate-hub\"}[20s])))", + "legendFormat": "{{gate}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 12, + "type": "row", + "title": "Gate lists", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 43 + } + }, + { + "id": 13, + "type": "state-timeline", + "title": "Gate list status", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 44 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "2 * sum by (gate) (gatepost_gate_list_status{job=\"gate-hub\",status=\"current\"}) + sum by (gate) (gatepost_gate_list_status{job=\"gate-hub\",status=\"stale\"})", + "legendFormat": "{{gate}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "mappings": [ + { + "type": "value", + "options": { + "2": { + "text": "current", + "color": "green" + }, + "1": { + "text": "stale", + "color": "red" + }, + "0": { + "text": "unknown", + "color": "orange" + } + } + } + ] + }, + "overrides": [] + }, + "options": { + "mergeValues": true, + "showValue": "always", + "rowHeight": 0.9, + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 14, + "type": "timeseries", + "title": "Seconds since list confirmation", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 44 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "gatepost_gate_list_confirmed_age_seconds{job=\"gate-hub\"}", + "legendFormat": "{{gate}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 15, + "type": "row", + "title": "Saturation", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 52 + } + }, + { + "id": 16, + "type": "timeseries", + "title": "Gates heard from in the last 30 s", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 53 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "count(gatepost_last_stats_age_seconds{job=\"gate-hub\"} < 30)", + "legendFormat": "gates" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "min": 0, + "decimals": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 17, + "type": "timeseries", + "title": "Seconds since last heartbeat", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 53 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "gatepost_last_stats_age_seconds{job=\"gate-hub\"}", + "legendFormat": "{{gate}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 18, + "type": "timeseries", + "title": "Worker queue depth", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 61 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "gatepost_worker_queue_depth{job=\"gate-hub\"}", + "legendFormat": "queued" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 19, + "type": "table", + "title": "Hub list version", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 61 + }, + "datasource": { + "type": "prometheus", + "uid": "venue-prometheus" + }, + "targets": [ + { + "refId": "A", + "expr": "gatepost_ticket_list_info{job=\"gate-hub\"}", + "format": "table", + "instant": true, + "range": false + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "Value": true, + "job": true, + "instance": true, + "__name__": true + } + } + } + ], + "options": { + "showHeader": true + } + } + ] +} diff --git a/lab/monitoring/prometheus.yml b/lab/monitoring/prometheus.yml new file mode 100644 index 0000000..47f8247 --- /dev/null +++ b/lab/monitoring/prometheus.yml @@ -0,0 +1,7 @@ +global: + scrape_interval: 5s +scrape_configs: + - job_name: gate-hub + metrics_path: /metrics + static_configs: + - targets: ["10.77.20.10:8081"] diff --git a/tests/test_monitoring_config.py b/tests/test_monitoring_config.py new file mode 100644 index 0000000..bbcf807 --- /dev/null +++ b/tests/test_monitoring_config.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Monitoring configuration must match the hub's live metric families.""" +import json +import os +from pathlib import Path +import re +import socket +import subprocess +import sys +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +compose = (ROOT / 'lab/compose.yaml').read_text() +assert not re.search(r'GRAFANA|prometheus|grafana', compose, re.IGNORECASE) + +monitor = (ROOT / 'lab/monitoring.yaml').read_text() +blocks = dict(re.findall(r'^ (prometheus|grafana):\n((?:^(?: |\n).*(?:\n|$))*)', + monitor, re.MULTILINE)) +assert set(blocks) == {'prometheus', 'grafana'}, blocks.keys() +for service, block in blocks.items(): + images = re.findall(r'^ image: (\S+)$', block, re.MULTILINE) + assert len(images) == 1 and re.fullmatch( + r'[a-z0-9/-]+:[A-Za-z0-9_.-]+@sha256:[0-9a-f]{64}', images[0]), (service, images) + ports = re.findall(r'^ ports: \["([^"]+)"\]$', block, re.MULTILINE) + assert len(ports) == 1 and re.fullmatch(r'127\.0\.0\.1:\d+:\d+', ports[0]), (service, ports) + +dashboard = json.loads((ROOT / 'lab/monitoring/grafana/venue-entrance.json').read_text()) +expressions = [target['expr'] for panel in dashboard['panels'] + for target in panel.get('targets', [])] +assert expressions and all('job="gate-hub"' in expr for expr in expressions) +all_expr = '\n'.join(expressions) +for required in ('status="incomplete"', 'status!~"200|206|304"', + 'gatepost_tls_handshake_failures_total', + 'gatepost_gate_list_status', 'gatepost_gate_list_confirmed_age_seconds'): + assert required in all_expr, required +assert not re.search(r'gatepost_\w*(?:list_age|fetch_failures)\w*', all_expr) +names = set(re.findall(r'gatepost_[a-z0-9_]+', all_expr)) +families = {re.sub(r'_(?:bucket|sum|count)$', '', name) for name in names} + +with tempfile.TemporaryDirectory() as directory: + tickets = Path(directory) / 'tickets.txt' + tickets.write_text('GP-000000000000\n') + with socket.socket() as reserved: + reserved.bind(('127.0.0.1', 0)) + port = reserved.getsockname()[1] + env = dict(os.environ, GATEPOST_STATUS='1') + hub = subprocess.Popen([sys.argv[1], str(tickets), str(port), 'pool'], env=env, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + try: + assert hub.stdout.readline().startswith(b'listening=') + deadline = time.monotonic() + 5 + while True: + try: + with socket.create_connection(('127.0.0.1', 8081), timeout=1) as peer: + peer.settimeout(2) + peer.sendall(b'GET /metrics HTTP/1.1\r\nHost: hub.venue.lan\r\n\r\n') + data = bytearray() + while block := peer.recv(65536): + data.extend(block) + break + except OSError: + if time.monotonic() >= deadline: + raise + time.sleep(.1) + header, body = bytes(data).split(b'\r\n\r\n', 1) + assert header.startswith(b'HTTP/1.1 200'), header + rendered = set(re.findall(rb'^# TYPE (gatepost_[a-z0-9_]+) ', body, re.MULTILINE)) + assert families <= {name.decode() for name in rendered}, families + finally: + hub.terminate() + hub.wait(timeout=5) diff --git a/tests/test_sync_metrics.py b/tests/test_sync_metrics.py new file mode 100644 index 0000000..dee6659 --- /dev/null +++ b/tests/test_sync_metrics.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""A completed data-centre synchronization is visible on the status listener.""" +from hashlib import sha256 +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import os +from pathlib import Path +import re +import socket +import subprocess +import sys +import tempfile +import threading +import time + +BODY = b'synthetic data-centre list\n' +ETAG = '"' + sha256(BODY).hexdigest() + '"' + + +class DataCentre(BaseHTTPRequestHandler): + protocol_version = 'HTTP/1.1' + + def log_message(self, *_): + pass + + def do_GET(self): + if self.headers.get('If-None-Match') == ETAG: + self.send_response(304) + self.send_header('ETag', ETAG) + self.send_header('Content-Length', '0') + self.end_headers() + return + self.send_response(200) + self.send_header('ETag', ETAG) + self.send_header('Content-Length', str(len(BODY))) + self.end_headers() + self.wfile.write(BODY) + + +def free_port(): + with socket.socket() as peer: + peer.bind(('127.0.0.1', 0)) + return peer.getsockname()[1] + + +def sync_runs(): + with socket.create_connection(('127.0.0.1', 8081), timeout=2) as peer: + peer.settimeout(2) + peer.sendall(b'GET /metrics HTTP/1.1\r\nHost: hub.venue.lan\r\n\r\n') + data = bytearray() + while block := peer.recv(65536): + data.extend(block) + return {outcome.decode(): int(count) for outcome, count in re.findall( + rb'gatepost_dc_sync_attempts_total\{outcome="(\w+)"\} (\d+)', data)} + + +with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + tickets = root / 'tickets.txt' + tickets.write_text('GP-000000000000\n') + server = ThreadingHTTPServer(('127.0.0.1', 8080), DataCentre) + threading.Thread(target=server.serve_forever, daemon=True).start() + env = dict(os.environ, GATEPOST_SYNC='1', GATEPOST_STATUS='1', + GATEPOST_DC_HOST='127.0.0.1', GATEPOST_REPORT_FILE=str(root / 'reports.txt')) + hub = subprocess.Popen([sys.argv[1], str(tickets), str(free_port()), 'pool'], env=env, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + try: + assert hub.stdout.readline().startswith(b'listening=') + deadline = time.monotonic() + 12 + runs = {} + while time.monotonic() < deadline: + try: + runs = sync_runs() + except OSError: + runs = {} + if runs.get('success', 0) >= 1: + break + time.sleep(.1) + assert runs.get('success', 0) >= 1 and runs.get('error') == 0, runs + finally: + hub.terminate() + hub.wait(timeout=5) + server.shutdown() + server.server_close() + for suffix in ('', '.etag', '.part'): + Path('/tmp/gatepost-tickets.gpb' + suffix).unlink(missing_ok=True) From 34d11c5e746a7e8fb9532b63fba0402cc4b96a17 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Wed, 28 Oct 2026 16:30:00 +1100 Subject: [PATCH 7/9] fix(gate-hub): leave unidentified connections out of gate list status The hub recorded connections that had not identified themselves under the name "unknown". Writing list status for every record made that pseudo-gate look like a gate reporting no version. Write list status only for gates that identified themselves and sent a heartbeat. A CONFIG from an unidentified connection records nothing. --- docs/operations/metrics.md | 4 ++-- docs/operations/metrics.zh-CN.md | 4 ++-- docs/operations/monitoring.md | 2 +- docs/operations/monitoring.zh-CN.md | 2 +- gate-hub/main.c | 6 ++++-- gate-hub/prometheus.c | 6 +++++- tests/test_gate_list_version.py | 25 +++++++++++++++++++++++++ 7 files changed, 40 insertions(+), 9 deletions(-) diff --git a/docs/operations/metrics.md b/docs/operations/metrics.md index aeeb29f..8e7d873 100644 --- a/docs/operations/metrics.md +++ b/docs/operations/metrics.md @@ -11,8 +11,8 @@ The hub exposes Prometheus text format 0.0.4 at `GET /metrics` on its staff-side | `gatepost_connected_gates` | Gauge | `gate` | 1 while that gate has an identified open RPC connection, otherwise 0. Connections not yet identified appear as `unknown`. | | `gatepost_connected_gates_count` | Gauge | None | Number of gates with an open identified RPC connection. | | `gatepost_last_stats_age_seconds` | Gauge | `gate` | Seconds since the last text `STATS` or framed CONFIG from that gate; absent until first report. | -| `gatepost_gate_list_status` | Gauge | `gate`, `status` (`current`, `stale`, `unknown`) | Three series per retained gate, exactly one equal to 1. `current` means the last reported SHA-256 matches the list the hub serves now; `stale` means another list or `list=none`; `unknown` means no valid version report, including empty or invalid CONFIG and text-line gates. | -| `gatepost_gate_list_confirmed_age_seconds` | Gauge | `gate` | The gate's reported confirmation age plus whole seconds since the report; absent if no age was reported or the list state is unknown. | +| `gatepost_gate_list_status` | Gauge | `gate`, `status` (`current`, `stale`, `unknown`) | Three series for each retained gate that has identified itself and sent a CONFIG or text-line STATS heartbeat, exactly one equal to 1. Unidentified connections have no list series. `current` means the last reported SHA-256 matches the list the hub serves now; `stale` means another list or `list=none`; `unknown` means no valid version report, including empty or invalid CONFIG and text-line gates. | +| `gatepost_gate_list_confirmed_age_seconds` | Gauge | `gate` | The identified gate's reported confirmation age plus whole seconds since the report; absent if no age was reported or the list state is unknown. Unidentified connections have no list series. | | `gatepost_ticket_list_info` | Gauge | `version` | Always 1 for the active hub list. Version is its SHA-256 in hex. | | `gatepost_ticket_list_age_seconds` | Gauge | None | Seconds since the active list file's modification time. | | `gatepost_dc_sync_attempts_total` | Counter | `outcome` (`success`, `error`) | Completed background data-centre synchronization runs. | diff --git a/docs/operations/metrics.zh-CN.md b/docs/operations/metrics.zh-CN.md index ce4fad4..2c46d1b 100644 --- a/docs/operations/metrics.zh-CN.md +++ b/docs/operations/metrics.zh-CN.md @@ -11,8 +11,8 @@ Hub 在员工网络一侧的 8081 端口通过 `GET /metrics` 提供 Prometheus | `gatepost_connected_gates` | Gauge | `gate` | 已确认身份的闸机 RPC 连接打开时为 1,否则为 0。尚未确认身份的连接记作 `unknown`。 | | `gatepost_connected_gates_count` | Gauge | 无 | 当前已确认身份且保持 RPC 连接的闸机数。 | | `gatepost_last_stats_age_seconds` | Gauge | `gate` | 距该闸机最近一次文本 `STATS` 或帧格式 CONFIG 的秒数;首次收到之前不显示。 | -| `gatepost_gate_list_status` | Gauge | `gate`、`status`(`current`、`stale`、`unknown`) | 每个保留的闸机固定输出三条序列,恰有一条为 1。最近报告的 SHA-256 与 hub 当前提供的票单一致时为 `current`;报告其他版本或 `list=none` 时为 `stale`;没有有效版本报告(包括空 CONFIG、无效 CONFIG 和文本行闸机)时为 `unknown`。 | -| `gatepost_gate_list_confirmed_age_seconds` | Gauge | `gate` | 闸机报告的确认时间加上报告后经过的整秒数;未报告确认时间或票单状态未知时不显示。 | +| `gatepost_gate_list_status` | Gauge | `gate`、`status`(`current`、`stale`、`unknown`) | 每个已确认身份并发送 CONFIG 或文本行 STATS 心跳的保留闸机输出三条序列,恰有一条为 1。未确认身份的连接没有票单序列。最近报告的 SHA-256 与 hub 当前提供的票单一致时为 `current`;报告其他版本或 `list=none` 时为 `stale`;没有有效版本报告(包括空 CONFIG、无效 CONFIG 和文本行闸机)时为 `unknown`。 | +| `gatepost_gate_list_confirmed_age_seconds` | Gauge | `gate` | 已确认身份的闸机报告的确认时间加上报告后经过的整秒数;未报告确认时间或票单状态未知时不显示。未确认身份的连接没有票单序列。 | | `gatepost_ticket_list_info` | Gauge | `version` | 当前 Hub 票单的值恒为 1;版本号是十六进制 SHA-256。 | | `gatepost_ticket_list_age_seconds` | Gauge | 无 | 当前票单文件自修改以来的秒数。 | | `gatepost_dc_sync_attempts_total` | Counter | `outcome`(`success`、`error`) | 后台数据中心同步完成的次数及结果。 | diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index c11271d..e76af5c 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -27,7 +27,7 @@ The **Venue entrance** dashboard reads the hub's staff-side `/metrics` route. Pr | Errors | Rejections by result | Compare `reject_used` and `reject_unknown` by gate. | | Errors | Data-centre sync runs | Compare successful and failed synchronization runs in the last minute. | | Latency | Decision latency p50, p95 and p99 | Compare the gate decision percentiles with the 300 ms scan deadline. | -| Gate lists | Gate list status | One row per gate: 2 means green `current`, 1 means red `stale`, and 0 means orange `unknown`. `stale` means the gate reports a different list from the one the hub serves; `unknown` means it reports no valid version and is not an error by itself. | +| Gate lists | Gate list status | One row per gate that has identified itself and sent a heartbeat: 2 means green `current`, 1 means red `stale`, and 0 means orange `unknown`. `stale` means the gate reports a different list from the one the hub serves; `unknown` means it reports no valid version and is not an error by itself. | | Gate lists | Seconds since list confirmation | Read the gate's reported confirmation age together with seconds since its last heartbeat. A disconnected gate's last report may be old. | | Saturation | Gates heard from in the last 30 s | Counts gates whose last STATS or CONFIG heartbeat was less than 30 seconds ago. `gatepost_connected_gates` counts connections open at that moment and is usually 0 because gates use short connections. | | Saturation | Seconds since last heartbeat | Time since each gate's last STATS or CONFIG report. Rising age calls for a connection check. | diff --git a/docs/operations/monitoring.zh-CN.md b/docs/operations/monitoring.zh-CN.md index f54bd7e..7948893 100644 --- a/docs/operations/monitoring.zh-CN.md +++ b/docs/operations/monitoring.zh-CN.md @@ -27,7 +27,7 @@ docker compose -f lab/compose.yaml -f lab/monitoring.yaml rm -sfv prometheus gra | Errors | Rejections by result | 按闸机比较 `reject_used` 和 `reject_unknown`。 | | Errors | Data-centre sync runs | 比较最近一分钟成功和失败的数据中心同步次数。 | | Latency | Decision latency p50、p95、p99 | 对照 300 毫秒扫码期限观察决策延迟。 | -| Gate lists | Gate list status | 每台闸机一行:2 为绿色 `current`,1 为红色 `stale`,0 为橙色 `unknown`。`stale` 表示闸机报告的票单与 hub 当前提供的不一致;`unknown` 表示没有报告有效版本,本身不算故障。 | +| Gate lists | Gate list status | 每台已确认身份并发送心跳的闸机一行:2 为绿色 `current`,1 为红色 `stale`,0 为橙色 `unknown`。`stale` 表示闸机报告的票单与 hub 当前提供的不一致;`unknown` 表示没有报告有效版本,本身不算故障。 | | Gate lists | Seconds since list confirmation | 结合距上次心跳的秒数判断确认时间。闸机断线后,最后一次报告可能已经过时。 | | Saturation | Gates heard from in the last 30 s | 统计上次 STATS 或 CONFIG 心跳距今不到 30 秒的闸机数。`gatepost_connected_gates` 统计该时刻仍保持连接的数量;闸机使用短连接,所以这个值通常为 0。 | | Saturation | Seconds since last heartbeat | 距每台闸机上次 STATS 或 CONFIG 报告的时间;持续增长时检查连接。 | diff --git a/gate-hub/main.c b/gate-hub/main.c index a9ffa69..dcd2659 100644 --- a/gate-hub/main.c +++ b/gate-hub/main.c @@ -536,6 +536,7 @@ static void serve_binary(hub *owner, int fd, SSL *tls, const char *peer_gate, size_t next_cache = 0; gate_message request, reply; char gate[64] = "unknown"; + bool gate_identified = false; char peer[INET_ADDRSTRLEN + 8]; peer_name(address, peer, sizeof peer); log_connection("connection_open", gate, peer); @@ -637,8 +638,8 @@ static void serve_binary(hub *owner, int fd, SSL *tls, const char *peer_gate, int has_age = 0; unsigned age = 0; int valid = !request.length || parse_gate_list(&request, hex, &has_age, &age); - if (prometheus_gate_list(gate, valid && request.length ? hex : NULL, has_age, age, - valid)) + if (gate_identified && prometheus_gate_list(gate, valid && request.length ? hex : NULL, + has_age, age, valid)) gate_log("WARN", "gate_list", "state=invalid gate=%s", gate); unsigned scans, tickets; char status[64]; @@ -683,6 +684,7 @@ static void serve_binary(hub *owner, int fd, SSL *tls, const char *peer_gate, prometheus_connection(gate, -1); memcpy(gate, request.payload, request.length); gate[request.length] = 0; + gate_identified = true; prometheus_connection(gate, 1); if (getenv("GATEPOST_ALERTS") && gate_watch_seen(&owner->watch, gate) != 0) break; diff --git a/gate-hub/prometheus.c b/gate-hub/prometheus.c index 6567ab3..93b50ab 100644 --- a/gate-hub/prometheus.c +++ b/gate-hub/prometheus.c @@ -31,6 +31,7 @@ typedef struct { unsigned confirmed_age; time_t list_reported_at; int list_state; /* 0 unknown, 1 none, 2 installed */ + int list_reported; int list_has_age; int invalid_logged; } gate_record; @@ -117,6 +118,7 @@ int prometheus_gate_list(const char *name, const char *hex, int has_age, unsigne } else gate->invalid_logged = 0; gate->list_state = hex ? (strcmp(hex, "none") == 0 ? 1 : 2) : 0; + gate->list_reported = 1; gate->list_has_age = gate->list_state == 2 && has_age; gate->confirmed_age = age; gate->list_reported_at = time(NULL); @@ -247,6 +249,8 @@ int prometheus_render(const char *version, double age, char **body, size_t *leng "# TYPE gatepost_gate_list_status gauge\n"); for (size_t i = 0; i < data.count; ++i) { gate_record *gate = &data.gates[i]; + if (!gate->list_reported) + continue; int current = gate->list_state == 2 && strcmp(gate->list_hex, version) == 0; int stale = gate->list_state != 0 && !current; fprintf(out, @@ -261,7 +265,7 @@ int prometheus_render(const char *version, double age, char **body, size_t *leng "# TYPE gatepost_gate_list_confirmed_age_seconds gauge\n"); for (size_t i = 0; i < data.count; ++i) { gate_record *gate = &data.gates[i]; - if (gate->list_state == 2 && gate->list_has_age) { + if (gate->list_reported && gate->list_state == 2 && gate->list_has_age) { double elapsed = difftime(now, gate->list_reported_at); fprintf(out, "gatepost_gate_list_confirmed_age_seconds{gate=\"%s\"} %.0f\n", gate->name, gate->confirmed_age + (elapsed > 0 ? elapsed : 0)); diff --git a/tests/test_gate_list_version.py b/tests/test_gate_list_version.py index 0e0a399..7f1b06a 100644 --- a/tests/test_gate_list_version.py +++ b/tests/test_gate_list_version.py @@ -192,6 +192,29 @@ def fake_hub(listener, stop, seen, scans): assert age(metrics(), 'fresh') is not None and age(metrics(), 'fresh') < 25, \ 'confirmation age was not refreshed after the new list was installed' + with socket.create_connection(('127.0.0.1', port), timeout=2) as peer: + peer.settimeout(2) + kind, body = rpc(peer, 2, 3, 1, b'GP-999999999999') + assert (kind, body) == (4, b'REJECT'), \ + f'unidentified SCAN reply changed: {(kind, body)!r}' + version = hashlib.sha256(source.read_bytes()).hexdigest().encode() + kind, body = rpc(peer, 2, 5, 2, b'list=' + version) + assert kind == 6 and body.startswith(b'scans='), \ + f'unidentified CONFIG reply changed: {(kind, body)!r}' + kind, body = rpc(peer, 2, 5, 3, b'list=xyz') + assert kind == 6 and body.startswith(b'scans='), \ + f'unidentified invalid CONFIG reply changed: {(kind, body)!r}' + data = metrics() + assert not any(line.startswith('gatepost_gate_list_status{gate="unknown",') + for line in data.splitlines()), \ + 'unidentified connection acquired list status series' + assert age(data, 'unknown') is None, \ + 'unidentified connection acquired a confirmation age' + scans = [line for line in data.splitlines() if line.startswith( + 'gatepost_scans_total{gate="unknown",result="reject_unknown"} ')] + assert len(scans) == 1 and int(scans[0].split()[-1]) >= 1, \ + 'unidentified scan was not counted under unknown' + for version in (2, 1): name = f'oldframe{version}' raw_gate(port, name, version) @@ -228,6 +251,8 @@ def fake_hub(listener, stop, seen, scans): _, logs = hub.communicate(timeout=5) assert logs.count(b'event=gate_list state=invalid gate=invalid') == 1, \ f'invalid CONFIG warning should appear once for two requests: {logs!r}' + assert b'event=gate_list state=invalid gate=unknown' not in logs, \ + 'unidentified CONFIG emitted a gate list warning' with socket.socket() as listener: listener.bind(('127.0.0.1', 0)) From fe1381d712264721099e218f393a7becc6680ec4 Mon Sep 17 00:00:00 2001 From: Noah Williams Date: Thu, 29 Oct 2026 09:30:00 +1100 Subject: [PATCH 8/9] test(lab): show nobody is told when the data centre is unreachable or the uplink watcher has stopped Cut both data-centre exits, restore them, then kill the hub's uplink watcher. Compare Mailpit message IDs across each separate fault. Each case expects exactly one mail to manager@elsworne.example from alerts@elsworne.example through the venue's own mail server, which remains available without the data-centre link. The subjects are "Data centre unreachable" and "Uplink watcher stopped". Allow 20 s: 5 s for the probe, 10 s for the alert threshold, 1 s for the alert loop, and 4 s for mail submission; the watcher checks every second. Today neither mail is sent, so both judgements fail. Exit 0 means both pass, 1 means a judgement fails, and 2 means an environment or cleanup failure. --- lab/README.md | 2 + lab/README.zh-CN.md | 2 + lab/dc-alert.sh | 301 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 305 insertions(+) create mode 100644 lab/dc-alert.sh diff --git a/lab/README.md b/lab/README.md index b28c2c9..48fd371 100644 --- a/lab/README.md +++ b/lab/README.md @@ -144,6 +144,8 @@ what this routing lab shows with `192.0.2.130`. The hub learns gate identities from framed `HELLO` messages rather than source IP. If a known gate stops reporting for ten seconds, the hub submits an alert through Mailpit with STARTTLS. Run `sh lab/mail-alert.sh` to stop Gate 1, capture the SMTP exchange and check Mailpit's message API. Mailpit is a local submission and viewing service; the venue manager would read delivered mail through their own mail client. +Run `sh lab/dc-alert.sh` alone to cut the data-centre-facing interfaces on both routers, then restore them and kill the hub's uplink watcher. Each case expects exactly one mail to `manager@elsworne.example` from `alerts@elsworne.example`, with subject `Data centre unreachable` or `Uplink watcher stopped` respectively, through the venue's own mail server, which does not depend on the data-centre link. Like the gate-offline alert, each is sent once when the fault begins, with no recovery mail; read the dashboard for recovery. The 20-second window allows up to 5 seconds for the data-centre probe (2-second connect timeout plus 3-second pause; the recorded outage took 3.3 seconds to detect), a watcher check every second, the `alert_after_seconds=10` threshold in [hub.conf](hub.conf) shared with the gate-offline alert, a one-second alert loop and 4 seconds for mail submission as in `lab/mail-alert.sh`: 5 + 10 + 1 + 4 = 20. The drill exits 0 if both alerts arrive once, 1 for failed judgements and 2 for an environment mismatch or cleanup failure; cleanup removes its router rules, restarts the hub and checks that the data-centre link and one watcher have returned. + The lab uses [hub.conf](hub.conf). For a deployment, copy [config/hub.conf.example](../config/hub.conf.example) to `/etc/gatepost/hub.conf`, set the SMTP URL, recipient, sender, CA certificate path, and state file path, and point `GATEPOST_HUB_CONFIG` to it if using another location. Set `smtp_user` and `smtp_password_file` for authenticated submission. Put the password in the referenced file with restricted permissions; never put it in the config. The hub atomically writes its alert state to `state_file`; keep that directory persistent and writable. An uncertain SMTP submission reply can cause a retry with the same stable `Message-ID`. SMTP submission cannot provide exactly-once delivery, so the recipient system should de-duplicate by `Message-ID`. ## HTTP ticket distribution diff --git a/lab/README.zh-CN.md b/lab/README.zh-CN.md index 57b35a3..b72b527 100644 --- a/lab/README.zh-CN.md +++ b/lab/README.zh-CN.md @@ -136,6 +136,8 @@ curl 状态 28 超时,光纤接入的丢包计数也须增加:回包仍按 hub 从有 frame 的 `HELLO` 消息获取闸机身份,不依靠来源 IP。若已知闸机十秒未报告,hub 通过 STARTTLS 向 Mailpit 提交告警。运行 `sh lab/mail-alert.sh` 停止 Gate 1、抓取 SMTP 交换并检查 Mailpit 消息 API。Mailpit 是本地提交与查看服务;场馆经理通过自己的邮件客户端读取已投递的邮件。 +请单独运行 `sh lab/dc-alert.sh`:脚本先切断两台路由器朝数据中心的接口,再恢复连接并强制终止 hub 的出口监视进程。每种故障都应在 20 秒内通过场馆自己的邮件服务器,分别以 `Data centre unreachable` 和 `Uplink watcher stopped` 为主题,从 `alerts@elsworne.example` 向 `manager@elsworne.example` 恰好发出一封邮件;这条通知路径不依赖数据中心链路。这两类告警和闸机离线告警一样,只在故障开始时发一封,不发恢复邮件,恢复与否看面板。20 秒由数据中心探测最多 5 秒(连接超时 2 秒、轮次间暂停 3 秒;事故记录为 3.3 秒)、监视进程每秒检查一次、[hub.conf](hub.conf) 中与闸机离线告警相同的 `alert_after_seconds=10` 阈值、告警循环每秒检查一次,以及 `lab/mail-alert.sh` 为提交邮件预留的 4 秒相加而得:5 + 10 + 1 + 4 = 20。两项均恰好收到一封邮件时以 0 退出,判定失败以 1 退出,环境不符或收尾失败以 2 退出;收尾会删除脚本添加的路由器规则,重启 hub,并检查数据中心链路恢复及恰有一个监视进程运行。 + 实验环境使用 [hub.conf](hub.conf)。部署时把 [config/hub.conf.example](../config/hub.conf.example) 复制到 `/etc/gatepost/hub.conf`,设置 SMTP URL、收件人、发件人、CA 证书路径和状态文件路径;若放在其他位置,用 `GATEPOST_HUB_CONFIG` 指向它。认证提交时设置 `smtp_user` 和 `smtp_password_file`。将密码放在被引用且权限受限的文件里,不要写进配置。hub 原子写入 `state_file`;其目录必须可写并持久保存。若 SMTP 提交回复不确定,hub 可能以同一个稳定的 `Message-ID` 重试。SMTP 提交无法保证 exactly-once 投递,接收系统应按 `Message-ID` 去重。 ## HTTP 票单分发 diff --git a/lab/dc-alert.sh b/lab/dc-alert.sh new file mode 100644 index 0000000..14ea810 --- /dev/null +++ b/lab/dc-alert.sh @@ -0,0 +1,301 @@ +#!/bin/sh +# Check that two failures notify the venue through its own mail service. +set -eu +export LC_ALL=C +umask 077 +cd "$(dirname "$0")/.." + +compose='docker compose -f lab/compose.yaml' +tag=dc-alert-$$ +work= +router_if= +backup_if= +cut_registered=0 +judged=0 +mismatch_reported=0 + +now() { date +%s; } +run() { service=$1; shift; $compose exec -T "$service" env LC_ALL=C "$@"; } +logs() { $compose logs --no-color --no-log-prefix hub; } +mismatch() { mismatch_reported=1; printf 'environment mismatch: %s\n' "$1" >&2; exit 2; } + +watcher_pids() { + run hub sh -s <<'SH' +watchers= +for path in /proc/[0-9]*/cmdline; do + [ -r "$path" ] || continue + args=$(tr '\000' ' ' < "$path") + case "$args" in + 'sh /src/lab/uplink-watch.sh ' | '/bin/sh /src/lab/uplink-watch.sh ') + pid=${path#/proc/} + watchers="$watchers ${pid%/cmdline}" + ;; + esac +done +for pid in $watchers; do + parent=$(awk '$1 == "PPid:" { print $2; exit }' "/proc/$pid/status" 2>/dev/null) || continue + case " $watchers " in + *" $parent "*) ;; + *) printf '%s\n' "$pid" ;; + esac +done +SH +} + +watcher_count() { + pids=$(watcher_pids) || return 1 + printf '%s\n' "$pids" | awk 'NF { n++ } END { print n + 0 }' +} +latest_dc_state() { + logs | awk '$3 == "event=dc_link" && $4 ~ /^state=/ { state=substr($4,7) } + END { print state }' +} +state_since() { + logs | awk -v start="$1" -v state="state=$2" ' + $1 ~ /^time=[0-9]+$/ && $3 == "event=dc_link" && $4 == state { + split($1, stamp, "=") + if (stamp[2] / 1000000 >= start) found=1 + } + END { exit !found }' +} +wait_state() { + start=$1; state=$2; limit=$3 + deadline=$(( $(now) + limit )) + while :; do + if state_since "$start" "$state"; then return 0; fi + [ "$(now)" -lt "$deadline" ] || return 1 + sleep 1 + done +} +wait_hub() { + deadline=$(( $(now) + 60 )) + until run hub curl -fsS --max-time 2 -H 'Host: hub.venue.lan' \ + http://10.77.20.10:8081/status >/dev/null 2>&1; do + [ "$(now)" -lt "$deadline" ] || return 1 + sleep 1 + done +} +mail_snapshot() { + run hub curl -fsS --max-time 3 http://10.77.20.25:8025/api/v1/messages > "$1" && + python3 - "$1" <<'PY' +import json, sys +with open(sys.argv[1], encoding='utf-8') as source: + data = json.load(source) +assert isinstance(data['messages'], list) +assert all(isinstance(item['ID'], str) for item in data['messages']) +PY +} +interface() { + run "$1" ip -o -4 addr show | awk -v address="$2" ' + $4 == address { sub(/@.*/, "", $2); dev=$2; count++ } + END { if (count != 1) exit 1; print dev }' +} + +rule() { + service=$1; dev=$2; action=$3; kind=$4 + run "$service" sh -s -- "$dev" "$tag" "$action" "$kind" <<'SH' +set -eu +dev=$1; tag=$2; action=$3; kind=$4 +case "$kind" in + input) set -- INPUT -i "$dev" ;; + output) set -- OUTPUT -o "$dev" ;; + forward_in) set -- FORWARD -i "$dev" ;; + forward_out) set -- FORWARD -o "$dev" ;; + *) exit 1 ;; +esac +if [ "$action" = add ]; then + iptables -w -I "$@" -m comment --comment "$tag" -j DROP +elif [ "$action" = check ]; then + iptables -w -C "$@" -m comment --comment "$tag" -j DROP +else + status=0 + iptables -w -C "$@" -m comment --comment "$tag" -j DROP 2>/dev/null || status=$? + case "$status" in + 0) iptables -w -D "$@" -m comment --comment "$tag" -j DROP ;; + 1) iptables -w -S "$1" >/dev/null ;; + *) exit "$status" ;; + esac +fi +SH +} +remove_cut() { + [ "$cut_registered" -eq 1 ] || return 0 + bad=0 + for entry in "router:$router_if" "backup-router:$backup_if"; do + service=${entry%%:*}; dev=${entry#*:} + [ -n "$dev" ] || continue + for kind in input output forward_in forward_out; do + rule "$service" "$dev" remove "$kind" || bad=1 + done + if ! run "$service" iptables -w -S | awk -v tag="$tag" ' + index($0, "--comment " tag " ") { found=1 } + END { exit found }'; then bad=1; fi + done + if [ "$bad" -eq 0 ]; then cut_registered=0; fi + return "$bad" +} +observe_logs() { + logs | awk -v start="$1" -v end="$2" ' + $1 ~ /^time=[0-9]+$/ && + ($3 == "event=dc_link" || $3 == "event=dc_sync" || + $3 == "event=uplink" || $3 == "event=mail_alert") { + split($1, stamp, "=") + second=stamp[2] / 1000000 + if (second >= start && second <= end) { + sub(/^time=[0-9]+[[:space:]]*/, "") + print "observation: hub " $0 + } + }' +} +observe_mail() { + python3 - "$1" "$2" "$3" "$4" "$5" <<'PY' +import datetime, json, sys + +before, after, subject, start, count_path = sys.argv[1:] +with open(before, encoding='utf-8') as source: + seen = {item['ID'] for item in json.load(source)['messages']} +with open(after, encoding='utf-8') as source: + fresh = [item for item in json.load(source)['messages'] if item['ID'] not in seen] + +def addresses(value): + if isinstance(value, dict): + return [value.get('Address', '')] + if isinstance(value, list): + return sum((addresses(item) for item in value), []) + return [str(value)] + +count = 0 +if not fresh: + print('observation: new Mailpit messages: none') +for item in fresh: + sender = ', '.join(addresses(item.get('From', ''))) + recipient = ', '.join(addresses(item.get('To', ''))) + created = item.get('Created', item.get('Date', 'unknown')) + try: + timestamp = datetime.datetime.fromisoformat(str(created).replace('Z', '+00:00')) + elapsed = f'{timestamp.timestamp() - float(start):.1f} s' + in_window = float(start) <= timestamp.timestamp() <= float(start) + 20 + except (ValueError, TypeError): + elapsed = 'unavailable' + in_window = True + print(f'observation: new mail Subject={item.get("Subject", "")} ' + f'From={sender} To={recipient} time={created} after={elapsed}') + if (in_window and item.get('Subject') == subject and + 'manager@elsworne.example' in addresses(item.get('To', '')) and + 'alerts@elsworne.example' in addresses(item.get('From', ''))): + count += 1 +with open(count_path, 'w', encoding='ascii') as target: + target.write(f'{count}\n') +PY +} +wait_window() { + deadline=$(( $1 + 20 )) + while [ "$(now)" -lt "$deadline" ]; do sleep 1; done +} +cleanup() { + status=$? + trap - 0 + trap '' HUP INT TERM + if remove_cut; then + printf 'cleanup: routers restored ok\n' + else + printf 'cleanup: routers restored FAIL\n' >&2 + status=2 + fi + restart_start=$(now) + if $compose restart hub >/dev/null && wait_hub && + wait_state "$restart_start" connected 30 && + [ "$(latest_dc_state)" = connected ] && + [ "$(watcher_count)" -eq 1 ]; then + printf 'cleanup: hub restarted with uplink watcher ok\n' + else + printf 'cleanup: hub restarted with uplink watcher FAIL\n' >&2 + status=2 + fi + if [ -n "$work" ] && ! rm -r "$work"; then + printf 'cleanup: temporary files FAIL\n' >&2 + status=2 + fi + if [ "$judged" -eq 0 ] && [ "$mismatch_reported" -eq 0 ]; then + printf 'environment mismatch: unexpected error\n' >&2 + status=2 + fi + exit "$status" +} +trap cleanup 0 +trap 'exit 2' HUP INT TERM + +command -v docker >/dev/null 2>&1 || mismatch 'docker unavailable' +command -v python3 >/dev/null 2>&1 || mismatch 'python3 unavailable' +work=$(mktemp -d "${TMPDIR:-/tmp}/dc-alert.XXXXXX") || mismatch 'temporary directory' +running=$($compose ps --status running --services) || mismatch 'lab services unavailable' +for service in hub router backup-router mail; do + printf '%s\n' "$running" | grep -qx "$service" || mismatch "$service is not running" +done +wait_hub || mismatch 'hub does not serve' +mail_snapshot "$work/a.before" || mismatch 'Mailpit API unavailable from hub' +[ "$(latest_dc_state)" = connected ] || mismatch 'data centre is not connected before cut' +router_if=$(interface router 10.77.30.2/24) || mismatch 'router data-centre interface' +backup_if=$(interface backup-router 10.77.30.3/24) || mismatch 'backup-router data-centre interface' + +# Detection takes at most 5 s (2 s connect timeout + 3 s pause); the watcher +# checks each second. The 10 s alert threshold, 1 s alert loop and 4 s mail +# submission allowance used by mail-alert.sh give 5 + 10 + 1 + 4 = 20 s. +cut_registered=1 +for entry in "router:$router_if" "backup-router:$backup_if"; do + service=${entry%%:*}; dev=${entry#*:} + for kind in input output forward_in forward_out; do + rule "$service" "$dev" add "$kind" || mismatch 'data-centre cut rules were not inserted' + rule "$service" "$dev" check "$kind" || mismatch 'data-centre cut rule could not be verified' + done +done +cut_start=$(now) +printf 'fault: data centre cut at router and backup-router\n' +wait_state "$cut_start" failed 10 || mismatch 'hub did not log failed data-centre link within 10 s' +wait_window "$cut_start" +cut_end=$(now) +mail_snapshot "$work/a.after" || mismatch 'Mailpit API unavailable after data-centre cut' +observe_mail "$work/a.before" "$work/a.after" 'Data centre unreachable' "$cut_start" "$work/a.count" || mismatch 'Mailpit messages could not be read' +observe_logs "$cut_start" "$cut_end" || mismatch 'hub logs unavailable after data-centre cut' + +restore_start=$(now) +remove_cut || mismatch 'router rules could not be restored between cases' +wait_state "$restore_start" connected 30 || mismatch 'hub did not reconnect after router restoration' +mail_snapshot "$work/b.before" || mismatch 'Mailpit API unavailable before watcher kill' +pids=$(watcher_pids) || mismatch 'watcher process list unavailable' +[ "$(printf '%s\n' "$pids" | awk 'NF { n++ } END { print n + 0 }')" -eq 1 ] || mismatch 'expected exactly one uplink watcher' +kill_start=$(now) +run hub sh -c 'kill -KILL "$1"' sh "$pids" || mismatch 'uplink watcher could not be killed' +gone_deadline=$(( $(now) + 3 )) +while :; do + count=$(watcher_count) || mismatch 'watcher process list unavailable after SIGKILL' + [ "$count" -ne 0 ] || break + [ "$(now)" -lt "$gone_deadline" ] || mismatch 'uplink watcher remained after SIGKILL' + sleep 1 +done +printf 'fault: uplink watcher killed\n' +wait_window "$kill_start" +kill_end=$(now) +mail_snapshot "$work/b.after" || mismatch 'Mailpit API unavailable after watcher kill' +observe_mail "$work/b.before" "$work/b.after" 'Uplink watcher stopped' "$kill_start" "$work/b.count" || mismatch 'Mailpit messages could not be read' +observe_logs "$kill_start" "$kill_end" || mismatch 'hub logs unavailable after watcher kill' + +a_count=$(cat "$work/a.count") +b_count=$(cat "$work/b.count") +failed=0 +case "$a_count" in + 1) : ;; + 0) printf 'result: data centre alert FAIL (no "Data centre unreachable" mail to manager@elsworne.example within 20 s)\n'; failed=1 ;; + *) printf 'result: data centre alert FAIL (more than one "Data centre unreachable" mail within 20 s)\n'; failed=1 ;; +esac +case "$b_count" in + 1) : ;; + 0) printf 'result: uplink watcher alert FAIL (no "Uplink watcher stopped" mail to manager@elsworne.example within 20 s)\n'; failed=1 ;; + *) printf 'result: uplink watcher alert FAIL (more than one "Uplink watcher stopped" mail within 20 s)\n'; failed=1 ;; +esac +judged=1 +if [ "$failed" -eq 0 ]; then + printf 'result: data centre and uplink watcher alerts ok\n' + exit 0 +fi +exit 1 From f859ab635592681585c63ed8d1c880cbe205ff9c Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Thu, 29 Oct 2026 14:00:00 +1100 Subject: [PATCH 9/9] fix(gate-hub): alert by mail when the data centre is unreachable or the uplink watcher stops The hub logged data-centre failures, and the uplink watcher could exit without notifying the venue. Submit mail after the shared alert threshold, once per incident. Keep sent incidents in the atomic state file across hub restarts, and re-arm each alert when its condition recovers without sending recovery mail. Have the watcher update a heartbeat file each loop. Its modification time uses the clock shared with the hub, since a shell cannot portably read a monotonic clock. Give restarted hubs a fresh threshold of grace. Add a CI test for transient and repeated faults, recovery, mail headers, restart persistence, and the watcher grace period. Co-authored-by: Yuki Tanaka --- CMakeLists.txt | 5 +- README.md | 2 +- README.zh-CN.md | 2 +- config/hub.conf.example | 2 + gate-hub/alert.c | 264 ++++++++++++++++++++++++------------ gate-hub/alert.h | 5 + gate-hub/dc_probe.c | 13 +- gate-hub/main.c | 5 +- lab/README.md | 2 +- lab/README.zh-CN.md | 2 +- lab/compose.yaml | 1 + lab/hub.conf | 1 + lab/uplink-watch.sh | 8 ++ tests/test_dc_alerts.py | 290 ++++++++++++++++++++++++++++++++++++++++ 14 files changed, 508 insertions(+), 94 deletions(-) create mode 100644 tests/test_dc_alerts.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 2f10cf9..7c61401 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -212,6 +212,9 @@ add_test(NAME dc_dns_failure COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_dc_dns_failure.py $) add_test(NAME mail_alert COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_mail_alert.py $) +add_test(NAME dc_alerts COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/tests/test_dc_alerts.py $) +set_tests_properties(dc_alerts PROPERTIES TIMEOUT 150) add_test(NAME http_distribution COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_http.py $ $) add_test(NAME ticket_reply_count COMMAND ${Python3_EXECUTABLE} @@ -251,5 +254,5 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") endif() add_test(NAME status_deadline COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_status_deadline.py $ $) -set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons ticket_fetch_progress http_distribution ticket_reply_count offline_reports protocol_compat gate_list_version status_deadline sync_metrics monitoring_config +set_tests_properties(gated_tls hub_tls device_tls second_hello tls_failure_reasons ticket_fetch_progress http_distribution ticket_reply_count offline_reports protocol_compat gate_list_version status_deadline sync_metrics monitoring_config dc_alerts PROPERTIES RESOURCE_LOCK status_ports) diff --git a/README.md b/README.md index 168e9bc..a9d62e4 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ Ticket work logs `event=ticket_sync` for build start, completion or failure and The data-centre probe logs `event=dc_dns` when resolution becomes `resolved`, `stale`, `failed`, or `recovered`. A stale address is usable for at most 30 seconds; `reason=stale_expired` means the grace period ended, and `reason=never_resolved` that the name has not resolved since the hub started. `resolved` is the first successful lookup, `recovered` one after a failure. It logs `event=dc_link state=connected` or `state=failed` only when the connection state changes, and `state=connected address=... previous=...` when it stays connected but moves to another address; this TCP probe uses port 8443 with device TLS configured, or 8080 otherwise. `GATEPOST_DC_HOST` sets the host that both the probe and the sync connect to (default `api.elsworne.example`); the sync always checks the certificate as `api.elsworne.example`. A failed probe startup or socket close uses `event=operation_failed`. -Mail submission logs `event=mail_alert gate=... state=failed` once when an incident cannot be submitted, and `state=sent` after submission and durable state update. Persistent alert-state file failures and their recovery use `event=mail_state state=failed` and `state=recovered`. Alert initialization failures use `event=operation_failed`. +Mail alerts also cover two hub faults: `Data centre unreachable` when probe rounds cannot connect, and `Uplink watcher stopped` when the configured heartbeat file stops changing. Each uses `alert_after_seconds`, sends once per incident after that threshold, sends no recovery mail, re-arms on recovery, and keeps the sent state across hub restarts. The watcher writes the file each loop; its modification time is the heartbeat because a shell has no portable monotonic clock and the watcher and hub share a wall clock in the same container. The hub grants a fresh threshold after restart. These alerts log `event=mail_alert alert=data_centre state=failed/sent` or `alert=uplink_watcher state=failed/sent`; gate alerts retain `event=mail_alert gate=... state=failed` once when submission fails and `state=sent` after submission and durable state update. Persistent alert-state file failures and their recovery use `event=mail_state state=failed` and `state=recovered`. Alert initialization failures use `event=operation_failed`. In the test builds, without device TLS, the hub serves `/tickets`, `/status` and `/metrics` over HTTP on port 8081. When device TLS and `GATEPOST_STATUS` are configured, port 8081 serves `/status` and `/metrics` but answers `GET /tickets` with 404; port 8444 serves the list and the other routes over TLS 1.3 at the same bind address. Port 8444 requires a venue CA-signed gate certificate and accepts only `Host: hub.venue.lan` or `Host: hub.venue.lan:8444`. With device TLS configured, a gate fetches `https://hub.venue.lan:8444/tickets` on startup and periodically, connecting to the `--hub` host while verifying the hub certificate as `hub.venue.lan` and presenting its own certificate. In the test builds, without device TLS, it fetches over 8081: with `--hub 10.77.20.10:7000`, it asks for `http://10.77.20.10:8081/tickets` and sends `Host: 10.77.20.10:8081`. Set `GATEPOST_TICKETS_URL` to override the URL; production builds accept only `https://` and `file://` overrides, while the `http://` override warning appears only in test builds. The hub answers only Host values listed in `GATEPOST_STATUS_HOSTS` (default `hub.venue.lan`, `hub.venue.lan:8081`, `127.0.0.1:8081` and `localhost:8081`) and returns 400 to any other. For plaintext gates reaching the hub by address, add `
:8081` to `GATEPOST_STATUS_HOSTS`; the variable replaces the default list, so keep the names you still use. A gate logs `event=ticket_fetch state=failed http= curl= reason= phase= received= expected=` when fetching starts failing or the reason or phase changes. It suppresses repeats with the same reason and phase even if the byte counts differ, and logs `event=ticket_fetch state=recovered` once when it works again. The gate retains used-ticket state when installing a new list. With device TLS configured, the hub syncs its binary data-centre copy over port 8443 using its certificate, with range requests and SHA-256 verification before installation. The hub also serves `/metrics` on its staff-side status listener, separate from the gate RPC port. In the lab it binds `10.77.20.10:8081`, and only staff-subnet or loopback clients may read metrics. See [metric names and labels](docs/operations/metrics.md). The hub sends `X-Content-SHA256` with each ticket list; a gate verifies the bytes and prepares its ETag metadata before replacing the old list. diff --git a/README.zh-CN.md b/README.zh-CN.md index 82a38a8..d63f80c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -92,7 +92,7 @@ time=1775170804235739 level=INFO event=hub_link gate=south state=online 数据中心探测的地址解析状态变为 `resolved`、`stale`、`failed` 或 `recovered` 时写入 `event=dc_dns`。旧地址最多沿用 30 秒;`reason=stale_expired` 表示宽限期结束,`reason=never_resolved` 表示 hub 启动以来这个名字还没解析成功过。`resolved` 是第一次解析成功,`recovered` 是失败之后再次成功。连接状态变化时写入 `event=dc_link state=connected` 或 `state=failed`;连接一直正常、只是换到另一个地址时,写入 `state=connected address=... previous=...`。这项 TCP 探测在配置设备 TLS 时使用 8443 端口,否则使用 8080 端口。`GATEPOST_DC_HOST` 指定探测和同步连接的主机,默认是 `api.elsworne.example`;同步始终按 `api.elsworne.example` 验证证书。探测启动或关闭套接字失败时写入 `event=operation_failed`。 -邮件发送失败时,每次故障只写一次 `event=mail_alert gate=... state=failed`;发送并持久化成功后写入 `state=sent`。告警状态文件持续失败及其恢复分别写入 `event=mail_state state=failed` 和 `state=recovered`。告警初始化失败写入 `event=operation_failed`。 +邮件也会报告 hub 的两类故障:探测轮次无法连接数据中心时,主题为 `Data centre unreachable`;已配置的心跳文件停止更新时,主题为 `Uplink watcher stopped`。两者都在持续达到 `alert_after_seconds` 后每次故障只发一封,不发恢复邮件;恢复后重新布防,已发送状态在 hub 重启后仍保留。监视脚本每轮更新文件,hub 读取修改时间作为心跳;shell 没有可移植的方法读取单调时钟,而脚本与 hub 同处一个容器、共用系统时钟。hub 重启后会重新给予一个阈值时长的宽限期。这两类告警分别记录 `event=mail_alert alert=data_centre state=failed/sent` 和 `alert=uplink_watcher state=failed/sent`;闸机告警仍在提交失败时每次故障只写一次 `event=mail_alert gate=... state=failed`,提交并持久化成功后写入 `state=sent`。告警状态文件持续失败及其恢复分别写入 `event=mail_state state=failed` 和 `state=recovered`。告警初始化失败写入 `event=operation_failed`。 测试构建未配置设备 TLS 时,Hub 在 8081 端口通过 HTTP 提供 `/tickets`、`/status` 和 `/metrics`。配置设备 TLS 和 `GATEPOST_STATUS` 后,8081 只提供 `/status` 和 `/metrics`,对 `GET /tickets` 返回 404;同一绑定地址的 8444 端口通过 TLS 1.3 提供票单和其他接口。8444 要求客户端出示场馆 CA 签发的闸机证书,只接受 `Host: hub.venue.lan` 或 `Host: hub.venue.lan:8444`。配置设备 TLS 后,闸机在启动时及之后定期请求 `https://hub.venue.lan:8444/tickets`,实际连接 `--hub` 指定的主机,按 `hub.venue.lan` 验证 hub 证书,并出示自己的设备证书。测试构建未配置设备 TLS 时仍使用 8081:以 `--hub 10.77.20.10:7000` 启动时,请求 `http://10.77.20.10:8081/tickets`,发送 `Host: 10.77.20.10:8081`。可用 `GATEPOST_TICKETS_URL` 覆盖地址;生产构建只接受 `https://` 和 `file://`,`http://` 覆盖地址的警告只在测试构建中出现。Hub 只接受 `GATEPOST_STATUS_HOSTS` 中列出的 Host(默认是 `hub.venue.lan`、`hub.venue.lan:8081`、`127.0.0.1:8081` 和 `localhost:8081`),其他一律回 400。明文闸机按地址连接 hub 时,要把 `<地址>:8081` 加进 `GATEPOST_STATUS_HOSTS`;这个变量会整个替换默认列表,仍要用的名字也要写上。闸机取票开始失败,或连续失败期间原因或阶段发生变化时,记录 `event=ticket_fetch state=failed http=<状态码> curl=<错误码> reason=<原因> phase=<阶段> received=<字节数> expected=<字节数|unknown>`;原因和阶段都相同的失败不重复记录,即使字节数不同也是如此;恢复后记录一次 `event=ticket_fetch state=recovered`。闸机安装新票单时保留已使用状态。配置设备 TLS 后,Hub 使用自己的证书通过 8443 端口分段同步数据中心的二进制票单,安装前验证 SHA-256。 Hub 还在员工网络一侧的状态服务上提供 `/metrics`,与闸机 RPC 端口分开。实验环境将其绑定到 `10.77.20.10:8081`;只有员工网段或本机能读取指标。指标名称和标签见[运维指标](docs/operations/metrics.zh-CN.md)。Hub 随票单发送 `X-Content-SHA256`;闸机验证文件内容,并在替换旧票单之前准备 ETag 元数据。 diff --git a/config/hub.conf.example b/config/hub.conf.example index c61389f..9560253 100644 --- a/config/hub.conf.example +++ b/config/hub.conf.example @@ -7,3 +7,5 @@ smtp_user=gatepost smtp_password_file=/etc/gatepost/smtp-password state_file=/var/lib/gatepost/alerts.state alert_after_seconds=10 +# Optional: the watcher's heartbeat file; its mtime uses the hub's shared wall clock. +# uplink_heartbeat_file=/tmp/gatepost-uplink.heartbeat diff --git a/gate-hub/alert.c b/gate-hub/alert.c index bf2b46f..2b21b24 100644 --- a/gate-hub/alert.c +++ b/gate-hub/alert.c @@ -79,23 +79,31 @@ static int load_config(gate_watch *watch, const char *path) { *equal++ = '\0'; char *dest = NULL; size_t size = 0; -#define FIELD(key, member) \ - if (!strcmp(line, key)) { \ - dest = watch->member; \ - size = sizeof watch->member; \ - } - FIELD("smtp_url", smtp_url) - else FIELD("smtp_ca", smtp_ca) else FIELD("smtp_from", smtp_from) else FIELD( - "smtp_to", - smtp_to) else FIELD("smtp_user", - smtp_user) else FIELD("state_file", - state_file) else if (!strcmp(line, - "smtp_password_" - "file")) { + if (!strcmp(line, "smtp_url")) { + dest = watch->smtp_url; + size = sizeof watch->smtp_url; + } else if (!strcmp(line, "smtp_ca")) { + dest = watch->smtp_ca; + size = sizeof watch->smtp_ca; + } else if (!strcmp(line, "smtp_from")) { + dest = watch->smtp_from; + size = sizeof watch->smtp_from; + } else if (!strcmp(line, "smtp_to")) { + dest = watch->smtp_to; + size = sizeof watch->smtp_to; + } else if (!strcmp(line, "smtp_user")) { + dest = watch->smtp_user; + size = sizeof watch->smtp_user; + } else if (!strcmp(line, "state_file")) { + dest = watch->state_file; + size = sizeof watch->state_file; + } else if (!strcmp(line, "uplink_heartbeat_file")) { + dest = watch->uplink_heartbeat_file; + size = sizeof watch->uplink_heartbeat_file; + } else if (!strcmp(line, "smtp_password_file")) { dest = secret_path; size = sizeof secret_path; - } - else if (!strcmp(line, "alert_after_seconds")) { + } else if (!strcmp(line, "alert_after_seconds")) { char *end = NULL; long value = strtol(equal, &end, 10); if (!end || *end || value < 1 || value > 3600) @@ -103,12 +111,10 @@ static int load_config(gate_watch *watch, const char *path) { else watch->alert_after_seconds = (int)value; continue; - } - else { + } else { failed = 1; break; } -#undef FIELD if (copy_value(dest, size, equal) != 0) { failed = 1; break; @@ -136,6 +142,11 @@ static int save_state(gate_watch *watch) { return -1; } int failed = 0; + gate_alert_entry *extra[] = {&watch->data_centre, &watch->uplink_watcher}; + for (size_t i = 0; i < 2; ++i) + if (fprintf(file, "%s %lld %lld %d\n", extra[i]->id, (long long)extra[i]->seen, + (long long)extra[i]->incident, extra[i]->sent) < 0) + failed = 1; for (size_t i = 0; i < watch->count; ++i) { gate_alert_entry *gate = &watch->gates[i]; if (fprintf(file, "%s %lld %lld %d\n", gate->id, (long long)gate->seen, @@ -162,11 +173,18 @@ static int load_state(gate_watch *watch) { long long seen, incident; int sent; while (fscanf(file, "%31s %lld %lld %d", id, &seen, &incident, &sent) == 4) { - if (watch->count == GATE_WATCH_LIMIT || !valid_id(id) || (sent != 0 && sent != 1)) { + gate_alert_entry *special = NULL; + if (!strcmp(id, ":data-centre")) + special = &watch->data_centre; + else if (!strcmp(id, ":uplink-watcher")) + special = &watch->uplink_watcher; + if ((sent != 0 && sent != 1) || + (!special && (watch->count == GATE_WATCH_LIMIT || !valid_id(id))) || + (special && special->id[0])) { (void)fclose(file); return -1; } - gate_alert_entry *gate = &watch->gates[watch->count++]; + gate_alert_entry *gate = special ? special : &watch->gates[watch->count++]; memcpy(gate->id, id, strlen(id) + 1); gate->seen = (time_t)seen; gate->incident = (time_t)incident; @@ -177,23 +195,19 @@ static int load_state(gate_watch *watch) { failed = 1; return failed ? -1 : 0; } -static int send_alert(gate_watch *watch, const gate_alert_entry *gate, time_t now) { - char date[80], message_id[160], message[1024]; +static int send_alert(gate_watch *watch, const char *subject, const char *body, + const char *message_id, time_t now) { + char date[80], message[1024]; struct tm utc; if (!gmtime_r(&now, &utc) || !strftime(date, sizeof date, "%a, %d %b %Y %H:%M:%S +0000", &utc)) return -1; - int n = snprintf(message_id, sizeof message_id, "", gate->id, - (long long)gate->incident); - if (n < 0 || (size_t)n >= sizeof message_id) - return -1; - n = snprintf(message, sizeof message, - "From: <%s>\r\nTo: <%s>\r\nDate: %s\r\nMessage-ID: %s\r\n" - "Subject: Gate %s offline\r\nMIME-Version: 1.0\r\n" - "Content-Type: text/plain; charset=UTF-8\r\n" - "Content-Transfer-Encoding: 8bit\r\n\r\n" - "Gate %s has stopped reporting for at least %d seconds.\r\n", - watch->smtp_from, watch->smtp_to, date, message_id, gate->id, gate->id, - watch->alert_after_seconds); + int n = snprintf(message, sizeof message, + "From: <%s>\r\nTo: <%s>\r\nDate: %s\r\nMessage-ID: %s\r\n" + "Subject: %s\r\nMIME-Version: 1.0\r\n" + "Content-Type: text/plain; charset=UTF-8\r\n" + "Content-Transfer-Encoding: 8bit\r\n\r\n" + "%s\r\n", + watch->smtp_from, watch->smtp_to, date, message_id, subject, body); if (n < 0 || (size_t)n >= sizeof message) return -1; CURL *curl = curl_easy_init(); @@ -223,6 +237,102 @@ static int send_alert(gate_watch *watch, const gate_alert_entry *gate, time_t no curl_easy_cleanup(curl); return result == CURLE_OK ? 0 : -1; } +static void state_result(gate_watch *watch, int result) { + if (result != 0 && !watch->state_failed) + gate_log("ERROR", "mail_state", "state=failed"); + if (result == 0 && watch->state_failed) + gate_log("INFO", "mail_state", "state=recovered"); + watch->state_failed = result != 0; +} + +/* A shell cannot read a portable monotonic clock. Both processes share this wall clock. */ +static void check_uplink(gate_watch *watch, time_t now) { + if (!watch->uplink_heartbeat_file[0]) + return; + struct stat heartbeat; + time_t latest = watch->started; + if (stat(watch->uplink_heartbeat_file, &heartbeat) == 0 && heartbeat.st_mtime > latest) + latest = heartbeat.st_mtime; + gate_alert_entry *entry = &watch->uplink_watcher; + if (now - latest < watch->alert_after_seconds) { + /* A restart's grace alone is not recovery from a persisted incident. */ + if (latest > watch->started && (entry->seen || entry->incident || entry->sent)) { + entry->seen = entry->incident = 0; + entry->sent = entry->smtp_failed = 0; + state_result(watch, save_state(watch)); + } + } else if (!entry->seen) { + entry->seen = latest; + state_result(watch, save_state(watch)); + } +} + +static int submit_entry(gate_watch *watch, gate_alert_entry *entry, int kind, time_t now) { + if ((kind && !entry->seen) || now - entry->seen < watch->alert_after_seconds || entry->sent || + entry->sending) + return 0; + if (!entry->incident) { + entry->incident = now; + if (save_state(watch) != 0) { + state_result(watch, -1); + entry->incident = 0; + return 0; + } + state_result(watch, 0); + } + char subject[128], body[256], message_id[160]; + if (kind == 0) { + (void)snprintf(subject, sizeof subject, "Gate %s offline", entry->id); + (void)snprintf(body, sizeof body, "Gate %s has stopped reporting for at least %d seconds.", + entry->id, watch->alert_after_seconds); + (void)snprintf(message_id, sizeof message_id, "", entry->id, + (long long)entry->incident); + } else { + const char *name = kind == 1 ? "data-centre" : "uplink-watcher"; + (void)snprintf(subject, sizeof subject, "%s", + kind == 1 ? "Data centre unreachable" : "Uplink watcher stopped"); + (void)snprintf(body, sizeof body, + kind == 1 ? "The hub has not reached the data centre for at least %d " + "seconds." + : "The uplink watcher has not reported for at least %d seconds.", + watch->alert_after_seconds); + (void)snprintf(message_id, sizeof message_id, "<%s-%lld@hub.venue.lan>", name, + (long long)entry->incident); + } + gate_alert_entry snapshot = *entry; + entry->sending = 1; + (void)pthread_mutex_unlock(&watch->lock); + int submitted = send_alert(watch, subject, body, message_id, now) == 0; + if (pthread_mutex_lock(&watch->lock) != 0) + return -1; + const char *label = kind == 1 ? "data_centre" : "uplink_watcher"; + if (entry->incident == snapshot.incident && !submitted && !entry->smtp_failed) { + if (kind == 0) + gate_log("ERROR", "mail_alert", "gate=%s state=failed reason=submit", entry->id); + else + gate_log("ERROR", "mail_alert", "alert=%s state=failed reason=submit", label); + entry->smtp_failed = 1; + } + if (entry->incident == snapshot.incident && submitted) { + entry->smtp_failed = 0; + entry->sent = 1; + if (save_state(watch) != 0) { + state_result(watch, -1); + entry->sent = 0; + } else { + if (kind == 0) + gate_log("INFO", "mail_alert", "gate=%s state=sent incident=%lld", entry->id, + (long long)entry->incident); + else + gate_log("INFO", "mail_alert", "alert=%s state=sent incident=%lld", label, + (long long)entry->incident); + state_result(watch, 0); + } + } + entry->sending = 0; + return 0; +} + static void *watch_loop(void *context) { gate_watch *watch = context; if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) { @@ -234,51 +344,15 @@ static void *watch_loop(void *context) { time_t now = time(NULL); if (now == (time_t)-1 || pthread_mutex_lock(&watch->lock) != 0) continue; - for (size_t i = 0; i < watch->count; ++i) { - gate_alert_entry *gate = &watch->gates[i]; - if (now - gate->seen < watch->alert_after_seconds || gate->sent || gate->sending) - continue; - if (!gate->incident) { - gate->incident = now; - if (save_state(watch) != 0) { - if (!watch->state_failed) - gate_log("ERROR", "mail_state", "state=failed"); - watch->state_failed = 1; - gate->incident = 0; - continue; - } - if (watch->state_failed) - gate_log("INFO", "mail_state", "state=recovered"); - watch->state_failed = 0; - } - gate_alert_entry snapshot = *gate; - gate->sending = 1; - (void)pthread_mutex_unlock(&watch->lock); - int submitted = send_alert(watch, &snapshot, now) == 0; - if (pthread_mutex_lock(&watch->lock) != 0) + check_uplink(watch, now); + for (size_t i = 0; i < watch->count; ++i) + if (submit_entry(watch, &watch->gates[i], 0, now) != 0) return NULL; - if (gate->incident == snapshot.incident && !submitted && !gate->smtp_failed) { - gate_log("ERROR", "mail_alert", "gate=%s state=failed reason=submit", gate->id); - gate->smtp_failed = 1; - } - if (gate->incident == snapshot.incident && submitted) { - gate->smtp_failed = 0; - gate->sent = 1; - if (save_state(watch) != 0) { - if (!watch->state_failed) - gate_log("ERROR", "mail_state", "state=failed"); - watch->state_failed = 1; - gate->sent = 0; - } else { - gate_log("INFO", "mail_alert", "gate=%s state=sent incident=%lld", gate->id, - (long long)gate->incident); - if (watch->state_failed) - gate_log("INFO", "mail_state", "state=recovered"); - watch->state_failed = 0; - } - } - gate->sending = 0; - } + if (watch->dc_known && submit_entry(watch, &watch->data_centre, 1, now) != 0) + return NULL; + if (watch->uplink_heartbeat_file[0] && + submit_entry(watch, &watch->uplink_watcher, 2, now) != 0) + return NULL; (void)pthread_mutex_unlock(&watch->lock); } } @@ -289,6 +363,13 @@ int gate_watch_start(gate_watch *watch, const char *config_path) { if (load_config(watch, config_path ? config_path : "/etc/gatepost/hub.conf") != 0 || load_state(watch) != 0) return -1; + if (!watch->data_centre.id[0]) + memcpy(watch->data_centre.id, ":data-centre", sizeof ":data-centre"); + if (!watch->uplink_watcher.id[0]) + memcpy(watch->uplink_watcher.id, ":uplink-watcher", sizeof ":uplink-watcher"); + watch->started = time(NULL); + if (watch->uplink_heartbeat_file[0] && !watch->uplink_watcher.sent) + watch->uplink_watcher.seen = watch->started; pthread_t thread; int rc = pthread_create(&thread, NULL, watch_loop, watch); if (rc) { @@ -324,11 +405,28 @@ int gate_watch_seen(gate_watch *watch, const char *gate_id) { gate->sent = 0; gate->smtp_failed = 0; int result = save_state(watch); - if (result != 0 && !watch->state_failed) - gate_log("ERROR", "mail_state", "state=failed"); - if (result == 0 && watch->state_failed) - gate_log("INFO", "mail_state", "state=recovered"); - watch->state_failed = result != 0; + state_result(watch, result); + (void)pthread_mutex_unlock(&watch->lock); + return result; +} +int gate_watch_dc(gate_watch *watch, int connected) { + if (pthread_mutex_lock(&watch->lock) != 0) + return -1; + gate_alert_entry *entry = &watch->data_centre; + int first = !watch->dc_known; + watch->dc_known = 1; + int changed = 0; + if (connected) { + changed = entry->seen || entry->incident || entry->sent; + entry->seen = entry->incident = 0; + entry->sent = entry->smtp_failed = 0; + } else if (!entry->seen || (first && !entry->sent)) { + entry->seen = time(NULL); + changed = 1; + } + int result = changed ? save_state(watch) : 0; + if (changed) + state_result(watch, result); (void)pthread_mutex_unlock(&watch->lock); return result; } diff --git a/gate-hub/alert.h b/gate-hub/alert.h index 9803a9e..00ce298 100644 --- a/gate-hub/alert.h +++ b/gate-hub/alert.h @@ -15,12 +15,17 @@ typedef struct { typedef struct { pthread_mutex_t lock; gate_alert_entry gates[GATE_WATCH_LIMIT]; + gate_alert_entry data_centre, uplink_watcher; size_t count; char smtp_url[256], smtp_ca[256], smtp_from[128], smtp_to[128]; char smtp_user[128], smtp_password[128], state_file[256]; + char uplink_heartbeat_file[256]; + time_t started; int alert_after_seconds; int state_failed; + int dc_known; } gate_watch; int gate_watch_start(gate_watch *watch, const char *config_path); int gate_watch_seen(gate_watch *watch, const char *gate_id); +int gate_watch_dc(gate_watch *watch, int connected); #endif diff --git a/gate-hub/dc_probe.c b/gate-hub/dc_probe.c index 65ca6fc..83da9d5 100644 --- a/gate-hub/dc_probe.c +++ b/gate-hub/dc_probe.c @@ -1,5 +1,6 @@ #define _POSIX_C_SOURCE 200809L #include "../libgate/log.h" +#include "alert.h" #include "dc_dns.h" #include "sync.h" #include @@ -166,8 +167,8 @@ static void log_dns_event(dc_dns_event event, size_t count) { } } -static void *probe(void *unused) { - (void)unused; +static void *probe(void *context) { + gate_watch *watch = context; struct sockaddr_in *addresses = NULL; size_t count = 0; time_t resolved_at = 0; @@ -196,6 +197,8 @@ static void *probe(void *unused) { addresses = NULL; count = 0; refresh = true; + if (watch) + (void)gate_watch_dc(watch, 0); sleep(3); continue; } @@ -222,6 +225,8 @@ static void *probe(void *unused) { gate_log("WARN", "dc_link", "state=failed"); connection_known = true; was_connected = connected; + if (watch) + (void)gate_watch_dc(watch, connected); if (!connected) refresh = true; sleep(3); @@ -230,7 +235,7 @@ static void *probe(void *unused) { return NULL; } -int dc_probe_start(void) { +int dc_probe_start(gate_watch *watch) { pthread_condattr_t attr; int rc = pthread_condattr_init(&attr); if (rc == 0) { @@ -244,7 +249,7 @@ int dc_probe_start(void) { return -1; } pthread_t thread; - rc = pthread_create(&thread, NULL, probe, NULL); + rc = pthread_create(&thread, NULL, probe, watch); if (rc) { errno = rc; return -1; diff --git a/gate-hub/main.c b/gate-hub/main.c index dcd2659..a8ee238 100644 --- a/gate-hub/main.c +++ b/gate-hub/main.c @@ -836,7 +836,7 @@ static void *pool_worker(void *argument) { return NULL; } -int dc_probe_start(void); +int dc_probe_start(gate_watch *watch); int status_start(const char *path, SSL_CTX *context); int hub_sync_start(void); void status_set_duplicates(unsigned count); @@ -905,7 +905,8 @@ int main(int argc, char **argv) { gate_log_errno("hub_sync_start"); goto finish; } - if (getenv("GATEPOST_DC_PROBE") && dc_probe_start() != 0) { + if (getenv("GATEPOST_DC_PROBE") && + dc_probe_start(getenv("GATEPOST_ALERTS") ? &owner.watch : NULL) != 0) { gate_log_errno("dc_probe_start"); goto finish; } diff --git a/lab/README.md b/lab/README.md index 48fd371..8e29758 100644 --- a/lab/README.md +++ b/lab/README.md @@ -144,7 +144,7 @@ what this routing lab shows with `192.0.2.130`. The hub learns gate identities from framed `HELLO` messages rather than source IP. If a known gate stops reporting for ten seconds, the hub submits an alert through Mailpit with STARTTLS. Run `sh lab/mail-alert.sh` to stop Gate 1, capture the SMTP exchange and check Mailpit's message API. Mailpit is a local submission and viewing service; the venue manager would read delivered mail through their own mail client. -Run `sh lab/dc-alert.sh` alone to cut the data-centre-facing interfaces on both routers, then restore them and kill the hub's uplink watcher. Each case expects exactly one mail to `manager@elsworne.example` from `alerts@elsworne.example`, with subject `Data centre unreachable` or `Uplink watcher stopped` respectively, through the venue's own mail server, which does not depend on the data-centre link. Like the gate-offline alert, each is sent once when the fault begins, with no recovery mail; read the dashboard for recovery. The 20-second window allows up to 5 seconds for the data-centre probe (2-second connect timeout plus 3-second pause; the recorded outage took 3.3 seconds to detect), a watcher check every second, the `alert_after_seconds=10` threshold in [hub.conf](hub.conf) shared with the gate-offline alert, a one-second alert loop and 4 seconds for mail submission as in `lab/mail-alert.sh`: 5 + 10 + 1 + 4 = 20. The drill exits 0 if both alerts arrive once, 1 for failed judgements and 2 for an environment mismatch or cleanup failure; cleanup removes its router rules, restarts the hub and checks that the data-centre link and one watcher have returned. +Run `sh lab/dc-alert.sh` alone to cut the data-centre-facing interfaces on both routers, then restore them and kill the hub's uplink watcher. Each case expects exactly one mail to `manager@elsworne.example` from `alerts@elsworne.example`, with subject `Data centre unreachable` or `Uplink watcher stopped` respectively, through the venue's own mail server, which does not depend on the data-centre link. Like the gate-offline alert, each is sent once after the shared `alert_after_seconds` threshold, with no recovery mail; recovery re-arms it, and `state_file` preserves sent incidents across hub restarts. The watcher writes `/tmp/gatepost-uplink.heartbeat` each loop and [hub.conf](hub.conf) sets `uplink_heartbeat_file` to that path. The watcher takes the path from `GATEPOST_UPLINK_HEARTBEAT` in `compose.yaml`; the two settings must name the same file, or the hub reports `Uplink watcher stopped` one threshold after it starts. The file modification time is its heartbeat because a shell cannot read a portable monotonic clock and both processes share the same wall clock in the hub container; a hub restart gives a new threshold of grace. Submission logs use `event=mail_alert alert=data_centre state=failed/sent` and `alert=uplink_watcher state=failed/sent`; read the dashboard for recovery. The 20-second window allows up to 5 seconds for the data-centre probe (2-second connect timeout plus 3-second pause; the recorded outage took 3.3 seconds to detect), a watcher check every second, the `alert_after_seconds=10` threshold in [hub.conf](hub.conf) shared with the gate-offline alert, a one-second alert loop and 4 seconds for mail submission as in `lab/mail-alert.sh`: 5 + 10 + 1 + 4 = 20. The drill exits 0 if both alerts arrive once, 1 for failed judgements and 2 for an environment mismatch or cleanup failure; cleanup removes its router rules, restarts the hub and checks that the data-centre link and one watcher have returned. The lab uses [hub.conf](hub.conf). For a deployment, copy [config/hub.conf.example](../config/hub.conf.example) to `/etc/gatepost/hub.conf`, set the SMTP URL, recipient, sender, CA certificate path, and state file path, and point `GATEPOST_HUB_CONFIG` to it if using another location. Set `smtp_user` and `smtp_password_file` for authenticated submission. Put the password in the referenced file with restricted permissions; never put it in the config. The hub atomically writes its alert state to `state_file`; keep that directory persistent and writable. An uncertain SMTP submission reply can cause a retry with the same stable `Message-ID`. SMTP submission cannot provide exactly-once delivery, so the recipient system should de-duplicate by `Message-ID`. diff --git a/lab/README.zh-CN.md b/lab/README.zh-CN.md index b72b527..70b7fde 100644 --- a/lab/README.zh-CN.md +++ b/lab/README.zh-CN.md @@ -136,7 +136,7 @@ curl 状态 28 超时,光纤接入的丢包计数也须增加:回包仍按 hub 从有 frame 的 `HELLO` 消息获取闸机身份,不依靠来源 IP。若已知闸机十秒未报告,hub 通过 STARTTLS 向 Mailpit 提交告警。运行 `sh lab/mail-alert.sh` 停止 Gate 1、抓取 SMTP 交换并检查 Mailpit 消息 API。Mailpit 是本地提交与查看服务;场馆经理通过自己的邮件客户端读取已投递的邮件。 -请单独运行 `sh lab/dc-alert.sh`:脚本先切断两台路由器朝数据中心的接口,再恢复连接并强制终止 hub 的出口监视进程。每种故障都应在 20 秒内通过场馆自己的邮件服务器,分别以 `Data centre unreachable` 和 `Uplink watcher stopped` 为主题,从 `alerts@elsworne.example` 向 `manager@elsworne.example` 恰好发出一封邮件;这条通知路径不依赖数据中心链路。这两类告警和闸机离线告警一样,只在故障开始时发一封,不发恢复邮件,恢复与否看面板。20 秒由数据中心探测最多 5 秒(连接超时 2 秒、轮次间暂停 3 秒;事故记录为 3.3 秒)、监视进程每秒检查一次、[hub.conf](hub.conf) 中与闸机离线告警相同的 `alert_after_seconds=10` 阈值、告警循环每秒检查一次,以及 `lab/mail-alert.sh` 为提交邮件预留的 4 秒相加而得:5 + 10 + 1 + 4 = 20。两项均恰好收到一封邮件时以 0 退出,判定失败以 1 退出,环境不符或收尾失败以 2 退出;收尾会删除脚本添加的路由器规则,重启 hub,并检查数据中心链路恢复及恰有一个监视进程运行。 +请单独运行 `sh lab/dc-alert.sh`:脚本先切断两台路由器朝数据中心的接口,再恢复连接并强制终止 hub 的出口监视进程。每种故障都应在 20 秒内通过场馆自己的邮件服务器,分别以 `Data centre unreachable` 和 `Uplink watcher stopped` 为主题,从 `alerts@elsworne.example` 向 `manager@elsworne.example` 恰好发出一封邮件;这条通知路径不依赖数据中心链路。这两类告警和闸机离线告警一样,在故障持续达到共同的 `alert_after_seconds` 阈值后每次只发一封,不发恢复邮件;恢复后重新布防,`state_file` 会保留已发送的故障记录,hub 重启也不会重复发送。监视脚本每轮更新 `/tmp/gatepost-uplink.heartbeat`,[hub.conf](hub.conf) 的 `uplink_heartbeat_file` 指向此文件。脚本从 `compose.yaml` 里的 `GATEPOST_UPLINK_HEARTBEAT` 读这个路径;两处必须指向同一个文件,否则 hub 启动一个阈值时长之后就会报 `Uplink watcher stopped`。shell 无法以可移植的方法读取单调时钟,而脚本和 hub 在同一个容器中共用系统时钟,所以用文件修改时间作心跳;hub 重启后重新给予一个阈值时长的宽限期。提交邮件时分别记录 `event=mail_alert alert=data_centre state=failed/sent` 和 `alert=uplink_watcher state=failed/sent`;恢复与否看面板。20 秒由数据中心探测最多 5 秒(连接超时 2 秒、轮次间暂停 3 秒;事故记录为 3.3 秒)、监视进程每秒检查一次、[hub.conf](hub.conf) 中与闸机离线告警相同的 `alert_after_seconds=10` 阈值、告警循环每秒检查一次,以及 `lab/mail-alert.sh` 为提交邮件预留的 4 秒相加而得:5 + 10 + 1 + 4 = 20。两项均恰好收到一封邮件时以 0 退出,判定失败以 1 退出,环境不符或收尾失败以 2 退出;收尾会删除脚本添加的路由器规则,重启 hub,并检查数据中心链路恢复及恰有一个监视进程运行。 实验环境使用 [hub.conf](hub.conf)。部署时把 [config/hub.conf.example](../config/hub.conf.example) 复制到 `/etc/gatepost/hub.conf`,设置 SMTP URL、收件人、发件人、CA 证书路径和状态文件路径;若放在其他位置,用 `GATEPOST_HUB_CONFIG` 指向它。认证提交时设置 `smtp_user` 和 `smtp_password_file`。将密码放在被引用且权限受限的文件里,不要写进配置。hub 原子写入 `state_file`;其目录必须可写并持久保存。若 SMTP 提交回复不确定,hub 可能以同一个稳定的 `Message-ID` 重试。SMTP 提交无法保证 exactly-once 投递,接收系统应按 `Message-ID` 去重。 diff --git a/lab/compose.yaml b/lab/compose.yaml index 15214f1..b3d39ec 100644 --- a/lab/compose.yaml +++ b/lab/compose.yaml @@ -74,6 +74,7 @@ services: - GATEPOST_LISTEN_ALL=1 - GATEPOST_DC_PROBE=1 - GATEPOST_ALERTS=1 + - GATEPOST_UPLINK_HEARTBEAT=/tmp/gatepost-uplink.heartbeat - GATEPOST_STATUS=1 - GATEPOST_STATUS_BIND=10.77.20.10 - GATEPOST_STATUS_HOSTS=hub.venue.lan,hub.venue.lan:8081,10.77.20.10:8081,127.0.0.1:8081,localhost:8081 diff --git a/lab/hub.conf b/lab/hub.conf index 1dab716..6113e06 100644 --- a/lab/hub.conf +++ b/lab/hub.conf @@ -4,3 +4,4 @@ smtp_from=alerts@elsworne.example smtp_to=manager@elsworne.example state_file=/var/lib/gatepost/alerts.state alert_after_seconds=10 +uplink_heartbeat_file=/tmp/gatepost-uplink.heartbeat diff --git a/lab/uplink-watch.sh b/lab/uplink-watch.sh index f2bc59c..bdc02df 100755 --- a/lab/uplink-watch.sh +++ b/lab/uplink-watch.sh @@ -93,7 +93,15 @@ fi thresholds="failures_to_switch=$failures_to_switch successes_to_return=$successes_to_return" printf 'time=%s level=INFO event=uplink state=fibre %s interval_ms=%s\n' \ "$(date +%s%6N)" "$thresholds" "$interval_ms" >&2 +heartbeat() { + [ "${GATEPOST_UPLINK_HEARTBEAT+x}" = x ] || return 0 + stage=heartbeat_failed + # A shell has no portable monotonic clock; the hub shares this wall clock. + : > "$GATEPOST_UPLINK_HEARTBEAT" +} +heartbeat while :; do + heartbeat if [ "$interval_ms" -gt 0 ]; then stage=clock_failed started_ms=$(date +%s%3N) diff --git a/tests/test_dc_alerts.py b/tests/test_dc_alerts.py new file mode 100644 index 0000000..61aa602 --- /dev/null +++ b/tests/test_dc_alerts.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +"""Check data-centre and watcher mail, recovery, and saved incidents.""" +import os +import re +import socket +import ssl +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +BINARY = sys.argv[1] +FROM = b'From: ' +TO = b'To: ' + + +def wait_for(predicate, timeout=15): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(.1) + assert predicate(), 'timed out waiting for condition' + + +class Smtp: + def __init__(self, cert, key): + self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + self.context.load_cert_chain(str(cert), str(key)) + self.listener = socket.socket() + self.listener.bind(('127.0.0.1', 0)) + self.listener.listen(4) + self.listener.settimeout(.2) + self.messages = [] + self.stop = threading.Event() + self.thread = threading.Thread(target=self.serve, daemon=True) + self.thread.start() + + def serve(self): + while not self.stop.is_set(): + try: + connection, _ = self.listener.accept() + except socket.timeout: + continue + except OSError: + break + stream = None + try: + connection.settimeout(5) + stream = connection.makefile('rwb', buffering=0) + stream.write(b'220 localhost test smtp\r\n') + encrypted = False + while True: + command = stream.readline() + if not command: + break + if command.startswith(b'EHLO'): + stream.write(b'250-localhost\r\n250 SIZE 100000\r\n' if encrypted else + b'250-localhost\r\n250-STARTTLS\r\n250 SIZE 100000\r\n') + elif command.startswith(b'STARTTLS'): + stream.write(b'220 Go ahead\r\n') + stream.close() + connection = self.context.wrap_socket(connection, server_side=True) + stream = connection.makefile('rwb', buffering=0) + encrypted = True + elif command.startswith((b'MAIL FROM:', b'RCPT TO:')): + assert encrypted + stream.write(b'250 OK\r\n') + elif command.startswith(b'DATA'): + stream.write(b'354 Send data\r\n') + data = bytearray() + while True: + chunk = stream.readline() + if chunk == b'.\r\n': + break + data.extend(chunk) + self.messages.append(bytes(data)) + stream.write(b'250 queued\r\n') + elif command.startswith(b'QUIT'): + stream.write(b'221 bye\r\n') + break + else: + raise AssertionError(command) + except (EOFError, OSError): + pass + finally: + if stream: + stream.close() + connection.close() + + def count(self, subject): + return sum(b'Subject: ' + subject.encode() in message for message in self.messages) + + def check(self, subject, expected): + selected = [message for message in self.messages + if b'Subject: ' + subject.encode() in message] + assert len(selected) == expected, (subject, expected, self.messages) + assert all(FROM in message and TO in message for message in selected) + ids = [re.search(rb'^Message-ID: ([^\r\n]+)\r?$', message, re.M).group(1) + for message in selected] + assert len(ids) == len(set(ids)), ids + prefix = b'data-centre' if subject == 'Data centre unreachable' else b'uplink-watcher' + assert all(re.fullmatch(rb'<' + prefix + rb'-[0-9]+@hub\.venue\.lan>', item) + for item in ids), ids + + def close(self): + self.stop.set() + self.listener.close() + self.thread.join(timeout=2) + + +class DcListener: + def __init__(self): + self.listener = socket.socket() + self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.listener.bind(('127.0.0.1', 8080)) + self.listener.listen(8) + self.listener.settimeout(.2) + self.stop = threading.Event() + self.thread = threading.Thread(target=self.serve, daemon=True) + self.thread.start() + + def serve(self): + while not self.stop.is_set(): + try: + connection, _ = self.listener.accept() + connection.close() + except socket.timeout: + continue + except OSError: + break + + def close(self): + self.stop.set() + self.listener.close() + self.thread.join(timeout=2) + + +with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cert, key = root / 'cert.pem', root / 'key.pem' + subprocess.run(['openssl', 'req', '-x509', '-nodes', '-newkey', 'rsa:2048', + '-days', '1', '-subj', '/CN=localhost', + '-addext', 'subjectAltName=DNS:localhost', + '-keyout', str(key), '-out', str(cert)], check=True, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + smtp = Smtp(cert, key) + state, config = root / 'alerts.state', root / 'hub.conf' + heartbeat = root / 'uplink.heartbeat' + tickets = root / 'tickets.txt' + tickets.write_text('GP-000000000000\n') + with socket.socket() as reserved: + reserved.bind(('127.0.0.1', 0)) + hub_port = reserved.getsockname()[1] + log = root / 'hub.log' + log_file = log.open('wb') + env = dict(os.environ, GATEPOST_ALERTS='1', GATEPOST_DC_PROBE='1', + GATEPOST_DC_HOST='127.0.0.1', GATEPOST_HUB_CONFIG=str(config)) + process = None + dc = None + beat_stop = threading.Event() + beat_thread = None + + def configure(watcher): + config.write_text(f'smtp_url=smtp://localhost:{smtp.listener.getsockname()[1]}\n' + f'smtp_ca={cert}\n' + 'smtp_from=alerts@elsworne.example\n' + 'smtp_to=manager@elsworne.example\n' + f'state_file={state}\nalert_after_seconds=5\n' + + (f'uplink_heartbeat_file={heartbeat}\n' if watcher else '')) + + def start_hub(): + process = subprocess.Popen([BINARY, str(tickets), str(hub_port), 'pool'], + env=env, stdout=subprocess.PIPE, stderr=log_file) + assert process.stdout.readline().startswith(b'listening=') + process.stdout.close() + return process + + def stop_hub(): + global process + process.terminate() + process.wait(timeout=4) + + def logs_contain(text): + return text in log.read_text() + + def beats(): + while not beat_stop.is_set(): + heartbeat.touch() + beat_stop.wait(.5) + + def start_beats(): + global beat_thread + beat_stop.clear() + beat_thread = threading.Thread(target=beats, daemon=True) + beat_thread.start() + + def stop_beats(): + beat_stop.set() + beat_thread.join(timeout=2) + + try: + configure(True) + dc = DcListener() + start_beats() + process = start_hub() + wait_for(lambda: logs_contain('event=dc_link state=connected'), 10) + time.sleep(6) + smtp.check('Uplink watcher stopped', 0) + + # A failed probe round followed by recovery before five seconds is transient. + dc.close() + dc = None + wait_for(lambda: logs_contain('event=dc_link state=failed'), 8) + dc = DcListener() + wait_for(lambda: log.read_text().count('event=dc_link state=connected') >= 2, 8) + smtp.check('Data centre unreachable', 0) + + dc.close() + dc = None + wait_for(lambda: smtp.count('Data centre unreachable') == 1, 12) + wait_for(lambda: log.read_text().count('event=mail_alert alert=data_centre state=sent') == 1, 10) + time.sleep(11) + smtp.check('Data centre unreachable', 1) + dc = DcListener() + wait_for(lambda: log.read_text().count('event=dc_link state=connected') >= 3, 8) + dc.close() + dc = None + wait_for(lambda: smtp.count('Data centre unreachable') == 2, 12) + wait_for(lambda: log.read_text().count('event=mail_alert alert=data_centre state=sent') == 2, 10) + smtp.check('Data centre unreachable', 2) + dc = DcListener() + wait_for(lambda: log.read_text().count('event=dc_link state=connected') >= 4, 8) + + stop_beats() + wait_for(lambda: smtp.count('Uplink watcher stopped') == 1, 10) + wait_for(lambda: log.read_text().count('event=mail_alert alert=uplink_watcher state=sent') == 1, 10) + time.sleep(11) + smtp.check('Uplink watcher stopped', 1) + start_beats() + wait_for(lambda: ':uplink-watcher 0 0 0' in state.read_text(), 4) + stop_beats() + wait_for(lambda: smtp.count('Uplink watcher stopped') == 2, 10) + wait_for(lambda: log.read_text().count('event=mail_alert alert=uplink_watcher state=sent') == 2, 10) + smtp.check('Uplink watcher stopped', 2) + + stop_hub() + configure(False) + heartbeat.unlink(missing_ok=True) + process = start_hub() + time.sleep(7) + smtp.check('Uplink watcher stopped', 2) + + stop_hub() + configure(True) + start_beats() + process = start_hub() + wait_for(lambda: ':uplink-watcher 0 0 0' in state.read_text(), 5) + dc.close() + dc = None + wait_for(lambda: smtp.count('Data centre unreachable') == 3, 12) + wait_for(lambda: log.read_text().count('event=mail_alert alert=data_centre state=sent') == 3, 10) + stop_hub() + process = start_hub() + time.sleep(11) + smtp.check('Data centre unreachable', 3) + stop_beats() + stop_hub() + heartbeat.unlink(missing_ok=True) + process = start_hub() + time.sleep(2) + smtp.check('Uplink watcher stopped', 2) + wait_for(lambda: smtp.count('Uplink watcher stopped') == 3, 10) + wait_for(lambda: log.read_text().count('event=mail_alert alert=uplink_watcher state=sent') == 3, 10) + smtp.check('Uplink watcher stopped', 3) + smtp.check('Data centre unreachable', 3) + wait_for(lambda: log.read_text().count('event=mail_alert alert=data_centre state=sent') == 3) + wait_for(lambda: log.read_text().count('event=mail_alert alert=uplink_watcher state=sent') == 3) + finally: + if process and process.poll() is None: + process.terminate() + process.wait(timeout=4) + if beat_thread and beat_thread.is_alive(): + stop_beats() + if dc: + dc.close() + smtp.close() + log_file.close()