diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..67bf90a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,44 @@ +name: Release +on: + push: + tags: ['v*'] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false +jobs: + packages-and-images: + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - name: Build pinned tool image + run: docker build -f Dockerfile.build -t gatepost-build:current . + - name: Build, test and package + run: | + docker run --rm --security-opt seccomp=unconfined -v "$PWD:/src" -w /src gatepost-build:current sh -c ' + cmake --preset release && cmake --build --preset release && ctest --preset release --output-on-failure && + cmake --install build/release --prefix /tmp/gatepost-stage && + cpack --config build/release/CPackConfig.cmake -G DEB -B build/packages' + - name: Build lab image + run: docker build -f lab/Dockerfile -t gatepost-venue:release . + - name: Generate package SBOM with Syft 1.55.0 + run: | + docker run --rm -v "$PWD:/work" -w /work ghcr.io/anchore/syft:v1.55.0@sha256:4cc92b64ca74ffca4c94d4c8fcc01f217731375300be14d0b6eeb2e82eaa110a \ + dir:build/packages -o spdx-json=/work/build/packages.spdx.json + - name: Scan build and lab images with Trivy 0.71.1 + run: | + for image in gatepost-build:current gatepost-venue:release; do + docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v "$PWD:/work" \ + ghcr.io/aquasecurity/trivy:0.71.1@sha256:53570e6911c2361ebe7995228088cf83a6b9b73e7f3cdca44bd8f8f425e80fa7 \ + image --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 "$image" + done + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: gatepost-debian-and-sbom + path: | + build/packages/*.deb + build/packages.spdx.json + if-no-files-found: error diff --git a/CMakeLists.txt b/CMakeLists.txt index bddf1a5..5200229 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -65,7 +65,7 @@ endif() find_package(Threads REQUIRED) set(GATE_HUB_SOURCES gate-hub/main.c gate-hub/admission.c gate-hub/metrics.c gate-hub/prometheus.c gate-hub/dc_probe.c gate-hub/alert.c gate-hub/sync.c - gate-hub/status.c gate-hub/reports.c gate-hub/tls.c) + gate-hub/status.c gate-hub/reports.c gate-hub/tls.c gate-hub/queue.c) foreach(target gate-hub gate-hub-test) add_executable(${target} ${GATE_HUB_SOURCES}) target_link_libraries(${target} PRIVATE gate gate_security gate_ticket_signature Threads::Threads) @@ -283,5 +283,33 @@ 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 hub_season_reload hub_served_list hub_tickets_send_change monitoring_config dc_alerts +add_test(NAME status_tls_workers COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/tests/test_status_tls_workers.py $) +set_tests_properties(status_tls_workers PROPERTIES TIMEOUT 120) +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 status_tls_workers sync_metrics hub_season_reload hub_served_list hub_tickets_send_change monitoring_config dc_alerts PROPERTIES RESOURCE_LOCK status_ports) + +install(TARGETS gated RUNTIME DESTINATION usr/bin COMPONENT gate) +install(TARGETS gate-hub RUNTIME DESTINATION usr/bin COMPONENT hub) +install(PROGRAMS packaging/run-gated.sh DESTINATION usr/lib/gatepost RENAME run-gated COMPONENT gate) +install(PROGRAMS packaging/run-gate-hub.sh DESTINATION usr/lib/gatepost RENAME run-gate-hub COMPONENT hub) +install(FILES packaging/gated.service DESTINATION usr/lib/systemd/system COMPONENT gate) +install(FILES packaging/gate-hub.service DESTINATION usr/lib/systemd/system COMPONENT hub) +install(FILES config/gated.env.example DESTINATION etc/gatepost RENAME gated.env COMPONENT gate) +install(FILES config/gate-hub.env.example DESTINATION etc/gatepost RENAME gate-hub.env COMPONENT hub) +install(FILES config/hub.conf.example DESTINATION etc/gatepost RENAME hub.conf COMPONENT hub) + +set(CPACK_GENERATOR DEB) +set(CPACK_PACKAGING_INSTALL_PREFIX "/") +set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) +set(CPACK_PACKAGE_CONTACT "Gatepost maintainers ") +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Gatepost venue admission services") +set(CPACK_DEB_COMPONENT_INSTALL ON) +set(CPACK_COMPONENTS_ALL gate hub) +set(CPACK_DEBIAN_GATE_PACKAGE_NAME gatepost-gated) +set(CPACK_DEBIAN_HUB_PACKAGE_NAME gatepost-gate-hub) +set(CPACK_DEBIAN_GATE_PACKAGE_DEPENDS "adduser, libc6, libcurl4, libssl3, libsodium23, libgpiod2, libsystemd0") +set(CPACK_DEBIAN_HUB_PACKAGE_DEPENDS "adduser, libc6, libcurl4, libssl3, libsodium23") +set(CPACK_DEBIAN_GATE_PACKAGE_CONTROL_EXTRA "${CMAKE_SOURCE_DIR}/packaging/postinst;${CMAKE_SOURCE_DIR}/packaging/gate-control/conffiles") +set(CPACK_DEBIAN_HUB_PACKAGE_CONTROL_EXTRA "${CMAKE_SOURCE_DIR}/packaging/postinst;${CMAKE_SOURCE_DIR}/packaging/hub-control/conffiles") +include(CPack) diff --git a/Dockerfile.build b/Dockerfile.build index 995eaba..74783ca 100644 --- a/Dockerfile.build +++ b/Dockerfile.build @@ -2,10 +2,10 @@ FROM debian:12.12-slim@sha256:d5d3f9c23164ea16f31852f95bd5959aad1c5e854332fe00f7 ENV DEBIAN_FRONTEND=noninteractive RUN rm -f /etc/apt/sources.list.d/debian.sources && \ printf 'deb [check-valid-until=no] %s bookworm main\n' \ - 'http://snapshot.debian.org/archive/debian/20260115T000000Z' \ + 'http://snapshot.debian.org/archive/debian/20261020T000000Z' \ > /etc/apt/sources.list && \ printf 'deb [check-valid-until=no] %s bookworm-security main\n' \ - 'http://snapshot.debian.org/archive/debian-security/20260115T000000Z' \ + 'http://snapshot.debian.org/archive/debian-security/20261020T000000Z' \ >> /etc/apt/sources.list && \ apt-get -o Acquire::Check-Valid-Until=false update && apt-get install -y --no-install-recommends \ build-essential \ diff --git a/README.md b/README.md index f06a454..3bc45f3 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ time=1775170804236133 level=WARN event=hub_link gate=north state=offline reason= time=1775170804235739 level=INFO event=hub_link gate=south state=online ``` +For device installation, build the separate Debian packages with CPack and configure the hardened systemd units as described in [packages and device setup](docs/operations/packages.md). The release workflow builds packages, emits a Syft SBOM, and scans build and lab images with Trivy. [Logging compatibility](docs/operations/logging.md) explains the journal and admission records. + Exit the container with `exit`. For lights and turnstile movement, use the team's separate `gatepost-sim` repository with the [simulator protocol](docs/device/simulator-protocol.md). ## Build and test @@ -73,7 +75,7 @@ A gate can load a mapped `.gpb` list only without public keys; signed mode refus ## Operating it -Tickets in this repository are synthetic; generate them with `tools/gen_tickets.py`. On a device, choose the scanner and outputs at startup. Standard output carries decisions and standard error carries device errors and, for each rejected scan, one `event=scan` line with the reason (see [rejection diagnostics](docs/security/ticket-signing.md#rejection-diagnostics)). The hub writes one `event=scan` line to standard error for each scan, with `time` (Unix microseconds), `level`, `gate`, `ticket` (or `length` for malformed input), `result` and `decision_us` (elapsed microseconds). It also logs `event=connection_open` and `event=connection_close` with the peer address; the gate is `unknown` until a `SCAN` identifies it. On ports 7000 and 8444, handshake failures log `event=tls_handshake state=failed reason= peer=
` and `event=status_client state=handshake_failed reason= peer=
`, respectively; a 7000 handshake deadline logs `state=timeout peer=
`. The address comes from the accepted connection. The same peer and reason on a listener produce one line until the reason changes or a handshake succeeds. Each listener remembers 64 peers, forgetting the oldest seen when full. A status connection that runs out of time logs `event=status_client state=timeout` with the peer address and `held_ms`. `event=admission_unlock_failed state=after_decision` reports a failed ticket mutex unlock, and `event=operation_failed` reports a failed system operation. `gated` writes one `event=hub_link` line to standard error when its hub link becomes `online` or `offline`, or the offline reason changes; offline reasons are `refused`, `timeout`, `resolver`, or the TLS reasons below. The resolver logs `event=hub_resolver` only when DNS changes between `failed` and `resolved`. All daemon diagnostics use space-separated `key=value` fields, `time` as Unix microseconds, and `level` and `event` fields. It does not repeat the line for scans while both state and reason are unchanged. A local decision still appears on standard output and in the optional scan log. An optional scan log path records `barcode=... result=...` (in signed mode, ` result=...` under the rejection-diagnostic rule above) on a buffered, long-lived file descriptor. Use `scripts/scan-syscalls.sh` and `scripts/scan-latency.sh` in the build container to inspect system calls and latency; see the [measurements](docs/perf/scan-syscalls.md). +Tickets in this repository are synthetic; generate them with `tools/gen_tickets.py`. On a device, choose the scanner and outputs at startup. Standard output carries decisions and standard error carries device errors and, for each rejected scan, one `event=scan` line with the reason (see [rejection diagnostics](docs/security/ticket-signing.md#rejection-diagnostics)). The hub writes one `event=scan` line to standard error for each scan, with `time` (Unix microseconds), `level`, `gate`, `ticket` (or `length` for malformed input), `result` and `decision_us` (elapsed microseconds). It also logs `event=connection_open` and `event=connection_close` with the peer address; the gate is `unknown` until a `SCAN` identifies it. On ports 7000 and 8444, handshake failures log `event=tls_handshake state=failed reason= peer=
` and `event=status_client state=handshake_failed reason= peer=
`, respectively; a 7000 handshake deadline logs `state=timeout peer=
`. The address comes from the accepted connection. The same peer and reason on a listener produce one line until the reason changes or a handshake succeeds. Each listener remembers 64 peers, forgetting the oldest seen when full. A status connection that runs out of time logs `event=status_client state=timeout` with the peer address and `held_ms`. A full 8444 queue logs `event=status_queue state=full peer=
` at most once per second. `event=admission_unlock_failed state=after_decision` reports a failed ticket mutex unlock, and `event=operation_failed` reports a failed system operation. `gated` writes one `event=hub_link` line to standard error when its hub link becomes `online` or `offline`, or the offline reason changes; offline reasons are `refused`, `timeout`, `resolver`, or the TLS reasons below. The resolver logs `event=hub_resolver` only when DNS changes between `failed` and `resolved`. All daemon diagnostics use space-separated `key=value` fields, `time` as Unix microseconds, and `level` and `event` fields. It does not repeat the line for scans while both state and reason are unchanged. A local decision still appears on standard output and in the optional scan log. An optional scan log path records `barcode=... result=...` (in signed mode, ` result=...` under the rejection-diagnostic rule above) on a buffered, long-lived file descriptor. Use `scripts/scan-syscalls.sh` and `scripts/scan-latency.sh` in the build container to inspect system calls and latency; see the [measurements](docs/perf/scan-syscalls.md). TLS failure reasons in the device link logs (see the [device-certificate renewal runbook](docs/runbooks/renew-device-certificate.md)): @@ -97,7 +99,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 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 the signed season list from `/season.txt` over port 8443 using its certificate; without device TLS it uses port 8080. Before switching decisions, it checks that SHA-256 matches the ETag, the complete list loads under the start-file rules, and the downloaded file and its directory were synced. `/tickets` and decisions use the same immutable in-memory list. A switch logs `event=season_list state=installed tickets= used= load_ms=`; a refused list logs `event=season_list state=rejected reason=digest` or `reason=load errno=` once per ETag and reason. The hub keeps its current list after a refusal and tries again on the next round. +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 8081 uses one thread for staff; port 8444 uses four workers and a queue of 16. The venue has four gates (gate1, gate2, north1, north2), each with at most one 8444 connection open at a time. A stuck gate holds one worker while the others can still be served; if the north link fails, its two gates hold at most two workers, leaving workers for both venue gates. Four stuck clients at once make others wait again. 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 the signed season list from `/season.txt` over port 8443 using its certificate; without device TLS it uses port 8080. Before switching decisions, it checks that SHA-256 matches the ETag, the complete list loads under the start-file rules, and the downloaded file and its directory were synced. `/tickets` and decisions use the same immutable in-memory list. A switch logs `event=season_list state=installed tickets= used= load_ms=`; a refused list logs `event=season_list state=rejected reason=digest` or `reason=load errno=` once per ETag and reason. The hub keeps its current list after a refusal and tries again on the next round. 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 82aecd5..13dff5e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -38,6 +38,10 @@ time=1775170804236133 level=WARN event=hub_link gate=north state=offline reason= time=1775170804235739 level=INFO event=hub_link gate=south state=online ``` +设备安装可按[软件包与设备配置](docs/operations/packages.zh-CN.md)使用 CPack 构建独立的 Debian 软件包,并配置加固的 systemd 单元。发布工作流构建软件包、生成 Syft SBOM,并用 Trivy 扫描构建和实验镜像。[日志兼容性](docs/operations/logging.zh-CN.md)说明 journal 和入场记录。 + +## 扫描器监督与 systemd + 输入 `exit` 离开容器。要观察指示灯和转闸动作,可使用团队的独立仓库 `gatepost-sim`;通信格式见[模拟器协议](docs/device/simulator-protocol.zh-CN.md)。 ## 构建与测试 @@ -71,7 +75,7 @@ time=1775170804235739 level=INFO event=hub_link gate=south state=online ## 运行与排查 -仓库中的门票均为测试数据,可用 `tools/gen_tickets.py` 生成。设备启动时选择扫描器与输出设备。标准输出给出放行结果,标准错误输出给出设备故障;每次拒绝还会写一行带原因的 `event=scan`(见[拒绝诊断](docs/security/ticket-signing.zh-CN.md#拒绝诊断))。`hub` 向标准错误输出写日志:每次扫描一行 `event=scan`,其中 `time` 是 Unix 时间戳(微秒),`level` 是级别,`gate` 是闸机,`ticket` 是票号(格式错误的输入改记 `length` 字节数),`result` 是决定,`decision_us` 是决定耗时(微秒)。连接建立和关闭各有一行,记录对端地址;收到 `SCAN` 前,闸机标识为 `unknown`。7000 和 8444 端口的握手失败分别记录 `event=tls_handshake state=failed reason=<原因> peer=<地址>` 和 `event=status_client state=handshake_failed reason=<原因> peer=<地址>`;7000 的握手超时记录 `state=timeout peer=<地址>`。地址取自 `accept` 接收的连接。同一监听端口上,同一来源和原因只记一次,直到原因变化或一次握手成功。每个监听端口记住 64 个来源,满时先忘记最久未见的来源。状态连接超时时记一行 `event=status_client state=timeout`,带对端地址和 `held_ms`。`event=admission_unlock_failed state=after_decision` 表示门票互斥锁在作出决定后解锁失败;`event=operation_failed` 表示系统操作失败。`gated` 只在连接状态或断开原因改变时向标准错误输出写一行 `event=hub_link`;状态为 `online` 或 `offline`,断开原因是 `refused`、`timeout`、`resolver` 或下表中的 TLS 原因。地址解析进程仅在状态切换为 `failed` 或 `resolved` 时记录 `event=hub_resolver`。两个守护进程的诊断日志均使用空格分隔的 `key=value` 字段,`time` 为 Unix 时间戳(微秒),并包含 `level` 与 `event`。状态和原因都不变时,不会每次扫描重复记录。闸机独立作出的决定仍写入标准输出和可选的扫描日志。可选的扫描日志文件逐行记录 `barcode=... result=...`(签名模式记 `<字段> result=...`,字段遵循前述拒绝诊断规则),并保持文件打开以减少系统调用。在构建容器内运行 `scripts/scan-syscalls.sh` 和 `scripts/scan-latency.sh`,可查看系统调用与延迟;实测数据见[扫描路径测量](docs/perf/scan-syscalls.zh-CN.md)。 +仓库中的门票均为测试数据,可用 `tools/gen_tickets.py` 生成。设备启动时选择扫描器与输出设备。标准输出给出放行结果,标准错误输出给出设备故障;每次拒绝还会写一行带原因的 `event=scan`(见[拒绝诊断](docs/security/ticket-signing.zh-CN.md#拒绝诊断))。`hub` 向标准错误输出写日志:每次扫描一行 `event=scan`,其中 `time` 是 Unix 时间戳(微秒),`level` 是级别,`gate` 是闸机,`ticket` 是票号(格式错误的输入改记 `length` 字节数),`result` 是决定,`decision_us` 是决定耗时(微秒)。连接建立和关闭各有一行,记录对端地址;收到 `SCAN` 前,闸机标识为 `unknown`。7000 和 8444 端口的握手失败分别记录 `event=tls_handshake state=failed reason=<原因> peer=<地址>` 和 `event=status_client state=handshake_failed reason=<原因> peer=<地址>`;7000 的握手超时记录 `state=timeout peer=<地址>`。地址取自 `accept` 接收的连接。同一监听端口上,同一来源和原因只记一次,直到原因变化或一次握手成功。每个监听端口记住 64 个来源,满时先忘记最久未见的来源。状态连接超时时记一行 `event=status_client state=timeout`,带对端地址和 `held_ms`。8444 队列满时最多每秒记录一行 `event=status_queue state=full peer=<地址>`。`event=admission_unlock_failed state=after_decision` 表示门票互斥锁在作出决定后解锁失败;`event=operation_failed` 表示系统操作失败。`gated` 只在连接状态或断开原因改变时向标准错误输出写一行 `event=hub_link`;状态为 `online` 或 `offline`,断开原因是 `refused`、`timeout`、`resolver` 或下表中的 TLS 原因。地址解析进程仅在状态切换为 `failed` 或 `resolved` 时记录 `event=hub_resolver`。两个守护进程的诊断日志均使用空格分隔的 `key=value` 字段,`time` 为 Unix 时间戳(微秒),并包含 `level` 与 `event`。状态和原因都不变时,不会每次扫描重复记录。闸机独立作出的决定仍写入标准输出和可选的扫描日志。可选的扫描日志文件逐行记录 `barcode=... result=...`(签名模式记 `<字段> result=...`,字段遵循前述拒绝诊断规则),并保持文件打开以减少系统调用。在构建容器内运行 `scripts/scan-syscalls.sh` 和 `scripts/scan-latency.sh`,可查看系统调用与延迟;实测数据见[扫描路径测量](docs/perf/scan-syscalls.zh-CN.md)。 设备连接日志中的 TLS 失败原因如下;续签步骤见[设备证书续签手册](docs/runbooks/renew-device-certificate.zh-CN.md): @@ -95,7 +99,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`。 邮件也会报告 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 端口从 `/season.txt` 同步签名季票单;未配置设备 TLS 时使用 8080 端口。切换前会核对整份文件的 SHA-256 与 ETag 相符、票单符合启动文件的全部装载规则,以及下载文件和所在目录均已同步到磁盘。`/tickets` 与放行决定使用同一份内存票单。成功切换记录 `event=season_list state=installed tickets= used= load_ms=`;拒收时按 ETag 和原因去重记录 `event=season_list state=rejected reason=digest` 或 `reason=load errno=`。拒收后 Hub 继续使用当前票单,下一轮再试。 +测试构建未配置设备 TLS 时,Hub 在 8081 端口通过 HTTP 提供 `/tickets`、`/status` 和 `/metrics`。配置设备 TLS 和 `GATEPOST_STATUS` 后,8081 只提供 `/status` 和 `/metrics`,对 `GET /tickets` 返回 404;同一绑定地址的 8444 端口通过 TLS 1.3 提供票单和其他接口。8081 由一个线程服务员工请求;8444 用四个工作线程处理容量为 16 的队列。场馆有四台闸机(gate1、gate2、north1、north2),每台同时最多保持一条 8444 连接。一台闸机的连接卡住时只占一个线程,其他闸机仍可得到服务;北侧链路故障时,两台北侧闸机最多占住两个线程,余下两个仍能服务场馆内的闸机。如果四个客户端同时卡住,后续连接仍须等待。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 端口从 `/season.txt` 同步签名季票单;未配置设备 TLS 时使用 8080 端口。切换前会核对整份文件的 SHA-256 与 ETag 相符、票单符合启动文件的全部装载规则,以及下载文件和所在目录均已同步到磁盘。`/tickets` 与放行决定使用同一份内存票单。成功切换记录 `event=season_list state=installed tickets= used= load_ms=`;拒收时按 ETag 和原因去重记录 `event=season_list state=rejected reason=digest` 或 `reason=load errno=`。拒收后 Hub 继续使用当前票单,下一轮再试。 Hub 还在员工网络一侧的状态服务上提供 `/metrics`,与闸机 RPC 端口分开。实验环境将其绑定到 `10.77.20.10:8081`;只有员工网段或本机能读取指标。指标名称和标签见[运维指标](docs/operations/metrics.zh-CN.md)。Hub 随票单发送 `X-Content-SHA256`;闸机验证文件内容,并在替换旧票单之前准备 ETag 元数据。 diff --git a/config/gate-hub.env.example b/config/gate-hub.env.example new file mode 100644 index 0000000..c6fd1a6 --- /dev/null +++ b/config/gate-hub.env.example @@ -0,0 +1,7 @@ +GATEPOST_LISTEN_ALL=1 +GATEPOST_HUB_CONFIG=/etc/gatepost/hub.conf +GATEPOST_REPORT_FILE=/var/lib/gatepost/reports.log +GATEPOST_TICKETS=/var/lib/gatepost/tickets.txt +GATEPOST_LISTEN_PORT=7000 +GATEPOST_STATUS=1 +GATEPOST_SYNC=1 diff --git a/config/gated.env.example b/config/gated.env.example new file mode 100644 index 0000000..ea9c1dd --- /dev/null +++ b/config/gated.env.example @@ -0,0 +1,9 @@ +GATEPOST_ARP_INTERFACE=eth0 +GATEPOST_GATE_ID=gate-1 +GATEPOST_HUB=hub.example.invalid:7000 +GATEPOST_TLS_SERVER_NAME=hub.example.invalid +GATEPOST_PUBLIC_KEYS=/etc/gatepost/ticket-public.keys +GATEPOST_EVENT_ID=replace-with-event-id +GATEPOST_SCANNER=tty:/dev/ttyACM0 +GATEPOST_OUTPUTS=gpio:/dev/gpiochip0 +GATEPOST_TICKETS=/var/lib/gatepost/tickets.txt diff --git a/docs/adr/0020-keep-path-mtu-feedback-and-check-each-gate-list.md b/docs/adr/0020-keep-path-mtu-feedback-and-check-each-gate-list.md new file mode 100644 index 0000000..76e38e0 --- /dev/null +++ b/docs/adr/0020-keep-path-mtu-feedback-and-check-each-gate-list.md @@ -0,0 +1,41 @@ +English | [简体中文](0020-keep-path-mtu-feedback-and-check-each-gate-list.zh-CN.md) + +# ADR 0020: Keep path-MTU feedback and check each gate's ticket list + +- Status: Accepted +- Date: 2026-10-30 +- Decision makers: Ingrid Larsen, Yuki Tanaka, Ben Carter +- Consulted: Aisha Rahman (security review of the router change), Mateo Rossi (gate list version and download log), Noah Williams (drills), Wang Hao (season list), Fatima Zahra (venue) + +## Context + +[ADR 0019](0019-authenticate-devices-with-mutual-tls.md) put ticket lists on the mutual-TLS status port. The [north entrance review](../postmortems/2026-10-24-north-entrance-ticket-list.md) records the incident and lab measurements: an online gate could scan while the larger new list could not cross its path. On Monday, October 26, `feat(lab): add the north entrance segment` and `test(lab): show north gates keep their old list behind a path-MTU black hole` made that gap reproducible. + +On Tuesday, October 27, `fix(lab): let the venue router return fragmentation-needed to the hub` restored path-MTU feedback; `fix(gated): log the phase and bytes of a failed list download` and `test(gate-hub): show an aborted ticket reply is counted as 200` exposed gaps in diagnosis. On Wednesday, October 28, `fix(gate-hub): count only completed ticket replies` and `feat(gated,gate-hub): report each gate's installed list version in its heartbeat` made delivery and each gate's installed version visible. + +On Thursday, October 29, `feat(lab): publish the season list as signed text` supplied the larger list used in the drills. On Friday, October 30, `test(gate-hub): show a ticket only in the synced season list is rejected` and `fix(gate-hub): decide with and serve the verified season list` aligned admission with the served list; `test(lab): show a north gate behind a path-MTU black hole holds the TLS status port`, `test(gate-hub): show one stalled client holds the TLS status port for every gate`, and `fix(gate-hub): serve the TLS status port from four workers` addressed the shared listener. Ingrid, Yuki and Ben accepted this decision. + +## Decision + +1. Venue routers return ICMP “fragmentation needed” (type 3 code 4) to senders and continue dropping other destination-unreachable messages. Record the MTU of each routed segment in the network plan. +2. Each gate reports the version (ETag) of its installed list and when it last confirmed that list in its heartbeat. The hub shows and exports each gate as `current`, `stale` or `unknown`; no reported version means `unknown`, not an error. +3. Count a `/tickets` reply as 200 only after it has been sent completely; otherwise count `status="incomplete"`. A failed gate download logs its phase and bytes received. +4. Decide with and serve the same verified season list: its SHA-256 must equal its ETag, the whole list must load under the start-file rules, and the file and its directory must be synced. Keep a refused list out and try it again next round. The hub still leaves ticket-signature checks to gates, as in ADR 0018 and [ADR 0019](0019-authenticate-devices-with-mutual-tls.md), limit 6. +5. Serve port 8444 with four workers and a queue of 16. Close connections arriving beyond a full queue and count them in `gatepost_status_queue_full_total{listener="status"}`. Port 8081 remains one thread for staff. Deadlines remain 2 s per step and 10 s per connection. + +## Options considered + +- Clamp TCP MSS on the north link: this hides the path's real MTU and must be maintained on every path. Not chosen. +- Lower the hub or gate MTU: this changes every path to fix one. Not chosen. +- Judge a gate's list by file age: age keeps growing through 304 replies and does not say whether the list is newest. Comparing versions was chosen. +- Shorten the 8444 deadline for list replies or add jitter to gate fetch cycles: a shorter deadline ties the hub to the gates' 300 ms limit; jitter does not shorten a hold. Workers were chosen, while jitter remains an open action in the review. + +## Consequences and known limits + +1. Small replies can hide an interruption. The hub hands a reply to the kernel and counts it complete when every write returns. In the venue lab (Linux `7.0.14-linuxkit`, `net.ipv4.tcp_wmem` `4096 16384 4194304`), a gate that took nothing after its request and acknowledged nothing still had 30,750 bytes accepted by the kernel in 5 of 5 runs: 24,984 bytes at once and 5,766 more after the first 2 s step. `ss` showed `Send-Q` 30,750 and send buffer `tb46080`. Those bytes were a 342-byte header, three 8214-byte records and 5,766 bytes. Each 8214-byte record carries 8192 bytes of list, so the accepted data includes about 30 KB of list, roughly 175 to 180 lines of 170 to 174 characters. A list that small can be handed over whole and counted as 200 even when the gate has gone. The lab season list is much larger, about 3.5 MB (3,488,890 bytes), so `status="incomplete"` is meaningful for it. The threshold depends on the kernel and its settings. +2. `CONFIG` carries no MAC. The hub accepts the list version a gate reports. Anyone holding that gate's certificate and key can report a false list status for it; see [ADR 0019](0019-authenticate-devices-with-mutual-tls.md), limits 3 and 4. +3. A gate downloads its list synchronously in its scan loop with a 300 ms limit. Receiving the whole 3,488,890-byte list needs at least about 93 Mbit/s (3,488,890 × 8 / 0.3 s), more with the TLS handshake. On a slower link, a gate can only keep its old list through 304 replies. Moving the download out of the scan loop is Mateo Rossi's open action, not scheduled. +4. A stuck connection still holds one 8444 worker for up to 10 s; 4 to 6 s was measured for a client that stopped reading or lost power after its request. Four such connections make others wait, and a holder of gate certificates can do this deliberately. Port 8081 still has one thread. +5. Gates fetch on aligned 20 s cycles without jitter. +6. The router passes only type 3 code 4. A path elsewhere that drops it is again a black hole. Gate list status and the incomplete count reveal such a path; they do not repair it. +7. The hub decides with the verified season list but still does not check ticket signatures; the limit in ADR 0018 and [ADR 0019](0019-authenticate-devices-with-mutual-tls.md), limit 6, is unchanged. This ADR does not supersede any part of ADR 0019. diff --git a/docs/adr/0020-keep-path-mtu-feedback-and-check-each-gate-list.zh-CN.md b/docs/adr/0020-keep-path-mtu-feedback-and-check-each-gate-list.zh-CN.md new file mode 100644 index 0000000..5de9752 --- /dev/null +++ b/docs/adr/0020-keep-path-mtu-feedback-and-check-each-gate-list.zh-CN.md @@ -0,0 +1,41 @@ +[English](0020-keep-path-mtu-feedback-and-check-each-gate-list.md) | 简体中文 + +# ADR 0020:保留路径 MTU 反馈并核对每台闸机的票单 + +- 状态:已接受 +- 日期:2026-10-30 +- 决策者:Ingrid Larsen、Yuki Tanaka、Ben Carter +- 被咨询人:Aisha Rahman(路由器改动的安全审查)、Mateo Rossi(闸机票单版本与下载日志)、Noah Williams(演练)、Wang Hao(季票单)、Fatima Zahra(场馆) + +## 背景 + +[ADR 0019](0019-authenticate-devices-with-mutual-tls.zh-CN.md) 将票单放在双向 TLS 状态端口。[北入口事件复盘](../postmortems/2026-10-24-north-entrance-ticket-list.zh-CN.md) 记录了事件和实验室测量:闸机在线且能扫码,较大的新票单却过不了它所经的链路。10 月 26 日周一,`feat(lab): add the north entrance segment` 和 `test(lab): show north gates keep their old list behind a path-MTU black hole` 让这一差异可以复现。 + +10 月 27 日周二,`fix(lab): let the venue router return fragmentation-needed to the hub` 恢复路径 MTU 反馈;`fix(gated): log the phase and bytes of a failed list download` 与 `test(gate-hub): show an aborted ticket reply is counted as 200` 暴露了诊断上的缺口。10 月 28 日周三,`fix(gate-hub): count only completed ticket replies` 和 `feat(gated,gate-hub): report each gate's installed list version in its heartbeat` 让交付结果和各闸机安装的版本可见。 + +10 月 29 日周四,`feat(lab): publish the season list as signed text` 提供了演练所用的较大季票单。10 月 30 日周五,`test(gate-hub): show a ticket only in the synced season list is rejected` 与 `fix(gate-hub): decide with and serve the verified season list` 让放行判断和提供的票单一致;`test(lab): show a north gate behind a path-MTU black hole holds the TLS status port`、`test(gate-hub): show one stalled client holds the TLS status port for every gate` 和 `fix(gate-hub): serve the TLS status port from four workers` 处理了共用监听端口受阻的问题。Ingrid、Yuki 和 Ben 接受本决定。 + +## 决定 + +1. 场馆路由器向发送方返回 ICMP“需要分片”(type 3 code 4),仍丢弃其他“目的不可达”消息。网络规划记录每个路由网段的 MTU。 +2. 每台闸机在心跳中报告已安装票单的版本(ETag)以及上次确认该票单的时间。hub 显示并导出每台闸机的 `current`、`stale` 或 `unknown` 状态;未报告版本时记为 `unknown`,不算错误。 +3. `/tickets` 回复全部发送完毕才计为 200,否则计为 `status="incomplete"`。闸机下载失败时记录所处阶段和已收到的字节数。 +4. hub 用同一份已验证季票单进行放行判断并提供下载:SHA-256 必须等于 ETag,整份票单须按启动文件规则成功加载,文件及其目录都须同步到磁盘。拒绝的票单不启用,下一轮再试。hub 仍将票据签名检查交给闸机,这沿用 ADR 0018 和 [ADR 0019](0019-authenticate-devices-with-mutual-tls.zh-CN.md) 的第 6 条限制。 +5. 8444 端口由四个工作线程和容量为 16 的队列服务。队列满时关闭新连接,并计入 `gatepost_status_queue_full_total{listener="status"}`。供员工使用的 8081 端口仍为单线程。期限仍为每一步 2 s、每条连接 10 s。 + +## 考虑过的方案 + +- 在北入口链路上限制 TCP MSS:这会掩盖路径的真实 MTU,还须在每条路径上维护。未采用。 +- 降低 hub 或闸机的 MTU:为修复一条路径而改变所有路径。未采用。 +- 按文件年龄判断闸机票单:收到 304 回复后文件年龄仍会增长,也不能说明票单是不是最新。选择比较版本。 +- 缩短 8444 票单回复的期限,或给闸机的取票周期加抖动:更短的期限会把 hub 绑到闸机的 300 ms 限制;抖动不能缩短单条连接的占用时间。选择增加工作线程;复盘仍将抖动列为待办。 + +## 后果与已知限制 + +1. 较小的回复可能掩盖中断。hub 将回复交给内核;所有写入返回后,就计为完整。在场馆实验室(Linux `7.0.14-linuxkit`,`net.ipv4.tcp_wmem` 为 `4096 16384 4194304`),闸机发出请求后既不接收也不确认,内核在 5 次运行中每次仍接受 30,750 字节:起初一次接受 24,984 字节,第一个 2 s 步骤后又接受 5,766 字节。`ss` 显示 `Send-Q` 为 30,750,发送缓冲为 `tb46080`。这些字节包括 342 字节的响应头、三条各 8214 字节的记录,以及后续 5,766 字节。每条 8214 字节记录承载 8192 字节票单,因此内核接受了约 30 KB 票单,约为 175 至 180 行、每行 170 至 174 个字符。这样小的票单即使闸机已经断开,也可能整体交给内核并计为 200。实验室季票单大得多,约 3.5 MB(3,488,890 字节),因此 `status="incomplete"` 对它有意义。这个界限取决于内核及其设置。 +2. `CONFIG` 不携带 MAC。hub 接受闸机上报的票单版本。持有该闸机证书和私钥的人可以为其虚报票单状态;见 [ADR 0019](0019-authenticate-devices-with-mutual-tls.zh-CN.md) 的第 3、4 条限制。 +3. 闸机仍在扫码循环中同步下载票单,限时 300 ms。要在此期限内接收完整的 3,488,890 字节票单,链路至少需要约 93 Mbit/s(3,488,890 × 8 / 0.3 s);加上 TLS 握手还需要更快。在较慢链路上,闸机只能通过 304 回复维持旧票单。将下载移出扫码循环由 Mateo Rossi 负责,尚未排期。 +4. 卡住的连接仍可占用一个 8444 工作线程最多 10 s;客户端请求后停止读取或断电时,测得占用 4 至 6 s。四条这样的连接会让其他连接等待;持有闸机证书的人也可以故意这样做。8081 仍为单线程。 +5. 闸机按对齐的 20 s 周期取票,没有抖动。 +6. 路由器只放行 type 3 code 4;若其他路径丢弃它,就会再次形成黑洞。闸机票单状态和未完成计数能显示这类路径,但不能修复它。 +7. hub 用已验证季票单作放行判断,但仍不检查票据签名;ADR 0018 和 [ADR 0019](0019-authenticate-devices-with-mutual-tls.zh-CN.md) 第 6 条的限制没有改变。本 ADR 不取代 ADR 0019 的任何部分。 diff --git a/docs/concurrency/lock-order.md b/docs/concurrency/lock-order.md index 4f691e6..619ae33 100644 --- a/docs/concurrency/lock-order.md +++ b/docs/concurrency/lock-order.md @@ -33,3 +33,5 @@ The snapshot leaf lock protects the current list pointer and reference counts. write from the immutable snapshot. A season switch takes the leaf lock while holding `store_lock`; no path takes `store_lock` while holding the leaf lock. No I/O occurs under the leaf lock. + +The 8444 work queue mutex is a leaf. It is held only while adding or taking a connection; no other lock is held and no I/O occurs under it. The full-queue counter is updated after the mutex is released. The 7000 queue keeps its existing behavior: it updates `gatepost_worker_queue_depth` while holding its queue mutex. diff --git a/docs/concurrency/lock-order.zh-CN.md b/docs/concurrency/lock-order.zh-CN.md index 8b0c479..c36a2f0 100644 --- a/docs/concurrency/lock-order.zh-CN.md +++ b/docs/concurrency/lock-order.zh-CN.md @@ -9,3 +9,5 @@ 报告存储写入日志时一直持有自己的 `lock`,但不会与 `store_lock` 同时持有。新报告经 `reports_record` 记录后,hub 在 `store_lock` 下把这张票标记为已用,随后像扫描一样获取该票的入场状态锁。换表前,先在报告存储的锁下复制已有报告的条码,放开锁后才获取 `store_lock`。换表时按条码继承旧票的已用状态,再标记复制出的报告条码。复制之后、换表之前写入的报告,会在旧票单里标记它的票,再随换表继承下来;可如果这张票只在新票单里,旧票单里就没有可标记的票。所以换表之后,hub 在不持有任何锁的情况下再复制一次报告条码,然后重新获取 `store_lock`,像处理报告那样在新票单里标记这些票。第二次复制之后才写入的报告,会自己标记新票。启动时加载报告日志,并把其中的票标记为已用,此时尚未启动任何监听器。 票单快照有一把只保护当前指针和引用计数的小锁。`/tickets` 和 `/metrics` 取到引用就释放锁,发送数据时仅持有引用。换季票单时可在持有 `store_lock` 的情况下获取这把小锁,反过来获取则不允许;持有小锁期间不做 I/O。 + +8444 的工作队列锁也是这样一把小锁:只在连接入队或出队时持有,持锁期间不获取别的锁,也不做 I/O。队列满的计数器在释放队列锁后才更新。7000 的队列保持原有行为:持有自身队列锁时更新 `gatepost_worker_queue_depth`。 diff --git a/docs/operations/logging.md b/docs/operations/logging.md new file mode 100644 index 0000000..865e2e9 --- /dev/null +++ b/docs/operations/logging.md @@ -0,0 +1,7 @@ +English | [简体中文](logging.zh-CN.md) + +# Logging compatibility at 1.0.0 + +The daemons keep their existing text records in this release. `gated` writes `ACCEPT` and `REJECT` to standard output as the local device decision interface; the venue scripts and hardware adapter depend on those exact lines. The hub's status, sync and alert messages include `key=value` fields, but older diagnostic and capture scripts also parse specific text. Changing every record to a new timestamped format in this release would change those interfaces without a complete migration of the parsers and recorded incidents. + +Run both services under systemd to obtain journal timestamps, service identity and priority. Filter by `_SYSTEMD_UNIT=gated.service` or `_SYSTEMD_UNIT=gate-hub.service`. Do not treat stdout decisions as an audit log: use the gate's durable admission journal and the hub's report store for admission accounting. The ticket-fetch record includes `status`, HTTP code and curl result, and on installation the ETag. A later logging migration must add a timestamp and level to every event, keep stdout device decisions stable, and update all log-parsing tests and lab scripts together. diff --git a/docs/operations/logging.zh-CN.md b/docs/operations/logging.zh-CN.md new file mode 100644 index 0000000..3de7ac5 --- /dev/null +++ b/docs/operations/logging.zh-CN.md @@ -0,0 +1,7 @@ +[English](logging.md) | 简体中文 + +# 1.0.0 的日志兼容性 + +本次发布保留 daemon 现有的文本记录。`gated` 向标准输出写出 `ACCEPT` 和 `REJECT`,作为本地设备决策接口;场馆脚本和硬件适配层依赖这些准确的行。hub 的状态、同步和告警消息包含 `key=value` 字段,但较早的诊断和抓包脚本也解析特定文本。若在此次发布中把所有记录改为带时间戳的新格式,而没有同时迁移解析器和事件记录,就会改变这些接口。 + +通过 systemd 运行两个服务,可由 journal 提供时间戳、服务身份和优先级。按 `_SYSTEMD_UNIT=gated.service` 或 `_SYSTEMD_UNIT=gate-hub.service` 筛选。标准输出的放行决定并非审计日志;入场核算应使用闸机的持久放行日志和 hub 的报告存储。票据获取记录包含 `status`、HTTP 状态和 curl 结果;安装时还包含 ETag。后续日志迁移须为每个事件加入时间戳和级别,保持标准输出设备决定不变,并同时更新所有日志解析测试和实验脚本。 diff --git a/docs/operations/metrics.md b/docs/operations/metrics.md index 45f85b9..93dbd5e 100644 --- a/docs/operations/metrics.md +++ b/docs/operations/metrics.md @@ -18,6 +18,7 @@ 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`) | Background data-centre sync rounds. `success` means that, at the end of the round, hub decisions use the data centre's current season list, whether installed from a 200 response or confirmed by a 304. Download, HTTP, validation, or installation failures count as `error`. | | `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_status_queue_full_total` | Counter | `listener` (`status`) | Connections to 8444 closed without service because all four workers were busy and 16 connections were already waiting. | | `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 587095c..7a193c8 100644 --- a/docs/operations/metrics.zh-CN.md +++ b/docs/operations/metrics.zh-CN.md @@ -18,6 +18,7 @@ Hub 在员工网络一侧的 8081 端口通过 `GET /metrics` 提供 Prometheus | `gatepost_dc_sync_attempts_total` | Counter | `outcome`(`success`、`error`) | 每轮后台同步的结果。轮次结束时,hub 已用数据中心当前季票单作决定,才记 `success`;200 下载并安装、304 确认当前票单都符合。下载、HTTP、校验或安装失败均记 `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_status_queue_full_total` | Counter | `listener`(`status`) | 四个工作线程都在忙、等待队列也已有 16 条连接时,新到达 8444 的连接未经处理便被关闭的次数。 | | `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/docs/operations/monitoring.md b/docs/operations/monitoring.md index e76af5c..d53f3c7 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -22,7 +22,7 @@ The **Venue entrance** dashboard reads the hub's staff-side `/metrics` route. Pr | 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 | 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; see [ADR 0020](../adr/0020-keep-path-mtu-feedback-and-check-each-gate-list.md), limit 1. 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. | diff --git a/docs/operations/monitoring.zh-CN.md b/docs/operations/monitoring.zh-CN.md index 7948893..f1bfac0 100644 --- a/docs/operations/monitoring.zh-CN.md +++ b/docs/operations/monitoring.zh-CN.md @@ -22,7 +22,7 @@ docker compose -f lab/compose.yaml -f lab/monitoring.yaml rm -sfv prometheus gra | 分组 | 面板 | 值班时怎么读 | | --- | --- | --- | | 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 | Ticket HTTP errors | 按状态显示 `/tickets` 除 200、206、304 外的响应。`incomplete` 表示 hub 没能把响应全部交给内核;响应一旦全部交给内核,即使闸机最终没有收到,也计为 200 或 206,见 [ADR 0020](../adr/0020-keep-path-mtu-feedback-and-check-each-gate-list.zh-CN.md) 的第 1 条限制。`404` 持续增长,说明有闸机向启用 TLS 的 hub 的 8081 端口取票。 | | Errors | TLS handshake failures | 根据监听端口和原因,区分闸机 RPC 与状态服务的握手失败。 | | Errors | Rejections by result | 按闸机比较 `reject_used` 和 `reject_unknown`。 | | Errors | Data-centre sync runs | 比较最近一分钟成功和失败的数据中心同步次数。 | diff --git a/docs/operations/packages.md b/docs/operations/packages.md new file mode 100644 index 0000000..b49efc3 --- /dev/null +++ b/docs/operations/packages.md @@ -0,0 +1,17 @@ +English | [简体中文](packages.zh-CN.md) + +# Debian packages and device setup + +The release build produces separate `gatepost-gated` and `gatepost-gate-hub` Debian packages for the build architecture. From the repository root: + +```sh +./scripts/dev.sh build-image +./scripts/dev.sh test release +docker run --rm -v "$PWD:/src" -w /src gatepost-build:current sh -c 'cmake --install build/release --prefix /tmp/gatepost-stage && cpack --config build/release/CPackConfig.cmake -G DEB -B build/packages' +``` + +`cmake --install` places the binaries under `usr/bin`, service units under `usr/lib/systemd/system`, launchers under `usr/lib/gatepost`, and example configuration under `etc/gatepost` relative to the chosen prefix. CPack packages those paths as `/usr/bin`, `/usr/lib/...` and `/etc/gatepost/...`. The package scripts create the `gatepost` system user and group, the persistent state directory, and restricted credential directories. The `/etc/gatepost` configuration files are Debian conffiles. Packages do not enable or start a service automatically. + +Install only the package needed on each host. Replace the values in `/etc/gatepost/gated.env` or `gate-hub.env` and the hub configuration. Install trusted CA, chain and private-key files under `/etc/gatepost/credentials/` with root-only access. The units use `LoadCredential=` to pass those TLS files into each service's private credential directory. Install per-gate HMAC keys under `/etc/gatepost/mac-keys/gate/GATE_ID.hex` on a gate and `/etc/gatepost/mac-keys/hub/GATE_ID.hex` on the hub; restrict each file to the service group. Install the public ticket-signing keys at the path set by `GATEPOST_PUBLIC_KEYS`, and install signed tickets in `/var/lib/gatepost/tickets.txt`. The key names and gate ID must match the certificate device ID. + +The gate unit uses `/dev/ttyACM0` and `/dev/gpiochip0` by default; adjust the environment file and grant the `gatepost` user the device access needed by the hardware. Validate on the target system with `systemd-analyze verify /usr/lib/systemd/system/gated.service /usr/lib/systemd/system/gate-hub.service`, then enable the applicable service. The units set `NoNewPrivileges`, `ProtectSystem=strict`, `ProtectHome`, `PrivateTmp`, kernel and cgroup protections, and a writable state directory. See [logging compatibility](logging.md) for the journal and durable admission record boundaries. Test keys created by `lab/tls/prepare.sh` are for the local lab only. diff --git a/docs/operations/packages.zh-CN.md b/docs/operations/packages.zh-CN.md new file mode 100644 index 0000000..d409b33 --- /dev/null +++ b/docs/operations/packages.zh-CN.md @@ -0,0 +1,17 @@ +[English](packages.md) | 简体中文 + +# Debian 软件包与设备配置 + +发布构建为当前架构生成独立的 `gatepost-gated` 和 `gatepost-gate-hub` Debian 软件包。在仓库根目录执行: + +```sh +./scripts/dev.sh build-image +./scripts/dev.sh test release +docker run --rm -v "$PWD:/src" -w /src gatepost-build:current sh -c 'cmake --install build/release --prefix /tmp/gatepost-stage && cpack --config build/release/CPackConfig.cmake -G DEB -B build/packages' +``` + +`cmake --install` 相对于指定前缀把程序放在 `usr/bin`,服务单元放在 `usr/lib/systemd/system`,启动脚本放在 `usr/lib/gatepost`,示例配置放在 `etc/gatepost`。CPack 将其打包为 `/usr/bin`、`/usr/lib/...` 和 `/etc/gatepost/...`。软件包脚本创建 `gatepost` 系统用户和组、持久状态目录及受限凭据目录。`/etc/gatepost` 下的配置标记为 Debian conffile。安装软件包不会自动启用或启动服务。 + +每台主机只安装所需的软件包。修改 `/etc/gatepost/gated.env` 或 `gate-hub.env` 及 hub 配置。将受信任 CA、证书链和私钥放在 `/etc/gatepost/credentials/`,仅允许 root 访问。服务单元通过 `LoadCredential=` 将这些 TLS 文件传入各自的私有凭据目录。闸机的 HMAC 密钥放在 `/etc/gatepost/mac-keys/gate/GATE_ID.hex`,hub 对应密钥放在 `/etc/gatepost/mac-keys/hub/GATE_ID.hex`,文件访问限制为服务组。将票据签名公钥放在 `GATEPOST_PUBLIC_KEYS` 指定的路径,将已签名票据放在 `/var/lib/gatepost/tickets.txt`。密钥名称和 gate ID 必须与设备证书中的 ID 一致。 + +闸机单元默认使用 `/dev/ttyACM0` 和 `/dev/gpiochip0`;按硬件修改环境文件,并授予 `gatepost` 用户所需的设备访问权限。在目标系统上运行 `systemd-analyze verify /usr/lib/systemd/system/gated.service /usr/lib/systemd/system/gate-hub.service`,再启用相应服务。服务单元设置 `NoNewPrivileges`、`ProtectSystem=strict`、`ProtectHome`、`PrivateTmp`、内核和 cgroup 保护,以及可写状态目录。journal 和持久入场记录的界限参见[日志兼容性](logging.zh-CN.md)。`lab/tls/prepare.sh` 生成的测试密钥只供本地实验使用。 diff --git a/docs/postmortems/2026-10-03-data-centre-link-outage.md b/docs/postmortems/2026-10-03-data-centre-link-outage.md index a6f9116..005e35e 100644 --- a/docs/postmortems/2026-10-03-data-centre-link-outage.md +++ b/docs/postmortems/2026-10-03-data-centre-link-outage.md @@ -38,7 +38,7 @@ Open actions: | Action | Owner | Due | Status | |---|---|---|---| -| Address the lack of an alert when the data centre is unreachable, including when the uplink watcher has exited; notifications must reach people through a path that does not depend solely on the failed link. On 2026-10-26, after the due date passed, Ingrid reassigned this from Yuki Tanaka to Ben Carter; Yuki remains responsible for making the uplink watcher report that it is alive. Link the implementation here when it exists; until then this stays open. | Ben Carter with Noah Williams | 2026-10-29 | Open (overdue since 2026-10-23) | +| Address the lack of an alert when the data centre is unreachable, including when the uplink watcher has exited; notifications must reach people through a path that does not depend solely on the failed link. On 2026-10-26, after the due date passed, Ingrid reassigned this from Yuki Tanaka to Ben Carter; Yuki remains responsible for making the uplink watcher report that it is alive. The mail alerts are implemented in [gate-hub/alert.c](../../gate-hub/alert.c) and described under [Operating it](../../README.md#operating-it); the [drill](../../lab/dc-alert.sh) and [test](../../tests/test_dc_alerts.py) cover them, and the [uplink watcher](../../lab/uplink-watch.sh) supplies the heartbeat. | Ben Carter with Noah Williams | 2026-10-29 | Done (2026-10-29) | | Ask the 4G operator for a path to the data centre without AS 64496, or find another operator; review before the next season's contract renewal. Yuki supplies the looking-glass results; consult Wang because the data centre also connects to 64496. | Grace Kim | 2026-11-30 | Open | | Resolve the gap between ICMP and the hub's `dc_probe`: ICMP can answer while the API is down and nothing switches. | Ben Carter | Not scheduled | Open | diff --git a/docs/postmortems/2026-10-03-data-centre-link-outage.zh-CN.md b/docs/postmortems/2026-10-03-data-centre-link-outage.zh-CN.md index 56f07f2..83411f2 100644 --- a/docs/postmortems/2026-10-03-data-centre-link-outage.zh-CN.md +++ b/docs/postmortems/2026-10-03-data-centre-link-outage.zh-CN.md @@ -38,7 +38,7 @@ | 行动 | 负责人 | 期限 | 状态 | |---|---|---|---| -| 补上数据中心不可达时的告警,也要覆盖上行监视脚本已经退出的情况;通知必须通过不只依赖故障链路的路径送达相关人员。2026-10-26,期限已过,Ingrid 将此项从 Yuki Tanaka 转交给 Ben Carter;Yuki 仍负责让上行监视脚本上报自身存活状态。后续实现后从这里链接过去;在那之前始终保留为未完成项。 | Ben Carter,与 Noah Williams 合作 | 2026-10-29 | 未完成(自 2026-10-23 起逾期) | +| 补上数据中心不可达时的告警,也要覆盖上行监视脚本已经退出的情况;通知必须通过不只依赖故障链路的路径送达相关人员。2026-10-26,期限已过,Ingrid 将此项从 Yuki Tanaka 转交给 Ben Carter;Yuki 仍负责让上行监视脚本上报自身存活状态。邮件告警实现在 [gate-hub/alert.c](../../gate-hub/alert.c),说明见 README 的[运行与排查](../../README.zh-CN.md#运行与排查);[演练](../../lab/dc-alert.sh)和[测试](../../tests/test_dc_alerts.py)覆盖这两类告警,[上行监视脚本](../../lab/uplink-watch.sh)提供心跳。 | Ben Carter,与 Noah Williams 合作 | 2026-10-29 | 已完成(2026-10-29) | | 向 4G 运营商询问不经 AS 64496 到数据中心的路径,或另找运营商;在下一季合同续签前复查。Yuki 提供 looking glass 结果;咨询 Wang,因为数据中心也接在 64496 上。 | Grace Kim | 2026-11-30 | 未完成 | | 解决 ICMP 与 hub 的 `dc_probe` 互不相连的问题:ICMP 能回答、API 已坏时不会切换。 | Ben Carter | 尚未排期 | 未完成 | diff --git a/docs/postmortems/2026-10-24-north-entrance-ticket-list.md b/docs/postmortems/2026-10-24-north-entrance-ticket-list.md new file mode 100644 index 0000000..f37d5df --- /dev/null +++ b/docs/postmortems/2026-10-24-north-entrance-ticket-list.md @@ -0,0 +1,47 @@ +English | [简体中文](2026-10-24-north-entrance-ticket-list.zh-CN.md) + +# 2026-10-24 north entrance ticket list incident: blameless post-mortem + +- Date: 2026-10-30 +- Participants: Ingrid Larsen (technical lead), Yuki Tanaka (network), Aisha Rahman (security), Noah Williams (drills), Mateo Rossi (gates), Ben Carter (hub), Wang Hao (data centre), Grace Kim (event operations), Fatima Zahra (venue) + +## Summary and impact + +Before doors opened on Saturday, October 24, the hub was given that day's ticket list and restarted as usual. The north entrance was an event-specific segment behind a link with MTU 1400. Its firewall dropped ICMP destination-unreachable messages, including “fragmentation needed”. The north gates, north1 and north2, stayed online and scanned, but answered `not_in_list` for tickets sold that day; other entrances admitted those tickets. Fatima directed the affected ticket holders to the east entrance and kept the gate logs. Nobody was alerted. + +The north gates could connect to the hub, but could not receive the new list body across that link. The measurements below come from lab reproductions after the event; they are not measurements of how long ticket holders waited at the venue or how many were affected. + +## Timeline + +- 2026-10-24, Saturday before doors-open: The hub received the day's list and restarted. The north gates, north1 and north2, remained online but rejected newly sold tickets as `not_in_list`. Other entrances admitted them. Fatima sent the affected ticket holders east and retained the gate logs; no alert reached anyone. +- 2026-10-26, Monday: Ingrid moved the overdue data-centre alert action from the October 3 review to Ben Carter with Noah Williams, due October 29. Yuki added the north entrance segment to the lab with the entrance firewall as configured on site. Noah reproduced the failure with `lab/north-entrance.sh`: at MTU 1400, it printed `result: north1 new list FAIL (not installed within 90 s; gate1 installed it)` and `result: north1 new ticket FAIL (GP-900000000003 not_in_list)`. At MTU 1200, the handshake failed too, and the drill also printed `result: north1 hub link FAIL (offline during old-ticket scan)`. +- 2026-10-27, Tuesday: Yuki, reviewed by Aisha, changed `lab/compose.yaml` so the router returned “fragmentation needed” to the hub. The unchanged drill then printed `result: north1 ok` at both MTUs. Mateo made failed gate downloads report their phase and progress in `tests/test_ticket_fetch_progress.py`; behind the lab black hole, north1 logged `event=ticket_fetch state=failed http=200 curl=28 reason=timeout phase=body received=0 expected=17706`. Ben showed with `tests/test_ticket_reply_count.py` that an aborted ticket reply was counted as 200. +- 2026-10-28, Wednesday: The hub began counting only completed ticket replies as 200 and the rest as `status="incomplete"`. Mateo and Ben added each gate's installed list version to its heartbeat and a hub comparison with the current list (`tests/test_gate_list_version.py`). Wang and Yuki added Prometheus and Grafana to the venue lab (`lab/monitoring.yaml`). Ben removed an unidentified “unknown” row from gate list status. +- 2026-10-29, Thursday: Noah's `lab/dc-alert.sh` showed that nobody was told when the data centre was unreachable or the uplink watcher stopped. Ben added mail alerts for both, with Yuki supplying the watcher heartbeat. Wang made the data centre publish the signed season list as text; in the lab it held 20000 tickets and was 3,488,890 bytes. +- 2026-10-30, Friday: Noah's `tests/test_hub_season_reload.py`, `tests/test_hub_served_list.py`, and `tests/test_hub_tickets_send_change.py` exposed four failures in the hub as it had run that week: `result: season-only ticket still rejected 10 s after a successful sync (successes=1)`, `result: /tickets served the changed file while the hub decides with the list it loaded`, `result: grown file: sent 1048576 bytes beyond Content-Length 21473706`, and `result: shrunk file: sent 10736690 of 21473706 body bytes and counted the reply as 200`. Ben made the hub decide with and serve one immutable copy of the verified season list. Noah changed drills to deliver list changes through the data centre. His `lab/status-stall-blackhole.sh` then showed a lost north-gate download holding the hub's TLS status port 8444, which then served one connection at a time; a client that stopped reading held it in the same way on a healthy network. Ben changed 8444 to four workers with a queue of 16. The review met that afternoon. + +## Cause and detection + +Each gate scan and link check opens a TLS connection. The hub's first handshake flight is 1,250 bytes of TLS records (`lab/captures/socket-exchange/tls-connection.txt`) sent as one 1,302-byte IP packet (`lab/captures/socket-exchange/tls-connection.pcap`); its size depends on the certificate chain. That packet fits under MTU 1400, so the gates could appear online and scan. The list body left the hub in 1500-byte packets, which the north link dropped. With “fragmentation needed” filtered by the entrance firewall, the router never told the hub to send smaller packets. The MTU 1200 lab result also lost the handshake, which explains why that reproduction looked like an offline gate rather than a stale list. + +The gate logs were the venue evidence; no alert reported the stale list. Before the hub changes on Friday, `/tickets` served the file as it stood on disk while admission decisions used the list loaded at startup. The fetched list and the hub's decision list could therefore differ. That mismatch was a separate finding, not the cause of the north link's packet loss. The lab's incomplete-reply metric and gate list-version status now make stalled delivery and stale installations visible; the data-centre and watcher mail alerts close the overdue alert action from the earlier review. + +## Recovery measurements and actions + +The router change let the unchanged north entrance drill pass at both MTUs. These are lab results, not a measured venue recovery time. The gate's `phase=body received=0 expected=17706` line distinguished a completed HTTP response header followed by no list body from a failed handshake. Counting aborted replies as `status="incomplete"` and comparing reported installed versions with the current list gave the hub a way to show incomplete delivery and stale gates. The verified season list now supplies both admission decisions and `/tickets` from the same immutable copy, avoiding the separate file-change failures exposed on Friday. + +With the 3,488,890-byte season list and the black hole restored in `lab/status-stall-blackhole.sh`, a north gate's lost download held the hub's TLS status port 8444, which then served one connection at a time, for about 6.1 s once per 20 s fetch cycle (`held_ms` 6126 to 6161). A venue gate's `/status` request waited as long; its list fetch timed out after 300 ms. After a new list, venue gates installed it in 18, 38 or 58 s, or took more than 60 s. The roughly 6 s were three 2 s steps: the hub restarted its send deadline before each write, two writes still sent part of their data, and the third sent nothing. A client that stopped reading could hold the port the same way even on a healthy network. + +With four workers and a queue of 16 on 8444, the same lab drill's longest `/status` wait was 0.05 s. Each north gate still held one worker for about 6.1 s, but both venue gates installed the new list 18 s after the hub. This limits how a stalled transfer affects other gates; it does not make that transfer complete. + +Open actions: + +| Action | Owner | Due | Status | +|---|---|---|---| +| Record in ADR 0020 the gate's synchronous list download inside its scan loop and its 300 ms limit. A 3,488,890-byte body needs at least about 93 Mbit/s to arrive within that limit (3,488,890 × 8 / 0.3 s), more with the TLS handshake; a slower link can only keep the old list through 304 replies. Moving the download out of the scan loop remains unscheduled under Mateo Rossi. | Ingrid Larsen and Yuki Tanaka | 2026-10-30 | Open | +| Review port 8081, which is still served by one thread and is for staff only. | Ben Carter | Not scheduled | Open | +| Add jitter to gates' aligned 20 s fetch cycles so they do not all ask together. | Mateo Rossi | Not scheduled | Open | + +## What we learned + +An online gate and a successful scan connection did not show that a larger ticket list could cross the same path. The firewall's ICMP rule prevented the hub from learning the north link's MTU, while the small handshake concealed the difference. Gate list versions, incomplete-reply accounting and the download-progress log make that gap observable. The later season-list and stalled-client tests also showed that list consistency and a shared status listener matter to admission at other entrances. The lab changes reduce those effects, while the scan-loop download limit, staff port and synchronized fetch cycles remain open. diff --git a/docs/postmortems/2026-10-24-north-entrance-ticket-list.zh-CN.md b/docs/postmortems/2026-10-24-north-entrance-ticket-list.zh-CN.md new file mode 100644 index 0000000..fd32498 --- /dev/null +++ b/docs/postmortems/2026-10-24-north-entrance-ticket-list.zh-CN.md @@ -0,0 +1,47 @@ +[English](2026-10-24-north-entrance-ticket-list.md) | 简体中文 + +# 2026-10-24 北入口票单事件:无责复盘 + +- 日期:2026-10-30 +- 参与:Ingrid Larsen(技术负责人)、Yuki Tanaka(网络)、Aisha Rahman(安全)、Noah Williams(演练)、Mateo Rossi(闸机)、Ben Carter(hub)、Wang Hao(数据中心)、Grace Kim(活动运营)、Fatima Zahra(场馆) + +## 摘要与影响 + +10 月 24 日周六开门前,hub 像往常一样取得当天的票单并重启。北入口是为这场活动设置的独立网段,所经链路的 MTU 为 1400;入口防火墙丢弃 ICMP“目的不可达”消息,其中包括“需要分片”。north1 和 north2 一直在线,也能扫码,却对当天售出的票回答 `not_in_list`;其他入口可以放行这些票。Fatima 引导持票人改走东入口,并保留闸机日志。没有人收到告警。 + +北入口闸机能连上 hub,却收不到穿过这段链路的新票单正文。下文的数字来自事后的实验室复现,不代表持票人在现场等了多久,也不代表受影响人数。 + +## 时间线 + +- 2026-10-24 周六开门前:hub 取得当天票单并重启。north1 和 north2 保持在线,但把新售出的票判为 `not_in_list`;其他入口正常放行。Fatima 让受影响的持票人改走东入口,留下闸机日志;无人收到告警。 +- 2026-10-26 周一:Ingrid 把 10 月 3 日复盘中已经逾期的数据中心告警事项转交 Ben Carter,与 Noah Williams 合作,期限为 10 月 29 日。Yuki 按现场配置把北入口网段和防火墙加入实验室。Noah 用 `lab/north-entrance.sh` 复现:MTU 1400 时输出 `result: north1 new list FAIL (not installed within 90 s; gate1 installed it)` 和 `result: north1 new ticket FAIL (GP-900000000003 not_in_list)`;MTU 1200 时握手也失败,还输出 `result: north1 hub link FAIL (offline during old-ticket scan)`。 +- 2026-10-27 周二:Yuki 修改 `lab/compose.yaml`,让路由器向 hub 返回“需要分片”,Aisha 完成复核。原样重跑演练,两个 MTU 下都输出 `result: north1 ok`。Mateo 在 `tests/test_ticket_fetch_progress.py` 中让下载失败日志说明进度;实验室黑洞后的 north1 记录 `event=ticket_fetch state=failed http=200 curl=28 reason=timeout phase=body received=0 expected=17706`。Ben 用 `tests/test_ticket_reply_count.py` 证明,中途断开的票单回复仍被计为 200。 +- 2026-10-28 周三:hub 改为只把完整回复计为 200,其他计为 `status="incomplete"`。Mateo 和 Ben 让闸机在心跳中报告已安装的票单版本,hub 将其与当前版本比较(`tests/test_gate_list_version.py`)。Wang 和 Yuki 为场馆实验室加入 Prometheus、Grafana(`lab/monitoring.yaml`)。Ben 从闸机票单状态中去掉了未识别连接造成的“unknown”行。 +- 2026-10-29 周四:Noah 的 `lab/dc-alert.sh` 表明,数据中心不可达或上行监视脚本停止时都无人收到通知。Ben 为两种情况加入邮件告警,Yuki 补上监视脚本的心跳。Wang 让数据中心以文本形式发布签名的季票单;实验室票单含 20000 张票,大小为 3,488,890 字节。 +- 2026-10-30 周五:Noah 的 `tests/test_hub_season_reload.py`、`tests/test_hub_served_list.py` 和 `tests/test_hub_tickets_send_change.py` 暴露出 hub 本周运行版本的四个问题:`result: season-only ticket still rejected 10 s after a successful sync (successes=1)`、`result: /tickets served the changed file while the hub decides with the list it loaded`、`result: grown file: sent 1048576 bytes beyond Content-Length 21473706`、`result: shrunk file: sent 10736690 of 21473706 body bytes and counted the reply as 200`。Ben 让 hub 用同一份不可变的、已验证季票单作判断和对外提供票单。Noah 改为通过数据中心更新演练票单。随后,`lab/status-stall-blackhole.sh` 显示,北入口闸机丢失的下载会占住 hub 当时一次只服务一条连接的 TLS 状态端口 8444;即使网络正常,停止读取的客户端也能造成同样情况。Ben 将 8444 改为四个工作线程和容量为 16 的队列。当天下午,团队召开复盘会。 + +## 原因与发现 + +闸机每次扫码和链路检查都会新建 TLS 连接。hub 首轮握手发出 1,250 字节 TLS 记录(`lab/captures/socket-exchange/tls-connection.txt`),组成一个 1,302 字节 IP 包(`lab/captures/socket-exchange/tls-connection.pcap`);大小取决于证书链。它小于 MTU 1400,所以闸机可以保持在线并扫码。票单正文却装在 1500 字节的包里发出,被北入口链路丢弃。入口防火墙过滤了“需要分片”,路由器便无法通知 hub 改发较小的包。实验室把 MTU 降到 1200 后,连握手也过不去,因此那次复现呈现为闸机离线,而不是只缺新票单。 + +现场留下的证据是闸机日志;旧票单没有触发告警。周五修复 hub 之前,`/tickets` 提供的是磁盘上当时的文件,而放行判断仍使用启动时加载的票单。闸机取到的票单可能与 hub 判断用的票单不同。这是另一个发现,并非北入口丢包的原因。实验室现在能通过未完成回复的指标和闸机票单版本状态看见下载中断、安装过期;数据中心与监视脚本的邮件告警也结清了上次复盘的逾期事项。 + +## 恢复测量与行动 + +路由器改动后,北入口原样演练在两种 MTU 下均通过。这些是实验室结果,没有测出现场恢复用了多久。闸机的 `phase=body received=0 expected=17706` 日志说明 HTTP 响应头已经到达,票单正文却一个字节也没收到,可与握手失败区分。hub 现在把中断回复计为 `status="incomplete"`,并比较闸机报告的已安装版本与当前版本,能显示交付未完成或闸机仍在使用旧票单。已验证季票单的同一份不可变副本同时用于放行判断和 `/tickets`,也消除了周五测试暴露的文件变化问题。 + +在 `lab/status-stall-blackhole.sh` 中恢复黑洞,并使用 3,488,890 字节的季票单后,一台北入口闸机丢失的下载每隔 20 s 就占住 hub 当时一次只服务一条连接的 TLS 状态端口 8444 约 6.1 s(`held_ms` 为 6126 至 6161)。场馆闸机的 `/status` 请求要等同样久,票单下载在 300 ms 后超时。hub 换上新票单后,场馆闸机分别用了 18、38、58 s,或超过 60 s 才安装。约 6 s 是三步,每步最多等 2 s:hub 每次写入前都会重新设定发送期限,前两次只写出了一部分,第三次一个字节也没写出去。即使网络健康,客户端停止读取也能这样占住端口。 + +8444 改为四个工作线程、容量为 16 的队列后,同一实验室演练中,`/status` 最长等待 0.05 s。每台北入口闸机仍各占一个工作线程约 6.1 s,但两台场馆闸机都在 hub 更新后 18 s 安装了新票单。这个改动让卡住的下载不再拖累其他闸机,但那次下载本身仍然完不成。 + +未完成事项: + +| 行动 | 负责人 | 期限 | 状态 | +|---|---|---|---| +| 在 ADR 0020 中记录闸机仍在扫码循环里同步下载票单,期限为 300 ms。3,488,890 字节的正文若要在限时内收完,链路至少约需 93 Mbit/s(3,488,890 × 8 / 0.3 s),加上 TLS 握手还需更快;较慢的链路只能靠 304 回复维持旧票单。将下载移出扫码循环由 Mateo Rossi 负责,目前未排期。 | Ingrid Larsen 和 Yuki Tanaka | 2026-10-30 | 未完成 | +| 复查仍由单线程服务的 8081 端口;该端口只供工作人员使用。 | Ben Carter | 尚未排期 | 未完成 | +| 为闸机对齐的 20 s 取票周期加入抖动,避免同时请求。 | Mateo Rossi | 尚未排期 | 未完成 | + +## 学到的事 + +闸机在线、扫码连接成功,不能证明更大的票单也能穿过同一条路径。防火墙的 ICMP 规则让 hub 无从得知北入口链路的 MTU,而较小的握手包掩盖了差异。闸机票单版本、未完成回复计数和下载进度日志让这类问题有了可见证据。随后对季票单和停止读取的客户端的测试还表明,票单一致性和共用状态端口也会影响其他入口的放行。实验室改动降低了这些影响;扫码循环内下载的限时、工作人员端口和同步取票周期仍需处理。 diff --git a/gate-hub/main.c b/gate-hub/main.c index 77d7985..d0a2193 100644 --- a/gate-hub/main.c +++ b/gate-hub/main.c @@ -5,6 +5,7 @@ #include "metrics.h" #include "prometheus.h" #include "protocol_io.h" +#include "queue.h" #include "report.h" #include "reports.h" #include "season.h" @@ -31,16 +32,6 @@ /* SCAN, gate ID and barcode, with room to read LF and append NUL. */ enum { LINE_SIZE = 5 + 63 + 1 + GATE_BARCODE_MAX + 2, QUEUE_SIZE = 64, WORKERS = 8 }; -typedef struct { - int fd; - struct sockaddr_in address; -} accepted_client; -typedef struct { - accepted_client sockets[QUEUE_SIZE]; - size_t head, tail, count; - pthread_mutex_t mutex; - pthread_cond_t not_empty, not_full; -} queue; typedef struct { gate_store store; admission *entries; @@ -1000,59 +991,6 @@ static void *connection_thread(void *argument) { return NULL; } -static int queue_init(queue *q) { - if (pthread_mutex_init(&q->mutex, NULL) != 0) - return -1; - if (pthread_cond_init(&q->not_empty, NULL) != 0) { - pthread_mutex_destroy(&q->mutex); - return -1; - } - if (pthread_cond_init(&q->not_full, NULL) != 0) { - pthread_cond_destroy(&q->not_empty); - pthread_mutex_destroy(&q->mutex); - return -1; - } - return 0; -} - -static int queue_put(queue *q, accepted_client accepted) { - if (pthread_mutex_lock(&q->mutex) != 0) - return -1; - while (q->count == QUEUE_SIZE) - if (pthread_cond_wait(&q->not_full, &q->mutex) != 0) { - pthread_mutex_unlock(&q->mutex); - return -1; - } - q->sockets[q->tail] = accepted; - q->tail = (q->tail + 1) % QUEUE_SIZE; - ++q->count; - prometheus_queue(q->count); - int result = pthread_cond_signal(&q->not_empty); - if (pthread_mutex_unlock(&q->mutex) != 0) - return -1; - return result == 0 ? 0 : -1; -} - -static int queue_get(queue *q, accepted_client *accepted) { - if (pthread_mutex_lock(&q->mutex) != 0) - return -1; - while (q->count == 0) - if (pthread_cond_wait(&q->not_empty, &q->mutex) != 0) { - pthread_mutex_unlock(&q->mutex); - return -1; - } - *accepted = q->sockets[q->head]; - q->head = (q->head + 1) % QUEUE_SIZE; - --q->count; - prometheus_queue(q->count); - int result = pthread_cond_signal(&q->not_full); - if (pthread_mutex_unlock(&q->mutex) != 0 || result != 0) { - close(accepted->fd); - return -1; - } - return 0; -} - static void *pool_worker(void *argument) { hub *owner = argument; for (;;) { @@ -1165,7 +1103,7 @@ int main(int argc, char **argv) { } bool pooled = strcmp(argv[3], "pool") == 0; if (pooled) { - if (queue_init(&owner.work) != 0) { + if (queue_init(&owner.work, QUEUE_SIZE, prometheus_queue) != 0) { gate_log_errno("queue_init"); goto finish; } diff --git a/gate-hub/prometheus.c b/gate-hub/prometheus.c index 62b2a6a..a9ee50d 100644 --- a/gate-hub/prometheus.c +++ b/gate-hub/prometheus.c @@ -45,6 +45,7 @@ static struct { unsigned long long http_other[HTTP_STATUSES]; unsigned long long http_tickets_incomplete; unsigned long long tls_failures[2][TLS_REASONS]; + unsigned long long status_queue_full; } data = {.lock = PTHREAD_MUTEX_INITIALIZER}; static gate_record *find_gate(const char *name, int fold_when_full) { @@ -197,6 +198,12 @@ void prometheus_tls_failure(int status_listener, const char *reason) { ++data.tls_failures[status_listener ? 1 : 0][index < TLS_REASONS ? index : protocol]; (void)pthread_mutex_unlock(&data.lock); } +void prometheus_status_queue_full(void) { + if (pthread_mutex_lock(&data.lock) != 0) + return; + ++data.status_queue_full; + (void)pthread_mutex_unlock(&data.lock); +} int prometheus_render(const char *version, double age, char **body, size_t *length) { FILE *out = open_memstream(body, length); if (!out) @@ -314,6 +321,12 @@ int prometheus_render(const char *version, double age, char **body, size_t *leng "gatepost_tls_handshake_failures_total{listener=\"%s\",reason=\"%s\"} %llu\n", listener ? "status" : "gate", tls_reasons[reason], data.tls_failures[listener][reason]); + fprintf(out, + "# HELP gatepost_status_queue_full_total TLS status connections refused when the work " + "queue is full.\n" + "# TYPE gatepost_status_queue_full_total counter\n" + "gatepost_status_queue_full_total{listener=\"status\"} %llu\n", + data.status_queue_full); (void)pthread_mutex_unlock(&data.lock); if (fclose(out) != 0) { free(*body); diff --git a/gate-hub/prometheus.h b/gate-hub/prometheus.h index a3dfba4..cc18b39 100644 --- a/gate-hub/prometheus.h +++ b/gate-hub/prometheus.h @@ -13,5 +13,6 @@ 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); +void prometheus_status_queue_full(void); int prometheus_render(const char *version, double list_age_seconds, char **body, size_t *length); #endif diff --git a/gate-hub/queue.c b/gate-hub/queue.c new file mode 100644 index 0000000..2d8a98c --- /dev/null +++ b/gate-hub/queue.c @@ -0,0 +1,83 @@ +#include "queue.h" +#include +#include + +int queue_init(queue *q, size_t capacity, void (*depth)(size_t)) { + if (!capacity || capacity > QUEUE_STORAGE) { + errno = EINVAL; + return -1; + } + q->capacity = capacity; + q->depth = depth; + if (pthread_mutex_init(&q->mutex, NULL) != 0) + return -1; + if (pthread_cond_init(&q->not_empty, NULL) != 0) { + pthread_mutex_destroy(&q->mutex); + return -1; + } + if (pthread_cond_init(&q->not_full, NULL) != 0) { + pthread_cond_destroy(&q->not_empty); + pthread_mutex_destroy(&q->mutex); + return -1; + } + return 0; +} + +int queue_put(queue *q, accepted_client accepted) { + if (pthread_mutex_lock(&q->mutex) != 0) + return -1; + while (q->count == q->capacity) + if (pthread_cond_wait(&q->not_full, &q->mutex) != 0) { + pthread_mutex_unlock(&q->mutex); + return -1; + } + q->sockets[q->tail] = accepted; + q->tail = (q->tail + 1) % q->capacity; + ++q->count; + if (q->depth) + q->depth(q->count); + int result = pthread_cond_signal(&q->not_empty); + if (pthread_mutex_unlock(&q->mutex) != 0) + return -1; + return result == 0 ? 0 : -1; +} + +int queue_try_put(queue *q, accepted_client accepted) { + if (pthread_mutex_lock(&q->mutex) != 0) + return -1; + if (q->count == q->capacity) { + if (pthread_mutex_unlock(&q->mutex) != 0) + return -1; + return 1; + } + q->sockets[q->tail] = accepted; + q->tail = (q->tail + 1) % q->capacity; + ++q->count; + if (q->depth) + q->depth(q->count); + int result = pthread_cond_signal(&q->not_empty); + if (pthread_mutex_unlock(&q->mutex) != 0) + return -1; + return result == 0 ? 0 : -1; +} + +int queue_get(queue *q, accepted_client *accepted) { + if (pthread_mutex_lock(&q->mutex) != 0) + return -1; + while (q->count == 0) + if (pthread_cond_wait(&q->not_empty, &q->mutex) != 0) { + pthread_mutex_unlock(&q->mutex); + return -1; + } + *accepted = q->sockets[q->head]; + q->head = (q->head + 1) % q->capacity; + --q->count; + if (q->depth) + q->depth(q->count); + int result = pthread_cond_signal(&q->not_full); + if (pthread_mutex_unlock(&q->mutex) != 0 || result != 0) { + close(accepted->fd); + return -1; + } + return 0; +} diff --git a/gate-hub/queue.h b/gate-hub/queue.h new file mode 100644 index 0000000..7f78c2c --- /dev/null +++ b/gate-hub/queue.h @@ -0,0 +1,26 @@ +#ifndef GATE_HUB_QUEUE_H +#define GATE_HUB_QUEUE_H +#include +#include +#include + +enum { QUEUE_STORAGE = 64 }; +typedef struct { + int fd; + struct sockaddr_in address; +} accepted_client; +typedef struct { + accepted_client sockets[QUEUE_STORAGE]; + size_t head, tail, count; + size_t capacity; + void (*depth)(size_t); + pthread_mutex_t mutex; + pthread_cond_t not_empty, not_full; +} queue; + +int queue_init(queue *q, size_t capacity, void (*depth)(size_t)); +int queue_put(queue *q, accepted_client accepted); +/* Returns 1 when full, leaving the connection with the caller; -1 on error. */ +int queue_try_put(queue *q, accepted_client accepted); +int queue_get(queue *q, accepted_client *accepted); +#endif diff --git a/gate-hub/status.c b/gate-hub/status.c index 119de78..1b6c993 100644 --- a/gate-hub/status.c +++ b/gate-hub/status.c @@ -2,6 +2,7 @@ #define _POSIX_C_SOURCE 200809L #include "log.h" #include "prometheus.h" +#include "queue.h" #include "season.h" #include "tls.h" #include @@ -21,7 +22,12 @@ #include #include -enum { STATUS_STEP_MS = 2000, STATUS_CONNECTION_MS = 10000 }; +enum { + STATUS_STEP_MS = 2000, + STATUS_CONNECTION_MS = 10000, + STATUS_TLS_WORKERS = 4, + STATUS_TLS_QUEUE = 16 +}; /* A sender takes one reference, then releases this leaf lock before writing. */ static pthread_mutex_t snapshot_lock = PTHREAD_MUTEX_INITIALIZER; static season_snapshot *current_snapshot; @@ -73,7 +79,7 @@ season_snapshot *season_snapshot_swap(season_snapshot *snapshot) { pthread_mutex_unlock(&snapshot_lock); return old; } -/* Each status thread serves one connection at a time; this is its connection's deadline. */ +/* Each status worker serves one connection at a time; this is its connection's deadline. */ static _Thread_local long long connection_deadline_ms; static _Thread_local bool connection_timed_out; static _Thread_local bool connection_tls_fatal; @@ -410,10 +416,62 @@ typedef struct { SSL_CTX *context; unsigned short port; bool tickets_tls_only; + queue work; } status_listener; static status_listener plain_listener = {.port = 8081}; static status_listener tls_listener = {.port = 8444}; +static void serve_connection(status_listener *settings, accepted_client accepted) { + int fd = accepted.fd; + struct sockaddr_in peer = accepted.address; + SSL_CTX *context = settings->context; + long long started = now_ms(); + connection_deadline_ms = started + STATUS_CONNECTION_MS; + connection_timed_out = false; + connection_tls_fatal = false; + connection_reply_complete = false; + char address[INET_ADDRSTRLEN]; + (void)inet_ntop(AF_INET, &peer.sin_addr, address, sizeof address); + char gate_id[64]; + const char *reason = NULL; + SSL *tls = context ? hub_tls_accept(context, fd, gate_id, deadline_io, 0, &reason) : NULL; + if (context && !tls) { + /* A handshake that ran out of time is logged once below, as a timeout. */ + if (!connection_timed_out) + hub_tls_failure_note(1, &peer, reason); + else + prometheus_tls_failure(1, "timeout"); + } else { + if (tls) + hub_tls_success_note(1, &peer); + serve_status(fd, tls, settings->tickets_tls_only, &peer); + } + bool timed_out_before_close = connection_timed_out; + if (tls && connection_reply_complete && !timed_out_before_close && !connection_tls_fatal) { + /* A failed close_notify cannot turn a complete reply into a timeout. */ + (void)SSL_shutdown(tls); + } + if (timed_out_before_close) { + gate_log("WARN", "status_client", "state=timeout peer=%s held_ms=%lld", address, + now_ms() - started); + } + SSL_free(tls); + if (close(fd) != 0) + gate_log_errno("status_close"); +} + +static void *status_worker(void *argument) { + status_listener *settings = argument; + for (;;) { + accepted_client accepted; + if (queue_get(&settings->work, &accepted) < 0) + break; + serve_connection(settings, accepted); + } + SSL_CTX_free(settings->context); + return NULL; +} + static void *status_loop(void *argument) { status_listener *settings = argument; SSL_CTX *context = settings->context; @@ -440,6 +498,36 @@ static void *status_loop(void *argument) { } if (context) gate_log("INFO", "ticket_listener", "port=8444 state=tls"); + if (context) { + if (queue_init(&settings->work, STATUS_TLS_QUEUE, NULL) != 0) { + gate_log_errno("status_queue_init"); + close(listener); + goto done; + } + for (int i = 0; i < STATUS_TLS_WORKERS; ++i) { + if (SSL_CTX_up_ref(context) != 1) { + close(listener); + goto done; + } + pthread_t worker; + int rc = pthread_create(&worker, NULL, status_worker, settings); + if (rc) { + SSL_CTX_free(context); + errno = rc; + gate_log_errno("pthread_create"); + close(listener); + goto done; + } + rc = pthread_detach(worker); + if (rc) { + errno = rc; + gate_log_errno("pthread_detach"); + close(listener); + goto done; + } + } + } + long long last_full_log = 0; for (;;) { struct sockaddr_in peer = {0}; socklen_t peer_length = sizeof peer; @@ -449,39 +537,26 @@ static void *status_loop(void *argument) { continue; break; } - long long started = now_ms(); - connection_deadline_ms = started + STATUS_CONNECTION_MS; - connection_timed_out = false; - connection_tls_fatal = false; - connection_reply_complete = false; - char address[INET_ADDRSTRLEN]; - (void)inet_ntop(AF_INET, &peer.sin_addr, address, sizeof address); - char gate_id[64]; - const char *reason = NULL; - SSL *tls = context ? hub_tls_accept(context, fd, gate_id, deadline_io, 0, &reason) : NULL; - if (context && !tls) { - /* A handshake that ran out of time is logged once below, as a timeout. */ - if (!connection_timed_out) - hub_tls_failure_note(1, &peer, reason); - else - prometheus_tls_failure(1, "timeout"); - } else { - if (tls) - hub_tls_success_note(1, &peer); - serve_status(fd, tls, settings->tickets_tls_only, &peer); - } - bool timed_out_before_close = connection_timed_out; - if (tls && connection_reply_complete && !timed_out_before_close && !connection_tls_fatal) { - /* A failed close_notify cannot turn a complete reply into a timeout. */ - (void)SSL_shutdown(tls); + accepted_client accepted = {.fd = fd, .address = peer}; + if (!context) { + serve_connection(settings, accepted); + continue; } - if (timed_out_before_close) { - gate_log("WARN", "status_client", "state=timeout peer=%s held_ms=%lld", address, - now_ms() - started); + int result = queue_try_put(&settings->work, accepted); + if (result == 1) { + (void)close(fd); + prometheus_status_queue_full(); + long long now = now_ms(); + if (now - last_full_log >= 1000) { + char address[INET_ADDRSTRLEN]; + (void)inet_ntop(AF_INET, &peer.sin_addr, address, sizeof address); + gate_log("WARN", "status_queue", "state=full peer=%s", address); + last_full_log = now; + } + } else if (result != 0) { + (void)close(fd); + break; } - SSL_free(tls); - if (close(fd) != 0) - gate_log_errno("status_close"); } if (close(listener) != 0) gate_log_errno("status_listener_close"); diff --git a/lab/README.md b/lab/README.md index 7371af0..ece0487 100644 --- a/lab/README.md +++ b/lab/README.md @@ -39,7 +39,9 @@ With the lab running, `sh lab/device-tls.sh` first checks that the SHA-256 of th With the lab running, `sh lab/tls/record.sh` writes small text records to `lab/captures/device-tls/`: each device chain's verification result, gate1's TLS 1.3 HELLO and CONFIG replies on 7000, its authenticated ticket-list status and byte count on 8444, the hub's 200 and conditional 304 with ETag from the data-centre stub on 8443, and the hub's `dc_sync` and `dc_link` lines without `time=`. The script fails if an expected reply is missing and does not print keys, barcodes or ticket IDs. -Run `sh lab/status-stall.sh` to stall gate2’s ticket download over TLS on port 8444. By default it uses the data centre’s 20000-ticket season list; set `STALL_EXTRA` to sign and publish that many additional tickets before the stall. It prints the served ticket count and byte size, asks `/status` every five seconds on hub port 8081 and gate1 port 8444 with its certificate, and reports the hub send queue and relevant logs. `WATCH` sets the observation time. Cleanup restores the previous data-centre extra file, waits for the hub and checked gates to install the restored list, and removes the network rules. +Run `sh lab/status-stall.sh` to stall gate2’s ticket download over TLS on port 8444. By default it uses the data centre’s 20000-ticket season list; set `STALL_EXTRA` to sign and publish that many additional tickets before the stall. With the default `STALL_EXTRA=0`, the season list alone (about 3.5 MB) already holds the hub’s sender in this lab; raise `STALL_EXTRA` only if a faster machine sends the whole list before the stall appears and the drill no longer reports a hold. It prints the served ticket count and byte size, asks `/status` every five seconds on hub port 8081 and gate1 port 8444 with its certificate, and reports the hub send queue and relevant logs. `WATCH` sets the observation time. Cleanup restores the previous data-centre extra file, waits for the hub and checked gates to install the restored list, and removes the network rules. + +Run `sh lab/status-stall-blackhole.sh` with all four gates running to remove the router's ICMP fragmentation-needed ACCEPT rule, set the north interface MTU to 1400, and publish three signed tickets through the data centre. For 60 seconds it probes 8444 `/status` from gate1, reports waits over one second, hub and venue-gate logs, whether both venue gates installed the new list, and the hub's 8081 `/status` time. A wait over one second prints the held-listener result and exits 1; otherwise it exits 0, while an environment mismatch or failed cleanup exits 2. Cleanup stops the probe, restores the MTU and exact OUTPUT chain, restores the extra ticket file, restarts the hub to clear learned path MTU, and waits for all four gates to reinstall the original list. On a healthy network, a client that stops reading similarly holds one of the four 8444 workers. ```mermaid flowchart LR diff --git a/lab/README.zh-CN.md b/lab/README.zh-CN.md index b769076..1b91458 100644 --- a/lab/README.zh-CN.md +++ b/lab/README.zh-CN.md @@ -39,7 +39,9 @@ after connection duration ms: 3.6 实验环境启动后,运行 `sh lab/tls/record.sh`,将简短文本记录写入 `lab/captures/device-tls/`:各设备证书链的验证结果、gate1 在 7000 上通过 TLS 1.3 收到的 HELLO 和 CONFIG 回复、在 8444 上持证获取票单的 HTTP 状态及字节数、hub 在 8443 上从数据中心替身取得的 200 与带 ETag 条件请求的 304,以及去掉 `time=` 的 hub `dc_sync` 和 `dc_link` 日志。缺少预期回复时脚本失败;输出不含密钥、条码或票号。 -运行 `sh lab/status-stall.sh`,让 gate2 在 8444 端口通过 TLS 下载票单时停住。默认使用数据中心原有的 20000 张票;设置 `STALL_EXTRA` 后,脚本会自行签署指定数量的新票,经数据中心发布,再制造停滞。脚本先打印 hub 实际提供的票数和字节数,然后每五秒分别由 hub 查询 8081 的 `/status`、由 gate1 持证书查询 8444 的 `/status`,最后报告 hub 的发送队列及相关日志。`WATCH` 设置观察时长。收尾恢复数据中心额外票文件的原内容,等待 hub 和所检查的闸机装回原票单,并撤销网络规则。 +运行 `sh lab/status-stall.sh`,让 gate2 在 8444 端口通过 TLS 下载票单时停住。默认使用数据中心原有的 20000 张票;设置 `STALL_EXTRA` 后,脚本会自行签署指定数量的新票,经数据中心发布,再制造停滞。默认 `STALL_EXTRA=0` 时,单靠约 3.5 MB 的季票单就足以在本实验中占住 hub 的发送端;只有在更快的机器上整份票单已发完、停滞尚未出现,导致演练不再报告发送端被占住时,才调高 `STALL_EXTRA`。脚本先打印 hub 实际提供的票数和字节数,然后每五秒分别由 hub 查询 8081 的 `/status`、由 gate1 持证书查询 8444 的 `/status`,最后报告 hub 的发送队列及相关日志。`WATCH` 设置观察时长。收尾恢复数据中心额外票文件的原内容,等待 hub 和所检查的闸机装回原票单,并撤销网络规则。 + +四台闸机都运行时,执行 `sh lab/status-stall-blackhole.sh`。脚本移除路由器允许发送“需要分片”ICMP 的规则,将北侧接口 MTU 设为 1400,再通过数据中心发布三张新签名票;随后由 gate1 连续 60 秒探测 8444 的 `/status`,列出超过一秒的等待、hub 与场馆闸机日志、两台场馆闸机是否装上新票单,以及 hub 的 8081 `/status` 用时。只要有一次等待超过一秒,就报告 8444 被占住并以 1 退出;全部在一秒内应答则以 0 退出,环境不符或收尾失败以 2 退出。收尾停止探测,恢复 MTU 和原样的 OUTPUT 链,还原额外票文件,重启 hub 清除学到的路径 MTU,并等待四台闸机装回原票单。即使网络正常,下载时停止读取的客户端也会占住 8444 的四个工作线程之一。 ```mermaid flowchart LR diff --git a/lab/compose.yaml b/lab/compose.yaml index caaf1f2..b99f558 100644 --- a/lab/compose.yaml +++ b/lab/compose.yaml @@ -285,7 +285,7 @@ services: networks: venue: {ipv4_address: 10.77.20.53} mail: - image: axllent/mailpit:v1.27.7 + image: axllent/mailpit:v1.27.7@sha256:cae83a33cd9b9598e4acb210be673dda7e741d5271ed4045310ab456950a136a environment: MP_SMTP_BIND_ADDR: 0.0.0.0:587 MP_SMTP_TLS_CERT: /tls/test-cert.pem diff --git a/lab/status-stall-blackhole.sh b/lab/status-stall-blackhole.sh new file mode 100755 index 0000000..ee6010b --- /dev/null +++ b/lab/status-stall-blackhole.sh @@ -0,0 +1,256 @@ +#!/bin/sh +# Show whether a north download lost to a path-MTU black hole holds the TLS status listener. +set -eu +export LC_ALL=C +umask 077 +cd "$(dirname "$0")/.." + +compose='docker compose -f lab/compose.yaml' +. lab/season-extra.sh +backup= +iface= +original_mtu= +rule_removed=0 +mtu_changed=0 +changed=0 +probe_started=0 +probe_base=/tmp/status-stall-blackhole-$$ +judged=0 +mismatch_reported=0 +rule='-A OUTPUT -p icmp -m icmp --icmp-type 3/4 -j ACCEPT' + +run() { service=$1; shift; $compose exec -T "$service" env LC_ALL=C "$@"; } +logs() { $compose logs --no-color --no-log-prefix "$1"; } +lines() { logs "$1" | awk 'END { print NR + 0 }'; } +now() { date +%s; } +mismatch() { mismatch_reported=1; printf 'environment mismatch: %s\n' "$1" >&2; exit 2; } +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 +} +gate_etag() { run "$1" cat /var/lib/gatepost/tickets.txt.etag 2>/dev/null || :; } +cleanup() { + status=$? + trap - 0 + trap '' HUP INT TERM + bad=0 + if [ "$probe_started" -eq 1 ]; then + if run gate1 sh -c 'if [ -f "$1.pid" ]; then kill "$(cat "$1.pid")" 2>/dev/null || :; fi; rm -f "$1.pid" "$1.done" "$1.results"' sh "$probe_base"; then + printf 'cleanup: gate1 probe stopped ok\n' + else + printf 'cleanup: gate1 probe FAIL\n' >&2; bad=1 + fi + fi + if [ "$mtu_changed" -eq 1 ]; then + if run router ip link set dev "$iface" mtu "$original_mtu" && + [ "$(run router cat "/sys/class/net/$iface/mtu" 2>/dev/null || :)" = "$original_mtu" ]; then + printf 'cleanup: router mtu %s ok\n' "$original_mtu" + else + printf 'cleanup: router mtu FAIL\n' >&2; bad=1 + fi + fi + if [ "$rule_removed" -eq 1 ]; then + if run router iptables -I OUTPUT "$rule_position" -p icmp -m icmp --icmp-type 3/4 -j ACCEPT; then + printf 'cleanup: fragmentation-needed rule restored ok\n' + else + printf 'cleanup: fragmentation-needed rule FAIL\n' >&2; bad=1 + fi + fi + if [ -n "$backup" ] && [ -f "$backup/output.before" ]; then + if run router iptables -S OUTPUT > "$backup/output.after" && + cmp -s "$backup/output.before" "$backup/output.after"; then + printf 'cleanup: router OUTPUT restored ok\n' + else + printf 'cleanup: router OUTPUT restored FAIL\n' >&2; bad=1 + fi + fi + if [ -n "$backup" ]; then + if [ "$changed" -eq 1 ]; then + cleanup_first=$(season_hub_lines) + if season_extra_replace "$backup/season-extra.txt" && + cmp -s "$backup/season-extra.txt" "$season_extra"; then + printf 'cleanup: data centre extra tickets restored ok\n' + else + printf 'cleanup: data centre extra tickets FAIL\n' >&2; bad=1 + fi + if season_wait_hub "$cleanup_first" "$original_count" "$original_hash" "$(( $(now) + 90 ))"; then + printf 'cleanup: hub original list installed ok\n' + else + printf 'cleanup: hub original list FAIL\n' >&2; bad=1 + fi + # Restart the hub container so it forgets the path MTU it learned for the north gates. + if $compose restart hub && wait_hub; then + printf 'cleanup: hub restarted and /status ready ok\n' + else + printf 'cleanup: hub restart or /status FAIL\n' >&2; bad=1 + fi + gate_deadline=$(( $(now) + 90 )) + for gate in gate1 gate2 north1 north2; do + if season_wait_gate "$gate" "$original_hash" "$gate_deadline"; then + printf 'cleanup: %s original list installed ok\n' "$gate" + else + printf 'cleanup: %s original list FAIL\n' "$gate" >&2; bad=1 + fi + done + fi + fi + if [ "$bad" -ne 0 ]; then status=2; fi + if [ -n "$backup" ]; then + if [ "$status" -eq 0 ]; then + if ! rm -r "$backup"; then + printf 'cleanup: backup removal FAIL\n' >&2; status=2 + fi + fi + if [ "$status" -ne 0 ]; then printf 'cleanup: backup=%s\n' "$backup" >&2; fi + fi + if [ "$status" -ne 2 ] && [ "$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 + +backup=$(mktemp -d lab/keys/generated/.status-stall-blackhole.XXXXXX) +cp -p "$season_extra" "$backup/season-extra.txt" +wait_hub || mismatch 'hub /status on 8081' +season_served_file "$backup/original.txt" || mismatch 'hub served ticket list' +original_count=$(wc -l < "$backup/original.txt" | tr -d ' ') +[ "$original_count" -ge 20000 ] || mismatch 'hub served list has fewer than 20000 tickets' +original_hash=$(sha256sum "$backup/original.txt" | awk '{ print $1 }') +[ "$(season_served_etag)" = "\"$original_hash\"" ] || mismatch 'hub served ETag differs from its list' +for gate in gate1 gate2 north1 north2; do + [ "$(gate_etag "$gate")" = "\"$original_hash\"" ] || mismatch "$gate has not installed the served list" +done +run router iptables -S OUTPUT > "$backup/output.before" || mismatch 'router OUTPUT chain' +rule_position=$(awk -v rule="$rule" '/^-A OUTPUT / { position++; if ($0 == rule) { hits++; found=position } } + END { if (hits == 1) print found }' "$backup/output.before") +[ -n "$rule_position" ] || mismatch 'router fragmentation-needed ACCEPT rule must appear exactly once' +iface=$(run router ip -o -4 addr show | awk '$4 ~ /^10\.77\.11\.2\// { print $2 }') +[ "$(printf '%s\n' "$iface" | awk 'NF { n++ } END { print n+0 }')" -eq 1 ] || mismatch 'north router interface' +original_mtu=$(run router cat "/sys/class/net/$iface/mtu") || mismatch 'north router MTU' +case $original_mtu in *[!0-9]*|'') mismatch 'north router MTU' ;; esac +hub_first=$(lines hub) +gate1_first=$(lines gate1) +gate2_first=$(lines gate2) + +# Dropping only fragmentation-needed feedback makes the 1400-byte north link a black hole for full bodies. +run router iptables -D OUTPUT -p icmp -m icmp --icmp-type 3/4 -j ACCEPT || mismatch 'cannot remove fragmentation-needed rule' +rule_removed=1 +mtu_changed=1 +run router ip link set dev "$iface" mtu 1400 || mismatch 'cannot set north router MTU' +[ "$(run router cat "/sys/class/net/$iface/mtu")" = 1400 ] || mismatch 'north router MTU did not read back' +printf 'fault: router %s mtu=1400, fragmentation-needed not sent\n' "$iface" + +# Publish three fresh signed entries through the data centre to start full north downloads. +if ! awk -F '|' '{ used[$4]=1 } END { for (n=900000000001;n<=900000000003;n++) { + id=sprintf("GP-%012.0f",n); if (id in used) exit 1; + printf "event7,%s,north-%d\n",id,n-900000000000 +} }' "$backup/original.txt" > "$backup/new.csv"; then mismatch 'three new ticket ids collide'; fi +if ! docker run --rm -i --user "$(id -u):$(id -g)" \ + -v "$PWD/lab/keys/generated/signing-secret.hex:/signing-secret.hex:ro" \ + gatepost-venue:local sh -c 'cat > /tmp/north.csv; exec /src/build/debug/ticket_sign sign /signing-secret.hex season1 /tmp/north.csv' \ + < "$backup/new.csv" > "$backup/new.txt"; then mismatch 'three new tickets were not signed'; fi +[ "$(wc -l < "$backup/new.txt")" -eq 3 ] || mismatch 'three new tickets were not signed' +cat "$backup/original.txt" "$backup/new.txt" > "$backup/expected.txt" +new_hash=$(sha256sum "$backup/expected.txt" | awk '{ print $1 }') +new_count=$((original_count + 3)) +install_first=$(lines hub) +changed=1 +season_extra_append "$backup/new.txt" || mismatch 'data centre extra tickets were not published' +season_wait_hub "$install_first" "$new_count" "$new_hash" "$(( $(now) + 60 ))" || mismatch 'hub did not install data centre list' +hub_installed_us=$(logs hub | awk -v first="$install_first" -v count="tickets=$new_count" ' + NR > first && /event=season_list state=installed / && index(" " $0 " ", " " count " ") { + split($1, field, "="); print field[2]; exit + }') +[ -n "$hub_installed_us" ] || mismatch 'hub install time missing' +season_served_file "$backup/served.txt" || mismatch 'hub new ticket list unavailable' +[ "$(sha256sum "$backup/served.txt" | awk '{ print $1 }')" = "$new_hash" ] || mismatch 'hub served new list differs' +printf 'hub served list: %s tickets, %s bytes\n' \ + "$(wc -l < "$backup/served.txt" | tr -d ' ')" "$(wc -c < "$backup/served.txt" | tr -d ' ')" + +# Each gate1 TLS status request records its start and total wait during three ticket-fetch cycles. +probe_started=1 +$compose exec -T -d gate1 python3 -u -c ' +import os, socket, ssl, sys, time +base = sys.argv[1] +with open(base + ".pid", "w") as pid: + pid.write(str(os.getpid())) +ctx = ssl.create_default_context(cafile="/etc/gatepost/tls/ca.pem") +ctx.load_cert_chain("/etc/gatepost/tls/chain.pem", "/etc/gatepost/tls/key.pem") +end = time.monotonic() + 60 +with open(base + ".results", "w", buffering=1) as out: + while time.monotonic() < end: + started = time.monotonic() + clock = time.strftime("%H:%M:%S") + outcome = "ok" + deadline = started + 15 + def remaining(): + return max(0.001, deadline - time.monotonic()) + try: + with socket.create_connection(("10.77.20.10", 8444), timeout=15) as raw: + raw.settimeout(remaining()) + with ctx.wrap_socket(raw, server_hostname="hub.venue.lan") as tls: + tls.settimeout(remaining()) + tls.sendall(b"GET /status HTTP/1.1\r\nHost: hub.venue.lan:8444\r\nConnection: close\r\n\r\n") + while True: + tls.settimeout(remaining()) + if not tls.recv(4096): + break + except (OSError, ssl.SSLError): + outcome = "failed" + out.write(f"{clock} {time.monotonic() - started:.3f} {outcome}\n") + time.sleep(0.1) +with open(base + ".done", "w") as done: + done.write("done\n") +os.unlink(base + ".pid") +' "$probe_base" || mismatch 'gate1 probe could not start' +probe_deadline=$(( $(now) + 80 )) +gate1_delay= +gate2_delay= +while :; do + if [ -z "$gate1_delay" ] && [ "$(gate_etag gate1)" = "\"$new_hash\"" ]; then + gate1_delay=$(( $(now) - hub_installed_us / 1000000 )) + fi + if [ -z "$gate2_delay" ] && [ "$(gate_etag gate2)" = "\"$new_hash\"" ]; then + gate2_delay=$(( $(now) - hub_installed_us / 1000000 )) + fi + if run gate1 test -f "$probe_base.done"; then break; fi + [ "$(now)" -lt "$probe_deadline" ] || mismatch 'gate1 probe did not finish' + sleep 1 +done +run gate1 cat "$probe_base.results" > "$backup/probes.txt" || mismatch 'gate1 probe results unavailable' +probe_count=$(wc -l < "$backup/probes.txt" | tr -d ' ') +[ "$probe_count" -gt 0 ] || mismatch 'gate1 probe returned no results' +longest=$(awk 'BEGIN { longest=0 } $2 > longest { longest=$2 } END { printf "%.2f", longest }' "$backup/probes.txt") +printf '8444 status probes: %s, longest wait: %s s\n' "$probe_count" "$longest" +awk '$2 > 1 { printf "8444 status waited %.2f s at %s\n", $2, $1 }' "$backup/probes.txt" +printf 'hub status_client lines since drill start (time= removed):\n' +logs hub | awk -v first="$hub_first" 'NR > first && /event=status_client / { sub(/^time=[0-9]+ /, ""); print; found=1 } END { if (!found) print "none" }' +# A run of ticket-fetch failures is logged once, not on every failed cycle. +for gate in gate1 gate2; do + if [ "$gate" = gate1 ]; then first=$gate1_first; else first=$gate2_first; fi + printf '%s ticket_fetch lines since drill start (time= removed):\n' "$gate" + logs "$gate" | awk -v first="$first" 'NR > first && /event=ticket_fetch / { sub(/^time=[0-9]+ /, ""); print; found=1 } END { if (!found) print "none" }' + if [ "$gate" = gate1 ]; then delay=$gate1_delay; else delay=$gate2_delay; fi + if [ -n "$delay" ]; then + printf '%s new list: installed %s s after hub\n' "$gate" "$delay" + else + printf '%s new list: not installed within 60 s\n' "$gate" + fi +done +printf '8081 status: ' +run hub curl -fsS -o /dev/null -w 'HTTP %{http_code} in %{time_total} s\n' --max-time 5 \ + -H 'Host: hub.venue.lan' http://10.77.20.10:8081/status || mismatch 'hub /status on 8081 after watch' +judged=1 +if awk '$2 > 1 { found=1 } END { exit !found }' "$backup/probes.txt"; then + printf "result: 8444 held for %s s while a north gate's download was lost; gate1 waited behind it\n" "$longest" + exit 1 +fi +printf 'result: 8444 answered within 1 s\n' +exit 0 diff --git a/packaging/gate-control/conffiles b/packaging/gate-control/conffiles new file mode 100644 index 0000000..599925c --- /dev/null +++ b/packaging/gate-control/conffiles @@ -0,0 +1 @@ +/etc/gatepost/gated.env diff --git a/packaging/gate-hub.service b/packaging/gate-hub.service new file mode 100644 index 0000000..aad64e7 --- /dev/null +++ b/packaging/gate-hub.service @@ -0,0 +1,28 @@ +[Unit] +Description=Gatepost venue hub +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=gatepost +Group=gatepost +EnvironmentFile=/etc/gatepost/gate-hub.env +ExecStart=/usr/lib/gatepost/run-gate-hub +Restart=on-failure +RestartSec=2 +StateDirectory=gatepost +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +ReadWritePaths=/var/lib/gatepost +LoadCredential=ca.pem:/etc/gatepost/credentials/ca.pem +LoadCredential=server-chain.crt:/etc/gatepost/credentials/server-chain.crt +LoadCredential=server.key:/etc/gatepost/credentials/server.key + +[Install] +WantedBy=multi-user.target diff --git a/packaging/gated.service b/packaging/gated.service new file mode 100644 index 0000000..17085ad --- /dev/null +++ b/packaging/gated.service @@ -0,0 +1,31 @@ +[Unit] +Description=Gatepost gate device +After=network-online.target +Wants=network-online.target + +[Service] +Type=notify +User=gatepost +Group=gatepost +EnvironmentFile=/etc/gatepost/gated.env +ExecStart=/usr/lib/gatepost/run-gated +Restart=on-failure +RestartSec=2 +WatchdogSec=10 +StateDirectory=gatepost +AmbientCapabilities=CAP_NET_RAW +CapabilityBoundingSet=CAP_NET_RAW +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +ReadWritePaths=/var/lib/gatepost +LoadCredential=ca.pem:/etc/gatepost/credentials/ca.pem +LoadCredential=client-chain.crt:/etc/gatepost/credentials/client-chain.crt +LoadCredential=client.key:/etc/gatepost/credentials/client.key + +[Install] +WantedBy=multi-user.target diff --git a/packaging/hub-control/conffiles b/packaging/hub-control/conffiles new file mode 100644 index 0000000..722fb35 --- /dev/null +++ b/packaging/hub-control/conffiles @@ -0,0 +1,2 @@ +/etc/gatepost/gate-hub.env +/etc/gatepost/hub.conf diff --git a/packaging/postinst b/packaging/postinst new file mode 100755 index 0000000..fc57b40 --- /dev/null +++ b/packaging/postinst @@ -0,0 +1,16 @@ +#!/bin/sh +set -e +if ! getent group gatepost >/dev/null; then + addgroup --system gatepost +fi +install -d -m 0750 /var/lib/gatepost +if ! id gatepost >/dev/null 2>&1; then + adduser --system --ingroup gatepost --home /var/lib/gatepost --no-create-home --shell /usr/sbin/nologin gatepost +fi +install -d -o gatepost -g gatepost -m 0750 /var/lib/gatepost +install -d -o root -g root -m 0700 /etc/gatepost/credentials +install -d -o root -g gatepost -m 0750 /etc/gatepost/mac-keys +if command -v systemctl >/dev/null 2>&1; then + systemctl daemon-reload >/dev/null 2>&1 || : +fi +exit 0 diff --git a/packaging/run-gate-hub.sh b/packaging/run-gate-hub.sh new file mode 100755 index 0000000..f6c5283 --- /dev/null +++ b/packaging/run-gate-hub.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +: "${CREDENTIALS_DIRECTORY:?systemd credentials are required}" +export GATEPOST_TLS_CA="$CREDENTIALS_DIRECTORY/ca.pem" +export GATEPOST_TLS_CERT="$CREDENTIALS_DIRECTORY/server-chain.crt" +export GATEPOST_TLS_KEY="$CREDENTIALS_DIRECTORY/server.key" +export GATEPOST_MAC_KEY_DIR="/etc/gatepost/mac-keys" +exec /usr/bin/gate-hub "${GATEPOST_TICKETS:-/var/lib/gatepost/tickets.txt}" "${GATEPOST_LISTEN_PORT:-7000}" pool diff --git a/packaging/run-gated.sh b/packaging/run-gated.sh new file mode 100755 index 0000000..4c8b7a7 --- /dev/null +++ b/packaging/run-gated.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +: "${CREDENTIALS_DIRECTORY:?systemd credentials are required}" +export GATEPOST_TLS_CA="$CREDENTIALS_DIRECTORY/ca.pem" +export GATEPOST_TLS_CERT="$CREDENTIALS_DIRECTORY/client-chain.crt" +export GATEPOST_TLS_KEY="$CREDENTIALS_DIRECTORY/client.key" +export GATEPOST_MAC_KEY_DIR="/etc/gatepost/mac-keys" +exec /usr/bin/gated --scanner "${GATEPOST_SCANNER:-tty:/dev/ttyACM0}" --outputs "${GATEPOST_OUTPUTS:-gpio:/dev/gpiochip0}" --gate-id "${GATEPOST_GATE_ID:-gate-1}" --arp-interface "${GATEPOST_ARP_INTERFACE:-eth0}" --hub "${GATEPOST_HUB:?hub address is required}" "${GATEPOST_TICKETS:-/var/lib/gatepost/tickets.txt}" diff --git a/tests/test_gate_list_version.py b/tests/test_gate_list_version.py index 81f068e..c2bdcbd 100644 --- a/tests/test_gate_list_version.py +++ b/tests/test_gate_list_version.py @@ -6,6 +6,7 @@ import os from pathlib import Path import select +import signal import socket import struct import subprocess @@ -240,12 +241,22 @@ def fake_hub(listener, stop, seen, scans): finally: other.terminate() other.communicate(timeout=5) - SeasonHandler.body = b'GP-000000000002\n' - next_etag = '"' + hashlib.sha256(SeasonHandler.body).hexdigest() + '"' - until(lambda: list_etag() == next_etag, 30, - 'hub did not install the changed data-centre list within 30 seconds') - data = metrics() - assert value(data, 'fresh', 'stale') == 1, 'gate did not become stale after hub list changed' + # Keep the gate from fetching the new list before the stale metric is read. + os.kill(gate.pid, signal.SIGSTOP) + try: + SeasonHandler.body = b'GP-000000000002\n' + next_etag = '"' + hashlib.sha256(SeasonHandler.body).hexdigest() + '"' + until(lambda: list_etag() == next_etag, 30, + 'hub did not install the changed data-centre list within 30 seconds') + data = metrics() + state = Path(f'/proc/{gate.pid}/stat').read_text().rsplit(')', 1)[1].split()[0] + if state != 'T': + print(f'setup error: fresh gate is not stopped (state {state})') + sys.exit(2) + assert value(data, 'fresh', 'stale') == 1, 'gate did not become stale after hub list changed' + finally: + if gate.poll() is None: + os.kill(gate.pid, signal.SIGCONT) 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, \ diff --git a/tests/test_status_deadline.py b/tests/test_status_deadline.py index 842f5fc..49f89b8 100644 --- a/tests/test_status_deadline.py +++ b/tests/test_status_deadline.py @@ -5,7 +5,7 @@ a silent client sends nothing; a stalled reader asks for the ticket list and reads nothing; a slow reader takes what has arrived every 1.5 seconds, so each send by the hub completes within two seconds. The hub must cut the first two after the two-second step and the third at the -ten-second connection deadline, and /status must answer once each one is cut. A client that +ten-second connection deadline, while /status must answer with each one still held. A client that then reads the whole list must still get all of it: the deadlines must not cut a normal download. """ import os @@ -228,6 +228,13 @@ def read_slowly_tls(peer, stop): port = reserved.getsockname()[1] hub = subprocess.Popen([HUB, str(tickets), str(port), 'pool'], env=environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + log_lines = [] + def collect_log(): + for entry in iter(hub.stderr.readline, b''): + log_lines.append(entry) + + logger = threading.Thread(target=collect_log, daemon=True) + logger.start() gate = tls_context(certs) try: assert select.select([hub.stdout], [], [], 5)[0], 'TLS hub startup timed out' @@ -266,23 +273,36 @@ def read_slowly_tls(peer, stop): b'Host: 10.77.20.10:8444\r\n\r\n') assert head.startswith(b'HTTP/1.1 400 Bad Request') + # Each client is cut by the hub before the next starts, so the three timeout + # logs stay in order and held[0], held[1], held[2] keep their meaning. silent = socket.create_connection(('127.0.0.1', 8444), timeout=15) time.sleep(.2) line, waited = tls_status(gate, 5) print(f'tls_silent_client status={line} waited_s={waited:.1f}') - assert line == 'HTTP/1.1 200 OK' and waited <= 3 + assert line == 'HTTP/1.1 200 OK' and waited <= 1 + silent.settimeout(5) + try: + assert silent.recv(1) == b'' + except ConnectionResetError: + pass silent.close() + stalled_started = time.monotonic() stalled = tls_client(gate, window=4096) stalled.sendall(TICKETS) time.sleep(.5) line, waited = tls_status(gate, 12) print(f'tls_stalled_reader status={line} waited_s={waited:.1f}') - # Once reading stops, buffer sizes determine how long the kernel still takes bytes. - # Only require the listener to recover before the connection deadline. - assert line == 'HTTP/1.1 200 OK' and waited < 9 + assert line == 'HTTP/1.1 200 OK' and waited <= 1 + while time.monotonic() - stalled_started <= 10.5: + if sum(b'event=status_client state=timeout' in item for item in list(log_lines)) >= 2: + break + time.sleep(.02) + else: + assert False, 'stalled reader was not cut by the hub' stalled.close() + slow_started = time.monotonic() slow = tls_client(gate, window=262144) slow.sendall(TICKETS) stop = threading.Event() @@ -291,7 +311,15 @@ def read_slowly_tls(peer, stop): time.sleep(.5) line, waited = tls_status(gate, 15) print(f'tls_slow_reader status={line} waited_s={waited:.1f}') - assert line == 'HTTP/1.1 200 OK' and 8 <= waited <= 11 + assert line == 'HTTP/1.1 200 OK' and waited <= 1 + # The hub's close comes after the data still in its send buffer, so the reader may see + # end of file seconds after the cut; the hub's own timeout line marks the cut. + while time.monotonic() - slow_started <= 15: + if sum(b'event=status_client state=timeout' in item for item in list(log_lines)) >= 3: + break + time.sleep(.02) + else: + assert False, 'slow reader was not cut by the hub within 15 s' stop.set() reader.join(timeout=2) slow.close() @@ -304,13 +332,20 @@ def read_slowly_tls(peer, stop): except (OSError, ssl.SSLError): reply = b'' assert not reply.startswith(b'HTTP/'), (device, reply) - # Port 8444 serves one connection at a time, in the order the hub accepts them, so when - # this reply arrives the hub has finished both refused handshakes, their log lines included. - line, waited = tls_status(gate, 5) - assert line == 'HTTP/1.1 200 OK', (line, waited) + # With four workers both refused handshakes can still be logging when their clients see the + # refusal, so asking for status once more no longer proves anything: wait for both lines. + logged_started = time.monotonic() + while time.monotonic() - logged_started <= 5: + if sum(b'event=status_client state=handshake_failed' in item for item in list(log_lines)) >= 2: + break + time.sleep(.02) + else: + assert False, 'refused handshakes were not logged within 5 s' finally: hub.terminate() - _, log = hub.communicate(timeout=5) + hub.wait(timeout=5) + logger.join(timeout=2) + log = b''.join(log_lines) held = [int(ms) for ms in re.findall(rb'event=status_client state=timeout .*held_ms=(\d+)', log)] failed = re.findall(rb'level=WARN event=status_client state=handshake_failed[^\n]*\n', log) listener = re.findall(rb'level=INFO event=ticket_listener port=8444 state=tls', log) @@ -320,10 +355,11 @@ def read_slowly_tls(peer, stop): assert (len(held) == 3 and held[0] <= 3000 and held[1] < 9000 and 9500 <= held[2] <= 10500), held # The silent client timed out before its handshake: that is a timeout, not a refusal. - assert failed == [ + # With four workers either refusal may be logged first, so the order is not checked. + assert sorted(failed) == sorted([ b'level=WARN event=status_client state=handshake_failed ' b'reason=no_certificate peer=127.0.0.1\n', b'level=WARN event=status_client state=handshake_failed ' b'reason=certificate_invalid peer=127.0.0.1\n', - ], failed + ]), failed assert len(listener) == 1, listener diff --git a/tests/test_status_tls_workers.py b/tests/test_status_tls_workers.py new file mode 100644 index 0000000..8317be5 --- /dev/null +++ b/tests/test_status_tls_workers.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Show that stalled TLS readers must not block other gates or a full work queue.""" + +import errno +import os +from pathlib import Path +import re +import select +import socket +import ssl +import subprocess +import sys +import tempfile +import threading +import time + + +HUB = sys.argv[1] +STATUS = b'GET /status HTTP/1.1\r\nHost: hub.venue.lan\r\n\r\n' +TICKETS = b'GET /tickets HTTP/1.1\r\nHost: hub.venue.lan\r\n\r\n' +METRICS = b'GET /metrics HTTP/1.1\r\nHost: 127.0.0.1:8081\r\n\r\n' +ADDRESS = ('127.0.0.1', 8444) + + +def tls_context(certs, device): + context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, + cafile=str(certs / 'hub/ca.pem')) + context.load_cert_chain(str(certs / device / 'chain.pem'), + str(certs / device / 'key.pem')) + return context + + +def remaining(deadline): + left = deadline - time.monotonic() + if left <= 0: + raise TimeoutError + return left + + +def tls_status(context, timeout=5): + """Time connect, handshake, request and first reply with one deadline.""" + started = time.monotonic() + deadline = started + timeout + try: + raw = socket.create_connection(ADDRESS, timeout=remaining(deadline)) + with context.wrap_socket(raw, server_hostname='hub.venue.lan', + do_handshake_on_connect=False) as peer: + peer.settimeout(remaining(deadline)) + peer.do_handshake() + peer.settimeout(remaining(deadline)) + peer.sendall(STATUS) + head = bytearray() + while b'\r\n' not in head and len(head) < 1024: + peer.settimeout(remaining(deadline)) + block = peer.recv(64) + if not block: + break + head.extend(block) + line = bytes(head).split(b'\r\n', 1)[0] + except (OSError, ssl.SSLError, TimeoutError): + line = b'' + return line, time.monotonic() - started + + +def wait_for_status(context, case): + deadline = time.monotonic() + 15 + while (left := deadline - time.monotonic()) > 0: + line, _ = tls_status(context, min(1, left)) + if line == b'HTTP/1.1 200 OK': + return + time.sleep(min(.05, max(0, deadline - time.monotonic()))) + print(f'setup error: 8444 did not recover before case {case}', flush=True) + raise SystemExit(2) + + +def baseline(context): + line, waited = tls_status(context) + if line != b'HTTP/1.1 200 OK': + raise RuntimeError(f'baseline /status failed: {line!r}') + print(f'baseline: 8444 /status {waited:.3f} s', flush=True) + + +def status_result(context, count): + line, waited = tls_status(context) + description = 'one client' if count == 1 else 'three clients' + if line == b'HTTP/1.1 200 OK' and waited <= .3: + print(f'result: ok 8444 answered within 300 ms while {description} stopped reading', + flush=True) + return True + value = f'waited {waited:.1f} s' if line else 'got no reply within 5 s' + print(f'result: 8444 /status {value} behind {description} that stopped reading', + flush=True) + return False + + +def stalled_socket(context): + raw = socket.socket() + raw.settimeout(8) + raw.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096) + raw.connect(ADDRESS) + try: + peer = context.wrap_socket(raw, server_hostname='hub.venue.lan') + peer.sendall(TICKETS) + return peer + except BaseException: + raw.close() + raise + + +class StalledReaders: + def __init__(self, context, count): + self.context = context + self.count = count + self.stop = threading.Event() + self.lock = threading.Lock() + self.sent = [] + self.peers = [] + self.threads = [threading.Thread(target=self.run, daemon=True) for _ in range(count)] + + def run(self): + raw = socket.socket() + raw.settimeout(8) + raw.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096) + with self.lock: + self.peers.append(raw) + peer = raw + try: + raw.connect(ADDRESS) + peer = self.context.wrap_socket(raw, server_hostname='hub.venue.lan', + do_handshake_on_connect=False) + with self.lock: + self.peers.remove(raw) + self.peers.append(peer) + peer.do_handshake() + peer.sendall(TICKETS) + with self.lock: + self.sent.append(time.monotonic()) + self.stop.wait(12) + except (OSError, ssl.SSLError): + pass + finally: + with self.lock: + if peer in self.peers: + self.peers.remove(peer) + peer.close() + + def start(self): + for thread in self.threads: + thread.start() + deadline = time.monotonic() + 1 + while time.monotonic() < deadline: + with self.lock: + sent = len(self.sent) + if sent == self.count: + break + time.sleep(.01) + with self.lock: + sent = len(self.sent) + print(f'stalled readers sending: {sent} of {self.count}', flush=True) + + def sending(self): + with self.lock: + return len(self.sent) + + def close(self): + self.stop.set() + with self.lock: + for peer in self.peers: + peer.close() + deadline = time.monotonic() + 8.5 + for thread in self.threads: + thread.join(timeout=max(0, deadline - time.monotonic())) + + +def queue_connections(): + """Start all connects without waiting for a full kernel backlog to drain.""" + peers = [] + for _ in range(16): + peer = socket.socket() + peer.setblocking(False) + error = peer.connect_ex(ADDRESS) + if error not in (0, errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY): + peer.close() + raise OSError(error, os.strerror(error)) + peers.append(peer) + deadline = time.monotonic() + .5 + while (left := deadline - time.monotonic()) > 0: + _, writable, _ = select.select([], peers, [], min(.05, left)) + if len(writable) == len(peers): + break + return peers + + +def extra_connection_closed(): + deadline = time.monotonic() + 1 + try: + with socket.create_connection(ADDRESS, timeout=remaining(deadline)) as peer: + peer.settimeout(remaining(deadline)) + return peer.recv(1) == b'' and time.monotonic() <= deadline + except (ConnectionResetError, BrokenPipeError): + return time.monotonic() <= deadline + except (OSError, TimeoutError): + return False + + +def plain_metrics(): + deadline = time.monotonic() + 5 + with socket.create_connection(('127.0.0.1', 8081), timeout=remaining(deadline)) as peer: + peer.settimeout(remaining(deadline)) + peer.sendall(METRICS) + response = bytearray() + while True: + peer.settimeout(remaining(deadline)) + block = peer.recv(65536) + if not block: + break + response.extend(block) + head, _, body = bytes(response).partition(b'\r\n\r\n') + if not head.startswith(b'HTTP/1.1 200 OK'): + raise RuntimeError(f'/metrics failed: {head[:80]!r}') + return body + + +def run(): + failures = 0 + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + certs = root / 'certs' + subprocess.run(['sh', str(Path(__file__).resolve().parents[1] / 'lab/device-certs.sh'), + str(certs)], check=True, capture_output=True, timeout=15) + tickets = root / 'tickets.txt' + tickets.write_text(''.join(f'GP-{number:012d}\n' for number in range(1, 1_000_001))) + environment = {name: value for name, value in os.environ.items() + if not name.startswith('GATEPOST_')} + environment.update(GATEPOST_STATUS='1', + GATEPOST_STATUS_HOSTS='hub.venue.lan,127.0.0.1:8081,10.77.20.10:8444', + GATEPOST_TLS_CA=str(certs / 'hub/ca.pem'), + GATEPOST_TLS_CERT=str(certs / 'hub/chain.pem'), + GATEPOST_TLS_KEY=str(certs / 'hub/key.pem')) + with socket.socket() as reserved: + reserved.bind(('127.0.0.1', 0)) + port = reserved.getsockname()[1] + hub = subprocess.Popen([HUB, str(tickets), str(port), 'pool'], env=environment, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + log = [] + logger = threading.Thread(target=lambda: log.extend(iter(hub.stderr.readline, b'')), + daemon=True) + logger.start() + gate1 = tls_context(certs, 'gate1') + gate2 = tls_context(certs, 'gate2') + try: + if not select.select([hub.stdout], [], [], 5)[0]: + raise RuntimeError('hub startup timed out') + if not hub.stdout.readline().startswith(b'listening='): + raise RuntimeError('hub did not start') + + wait_for_status(gate2, 1) + baseline(gate2) + stalled = stalled_socket(gate1) + try: + time.sleep(.5) + failures += not status_result(gate2, 1) + finally: + stalled.close() + + wait_for_status(gate2, 2) + baseline(gate2) + readers = StalledReaders(gate1, 3) + try: + readers.start() + failures += not status_result(gate2, 3) + finally: + readers.close() + + wait_for_status(gate2, 3) + baseline(gate2) + readers = StalledReaders(gate1, 4) + queued = [] + timeouts = lambda: sum(b'event=status_client state=timeout' in line for line in list(log)) + try: + released_before = timeouts() + readers.start() + queued = queue_connections() + closed = extra_connection_closed() + # Only an extra connection that was not closed needs this check: four workers held + # the four readers, and one released early may have taken a queued connection and + # made room for it. A hub that serves one connection at a time never gets all four + # requests within the first second. + if not closed and readers.sending() == 4 and timeouts() != released_before: + print('setup error: a stalled reader was released before the extra connection ' + 'was judged', flush=True) + raise SystemExit(2) + if closed: + print('result: ok connection beyond the queue closed at once', flush=True) + else: + print('result: connection beyond the queue was not closed within 1 s', flush=True) + failures += 1 + finally: + for peer in queued: + peer.close() + readers.close() + wait_for_status(gate2, 4) + body = plain_metrics() + counts = re.findall(rb'gatepost_status_queue_full_total\{listener="status"\} (\d+)', + body) + if counts and int(counts[0]) >= 1: + print('result: ok queue-full refusals counted', flush=True) + else: + print('result: queue-full refusals not counted', flush=True) + failures += 1 + finally: + if hub.poll() is None: + hub.terminate() + try: + hub.wait(timeout=5) + except subprocess.TimeoutExpired: + hub.kill() + hub.wait(timeout=5) + logger.join(timeout=2) + for line in log: + if b'event=status_client' in line or b'event=status_queue' in line: + print(re.sub(rb'^time=\d+ ', b'', line).decode(errors='replace').rstrip(), + flush=True) + return int(failures != 0) + + +if __name__ == '__main__': + sys.exit(run())