From 74c870a51750d9a7bf4c6c076b3c97631e82a702 Mon Sep 17 00:00:00 2001 From: Stelios Fragkakis <52996999+stelfrag@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:00:58 +0200 Subject: [PATCH] Resend lookup requests unchanged when a call retries The C apps and cgroups lookup clients encoded each request into send_buf, which SHM framing rewrites in place and a reconnect may resize. A lookup that reconnected inside the call (a server restart, or a response over the server's limit) resent the framed bytes, so the server rejected it, or read the request through a pointer the reconnect had freed. Encode lookup requests into a separate request_buf, as the Rust and Go clients already do; send_buf only holds the SHM frame. Add N12 robustness tests on POSIX and Windows and run test_robustness under ASAN. SOW-0073; SOW-0074 tracks a test_uds link failure on 64-bit glibc 2.41 found during validation. --- ...-20261123-c-lookup-retry-request-buffer.md | 327 ++++++++++++++++++ ...74-20261124-uds-eintr-wrap-glibc-time64.md | 95 +++++ .../netipc/include/netipc/netipc_service.h | 6 + .../netipc/src/service/netipc_service.c | 8 +- .../src/service/netipc_service_apps_lookup.c | 6 +- .../service/netipc_service_cgroups_lookup.c | 6 +- .../src/service/netipc_service_common.c | 7 +- .../src/service/netipc_service_platform.h | 4 +- .../service/netipc_service_posix_internal.h | 1 + .../netipc/src/service/netipc_service_win.c | 8 +- .../src/service/netipc_service_win_internal.h | 1 + tests/fixtures/c/test_robustness.c | 316 +++++++++++++++++ tests/fixtures/c/test_service.c | 8 +- tests/fixtures/c/test_win_robustness.c | 309 +++++++++++++++++ tests/fixtures/c/test_win_service_extra.c | 8 +- tests/run-sanitizer-asan.sh | 2 +- 16 files changed, 1086 insertions(+), 26 deletions(-) create mode 100644 .agents/sow/done/SOW-0073-20261123-c-lookup-retry-request-buffer.md create mode 100644 .agents/sow/pending/SOW-0074-20261124-uds-eintr-wrap-glibc-time64.md diff --git a/.agents/sow/done/SOW-0073-20261123-c-lookup-retry-request-buffer.md b/.agents/sow/done/SOW-0073-20261123-c-lookup-retry-request-buffer.md new file mode 100644 index 0000000..c073493 --- /dev/null +++ b/.agents/sow/done/SOW-0073-20261123-c-lookup-retry-request-buffer.md @@ -0,0 +1,327 @@ +# SOW-0073 - C lookup retry resends an intact request + +## Status + +Status: completed + +Sub-state: delivered as one commit; draft PR against netdata/plugin-ipc. + +## Requirements + +### Purpose + +A C APPS_LOOKUP or CGROUPS_LOOKUP call that reconnects inside the call must resend the same request bytes, as +`docs/level2-typed-api.md` section 5 (at-least-once, "resend the request") requires. + +### User Request + +Fix the C client lookup retry that resends an overwritten request (found by a Netdata review of the vendored copy, +reproduced with a standalone program), with a separate request buffer, as a local change: no push, no PR. + +### Assistant Understanding + +Facts: + +- The lookup clients encode each subcall into `ctx->send_buf` (`src/service/netipc_service_apps_lookup.c:233-240`, + `netipc_service_cgroups_lookup.c:328-335`) and pass that pointer as the request of every attempt + (`apps_lookup.c:66-78`, `:255`; `cgroups_lookup.c:350`). +- On an SHM session `nipc_service_common_client_prepare_shm_request` (`netipc_service_common.c:270-303`) moves the + payload to `send_buf + 32` and writes the header at offset 0, i.e. it frames the request in place. +- `nipc_service_common_call_with_retry` (`netipc_service_common.c:425-470`) reconnects and runs the attempt again on + an ordinary failure and in the overflow-resize loop. The retry then sends the framed bytes again as the payload: + the server rejects it (`NIPC_ERR_BAD_LAYOUT`, handler not called). +- A reconnect that negotiates SHM or a larger request size resizes `send_buf` + (`netipc_service_posix_client_connect.c:29-38`, `netipc_service_win_client_connect.c:33-41`); the retry then reads + the request through the old pointer. +- Trigger: a server restart while the client stays up (fails fast since SOW-0044 dead-peer detection; before it, + an SHM call timed out instead of retrying). +- The overflow-resize retry in the same function resends too. A response that does not fit is normally answered + with `PAYLOAD_EXCEEDED` markers and split into further subcalls (`apps_lookup.c:275-328`), so a server with the + default 64 KiB response size does not reach it while requests stay within a 4 KiB request cap (Netdata's + configuration; a much larger request cap could make the markers alone exceed 64 KiB). It is reached when even the markers do not fit the server's + response limit (`nipc_dispatch_apps_lookup`, `netipc_protocol_apps_lookup.c:738-790`, then `LIMIT_EXCEEDED` at + `netipc_service_common.c:663-672`): e.g. 16 PIDs need about 1.2 KiB against a 1 KiB server limit. The client + raises its own response size, reconnects and resends (`netipc_service_common.c:460-482`); on 1ff116f1dc the + resend is the framed bytes, so the call ends in `NIPC_ERR_BAD_LAYOUT` instead of `NIPC_ERR_OVERFLOW`. +- Rust and Go keep a separate request buffer and SHM frame buffer (`src/crates/netipc/src/service/raw/client.rs:77-79`, + `client_call.rs:192-273`; Go `service/raw/client_unix.go`, `client_windows.go`), so they are not affected. +- `cgroups_snapshot` encodes into a stack buffer inside each attempt (`netipc_service_cgroups_snapshot.c:41-56`): + not affected. + +Inferences: + +- None beyond the facts; the design was cross-checked with Codex (agreement recorded under Execution Log). + +Unknowns: + +- None. + +### Acceptance Criteria + +- New C robustness tests (POSIX `test_robustness`, Windows `test_win_robustness`) restart an APPS_LOOKUP and a + CGROUPS_LOOKUP server under a READY SHM client; the next call succeeds with exactly one reconnect and the replacement + handler sees the exact items, for SHM->SHM and baseline-only->SHM restarts. A third case sends an APPS_LOOKUP + whose response exceeds a fixed 1 KiB server limit: the server must see the same items twice and the call must end + in `NIPC_ERR_OVERFLOW`. They fail on 1ff116f1dc and pass after, on Linux and Windows. +- Existing C suites pass (CTest) on Linux and the Windows service suites on MSYS; the ASAN suites, now including + `test_robustness` (`tests/run-sanitizer-asan.sh`), report nothing. + +## Analysis + +Sources checked: + +- The files and lines under Facts; `docs/level2-typed-api.md` sections 4-5; the fault-site tests + `tests/fixtures/c/test_service.c:3821`, `:3870`, `test_service_extra.c:505`, `test_win_service_extra.c:3684`, + `:3715`, `:3778`. + +Current state: + +- C lookups violate the resend contract on SHM sessions whenever the in-call retry runs. + +Risks: + +- `nipc_client_ctx_t` is a public struct (fields marked internal); appending fields changes its size. Consumers that + vendor and rebuild together (Netdata) are unaffected; mixing headers and library builds is already unsupported. + +## Pre-Implementation Gate + +Status: ready + +Problem / root-cause model: + +- The request and the SHM frame share one buffer: framing rewrites the request in place, and a reconnect can resize + it, while the retry state keeps the request pointer. Evidence: Facts above; standalone reproduction on Linux + (SHM restart -> `NIPC_ERR_BAD_LAYOUT`; baseline->SHM restart -> sanitizer report on the old pointer). + +Evidence reviewed: + +- Code paths under Facts, Rust/Go client buffers, Level 2 docs sections 4-5, existing fault-site tests. + +Affected contracts and surfaces: + +- `nipc_client_ctx_t` (new `request_buf`, `request_buf_size`), test fault-site enums (new + `*_CLIENT_REQUEST_BUF_REALLOC`, appended), internal `nipc_service_platform_ensure_client_request_buffer` + (renamed from `..._send_buffer`), C lookup clients, C SHM request framing. No wire or API behaviour change other than + the retry now working. + +Existing patterns to reuse: + +- `nipc_service_posix_ensure_buffer` / `nipc_service_win_ensure_buffer` with fault sites; Rust `request_buf` / + `send_buf` split; robustness test server helpers. + +Risk and blast radius: + +- Client-side only, C only. Extra memory: one lazily grown buffer per client, sized like the largest lookup + subrequest. +- Performance assessment (Test Cadence): per request on an established SHM session, lookups now encode into + `request_buf` and copy into `send_buf` (`netipc_service_common.c:296`), where 1ff116f1dc encoded into `send_buf` + and moved the bytes 32 bytes up in place. The bytes copied are the same; the request now touches two buffers + instead of one overlapping region, so the working set grows by one request (at most the 4 KiB request cap in + Netdata's configuration). Baseline (UDS) sessions and `cgroups_snapshot` are unchanged. The effect is expected to + be below benchmark noise. The benchmark matrix has no row for this path (`lookup-method-bench` times codec and + dispatch in-process, `bench/drivers/c/bench_posix.c:1282-1410`, without a client or transport), so the user chose + a short targeted A/B instead (Validation). + +Sensitive data handling plan: + +- No sensitive data: library code, synthetic PIDs and cgroup paths in tests. + +Implementation plan: + +1. Add `request_buf` to the client context, its ensure helper (POSIX, Windows) and fault site; free it on close. +2. Lookups encode into `request_buf`; `prepare_shm_request` copies it into `send_buf` with memcpy. +3. Retarget the lookup fault-site tests to the request site; keep the SHM frame fault tests on `send_buf`. +4. Add POSIX and Windows robustness reproduction tests (restart SHM->SHM and baseline->SHM; apps and cgroups) and + run `test_robustness` in the ASAN script, so the baseline->SHM case catches a stale pointer in CI. + +Validation plan: + +- Red: new tests on 1ff116f1dc (Linux, plain and ASAN). Green: full CTest, `tests/run-sanitizer-asan.sh` on Linux. + Windows suites: built and run on a Windows host if available, otherwise recorded as a gap. +- Performance: a short A/B of the C typed lookup client over an established SHM_FUTEX session, 1ff116f1dc vs the + fix (user decision 2026-11-24; the benchmark matrix has no row for this path). +- Independent review before closing. + +Artifact impact plan: + +- AGENTS.md: unaffected (no workflow change). +- Runtime project skills: unaffected (vendoring workflow unchanged). +- Specs: `docs/level2-typed-api.md` already requires resending the request; no change. +- End-user/operator docs: unaffected (no public behaviour beyond the fix). +- End-user/operator skills: `docs/netipc-integrator-skill.md` does not describe client buffers; unaffected. +- SOW lifecycle: this SOW closes with the commit. + +Open-source reference evidence: + +- None: only this repository was checked. + +Open decisions: + +- None: the fix shape (separate request buffer) was the user's request. + +## Implications And Decisions + +1. User decision 2026-11-23: fix with a separate request buffer, keep the work local (no push, no PR). +2. User decision 2026-11-24: a short benchmark run instead of the full matrix; run as a targeted lookup-client A/B + because no matrix row exercises the changed path. + +## Plan + +1. Library change (Implementation plan 1-2). +2. Tests (Implementation plan 3-4), red on 1ff116f1dc, green after. +3. Independent review, then close. + +User decision 3 (2026-11-24): squash into one commit and open a draft PR against netdata/plugin-ipc. + +## Execution Log + +### 2026-11-23 + +- Codex agreed the root cause (including the overflow-retry path and Windows), the separate buffer over re-encoding, + no other affected callers, the struct change for source-vendored consumers, and asked for Windows tests, a response + overflow case and deterministic restart synchronization. +- Implemented: `request_buf` + `nipc_service_platform_ensure_client_request_buffer` (POSIX, Windows) + fault site + `*_CLIENT_REQUEST_BUF_REALLOC` (appended to the public and internal enums); lookups encode into it; + `prepare_shm_request` memcpy; `close_buffers` frees it. Lookup fault tests retargeted to the request site + (`test_service.c`, `test_win_service_extra.c`); the SHM-connect fault test stays on `send_buf`. +- Tests: N12 in `test_robustness.c` and `test_win_robustness.c`; no sleeps (the restart is a stop + join, the + replacement listens before the call returns from init, handler observations are read under a lock). +- Review round 1 (Codex READY, three SHOULD-FIX): added the fixed-server-limit APPS_LOOKUP case (the response + growth variant tried first used the 64 KiB default and never overflowed; a CGROUPS_LOOKUP of 16 short paths fits + 1 KiB, and it shares the retry code); the new test fixtures now check thread creation and destroy the server on + failure; the performance assessment above now names the two-buffer working set. +- `tests/run-sanitizer-asan.sh` now runs `test_robustness` (it ran clean under ASAN with leak detection). + +## Validation + +Acceptance criteria evidence: + +- Red, 1ff116f1dc + tests only, Linux x86_64 gcc (Debian, glibc 2.41): all five N12 cases fail; the restarts + return `NIPC_ERR_BAD_LAYOUT` (6) with one reconnect, the limit case returns `NIPC_ERR_BAD_LAYOUT` with the handler + called once (89 passed, 14 failed, three runs); ASAN build: `heap-use-after-free` READ in `memmove` in + `prepare_shm_request` at the baseline->SHM case. +- Red, Windows Server 2022, MSYS gcc 16.2: the SHM->SHM and limit cases fail every run; the baseline->SHM cases fail + only when the reconnect's `realloc` moves `send_buf` (one run: all four restarts failed; a later run: the cgroups + baseline->SHM case passed; the final fixtures failed 14 checks in each of three runs). That case reads the request through the old pointer, so a non-sanitizer build sees it + only when the block moves; the Linux ASAN run (now part of `tests/run-sanitizer-asan.sh`) catches it every time. +- Green, final fixtures: N12 passes on Linux plain and ASAN (103 passed, 0 failed, three runs each) and on Windows + (81 passed, 0 failed, three runs); the limit case returns `NIPC_ERR_OVERFLOW` (11) after exactly two reconnects + with the server seeing the same 16 PIDs twice. + +Tests or equivalent validation: + +- Linux, on a2c4437 (the review fixes touch only the N12 fixtures, rerun above): + `ctest --test-dir build -E '^test_uds$'` 31/31 passed (C, Rust, Go and interop suites). + `test_uds` does not link on this host on main either: `uds_eintr_wrap.c` wraps `__sendmsg64` under + `__USE_TIME_BITS64`, which glibc 2.41 defines on 64-bit time too, while only `__USE_TIME64_REDIRECTS` redirects + `sendmsg`; unrelated to this change, tracked in SOW-0074. +- Linux ASAN+UBSAN with leak detection (`tests/run-sanitizer-asan.sh` flags, run per binary because of the same + `test_uds` link failure): test_protocol, test_shm, test_service, test_service_extra, test_cache, + test_multi_server, test_robustness exit 0, no sanitizer reports. +- Windows MSYS, with the review fixes: `test_win_service`, `test_win_service_extra`, + `test_win_service_payload_limits`, `test_win_robustness`, `test_win_service_guards`, + `test_win_service_guards_extra` 6/6 passed. + +Performance evidence (2026-11-24, beast, idle, client and server pinned to 2 CPUs, `-O2`, 5 interleaved rounds of +4 s per row, calls/s median and range): + +| Row | 1ff116f1dc | fix | delta | +|---|---|---|---| +| apps, 16 PIDs | 39812 (36818-43352) | 38523 (34142-41694) | -3.2% | +| apps, 256 PIDs | 9898 (8931-10475) | 10086 (9053-10300) | +1.9% | +| cgroups, 16 paths | 42510 (37495-47148) | 39429 (37295-44514) | -7.2% | +| cgroups, 256 paths | 9646 (8762-10141) | 9584 (9478-9806) | -0.6% | + +- Run-to-run spread within one variant is 12-26%, and the medians move in both directions, so no difference is + resolved at this length. A call costs 22-110 us, dominated by the futex round trip and the codec; the added work is + one buffer of at most a few KiB in the working set, with the same bytes copied. A smaller effect than the noise + would need the full benchmark cadence with longer runs. + +Real-use evidence: + +- Standalone apps-lookup program against the public API (server restart under a live client): failed on + 1ff116f1dc as above; the N12 tests reproduce the same sequence in the suite. + +Reviewer findings: + +- Codex (read-only, on a2c4437): READY; SHOULD-FIX 1, a response over a fixed server limit reaches the overflow + retry: fixed (new limit case, red/green above); SHOULD-FIX 2, new fixtures ignored thread-creation failure: + fixed; SHOULD-FIX 3, performance assessment should name the two-buffer working set: fixed in the gate, benchmark + left to the user. +- Codex round 2 (on f7078f8): READY; SHOULD-FIX the limit case accepted `calls >= 2`, so a refused final reconnect + could pass: fixed (4 server workers, assert exactly 2 reconnects and 2 handler calls); NIT qualify the 64 KiB claim + with the request cap: fixed. +- claude-swarm GLM-5.3 lead (on a2c4437): READY; NIT unused `n` parameter (removed with the round-1 changes); NIT + `memcpy` overlap would be undefined for a future aliasing caller: no change (internal function, every caller passes + a separate buffer, the comment at the copy states it); NIT thread creation unchecked: fixed. +- claude-swarm Kimi K3 (on a2c4437): READY; NIT second server stop unchecked: fixed (checks added); NIT + function-static path buffers: no change (single-threaded fixture, no defect). + +Same-failure scan: + +- `grep -rn 'send_buf' src/libnetdata/netipc`: after the change only the SHM frame paths use it + (`prepare_shm_request`, client connect on POSIX and Windows, `close_buffers`). `do_raw_call` callers: lookups + (now `request_buf`) and `cgroups_snapshot` (stack buffer, encoded per attempt). Rust and Go already split the + buffers. + +Sensitive data gate: + +- No sensitive data: synthetic PIDs and paths; no hosts, credentials or customer data in code, tests or this SOW. + +Artifact maintenance gate: + +- `AGENTS.md`: no workflow change; the validation commands it lists are unchanged. +- Runtime project skills: `project-netdata-vendoring` unaffected (vendoring workflow unchanged). +- Specs: `docs/level2-typed-api.md` section 5 already requires resending the request; `.agents/sow/specs/` holds + no decision this changes. +- End-user/operator docs: no public behavior change beyond the fix; no doc describes the client scratch buffers. +- End-user/operator skills: `docs/netipc-integrator-skill.md` does not describe client buffers; unaffected. +- SOW lifecycle: this SOW moves to `done/` as `completed` in the same commit as the work; SOW-0074 (pending) + tracks the `test_uds` link failure found during validation. + +Specs update: + +- None needed: the public spec already states the contract the fix restores. + +Project skills update: + +- None needed. + +End-user/operator docs update: + +- None needed. + +End-user/operator skills update: + +- None needed. + +Lessons: + +- See Lessons Extracted. + +Follow-up mapping: + +- `test_uds` link failure on 64-bit glibc 2.41: tracked, SOW-0074 (pending). +- Forced `realloc` relocation for the baseline->SHM case without a sanitizer: rejected; the ASAN run of + `test_robustness` catches it every time, and the SHM->SHM and limit cases fail deterministically without it. +- Full benchmark matrix: rejected for this change; the matrix has no row for the lookup client path and the + targeted A/B showed no difference above noise. + +## Outcome + +C lookup clients resend the exact request when a call reconnects and retries, on POSIX and Windows, matching +Rust and Go. N12 reproduction tests cover server restarts (SHM->SHM, baseline->SHM) and a response over a fixed +server limit; `test_robustness` now runs under ASAN. + +## Lessons Extracted + +- A buffer that a lower layer rewrites in place cannot also be the input a retry replays: the retry state must own, + or point to, storage nothing below it touches. +- A path judged unreachable from stock configuration can still be reached by a non-default configuration: the + overflow retry is reached by a server with a small fixed response limit. +- A reproduction that depends on `realloc` moving a block is not deterministic without a sanitizer; keep the case + under ASAN in CI rather than relying on plain runs. + +## Followup + +- SOW-0074 (pending): `test_uds` EINTR wrapper guard on 64-bit glibc 2.41. diff --git a/.agents/sow/pending/SOW-0074-20261124-uds-eintr-wrap-glibc-time64.md b/.agents/sow/pending/SOW-0074-20261124-uds-eintr-wrap-glibc-time64.md new file mode 100644 index 0000000..94621ce --- /dev/null +++ b/.agents/sow/pending/SOW-0074-20261124-uds-eintr-wrap-glibc-time64.md @@ -0,0 +1,95 @@ +# SOW-0074 - test_uds EINTR wrapper on 64-bit glibc 2.41 + +## Status + +Status: open + +Sub-state: found during SOW-0073 validation; not started. + +## Requirements + +### Purpose + +`test_uds` must build on every glibc the project supports. + +### User Request + +Tracked from SOW-0073 (found while validating on Debian 13, glibc 2.41, x86_64). + +### Assistant Understanding + +Facts: + +- `tests/fixtures/c/uds_eintr_wrap.c` defines `__wrap___sendmsg64` and calls `__real___sendmsg64` under + `#if defined(__GLIBC__) && defined(__USE_TIME_BITS64)`; `CMakeLists.txt` links `test_uds` with + `--wrap=__sendmsg64` on every non-Apple platform. +- glibc 2.41 (`bits/features-time64.h`) defines `__USE_TIME_BITS64` whenever `__TIMESIZE == 64`, i.e. on every + 64-bit target. `sys/socket.h` redirects `sendmsg` to `__sendmsg64` only under `__USE_TIME64_REDIRECTS` (32-bit + `time_t` targets built with `_TIME_BITS=64`). +- So on x86_64 glibc 2.41 the wrapper references `__sendmsg64`, which libc does not export: + `undefined reference to '__sendmsg64'`, and `test_uds` does not link (reproduced on 1ff116f1dc). + +Inferences: + +- The guard should follow the header's own condition (`__USE_TIME64_REDIRECTS`, falling back to `__TIMESIZE == 32` + with `__USE_TIME_BITS64` for glibc versions that predate that macro). + +Unknowns: + +- Which glibc version started defining `__USE_TIME_BITS64` on 64-bit targets (CI's Ubuntu glibc still links). + +### Acceptance Criteria + +- `test_uds` links and passes on x86_64 glibc 2.41 and on the 32-bit time64 targets of `tests/run-linux-target.sh`. + +## Analysis + +Sources checked: + +- `tests/fixtures/c/uds_eintr_wrap.c`, `CMakeLists.txt` (`test_uds` link options), glibc 2.41 headers on Debian 13. + +Current state: + +- Test-only build failure; library code unaffected. + +Risks: + +- None for production; the EINTR injection tests do not run on affected hosts until fixed. + +## Pre-Implementation Gate + +Status: blocked + +Not started: fill the gate before implementation. + +## Implications And Decisions + +None yet. + +## Plan + +1. Fix the guard; validate on glibc 2.41 x86_64 and a 32-bit time64 target. + +## Execution Log + +None yet. + +## Validation + +Pending. + +## Outcome + +Pending. + +## Lessons Extracted + +Pending. + +## Followup + +None yet. + +## Regression Log + +None yet. diff --git a/src/libnetdata/netipc/include/netipc/netipc_service.h b/src/libnetdata/netipc/include/netipc/netipc_service.h index 5a076ad..a9f60d8 100644 --- a/src/libnetdata/netipc/include/netipc/netipc_service.h +++ b/src/libnetdata/netipc/include/netipc/netipc_service.h @@ -179,8 +179,12 @@ typedef struct { /* Internal reusable Level 2 scratch, allocated lazily from session sizes. */ uint8_t *response_buf; size_t response_buf_size; + /* SHM frame (header + request copy); a reconnect may resize it. */ uint8_t *send_buf; size_t send_buf_size; + /* Encoded lookup request; an in-call retry resends it unchanged. */ + uint8_t *request_buf; + size_t request_buf_size; } nipc_client_ctx_t; /* ------------------------------------------------------------------ */ @@ -505,6 +509,7 @@ typedef enum { NIPC_WIN_SERVICE_TEST_FAULT_CACHE_ITEMS_CALLOC, NIPC_WIN_SERVICE_TEST_FAULT_CACHE_ITEM_NAME_MALLOC, NIPC_WIN_SERVICE_TEST_FAULT_CACHE_ITEM_PATH_MALLOC, + NIPC_WIN_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC, } nipc_win_service_test_fault_site_t; void nipc_win_service_test_fault_set(int site, uint32_t skip_matches); @@ -524,6 +529,7 @@ typedef enum { NIPC_POSIX_SERVICE_TEST_FAULT_CACHE_ITEMS_CALLOC, NIPC_POSIX_SERVICE_TEST_FAULT_CACHE_ITEM_NAME_MALLOC, NIPC_POSIX_SERVICE_TEST_FAULT_CACHE_ITEM_PATH_MALLOC, + NIPC_POSIX_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC, } nipc_posix_service_test_fault_site_t; void nipc_posix_service_test_fault_set(int site, uint32_t skip_matches); diff --git a/src/libnetdata/netipc/src/service/netipc_service.c b/src/libnetdata/netipc/src/service/netipc_service.c index 781c212..e1aff8a 100644 --- a/src/libnetdata/netipc/src/service/netipc_service.c +++ b/src/libnetdata/netipc/src/service/netipc_service.c @@ -137,11 +137,11 @@ bool nipc_service_posix_ensure_buffer(uint8_t **buf, size_t *buf_size, return true; } -bool nipc_service_platform_ensure_client_send_buffer(nipc_client_ctx_t *ctx, - size_t need) { +bool nipc_service_platform_ensure_client_request_buffer(nipc_client_ctx_t *ctx, + size_t need) { return nipc_service_posix_ensure_buffer( - &ctx->send_buf, &ctx->send_buf_size, need, - NIPC_POSIX_SERVICE_TEST_FAULT_CLIENT_SEND_BUF_REALLOC_INTERNAL); + &ctx->request_buf, &ctx->request_buf_size, need, + NIPC_POSIX_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC_INTERNAL); } bool nipc_service_platform_ensure_client_response_buffer(nipc_client_ctx_t *ctx, diff --git a/src/libnetdata/netipc/src/service/netipc_service_apps_lookup.c b/src/libnetdata/netipc/src/service/netipc_service_apps_lookup.c index eab0b7b..f434736 100644 --- a/src/libnetdata/netipc/src/service/netipc_service_apps_lookup.c +++ b/src/libnetdata/netipc/src/service/netipc_service_apps_lookup.c @@ -230,13 +230,13 @@ static nipc_error_t do_apps_lookup_attempt(nipc_client_ctx_t *ctx, goto cleanup; } /* next_request_count returns only sizes bounded by the uint32 transport cap. */ - if (!nipc_service_platform_ensure_client_send_buffer(ctx, req_size)) { + if (!nipc_service_platform_ensure_client_request_buffer(ctx, req_size)) { err = NIPC_ERR_OVERFLOW; goto cleanup; } size_t req_len = nipc_apps_lookup_req_encode( - req_pids, req_count, ctx->send_buf, ctx->send_buf_size); + req_pids, req_count, ctx->request_buf, ctx->request_buf_size); if (req_len == 0) { err = NIPC_ERR_BAD_LAYOUT; goto cleanup; @@ -252,7 +252,7 @@ static nipc_error_t do_apps_lookup_attempt(nipc_client_ctx_t *ctx, err = apps_lookup_remaining_timeout(ctx, s->deadline_ms, &timeout_ms); if (err != NIPC_OK) goto cleanup; - err = apps_lookup_do_raw_call_with_retry(ctx, ctx->send_buf, req_len, + err = apps_lookup_do_raw_call_with_retry(ctx, ctx->request_buf, req_len, &payload, &payload_len, timeout_ms); if (err != NIPC_OK) diff --git a/src/libnetdata/netipc/src/service/netipc_service_cgroups_lookup.c b/src/libnetdata/netipc/src/service/netipc_service_cgroups_lookup.c index 01c0b93..92de5d9 100644 --- a/src/libnetdata/netipc/src/service/netipc_service_cgroups_lookup.c +++ b/src/libnetdata/netipc/src/service/netipc_service_cgroups_lookup.c @@ -325,13 +325,13 @@ static nipc_error_t do_cgroups_lookup_attempt(nipc_client_ctx_t *ctx, goto cleanup; } /* next_request_count returns only sizes bounded by the uint32 transport cap. */ - if (!nipc_service_platform_ensure_client_send_buffer(ctx, req_size)) { + if (!nipc_service_platform_ensure_client_request_buffer(ctx, req_size)) { err = NIPC_ERR_OVERFLOW; goto cleanup; } size_t req_len = nipc_cgroups_lookup_req_encode( - req_paths, req_count, ctx->send_buf, ctx->send_buf_size); + req_paths, req_count, ctx->request_buf, ctx->request_buf_size); if (req_len == 0) { err = NIPC_ERR_BAD_LAYOUT; goto cleanup; @@ -347,7 +347,7 @@ static nipc_error_t do_cgroups_lookup_attempt(nipc_client_ctx_t *ctx, err = cgroups_lookup_remaining_timeout(ctx, s->deadline_ms, &timeout_ms); if (err != NIPC_OK) goto cleanup; - err = cgroups_lookup_do_raw_call_with_retry(ctx, ctx->send_buf, req_len, + err = cgroups_lookup_do_raw_call_with_retry(ctx, ctx->request_buf, req_len, &payload, &payload_len, timeout_ms); if (err != NIPC_OK) diff --git a/src/libnetdata/netipc/src/service/netipc_service_common.c b/src/libnetdata/netipc/src/service/netipc_service_common.c index ce8cf25..676af37 100644 --- a/src/libnetdata/netipc/src/service/netipc_service_common.c +++ b/src/libnetdata/netipc/src/service/netipc_service_common.c @@ -160,10 +160,13 @@ void nipc_service_common_client_status(const nipc_client_ctx_t *ctx, void nipc_service_common_client_close_buffers(nipc_client_ctx_t *ctx) { free(ctx->response_buf); free(ctx->send_buf); + free(ctx->request_buf); ctx->response_buf = NULL; ctx->send_buf = NULL; + ctx->request_buf = NULL; ctx->response_buf_size = 0; ctx->send_buf_size = 0; + ctx->request_buf_size = 0; ctx->state = NIPC_CLIENT_DISCONNECTED; } @@ -287,8 +290,10 @@ nipc_error_t nipc_service_common_client_prepare_shm_request( if (!msg || msg_len > ctx->send_buf_size) return NIPC_ERR_OVERFLOW; + /* The payload lives outside send_buf, so an in-call retry, which may + * reconnect and resize send_buf, resends it unchanged. */ if (payload_len > 0) - memmove(msg + NIPC_HEADER_LEN, payload, payload_len); + memcpy(msg + NIPC_HEADER_LEN, payload, payload_len); hdr->magic = NIPC_MAGIC_MSG; hdr->version = NIPC_VERSION; diff --git a/src/libnetdata/netipc/src/service/netipc_service_platform.h b/src/libnetdata/netipc/src/service/netipc_service_platform.h index a3e923e..a7eef57 100644 --- a/src/libnetdata/netipc/src/service/netipc_service_platform.h +++ b/src/libnetdata/netipc/src/service/netipc_service_platform.h @@ -26,8 +26,8 @@ void *nipc_service_platform_malloc(size_t size, int fault_site); void *nipc_service_platform_calloc(size_t count, size_t size, int fault_site); uint64_t nipc_service_platform_monotonic_ms(void); -bool nipc_service_platform_ensure_client_send_buffer(nipc_client_ctx_t *ctx, - size_t need); +bool nipc_service_platform_ensure_client_request_buffer(nipc_client_ctx_t *ctx, + size_t need); bool nipc_service_platform_ensure_client_response_buffer(nipc_client_ctx_t *ctx, size_t need); diff --git a/src/libnetdata/netipc/src/service/netipc_service_posix_internal.h b/src/libnetdata/netipc/src/service/netipc_service_posix_internal.h index f7dc557..6523219 100644 --- a/src/libnetdata/netipc/src/service/netipc_service_posix_internal.h +++ b/src/libnetdata/netipc/src/service/netipc_service_posix_internal.h @@ -38,6 +38,7 @@ enum { NIPC_POSIX_SERVICE_TEST_FAULT_CACHE_ITEMS_CALLOC_INTERNAL, NIPC_POSIX_SERVICE_TEST_FAULT_CACHE_ITEM_NAME_MALLOC_INTERNAL, NIPC_POSIX_SERVICE_TEST_FAULT_CACHE_ITEM_PATH_MALLOC_INTERNAL, + NIPC_POSIX_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC_INTERNAL, }; void nipc_service_posix_sleep_us(unsigned int usec); diff --git a/src/libnetdata/netipc/src/service/netipc_service_win.c b/src/libnetdata/netipc/src/service/netipc_service_win.c index 7a123b7..56d419a 100644 --- a/src/libnetdata/netipc/src/service/netipc_service_win.c +++ b/src/libnetdata/netipc/src/service/netipc_service_win.c @@ -188,11 +188,11 @@ uint64_t nipc_service_platform_monotonic_ms(void) { return monotonic_time_ms(); } -bool nipc_service_platform_ensure_client_send_buffer(nipc_client_ctx_t *ctx, - size_t need) { +bool nipc_service_platform_ensure_client_request_buffer(nipc_client_ctx_t *ctx, + size_t need) { return nipc_service_win_ensure_buffer( - &ctx->send_buf, &ctx->send_buf_size, need, - NIPC_WIN_SERVICE_TEST_FAULT_CLIENT_SEND_BUF_REALLOC_INTERNAL); + &ctx->request_buf, &ctx->request_buf_size, need, + NIPC_WIN_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC_INTERNAL); } bool nipc_service_platform_ensure_client_response_buffer(nipc_client_ctx_t *ctx, diff --git a/src/libnetdata/netipc/src/service/netipc_service_win_internal.h b/src/libnetdata/netipc/src/service/netipc_service_win_internal.h index 48ef265..57a651e 100644 --- a/src/libnetdata/netipc/src/service/netipc_service_win_internal.h +++ b/src/libnetdata/netipc/src/service/netipc_service_win_internal.h @@ -32,6 +32,7 @@ enum { NIPC_WIN_SERVICE_TEST_FAULT_CACHE_ITEMS_CALLOC_INTERNAL, NIPC_WIN_SERVICE_TEST_FAULT_CACHE_ITEM_NAME_MALLOC_INTERNAL, NIPC_WIN_SERVICE_TEST_FAULT_CACHE_ITEM_PATH_MALLOC_INTERNAL, + NIPC_WIN_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC_INTERNAL, }; const nipc_service_common_client_ops_t *nipc_service_win_client_ops(void); diff --git a/tests/fixtures/c/test_robustness.c b/tests/fixtures/c/test_robustness.c index 01e5278..e807d2a 100644 --- a/tests/fixtures/c/test_robustness.c +++ b/tests/fixtures/c/test_robustness.c @@ -22,6 +22,9 @@ * N5 SHM client notices a crashed server before its timeout * N5 baseline client reports a crashed server as disconnected * N5 SHM attach stops when the server closes the session + * N12 a lookup retried after a reconnect resends the same request + * (server restart SHM->SHM and baseline->SHM, apps and cgroups; + * apps response over a fixed server limit) * CLOEXEC every NetIPC socket and pipe is close-on-exec * N11 default packet size carries a message larger than SO_SNDBUF * (plus an explicit-packet-size control) @@ -1229,6 +1232,318 @@ static void test_default_packet_size_carries_large_message(void) large_message_round_trip("rob_bigmsg_oversized", 4u * 1024u * 1024u)); } +/* ------------------------------------------------------------------ */ +/* N12: a lookup retried after a reconnect resends the same request */ +/* ------------------------------------------------------------------ */ + +#if defined(__linux__) || defined(__FreeBSD__) +#define LOOKUP_RETRY_ITEMS 16u +/* Spare workers: a session the server closes after LIMIT_EXCEEDED may still + * hold its worker while the client reconnects. */ +#define LOOKUP_SERVER_WORKERS 4 + +/* What the lookup handler of one server saw, read under the lock. */ +typedef struct { + pthread_mutex_t lock; + uint32_t calls; + uint32_t mismatched; /* calls whose items differ from retry_path / 4000+i */ + uint32_t item_count; + uint32_t pids[LOOKUP_RETRY_ITEMS]; + char paths[LOOKUP_RETRY_ITEMS][16]; +} lookup_seen_t; + +typedef struct { + const char *service; + bool apps; + bool shm; + uint32_t max_response; /* 0 = RESPONSE_BUF_SIZE */ + lookup_seen_t seen; + nipc_apps_lookup_service_handler_t apps_handler; + nipc_cgroups_lookup_service_handler_t cgroups_handler; + nipc_managed_server_t server; + test_server_events_t events; + pthread_t tid; +} lookup_server_t; + +static void retry_path(uint32_t i, char *buf, size_t size) +{ + snprintf(buf, size, "/rt/%u", (unsigned)i); +} + +static bool apps_lookup_record_handler(void *user, + const nipc_apps_lookup_req_view_t *request, + nipc_apps_lookup_builder_t *builder) +{ + lookup_seen_t *seen = (lookup_seen_t *)user; + pthread_mutex_lock(&seen->lock); + seen->calls++; + seen->item_count = request->item_count; + bool mismatch = request->item_count != LOOKUP_RETRY_ITEMS; + for (uint32_t i = 0; i < request->item_count; i++) { + nipc_apps_lookup_req_item_t item; + if (nipc_apps_lookup_req_item(request, i, &item) != NIPC_OK) + break; + if (i < LOOKUP_RETRY_ITEMS) + seen->pids[i] = item.pid; + if (item.pid != 4000u + i) + mismatch = true; + } + if (mismatch) + seen->mismatched++; + pthread_mutex_unlock(&seen->lock); + + for (uint32_t i = 0; i < request->item_count; i++) { + nipc_apps_lookup_req_item_t item; + if (nipc_apps_lookup_req_item(request, i, &item) != NIPC_OK || + nipc_apps_lookup_builder_add(builder, NIPC_PID_LOOKUP_UNKNOWN, 0, 0, + item.pid, 0, NIPC_UID_UNSET, 0, "", 0, + "", 0, "", 0, NULL, 0) != NIPC_OK) + return false; + } + return true; +} + +static bool cgroups_lookup_record_handler(void *user, + const nipc_cgroups_lookup_req_view_t *request, + nipc_cgroups_lookup_builder_t *builder) +{ + lookup_seen_t *seen = (lookup_seen_t *)user; + pthread_mutex_lock(&seen->lock); + seen->calls++; + seen->item_count = request->item_count; + bool mismatch = request->item_count != LOOKUP_RETRY_ITEMS; + for (uint32_t i = 0; i < request->item_count; i++) { + nipc_cgroups_lookup_req_item_t item; + if (nipc_cgroups_lookup_req_item(request, i, &item) != NIPC_OK) + break; + if (i < LOOKUP_RETRY_ITEMS) { + size_t n = item.path.len < sizeof(seen->paths[i]) - 1 + ? item.path.len : sizeof(seen->paths[i]) - 1; + memcpy(seen->paths[i], item.path.ptr, n); + seen->paths[i][n] = '\0'; + } + char want[16]; + retry_path(i, want, sizeof(want)); + if (item.path.len != strlen(want) || memcmp(item.path.ptr, want, item.path.len) != 0) + mismatch = true; + } + if (mismatch) + seen->mismatched++; + pthread_mutex_unlock(&seen->lock); + + for (uint32_t i = 0; i < request->item_count; i++) { + nipc_cgroups_lookup_req_item_t item; + if (nipc_cgroups_lookup_req_item(request, i, &item) != NIPC_OK || + nipc_cgroups_lookup_builder_add(builder, NIPC_CGROUP_LOOKUP_UNKNOWN_RETRY_LATER, + 0, item.path.ptr, item.path.len, "", 0, + NULL, 0) != NIPC_OK) + return false; + } + return true; +} + +static void *lookup_server_fn(void *arg) +{ + lookup_server_t *ls = (lookup_server_t *)arg; + nipc_server_run(&ls->server); + nipc_server_destroy(&ls->server); + return NULL; +} + +static bool start_lookup_server(lookup_server_t *ls) +{ + cleanup_all(ls->service); + pthread_mutex_init(&ls->seen.lock, NULL); + nipc_server_config_t scfg = { + .supported_profiles = NIPC_PROFILE_BASELINE | + (ls->shm ? NIPC_PROFILE_SHM_HYBRID : 0), + .preferred_profiles = ls->shm ? NIPC_PROFILE_SHM_HYBRID : 0, + .max_request_payload_bytes = 4096, + .max_request_batch_items = 1, + .max_response_payload_bytes = ls->max_response ? ls->max_response : RESPONSE_BUF_SIZE, + .auth_token = AUTH_TOKEN, + }; + nipc_error_t err; + if (ls->apps) { + ls->apps_handler.handle = apps_lookup_record_handler; + ls->apps_handler.user = &ls->seen; + err = nipc_server_init_apps_lookup(&ls->server, TEST_RUN_DIR, ls->service, + &scfg, LOOKUP_SERVER_WORKERS, &ls->apps_handler); + } else { + ls->cgroups_handler.handle = cgroups_lookup_record_handler; + ls->cgroups_handler.user = &ls->seen; + err = nipc_server_init_cgroups_lookup(&ls->server, TEST_RUN_DIR, ls->service, + &scfg, LOOKUP_SERVER_WORKERS, &ls->cgroups_handler); + } + if (err != NIPC_OK) { + fprintf(stderr, "lookup server init failed: %d\n", err); + pthread_mutex_destroy(&ls->seen.lock); + return false; + } + test_server_use_test_timings(&ls->server, &ls->events); + if (pthread_create(&ls->tid, NULL, lookup_server_fn, ls) != 0) { + nipc_server_destroy(&ls->server); + pthread_mutex_destroy(&ls->seen.lock); + return false; + } + return true; +} + +static bool stop_lookup_server(lookup_server_t *ls) +{ + nipc_server_stop(&ls->server); + bool stopped = join_within(ls->tid, 5000); + if (!stopped) + join_rest(ls->tid); + pthread_mutex_destroy(&ls->seen.lock); + return stopped; +} + +/* One lookup of LOOKUP_RETRY_ITEMS items; true when the call succeeded and + * the server's last handled request held exactly those items. */ +static bool lookup_call_matches(nipc_client_ctx_t *client, lookup_server_t *ls, + nipc_error_t *err_out) +{ + static char path_bufs[LOOKUP_RETRY_ITEMS][16]; + nipc_error_t err; + if (ls->apps) { + uint32_t pids[LOOKUP_RETRY_ITEMS]; + for (uint32_t i = 0; i < LOOKUP_RETRY_ITEMS; i++) + pids[i] = 4000u + i; + nipc_apps_lookup_resp_view_t view; + err = nipc_client_call_apps_lookup(client, pids, LOOKUP_RETRY_ITEMS, &view); + if (err == NIPC_OK && view.item_count != LOOKUP_RETRY_ITEMS) + err = NIPC_ERR_BAD_ITEM_COUNT; + } else { + nipc_str_view_t paths[LOOKUP_RETRY_ITEMS]; + for (uint32_t i = 0; i < LOOKUP_RETRY_ITEMS; i++) { + retry_path(i, path_bufs[i], sizeof(path_bufs[i])); + paths[i].ptr = path_bufs[i]; + paths[i].len = (uint32_t)strlen(path_bufs[i]); + } + nipc_cgroups_lookup_resp_view_t view; + err = nipc_client_call_cgroups_lookup(client, paths, LOOKUP_RETRY_ITEMS, &view); + if (err == NIPC_OK && view.item_count != LOOKUP_RETRY_ITEMS) + err = NIPC_ERR_BAD_ITEM_COUNT; + } + *err_out = err; + if (err != NIPC_OK) + return false; + + pthread_mutex_lock(&ls->seen.lock); + bool same = ls->seen.calls >= 1 && ls->seen.item_count == LOOKUP_RETRY_ITEMS; + for (uint32_t i = 0; same && i < LOOKUP_RETRY_ITEMS; i++) { + char want[16]; + retry_path(i, want, sizeof(want)); + same = ls->apps ? ls->seen.pids[i] == 4000u + i + : strcmp(ls->seen.paths[i], want) == 0; + } + pthread_mutex_unlock(&ls->seen.lock); + return same; +} + +/* A READY client keeps its session while the server is replaced; the next + * call fails on the dead session, reconnects to the replacement inside the + * call and must resend the request it was given. */ +static void lookup_retry_after_restart(const char *service, bool apps, bool first_shm) +{ + printf("N12: %s lookup retried after a server restart (%s -> SHM)\n", + apps ? "apps" : "cgroups", first_shm ? "SHM" : "baseline"); + lookup_server_t first = {.service = service, .apps = apps, .shm = first_shm}; + if (!start_lookup_server(&first)) { + check("first server started", 0); + return; + } + + nipc_client_config_t ccfg = client_config(true); + ccfg.call_timeout_ms = 5000; + nipc_client_ctx_t client; + nipc_client_init(&client, TEST_RUN_DIR, service, &ccfg); + nipc_client_refresh(&client); + check("client ready", nipc_client_ready(&client)); + check(first_shm ? "first session is SHM" : "first session is baseline", + (client.shm != NULL) == first_shm); + + nipc_error_t err; + check("call 1 served with the exact items", lookup_call_matches(&client, &first, &err)); + check("first server stops", stop_lookup_server(&first)); + + lookup_server_t second = {.service = service, .apps = apps, .shm = true}; + if (!start_lookup_server(&second)) { + check("second server started", 0); + nipc_client_close(&client); + return; + } + + bool matches = lookup_call_matches(&client, &second, &err); + nipc_client_status_t status; + nipc_client_status(&client, &status); + printf(" call 2 err=%d reconnects=%u\n", err, status.reconnect_count); + check("call 2 succeeds after reconnecting inside the call", err == NIPC_OK); + check("call 2 reconnected exactly once", status.reconnect_count == 1); + check("replacement server saw the exact items", matches); + check("second session is SHM", client.shm != NULL); + + nipc_client_close(&client); + check("second server stops", stop_lookup_server(&second)); + cleanup_all(service); +} + +/* The response does not fit the server's fixed limit. The server answers + * LIMIT_EXCEEDED; the client raises its own response size, reconnects and + * resends inside the call, then reports the overflow once the server limit + * does not move. Every request the server sees must hold the same items. + * (A CGROUPS_LOOKUP of LOOKUP_RETRY_ITEMS short paths fits 1 KiB; it shares + * the retry code with APPS_LOOKUP.) */ +static void lookup_resend_after_response_limit(void) +{ + printf("N12: apps lookup resent after a response over the server limit\n"); + const char *service = "rob_lookup_limit_apps"; + lookup_server_t ls = {.service = service, .apps = true, .shm = true, .max_response = 1024}; + if (!start_lookup_server(&ls)) { + check("server started", 0); + return; + } + + nipc_client_config_t ccfg = client_config(true); + ccfg.max_response_payload_bytes = 1024; + ccfg.call_timeout_ms = 5000; + nipc_client_ctx_t client; + nipc_client_init(&client, TEST_RUN_DIR, service, &ccfg); + nipc_client_refresh(&client); + check("client ready on SHM", nipc_client_ready(&client) && client.shm != NULL); + + nipc_error_t err; + (void)lookup_call_matches(&client, &ls, &err); + nipc_client_status_t status; + nipc_client_status(&client, &status); + pthread_mutex_lock(&ls.seen.lock); + uint32_t calls = ls.seen.calls, mismatched = ls.seen.mismatched; + pthread_mutex_unlock(&ls.seen.lock); + printf(" call err=%d reconnects=%u server calls=%u mismatched=%u\n", err, + status.reconnect_count, calls, mismatched); + check("call reports the overflow", err == NIPC_ERR_OVERFLOW); + check("client reconnected twice (one size raise, one final check)", + status.reconnect_count == 2); + check("request was sent twice", calls == 2); + check("every resent request held the same items", mismatched == 0); + + nipc_client_close(&client); + check("server stops", stop_lookup_server(&ls)); + cleanup_all(service); +} + +static void test_lookup_retry_after_restart(void) +{ + lookup_retry_after_restart("rob_lookup_retry_apps_shm", true, true); + lookup_retry_after_restart("rob_lookup_retry_apps_up", true, false); + lookup_retry_after_restart("rob_lookup_retry_cg_shm", false, true); + lookup_retry_after_restart("rob_lookup_retry_cg_up", false, false); + lookup_resend_after_response_limit(); +} + +#endif + /* ------------------------------------------------------------------ */ int main(int argc, char **argv) @@ -1271,6 +1586,7 @@ int main(int argc, char **argv) test_uds_client_reports_crashed_server_as_disconnected(); #if defined(__linux__) || defined(__FreeBSD__) test_shm_attach_stops_when_server_closes_session(); + test_lookup_retry_after_restart(); #endif test_ipc_fds_are_cloexec(); test_default_packet_size_carries_large_message(); diff --git a/tests/fixtures/c/test_service.c b/tests/fixtures/c/test_service.c index acd1f41..a4e2f30 100644 --- a/tests/fixtures/c/test_service.c +++ b/tests/fixtures/c/test_service.c @@ -3818,10 +3818,10 @@ static void test_lookup_client_invalid_requests(void) { .ptr = "/known", .len = 6 }, }; nipc_posix_service_test_fault_set( - NIPC_POSIX_SERVICE_TEST_FAULT_CLIENT_SEND_BUF_REALLOC, 0); + NIPC_POSIX_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC, 0); err = nipc_client_call_cgroups_lookup(&client, valid_paths, 1, &view); nipc_posix_service_test_fault_clear(); - check("cgroups lookup send buffer fault rejected", err == NIPC_ERR_OVERFLOW); + check("cgroups lookup request buffer fault rejected", err == NIPC_ERR_OVERFLOW); nipc_client_close(&client); nipc_client_init(&client, TEST_RUN_DIR, svc, &ccfg); @@ -3867,10 +3867,10 @@ static void test_lookup_client_invalid_requests(void) nipc_apps_lookup_resp_view_t view; uint32_t pids[] = {1234}; nipc_posix_service_test_fault_set( - NIPC_POSIX_SERVICE_TEST_FAULT_CLIENT_SEND_BUF_REALLOC, 0); + NIPC_POSIX_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC, 0); nipc_error_t err = nipc_client_call_apps_lookup(&client, pids, 1, &view); nipc_posix_service_test_fault_clear(); - check("apps lookup send buffer fault rejected", err == NIPC_ERR_OVERFLOW); + check("apps lookup request buffer fault rejected", err == NIPC_ERR_OVERFLOW); nipc_client_close(&client); nipc_client_init(&client, TEST_RUN_DIR, svc, &ccfg); diff --git a/tests/fixtures/c/test_win_robustness.c b/tests/fixtures/c/test_win_robustness.c index ad9d6c3..ec85e18 100644 --- a/tests/fixtures/c/test_win_robustness.c +++ b/tests/fixtures/c/test_win_robustness.c @@ -18,6 +18,9 @@ * N3 stop before run is honored * N5 SHM client notices a crashed server before its timeout * N5 SHM attach stops when the server closes the session + * N12 a lookup retried after a reconnect resends the same request + * (server restart SHM->SHM and baseline->SHM, apps and cgroups; + * apps response over a fixed server limit) * * The binary re-executes itself with --helper-shm-client / --helper-shm-server * to simulate a peer process that is killed with TerminateProcess. @@ -806,6 +809,311 @@ static void test_shm_attach_stops_when_server_closes_session(void) check("server stops", stop_server_within(&rs, 5000)); } + +/* ------------------------------------------------------------------ */ +/* N12: a lookup retried after a reconnect resends the same request */ +/* ------------------------------------------------------------------ */ + +#define LOOKUP_RETRY_ITEMS 16u +/* Spare workers: a session the server closes after LIMIT_EXCEEDED may still + * hold its worker while the client reconnects. */ +#define LOOKUP_SERVER_WORKERS 4 + +/* What the lookup handler of one server saw, read under the lock. */ +typedef struct { + SRWLOCK lock; + uint32_t calls; + uint32_t mismatched; /* calls whose items differ from retry_path / 4000+i */ + uint32_t item_count; + uint32_t pids[LOOKUP_RETRY_ITEMS]; + char paths[LOOKUP_RETRY_ITEMS][16]; +} lookup_seen_t; + +typedef struct { + const char *service; + BOOL apps; + BOOL shm; + uint32_t max_response; /* 0 = RESPONSE_BUF_SIZE */ + lookup_seen_t seen; + nipc_apps_lookup_service_handler_t apps_handler; + nipc_cgroups_lookup_service_handler_t cgroups_handler; + nipc_managed_server_t server; + test_server_events_t events; + HANDLE thread; +} lookup_server_t; + +static void retry_path(uint32_t i, char *buf, size_t size) +{ + snprintf(buf, size, "/rt/%u", (unsigned)i); +} + +static bool apps_lookup_record_handler(void *user, + const nipc_apps_lookup_req_view_t *request, + nipc_apps_lookup_builder_t *builder) +{ + lookup_seen_t *seen = (lookup_seen_t *)user; + AcquireSRWLockExclusive(&seen->lock); + seen->calls++; + seen->item_count = request->item_count; + bool mismatch = request->item_count != LOOKUP_RETRY_ITEMS; + for (uint32_t i = 0; i < request->item_count; i++) { + nipc_apps_lookup_req_item_t item; + if (nipc_apps_lookup_req_item(request, i, &item) != NIPC_OK) + break; + if (i < LOOKUP_RETRY_ITEMS) + seen->pids[i] = item.pid; + if (item.pid != 4000u + i) + mismatch = true; + } + if (mismatch) + seen->mismatched++; + ReleaseSRWLockExclusive(&seen->lock); + + for (uint32_t i = 0; i < request->item_count; i++) { + nipc_apps_lookup_req_item_t item; + if (nipc_apps_lookup_req_item(request, i, &item) != NIPC_OK || + nipc_apps_lookup_builder_add(builder, NIPC_PID_LOOKUP_UNKNOWN, 0, 0, + item.pid, 0, NIPC_UID_UNSET, 0, "", 0, + "", 0, "", 0, NULL, 0) != NIPC_OK) + return false; + } + return true; +} + +static bool cgroups_lookup_record_handler(void *user, + const nipc_cgroups_lookup_req_view_t *request, + nipc_cgroups_lookup_builder_t *builder) +{ + lookup_seen_t *seen = (lookup_seen_t *)user; + AcquireSRWLockExclusive(&seen->lock); + seen->calls++; + seen->item_count = request->item_count; + bool mismatch = request->item_count != LOOKUP_RETRY_ITEMS; + for (uint32_t i = 0; i < request->item_count; i++) { + nipc_cgroups_lookup_req_item_t item; + if (nipc_cgroups_lookup_req_item(request, i, &item) != NIPC_OK) + break; + if (i < LOOKUP_RETRY_ITEMS) { + size_t n = item.path.len < sizeof(seen->paths[i]) - 1 + ? item.path.len : sizeof(seen->paths[i]) - 1; + memcpy(seen->paths[i], item.path.ptr, n); + seen->paths[i][n] = '\0'; + } + char want[16]; + retry_path(i, want, sizeof(want)); + if (item.path.len != strlen(want) || memcmp(item.path.ptr, want, item.path.len) != 0) + mismatch = true; + } + if (mismatch) + seen->mismatched++; + ReleaseSRWLockExclusive(&seen->lock); + + for (uint32_t i = 0; i < request->item_count; i++) { + nipc_cgroups_lookup_req_item_t item; + if (nipc_cgroups_lookup_req_item(request, i, &item) != NIPC_OK || + nipc_cgroups_lookup_builder_add(builder, NIPC_CGROUP_LOOKUP_UNKNOWN_RETRY_LATER, + 0, item.path.ptr, item.path.len, "", 0, + NULL, 0) != NIPC_OK) + return false; + } + return true; +} + +static DWORD WINAPI lookup_server_fn(LPVOID arg) +{ + lookup_server_t *ls = (lookup_server_t *)arg; + nipc_server_run(&ls->server); + nipc_server_destroy(&ls->server); + return 0; +} + +static BOOL start_lookup_server(lookup_server_t *ls) +{ + InitializeSRWLock(&ls->seen.lock); + nipc_server_config_t scfg = { + .supported_profiles = NIPC_PROFILE_BASELINE | + (ls->shm ? NIPC_WIN_SHM_PROFILE_HYBRID : 0), + .preferred_profiles = ls->shm ? NIPC_WIN_SHM_PROFILE_HYBRID : 0, + .max_request_payload_bytes = 4096, + .max_request_batch_items = 1, + .max_response_payload_bytes = ls->max_response ? ls->max_response : RESPONSE_BUF_SIZE, + .auth_token = AUTH_TOKEN, + }; + nipc_error_t err; + if (ls->apps) { + ls->apps_handler.handle = apps_lookup_record_handler; + ls->apps_handler.user = &ls->seen; + err = nipc_server_init_apps_lookup(&ls->server, TEST_RUN_DIR, ls->service, + &scfg, LOOKUP_SERVER_WORKERS, &ls->apps_handler); + } else { + ls->cgroups_handler.handle = cgroups_lookup_record_handler; + ls->cgroups_handler.user = &ls->seen; + err = nipc_server_init_cgroups_lookup(&ls->server, TEST_RUN_DIR, ls->service, + &scfg, LOOKUP_SERVER_WORKERS, &ls->cgroups_handler); + } + if (err != NIPC_OK) { + fprintf(stderr, "lookup server init failed: %d\n", err); + return FALSE; + } + test_server_use_test_timings(&ls->server, &ls->events); + ls->thread = test_create_thread(NULL, 0, lookup_server_fn, ls, 0, NULL); + if (!ls->thread) { + nipc_server_destroy(&ls->server); + return FALSE; + } + return TRUE; +} + +static BOOL stop_lookup_server(lookup_server_t *ls) +{ + nipc_server_stop(&ls->server); + BOOL stopped = WaitForSingleObject(ls->thread, 5000) == WAIT_OBJECT_0; + if (!stopped) + WaitForSingleObject(ls->thread, INFINITE); + CloseHandle(ls->thread); + return stopped; +} + +/* One lookup of LOOKUP_RETRY_ITEMS items; true when the call succeeded and + * the server's last handled request held exactly those items. */ +static BOOL lookup_call_matches(nipc_client_ctx_t *client, lookup_server_t *ls, + nipc_error_t *err_out) +{ + static char path_bufs[LOOKUP_RETRY_ITEMS][16]; + nipc_error_t err; + if (ls->apps) { + uint32_t pids[LOOKUP_RETRY_ITEMS]; + for (uint32_t i = 0; i < LOOKUP_RETRY_ITEMS; i++) + pids[i] = 4000u + i; + nipc_apps_lookup_resp_view_t view; + err = nipc_client_call_apps_lookup(client, pids, LOOKUP_RETRY_ITEMS, &view); + if (err == NIPC_OK && view.item_count != LOOKUP_RETRY_ITEMS) + err = NIPC_ERR_BAD_ITEM_COUNT; + } else { + nipc_str_view_t paths[LOOKUP_RETRY_ITEMS]; + for (uint32_t i = 0; i < LOOKUP_RETRY_ITEMS; i++) { + retry_path(i, path_bufs[i], sizeof(path_bufs[i])); + paths[i].ptr = path_bufs[i]; + paths[i].len = (uint32_t)strlen(path_bufs[i]); + } + nipc_cgroups_lookup_resp_view_t view; + err = nipc_client_call_cgroups_lookup(client, paths, LOOKUP_RETRY_ITEMS, &view); + if (err == NIPC_OK && view.item_count != LOOKUP_RETRY_ITEMS) + err = NIPC_ERR_BAD_ITEM_COUNT; + } + *err_out = err; + if (err != NIPC_OK) + return FALSE; + + AcquireSRWLockExclusive(&ls->seen.lock); + BOOL same = ls->seen.calls >= 1 && ls->seen.item_count == LOOKUP_RETRY_ITEMS; + for (uint32_t i = 0; same && i < LOOKUP_RETRY_ITEMS; i++) { + char want[16]; + retry_path(i, want, sizeof(want)); + same = ls->apps ? ls->seen.pids[i] == 4000u + i + : strcmp(ls->seen.paths[i], want) == 0; + } + ReleaseSRWLockExclusive(&ls->seen.lock); + return same; +} + +/* A READY client keeps its session while the server is replaced; the next + * call fails on the dead session, reconnects to the replacement inside the + * call and must resend the request it was given. */ +static void lookup_retry_after_restart(const char *prefix, BOOL apps, BOOL first_shm) +{ + printf("N12: %s lookup retried after a server restart (%s -> SHM)\n", + apps ? "apps" : "cgroups", first_shm ? "SHM" : "baseline"); + const char *service = svc_name(prefix); + lookup_server_t first = {.service = service, .apps = apps, .shm = first_shm}; + if (!start_lookup_server(&first)) { + check("first server started", 0); + return; + } + + nipc_client_config_t ccfg = client_config(TRUE, 5000); + nipc_client_ctx_t client; + nipc_client_init(&client, TEST_RUN_DIR, service, &ccfg); + nipc_client_refresh(&client); + check("client ready", nipc_client_ready(&client)); + check(first_shm ? "first session is SHM" : "first session is baseline", + (client.shm != NULL) == first_shm); + + nipc_error_t err; + check("call 1 served with the exact items", lookup_call_matches(&client, &first, &err)); + check("first server stops", stop_lookup_server(&first)); + + lookup_server_t second = {.service = service, .apps = apps, .shm = TRUE}; + if (!start_lookup_server(&second)) { + check("second server started", 0); + nipc_client_close(&client); + return; + } + + BOOL matches = lookup_call_matches(&client, &second, &err); + nipc_client_status_t status; + nipc_client_status(&client, &status); + printf(" call 2 err=%d reconnects=%u\n", err, status.reconnect_count); + check("call 2 succeeds after reconnecting inside the call", err == NIPC_OK); + check("call 2 reconnected exactly once", status.reconnect_count == 1); + check("replacement server saw the exact items", matches); + check("second session is SHM", client.shm != NULL); + + nipc_client_close(&client); + check("second server stops", stop_lookup_server(&second)); +} + +/* The response does not fit the server's fixed limit. The server answers + * LIMIT_EXCEEDED; the client raises its own response size, reconnects and + * resends inside the call, then reports the overflow once the server limit + * does not move. Every request the server sees must hold the same items. + * (A CGROUPS_LOOKUP of LOOKUP_RETRY_ITEMS short paths fits 1 KiB; it shares + * the retry code with APPS_LOOKUP.) */ +static void lookup_resend_after_response_limit(void) +{ + printf("N12: apps lookup resent after a response over the server limit\n"); + const char *service = svc_name("wrob_lookup_limit_apps"); + lookup_server_t ls = {.service = service, .apps = TRUE, .shm = TRUE, .max_response = 1024}; + if (!start_lookup_server(&ls)) { + check("server started", 0); + return; + } + + nipc_client_config_t ccfg = client_config(TRUE, 5000); + ccfg.max_response_payload_bytes = 1024; + nipc_client_ctx_t client; + nipc_client_init(&client, TEST_RUN_DIR, service, &ccfg); + nipc_client_refresh(&client); + check("client ready on SHM", nipc_client_ready(&client) && client.shm != NULL); + + nipc_error_t err; + (void)lookup_call_matches(&client, &ls, &err); + nipc_client_status_t status; + nipc_client_status(&client, &status); + AcquireSRWLockExclusive(&ls.seen.lock); + uint32_t calls = ls.seen.calls, mismatched = ls.seen.mismatched; + ReleaseSRWLockExclusive(&ls.seen.lock); + printf(" call err=%d reconnects=%u server calls=%u mismatched=%u\n", err, + status.reconnect_count, calls, mismatched); + check("call reports the overflow", err == NIPC_ERR_OVERFLOW); + check("client reconnected twice (one size raise, one final check)", + status.reconnect_count == 2); + check("request was sent twice", calls == 2); + check("every resent request held the same items", mismatched == 0); + + nipc_client_close(&client); + check("server stops", stop_lookup_server(&ls)); +} + +static void test_lookup_retry_after_restart(void) +{ + lookup_retry_after_restart("wrob_lookup_retry_apps_shm", TRUE, TRUE); + lookup_retry_after_restart("wrob_lookup_retry_apps_up", TRUE, FALSE); + lookup_retry_after_restart("wrob_lookup_retry_cg_shm", FALSE, TRUE); + lookup_retry_after_restart("wrob_lookup_retry_cg_up", FALSE, FALSE); + lookup_resend_after_response_limit(); +} + int main(int argc, char **argv) { if (argc == 3 && strcmp(argv[1], "--helper-shm-client") == 0) @@ -828,6 +1136,7 @@ int main(int argc, char **argv) test_stop_before_run_is_honored(); test_shm_client_notices_crashed_server(); test_shm_attach_stops_when_server_closes_session(); + test_lookup_retry_after_restart(); printf("\n%d passed, %d failed\n", g_pass, g_fail); fflush(stdout); diff --git a/tests/fixtures/c/test_win_service_extra.c b/tests/fixtures/c/test_win_service_extra.c index b911a5f..c2777d6 100644 --- a/tests/fixtures/c/test_win_service_extra.c +++ b/tests/fixtures/c/test_win_service_extra.c @@ -3681,10 +3681,10 @@ static void test_lookup_init_and_client_guards(void) { .ptr = "/known", .len = 6 }, }; nipc_win_service_test_fault_set( - NIPC_WIN_SERVICE_TEST_FAULT_CLIENT_SEND_BUF_REALLOC, 0); + NIPC_WIN_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC, 0); err = nipc_client_call_cgroups_lookup(&client, valid_paths, 1, &view); clear_test_faults(); - check("cgroups lookup send buffer fault rejected", err == NIPC_ERR_OVERFLOW); + check("cgroups lookup request buffer fault rejected", err == NIPC_ERR_OVERFLOW); nipc_client_close(&client); stop_lookup_server_drain(&sctx, server_thread); @@ -3712,10 +3712,10 @@ static void test_lookup_init_and_client_guards(void) nipc_apps_lookup_resp_view_t view; uint32_t pids[] = {1234}; nipc_win_service_test_fault_set( - NIPC_WIN_SERVICE_TEST_FAULT_CLIENT_SEND_BUF_REALLOC, 0); + NIPC_WIN_SERVICE_TEST_FAULT_CLIENT_REQUEST_BUF_REALLOC, 0); nipc_error_t err = nipc_client_call_apps_lookup(&client, pids, 1, &view); clear_test_faults(); - check("apps lookup send buffer fault rejected", err == NIPC_ERR_OVERFLOW); + check("apps lookup request buffer fault rejected", err == NIPC_ERR_OVERFLOW); nipc_client_close(&client); nipc_client_init(&client, TEST_RUN_DIR, service, &ccfg); diff --git a/tests/run-sanitizer-asan.sh b/tests/run-sanitizer-asan.sh index c618947..ef1fcc2 100755 --- a/tests/run-sanitizer-asan.sh +++ b/tests/run-sanitizer-asan.sh @@ -52,7 +52,7 @@ echo -e "${YELLOW}Building test binaries...${NC}" run cmake --build "$BUILD_DIR" -j"$(nproc)" 2>&1 # All C test binaries to run -TESTS=(test_protocol test_uds test_shm test_service test_service_extra test_cache test_multi_server) +TESTS=(test_protocol test_uds test_shm test_service test_service_extra test_cache test_multi_server test_robustness) total=0 passed=0