Skip to content

Keep logging from hanging on a stalled systemd journal - #303

Merged
TheJokr merged 9 commits into
cloudflare:mainfrom
zaidoon1:log-output-safety
Nov 24, 2026
Merged

TheJokr merged 9 commits into
cloudflare:mainfrom
zaidoon1:log-output-safety

Conversation

@zaidoon1

@zaidoon1 zaidoon1 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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_behavior setting on LoggingSettings (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 in JOURNAL_STREAM, log records go through JournalWriter, leaving fd flags (O_NONBLOCK) alone so println!/eprintln! and child processes are unaffected.
  • non_blocking_stdio: same as non_blocking_logger, and also sets O_NONBLOCK on stdout/stderr when they are the journal stream (whatever output is configured to), so direct writers like the default panic hook can't hang on a stalled journal either.
logging thread, per record (when non_blocking_logger / non_blocking_stdio and output matches JOURNAL_STREAM)
  format into a 4KiB-preallocated buffer
  send with MSG_DONTWAIT
    WouldBlock -> if not yet stalled, poll(POLLOUT) up to 50ms so bursts and >SO_SNDBUF records complete intact
                  on timeout -> mark stalled, drop, count logging_records_dropped{reason="journal_full"}
                  while stalled -> drop immediately without polling until the stream accepts bytes again
    ENOTSOCK   -> stdout/stderr was replaced after init, clear cut_short (if sent == 0) and write() to it like any other writer
    error      -> count reason="journal_error", then ignore_io_errors as before

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_errors off (the default), the first journal_error stops 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

  • Reproduced & fixed:
    • Stalled journal hangs shutdown_logger() and panics on main (JSON and text); with non_blocking_stdio both finish without hanging, and non_blocking_logger finishes shutdown_logger() while leaving O_NONBLOCK off.
    • Default blocking behavior verified not to set O_NONBLOCK, not to activate JournalWriter, and to succeed under a seccomp filter rejecting sendto with EPERM.
    • Transient backpressure & large records: a 1 MiB JSON record on an actively reading journald and a 400-record burst across a 15ms pause both deliver with 0 drops and intact JSON.
    • Shutdown fd tests fail on main with EBADF and pass on both Linux and macOS.
    • ENOTSOCK fallback after a cut-short record no longer prepends a stray newline to a fresh replacement file; flush() after new_record without write() discards stale partial bytes.
  • Verified on Linux aarch64: rustfmt --check, cargo clippy --all-targets (CI lint flags), cargo nextest run (398/398), cargo nextest run --all-features with 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 verified cargo check --all-targets and the cross-platform StdioWriter shutdown tests on macOS.

Merge Danger

Door: two-way

Default behavior is unchanged (journal_stream_behavior: blocking). For services that opt in:

  • non_blocking_logger: requires sendto (NET_SOCKET_API, not SERVICE_BASICS) and poll (x86_64) / ppoll (aarch64) if seccomp applies to telemetry init/logging.
  • non_blocking_stdio: additionally requires fcntl during init (RUST_BASICS only allows it in debug builds) and sets O_NONBLOCK on the journal stream itself (shared across writers and inherited by child processes; println!/eprintln! panic on WouldBlock; stays on the stream until service restart).
  • The StdioWriter (ManuallyDrop<File>) fd-closing fix applies to any service logging JSON to stdout or stderr and is strictly safer on shutdown.

@zaidoon1 zaidoon1 changed the title Keep logging from hanging on a stuck systemd journal Keep logging from hanging on a stalled systemd journal Nov 8, 2026
@zaidoon1
zaidoon1 marked this pull request as ready for review November 8, 2026 09:32
@zaidoon1
zaidoon1 force-pushed the log-output-safety branch 3 times, most recently from 1e09d4f to 83f8949 Compare November 10, 2026 23:56
@zaidoon1

Copy link
Copy Markdown
Contributor Author

@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 File made from fd 1 or 2, so dropping the drain at shutdown closed the fd. Whatever got opened next took that number, and a panic message after shutdown would end up in it. The File is wrapped in ManuallyDrop now, so the fd stays open like it does for the journal writer.

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, send fails with ENOTSOCK, and with ignore_io_errors off that killed the logging thread on the next record. It falls back to a plain write() now so logs follow the redirect. That write can block if the new file does, same as any other writer.

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 journal_error stops logging after the first one unless ignore_io_errors is on, and what seccomp needs to allow.

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.

Comment thread foundations/src/telemetry/log/init.rs Resolved
Comment thread foundations/src/telemetry/log/init.rs Resolved
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.
@TheJokr
TheJokr merged commit e7a2891 into cloudflare:main Nov 24, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants