Files
mxaccessgw/docs/WorkerProcessLauncher.md
T
Joseph Doherty ee0f836886
ci / windows-x86 (push) Successful in 3m50s
ci / java (push) Failing after 10m14s
ci / portable (push) Failing after 19m55s
fix(workers): capture worker stderr/stdout, forward it to the gateway log, and attach the stderr tail to early-exit StartupFailed (WRK-002, #259)
The worker was started with CreateNoWindow and no redirection, so its log lines
went to a hidden console of its own and were lost under both a console run and
the NSSM service (verified on windev). The launcher now redirects both streams
and WorkerOutputCapture drains them: each line is forwarded under the
ZB.MOM.WW.MxGateway.Worker category at the worker's own level, the session
nonce is scrubbed, and the last 50 lines / 4 KB of stderr are kept. The drain
never waits on the logger (bounded drop-oldest queue) and ends at EOF when the
worker exits. A worker that exits before connecting (session factory race) or
that the probe finds already exited now fails StartupFailed with the stderr tail.
2026-12-03 13:10:12 -05:00

163 lines
8.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Worker Process Launcher
The gateway uses `WorkerProcessLauncher` to validate and start one worker
process for a gateway session. The launcher owns process start semantics only;
pipe handshaking and `WorkerReady` validation remain part of the worker client
startup path.
## Launch Inputs
`WorkerProcessLaunchRequest` carries the per-session bootstrap values:
- `SessionId`,
- `PipeName`,
- `ProtocolVersion`,
- `Nonce`,
- optional `PipeReservation` cleanup handle.
The launcher passes `SessionId`, `PipeName`, and `ProtocolVersion` as command
line arguments:
```text
--session-id <sessionId> --pipe-name <pipeName> --protocol-version <version>
```
The launcher sets the nonce through the `MXGATEWAY_WORKER_NONCE` environment
variable. The nonce is not included in `WorkerProcessCommandLine` so logs and
diagnostics can report the launch command without exposing the secret.
All launch-variable names live in the shared Contracts
`WorkerLaunchEnvironment` class and are consumed by both the launcher and the
worker. The launcher always exports every value below:
| Environment variable | Gateway source | Worker default when missing/invalid |
|---|---|---|
| `MXGATEWAY_WORKER_NONCE` | `WorkerProcessLaunchRequest.Nonce` | None; bootstrap fails because the nonce is required |
| `MXGATEWAY_WORKER_PIPE_CONNECT_ATTEMPT_TIMEOUT_MS` | `MxGateway:Worker:PipeConnectAttemptTimeoutMilliseconds` | `2000` ms |
| `MXGATEWAY_WORKER_WRITE_COMPLETION_WAIT_MS` | `MxGateway:Worker:WriteCompletionWaitMilliseconds` | `1500` ms |
| `MXGATEWAY_EVENT_QUEUE_CAPACITY` | `MxGateway:Worker:EventQueueCapacity` | `10000` events |
| `MXGATEWAY_ALARM_POLL_INTERVAL_MS` | `MxGateway:Alarms:PollIntervalMilliseconds` | `500` ms |
| `MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH` | `MxGateway:Alarms:MaxAlarmsPerFetch` | `1024` alarms |
| `MXGATEWAY_ALARM_ACK_CLIENT_NAME` | `MxGateway:Alarms:AckClientName` | `MxGateway` |
| `MXGATEWAY_WORKER_HEARTBEAT_SEND_INTERVAL_MS` | `MxGateway:Worker:WorkerHeartbeatSendIntervalSeconds` (× 1000) | `5000` ms |
| `MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS` | `MxGateway:Worker:WorkerHeartbeatGraceSeconds` (× 1000) | `15000` ms (also kept when the ceiling is not above it) |
| `MXGATEWAY_WORKER_HEARTBEAT_STUCK_CEILING_MS` | `MxGateway:Worker:WorkerHeartbeatStuckCeilingSeconds` (× 1000) | `75000` ms (also kept when the value is not above the worker's watchdog grace) |
The write-completion wait applies to the four single-item write variants:
`Write`, `Write2`, `WriteSecured`, and `WriteSecured2`. Bulk writes report COM
acceptance per entry and do not wait for `OnWriteComplete` rows.
## Validation And Cleanup
Before starting the process, the launcher validates that the configured worker
path exists, has a `.exe` extension, contains a valid Windows Portable
Executable header, and matches the configured `RequiredArchitecture`.
After the process starts, `IWorkerStartupProbe` waits for startup readiness.
The default probe only verifies that the worker did not exit immediately, which
it checks once, microseconds after the process is created. A worker that dies
after that and before it connects is caught by the session factory instead:
`SessionWorkerClientFactory` races the pipe connect against the process exit,
so an early exit fails the open at once with `StartupFailed` and the worker's
exit code rather than holding the open (and its session slot) for the whole
startup timeout and reporting a timeout. Once the pipe is connected, a worker
exit surfaces as pipe end-of-stream in the handshake reads. Both early-exit
failures (the probe's and the session factory's) end with the tail of the
worker's stderr, `Last worker stderr output:` followed by up to the last 50
lines / 4 KB. The factory first waits up to one second for stderr to reach
end-of-stream so the lines the worker wrote on its way out are included. The
`StartupFailed` message reaches the gateway log (`Failed to open gateway
session`) and the session's fault reason; a gRPC client still sees only
`Failed to open session <id>.`
## Worker Output Capture
The launcher starts the worker with `RedirectStandardError` and
`RedirectStandardOutput` set and hands both streams to `WorkerOutputCapture`
before anything else runs (mxaccessgw#259).
Before this change the worker's output was lost. It was started with
`CreateNoWindow` and no redirection, which gives the child a hidden console of
its own, so its `level=... event=...` log lines reached neither the gateway's
console (console run) nor the NSSM `AppStdout`/`AppStderr` files (service run).
This was checked on windev: a probe child's stderr did not appear in the
parent's redirected files, and the windev service's `stderr.log` and
`stdout.log` held no worker lines. Capturing the output therefore adds log lines
and loses none. Stdout is redirected as well because, once the child's standard
handles are set explicitly, an unredirected stdout would be the gateway's own
(the NSSM stdout log). The worker writes nothing to stdout itself.
Each line is forwarded to the gateway log under the category
`ZB.MOM.WW.MxGateway.Worker`, with the session id, worker process id and stream
as properties. It uses one category rather than one per session because the
logger factory caches categories for the life of the process. The level follows
the worker's own `level=` prefix (`Information`, `Warning`, `Error`). Any other
stderr text, such as CLR or native crash output, is logged as `Warning`, and
other stdout text as `Information`. Lines longer than 2048 characters are cut
and marked `...[truncated]`. The capture also keeps the most recent stderr lines
in a bounded tail for the startup-failure messages above.
The capture cannot block the worker or leak:
- The pipes are always drained. A reader only appends the line to the tail and
offers it to a bounded drop-oldest queue (1024 lines), which never waits. A
separate task does the logging. When the log sink falls behind, the oldest
queued lines are dropped and a `Dropped N worker output lines` warning is
logged. Backpressure never reaches the worker's `Console.Error` writes, some
of which run on its STA thread. A throwing log sink is ignored.
- The readers run until end-of-stream and then dispose their own reader.
End-of-stream arrives when the worker exits, and the gateway always kills the
worker before disposing its process handle, so the capture needs no
cancellation and does not cut off the worker's last lines.
The worker redacts its own lines (`WorkerLogRedactor`: nonce, secret, password,
token, credential and API-key fields and assignments; the unhandled-exception
hook logs the exception type only). As defense in depth, the capture also
replaces any occurrence of the session's bootstrap nonce, the one secret the
gateway gives the worker, with `[redacted]` before a line is logged or kept.
There is no option to turn the capture off. Worker log volume is low unless
`MXGATEWAY_WORKER_LOG_COMMANDS` is set, and that variable is what turns on the
noisy per-command lines.
The startup probe runs once, bounded by `WorkerOptions.StartupTimeoutSeconds`;
it is not retried. The default probe only checks that the process is still
alive, which cannot change on a retry, so the former
`StartupProbeRetryAttempts` / `StartupProbeRetryDelayMilliseconds` options were
removed (mxaccessgw#188). Stale keys in existing configuration are ignored by
the binder. The worker pipe connect and handshake have their own retry loop.
The worker uses the exported pipe-attempt value inside its own bounded Polly
retry loop.
If startup fails or exceeds `WorkerOptions.StartupTimeoutSeconds`, the launcher
kills the worker process tree, disposes the process handle, disposes the
optional pipe reservation, records a worker kill metric, and reports a
`WorkerProcessLaunchException`. A `Kill` that throws during this cleanup (the
process is mid-termination, access is denied, a descendant could not be
terminated) is logged and does not replace the launch error; the process handle
and the pipe are disposed regardless. The session factory's own cleanup follows
the same rule.
## Verification
Run the focused launcher tests after changing process launch behavior:
```bash
dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj --filter "FullyQualifiedName~WorkerProcessLauncherTests|FullyQualifiedName~WorkerOutputCaptureTests"
```
`WorkerOutputCaptureTests` includes a real child process (`/bin/sh`, or `cmd.exe`
on Windows) that writes well past a pipe buffer to stderr, to show the drain
cannot block the child.
Run the gateway build because the launcher is part of `ZB.MOM.WW.MxGateway.Server`:
```bash
dotnet build src/ZB.MOM.WW.MxGateway.Server/ZB.MOM.WW.MxGateway.Server.csproj
```
## Related Documentation
- [Gateway Process Detailed Design](./GatewayProcessDesign.md)
- [Worker Frame Protocol](./WorkerFrameProtocol.md)