Repository navigation
Keep logging from hanging on a stalled systemd journal - #303
Conversation
68df7c1 to
5aedd2c
Compare
5aedd2c to
8eb6432
Compare
1e09d4f to
83f8949
Compare
aea4837 to
380fa72
Compare
|
@kornelski heads up, I pushed a few more commits after you approved and two of them change behaviour, so I wanted to make sure you saw them. 4c53856 fixes something that's already broken on main. When JSON logs go to stdout or stderr and it isn't the journal, the writer is a c8b7e50 covers stdout or stderr getting replaced after init. If something dup2's a regular file or a pipe over what was the journal stream, The rest is tests and docs. There's a test for the 64KiB buffer cap now, and the journal tests report failures without panicking, because if the nonblocking code ever regressed, a panic stuck in the hook on the full stream would make a test hang instead of fail. The docs now say that I also force pushed once to fix the first commit's message. It said a record that fails to format gets discarded, but that's only true for JSON, slog-term flushes a text one anyway. No code change from that. Would appreciate another look at those two commits when you get a chance. |
systemd connects a service's stdout and stderr to a journald socket and names it in JOURNAL_STREAM. If journald stops reading that socket but keeps it open, as systemd/systemd#44521 describes after a journald restart, every blocking write to it waits for good: the logging thread, then TelemetryDriver::shutdown_logger, and any thread that panics, because the default panic hook writes its message to stderr. When stdout or stderr is the stream JOURNAL_STREAM names, log output to it now goes through a writer that never waits. The writer buffers each record until the formatter flushes it, then sends it with MSG_DONTWAIT, so it doesn't wait even if something sharing the descriptor makes it blocking again. A record that doesn't fit is dropped and counted in logging_records_dropped{reason="journal_full"}. A full stream isn't an I/O error, so it never stops the logging thread, whatever ignore_io_errors is. Other send errors are reported as before and counted as journal_error. When a record is cut short, the next one starts with a newline, so journald doesn't join the two. A JSON record that fails to format is discarded rather than sent with the next one. slog-term flushes a text record even when formatting fails, so that one goes out cut short, on its own line. Initialization also makes those streams nonblocking, whatever the log output is, so the default panic hook and other writers can't wait for journald either. The flag is shared by every process holding the stream. When the stream is full, println! and eprintln! panic and the panic hook's message can be lost. allow_blocking_journal_stdio leaves the streams as they are.
When JSON logs go to a stdout or stderr that isn't the journal stream, the drain writes through a File made from fd 1 or 2, and dropping it at shutdown closed the descriptor. The next file or socket opened took that number, so anything written to stderr afterwards, like a panic message, went into it. The writer wraps the File in ManuallyDrop, so dropping the drain leaves the descriptor open, the same as the journal writer does.
The journal writer sends with MSG_DONTWAIT, and send fails with ENOTSOCK if something replaces stdout or stderr with a regular file or a pipe after logging started. With ignore_io_errors off, that stopped the logging thread on the next record, so every log after the swap was lost. On ENOTSOCK the writer writes to the descriptor instead, the same way the other stdout and stderr writers do, so logs follow the redirect.
When the journal stream blocks, a panic on the logging thread can get stuck writing its message in the default panic hook, which holds the hook's lock. A failing assert! in the test then waits for that lock forever, and nextest has no timeout here, so CI would hang instead of reporting the failure. The checks that can run in that state go through fail_without_panicking, like the stalled journal test already does. Also test that the journal writer keeps the buffer of a normal record for the next one and frees the buffer of a huge one.
With ignore_io_errors off, the logging thread stops after the first journal_error, so the counter stays at 1 while every later record is lost. The metric's help text and the DropReason docs say so, so an alert can fire on any increase. ignore_io_errors also says that a full journal stream isn't an I/O error. The allow_blocking_journal_stdio docs say that a stream stays nonblocking until the service restarts, and which of foundations' seccomp allow lists has sendto and fcntl. The comment on the record reset says what each formatter does with a record it fails to finish: JSON never flushes it, so it's discarded, and text flushes it cut short, so it goes out on its own line.
OsStr compares with str directly, so is_journal doesn't need to go through encoded bytes. The record-start flag check in JournalWriter::write is a load followed by a store, which reads like a missing compare-and-swap. A comment explains that only the logging thread touches the flag, and that the load keeps every write after a record's first to a plain read.
Address review feedback and fix edge cases found during testing: - Replace allow_blocking_journal_stdio with an opt-in JournalStreamBehavior enum defaulting to Blocking, so existing services see no behavior or seccomp changes unless they opt in. NonBlockingLogger covers the foundations logging thread without changing fd flags; NonBlockingStdio also sets O_NONBLOCK on journal stdio descriptors. - Wait up to 50ms via poll(POLLOUT) on WouldBlock before marking the journal stream stalled, then drop immediately without polling while stalled until the stream accepts bytes again. This prevents healthy bursts and records larger than SO_SNDBUF from being dropped or truncated mid-JSON. - Replace JournalStreams::includes + stdio_fd with JournalStreams::fd returning Option<BorrowedFd<'static>>. - Remove the start parameter from JournalWriter::send, check empty records at the top of the loop, check new_record in flush(), make JournalDrain !Sync, preallocate the record buffer to 4KiB, and inline Write impls on StdioWriter and JournalWriter. - Reset cut_short on ENOTSOCK fallback before writing to a replacement file so a fresh file doesn't get a stray leading newline. - Add regression tests for default blocking/seccomp behavior, large records on a healthy journal, 15ms transient bursts, text stalls, journal_error stopping after the first error, flush-without-write, and ENOTSOCK after a cut-short record; run StdioWriter shutdown tests on all Unix targets.
380fa72 to
39c8d0b
Compare
Summary
We had some services (not on foundations yet) hang when journald stopped reading their stdout/stderr stream. Once the socket buffer is full, every blocking write to it waits forever: the foundations logging thread (so
shutdown_logger()never returns), and any thread that panics, because the default panic hook writes to stderr. systemd/systemd#44521 fixed one way journald ends up like that, but any other bug that leaves the stream unread has the same effect.This adds an opt-in
journal_stream_behaviorsetting onLoggingSettings(default:blocking, so existing services see no behavior or seccomp changes):blocking(default): leaves stdout and stderr untouched; no extra syscalls (fstat,sendto,poll/ppoll,fcntl) are issued.non_blocking_logger: when stdout or stderr is the stream named inJOURNAL_STREAM, log records go throughJournalWriter, leaving fd flags (O_NONBLOCK) alone soprintln!/eprintln!and child processes are unaffected.non_blocking_stdio: same asnon_blocking_logger, and also setsO_NONBLOCKon stdout/stderr when they are the journal stream (whateveroutputis configured to), so direct writers like the default panic hook can't hang on a stalled journal either.If a record only partly fits when the stream stalls, the next one starts with a newline so journald doesn't merge them. A JSON record that fails to serialize is thrown away instead of being sent with the next one. A text record that fails goes out cut short on its own line, because slog-term flushes it anyway.
With
ignore_io_errorsoff (the default), the firstjournal_errorstops the logging thread like any other output error does. So that counter goes to 1 and stays there, and an alert should fire on any increase.Logger shutdown leaves stdout and stderr open (including for the JSON stdout/stderr writer outside the journal case), so a panic message written after shutdown can't land in whatever file got fd 1/2 next.
Evidence
shutdown_logger()and panics onmain(JSON and text); withnon_blocking_stdioboth finish without hanging, andnon_blocking_loggerfinishesshutdown_logger()while leavingO_NONBLOCKoff.blockingbehavior verified not to setO_NONBLOCK, not to activateJournalWriter, and to succeed under a seccomp filter rejectingsendtowithEPERM.mainwithEBADFand pass on both Linux and macOS.ENOTSOCKfallback after a cut-short record no longer prepends a stray newline to a fresh replacement file;flush()afternew_recordwithoutwrite()discards stale partial bytes.rustfmt --check,cargo clippy --all-targets(CI lint flags),cargo nextest run(398/398),cargo nextest run --all-featureswith CI unstable flags (480/480),cargo test --doc(86/86),cargo doc(zero warnings in touched files),http_server --dry-run, and feature-flag checks (logging,settings,logging,settings,logging,metrics,logging,metrics,foundations-metrics-backend,default-no-jemalloc,server-client-common-default). Also verifiedcargo check --all-targetsand the cross-platformStdioWritershutdown tests on macOS.Merge Danger
Door: two-way
Default behavior is unchanged (
journal_stream_behavior: blocking). For services that opt in:non_blocking_logger: requiressendto(NET_SOCKET_API, notSERVICE_BASICS) andpoll(x86_64) /ppoll(aarch64) if seccomp applies to telemetry init/logging.non_blocking_stdio: additionally requiresfcntlduring init (RUST_BASICSonly allows it in debug builds) and setsO_NONBLOCKon the journal stream itself (shared across writers and inherited by child processes;println!/eprintln!panic onWouldBlock; stays on the stream until service restart).StdioWriter(ManuallyDrop<File>) fd-closing fix applies to any service logging JSON to stdout or stderr and is strictly safer on shutdown.