Documentation
¶
Overview ¶
Package syslog forwards log lines to a remote syslog server over UDP or TCP. It is a self-contained leaf (stdlib only, no Culvert coupling) extracted from the flat package main per ADR-0002. The structured-entry writers take `any` (the entry is only JSON-marshalled) so the forwarder needn't know the concrete audit/request-log struct types.
Two formats are supported:
RFC 3164 (BSD syslog) — legacy, accepted everywhere. RFC 5424 (IETF syslog) — modern SIEMs prefer this for structured data, microsecond timestamps, and proper UTF-8 BOM handling.
Priority: facility=1 (user-level), severity=6 (informational) → PRI=14. Audit events are sent at severity=5 (notice) → PRI=13.
Delivery is ASYNCHRONOUS: senders format the line and enqueue it on a bounded channel; a single drain goroutine (started by NewWriter) owns the connection, the reconnect/backoff state machine, and every network write. The request path therefore never takes the connection mutex and never blocks on a socket — a slow or wedged TCP collector costs the caller a channel send, with overflow counted in Drops rather than propagated as proxy latency. Ordering is preserved (one drain goroutine).
Index ¶
- Constants
- func LateDrops() uint64
- func ResetLateDropsForTest()
- func SetNowForTest(fn func() time.Time) (restore func())
- type ProbeOutcome
- type Stats
- type Writer
- func (s *Writer) Close() error
- func (s *Writer) CumulativeStats() (Stats, bool)
- func (s *Writer) DeliveryProvable() bool
- func (s *Writer) Drops() uint64
- func (s *Writer) FinalStats() (Stats, bool)
- func (s *Writer) Format() string
- func (s *Writer) HandOffTo(next *Writer)
- func (s *Writer) MarkRetired()
- func (s *Writer) Panics() uint64
- func (s *Writer) Sealed() bool
- func (s *Writer) SetDeliveryObserver(fn func(delivered bool))
- func (s *Writer) SetPanicObserver(fn func(recovered any))
- func (s *Writer) Stats() Stats
- func (s *Writer) Write(p []byte) (int, error)
- func (s *Writer) WriteAudit(e any)
- func (s *Writer) WriteProbe(msg string) (<-chan ProbeOutcome, bool)
- func (s *Writer) WriteRequest(e any)
Constants ¶
const ( ReasonQueueFull = "queue_full" // the collector is slower than the entry rate ReasonClosed = "closed" // send after Close ReasonConnectFail = "connect_failed" // dial to the collector failed ReasonWriteFail = "write_failed" // the socket write failed or timed out ReasonBackoff = "backoff" // fast-dropped inside the reconnect backoff window ReasonPanic = "panic" // a recovered panic in the drain goroutine ReasonFlushTimeout = "flush_timeout" // still queued when Close's flush window expired )
Bounded reason classes for a delivery failure.
A reason reaches an alert Detail and an operator-contract row, so it must be a CLOSED SET, never a raw error string: the transport error embeds the collector address (and for a dial failure the ephemeral local port), and the alert store dedups on event+Detail — a per-failure-unique reason defeats the dedup window by construction and evicts real alerts from the bounded retry queue. That is the WK-12/RS-5 defect, recorded twice already in this tree. The verbose cause stays in the process log.
const DialTimeout = 5 * time.Second
DialTimeout bounds the ONE blocking step in NewWriter: the connect. It is exported because the health plane has to know how long a caller's synchronous NewWriter/InitSyslog can take before it has a verdict — a recorded intent whose dial is still in flight is not yet an unmet one, and deriving that window from this constant is what stops the two drifting (Codex P2, PR #1494). Everything else NewWriter does is a hostname lookup and a channel allocation.
Variables ¶
This section is empty.
Functions ¶
func LateDrops ¶ added in v1.0.363
func LateDrops() uint64
LateDrops returns the process-lifetime count of losses that were charged to a displaced Writer whose totals had already been retired. The health plane folds it into the exported drop total; see lateDrops.
func ResetLateDropsForTest ¶ added in v1.0.363
func ResetLateDropsForTest()
ResetLateDropsForTest clears the process-lifetime late-drop counter.
That counter is process-lifetime BY DESIGN — its whole purpose is to outlive the Writer the loss was charged against — which makes it exactly the kind of global a test must hand back rather than merely stop looking at. A gate that produces one late drop otherwise shifts the exported drop total for every gate that runs after it, and those assert exact counts. Observed, not hypothetical: adding the late-drop gate turned seven unrelated CHAOS-81 gates red. Same rule as swapAutoExclude and armSyslogFeed closing the writer it installs.
func SetNowForTest ¶ added in v1.0.363
SetNowForTest replaces the package clock and returns a restore function. Test-only; production never calls it.
Types ¶
type ProbeOutcome ¶ added in v1.0.363
type ProbeOutcome struct {
Delivered bool
Provable bool
// Reason is the bounded failure class for THIS line, stamped by the
// Writer that actually attempted (or refused) the send. Empty when
// Delivered.
//
// It travels on the acknowledgement for the same reason Provable does: a
// handoff moves a queued line and its ack together to a successor, so the
// Writer the prober called is one hop short of the sender and its
// writer-wide LastFailureReason can be `unknown` or an unrelated line's
// class. Reading that field at ack time would ALSO repeat the defect the
// per-line ack was introduced to fix, since a concurrent line's failure
// can overwrite it between the drop and the read (Codex P2, PR #1494).
Reason string
}
ProbeOutcome is the result of one probed line, reported by the drain goroutine of the Writer that ACTUALLY SENT IT.
Provable is that sending Writer's DeliveryProvable(), never the one the caller handed to WriteProbe. The two differ: handOffQueued moves a queued line — its ack channel included — to a successor that may speak a different transport, so a probe queued on a TCP writer and handed off to a UDP one was reported with the TCP sentence ("the collector accepted the test event") for a datagram nothing may have received (Codex P2, PR #1494). Binding the transport to the Writer the caller holds was the previous round's fix and was correct exactly one hop short: the acknowledgement has to carry the transport, because only the sender knows it.
type Stats ¶ added in v1.0.363
type Stats struct {
Delivered uint64
Drops uint64
Panics uint64
ConsecutiveFailures uint64
QueueDepth int
QueueCap int
// LastSuccess is zero when no line has EVER been delivered by this Writer.
// That case is distinct from "delivered a while ago" and the surfaces
// treat it as such: a feed that has never delivered was misconfigured or
// pointed at a dead collector from the start.
LastSuccess time.Time
LastFailure time.Time
// FailingSince is when the CURRENT unresolved failure episode began — the
// first loss after the last delivery. Zero when ConsecutiveFailures is 0.
// A duration-based degradation predicate must be timed from here, not
// from LastSuccess: a feed idle for an hour whose next line happens to
// drop has been failing for zero seconds, not for an hour.
FailingSince time.Time
// LastFailureReason is one of the Reason* constants, or "" before the
// first failure. Never a raw error.
LastFailureReason string
}
Stats is a point-in-time snapshot of delivery health.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer forwards log lines to a remote syslog server over UDP or TCP.
A Writer built by NewWriter delivers asynchronously via queue/drainLoop; a zero-value Writer (tests build these directly) has a nil queue and falls back to the synchronous writeMsg path, so the delivery state machine stays directly testable.
func NewWriter ¶
NewWriter dials the syslog server and returns a ready Writer. format selects the wire format: "rfc3164" (default) or "rfc5424".
func (*Writer) Close ¶
Close stops the drain goroutine (flushing already-queued lines within flushTimeout) and releases the connection. Idempotent; concurrent sends after Close count as drops. On an async Writer the connection is owned and released by the drain goroutine; Close waits up to closeWait for it — if a wedged collector outlasts even that, Close returns and the goroutine releases the conn when its write deadline fires.
func (*Writer) CumulativeStats ¶ added in v1.0.363
CumulativeStats returns the snapshot a FOLDING consumer must use — the sealed finals once this Writer has sealed, the live counters until then — together with whether it has sealed.
A consumer that instead calls FinalStats() and then falls back to Stats() has the two reads in the WRONG ORDER, and the Writer can seal between them. Its live counters keep moving after the seal (deliberately — see chargeTerminalDrop), and every post-seal loss is ALREADY charged to lateDrops, so folding that live value counts the same loss twice. Worse, the next settle reads the sealed snapshot, which is SMALLER than the live value already folded, so the delta goes negative and the exported culvert_syslog_drops_total DECREASES — the one thing a Prometheus counter may not do, and precisely the contract the sealing boundary exists to keep (Codex P2, PR #1494).
The order below is what makes the pair safe, and it needs no lock:
- If the seal is present, the finals ARE the answer, exactly.
- If it is absent, the Writer had not sealed at the LATER of the two reads, so it had not sealed at the earlier one either. The live value therefore predates the seal and cannot exceed the finals that follow — so a folded value is never succeeded by a smaller one, which is the whole guarantee.
Reading both under sendMu would also be exact, and it was the first shape. It deadlocks, and the ordering argument is what replaces it. Both folding consumers run with syslogHealth.mu held, while a line refused by tryEnqueue charges its drop holding sendMu.RLock and notifies the delivery observer from there — which takes syslogHealth.mu. That is a lock-order inversion, and with a Close() blocked on sendMu.Lock in between (which stops any new reader barging in) it is a three-way cycle, not a window: measured, with TestChaos81_WriterHandleIsSafeUnderConcurrentRepointAndTraffic hanging to the test timeout and the dump naming all three edges.
So no lock may be taken here at all, however briefly: this is called from under the very mutex that this Writer's delivery observer goes on to take.
func (*Writer) DeliveryProvable ¶ added in v1.0.363
DeliveryProvable reports whether this Writer's transport can give evidence that the collector received a line.
TCP can: a write that returns without error means the peer's kernel accepted the bytes. UDP cannot — a write to a connected UDP socket almost always succeeds whether or not anything is listening — so a `Delivered` on a UDP Writer means only "this host sent the datagram" (register row SL-1).
It is a property of the WRITER, read off the transport it was constructed with, deliberately not re-derived from an address string held elsewhere. The probe used to classify its own acknowledged send by re-reading the health record's `target` AFTER the Writer had been passed in, so an admin re-point landing between the two made it describe a UDP send with TCP wording — "the collector accepted the test event" — for a datagram nothing may have received (Codex P2, PR #1494). The writer that served the line is the only thing that knows how it was sent.
The comparison is exact rather than a prefix test, so any network this package does not construct today — "tcp4", "tcp6", a unix socket — reports FALSE and carries the caveat. That is the fail-safe direction: claiming a transport cannot prove delivery when it can costs an operator one unnecessary sentence, while the reverse tells them their SIEM has events it may never have received. A new provable transport must be added here deliberately.
func (*Writer) Drops ¶ added in v1.0.39
Drops reports the number of messages dropped because the collector was unreachable or not draining, the delivery queue overflowed, or the Writer was already closed. Monotonic per Writer.
This is a CUMULATIVE count with no time axis and is therefore not, on its own, an answer to "is the feed delivering right now?" — use Stats, which pairs it with the last-success timestamp and the bounded failure reason.
func (*Writer) FinalStats ¶ added in v1.0.363
FinalStats returns the cumulative snapshot taken when this Writer sealed, and whether it has sealed at all. A consumer that folds this Writer's totals into a process-lifetime accumulator must use THIS once it is available: the live counters keep moving afterwards, and every one of those later losses is already charged to LateDrops, so folding the live value instead would count them twice.
func (*Writer) HandOffTo ¶ added in v1.0.363
HandOffTo records next as the Writer that replaces s. Call it BEFORE Close: from then on a send that races the close, and every line still queued when the drain goroutine stops, goes to next rather than being dropped against (or delivered to) the collector being replaced. nil or s itself is ignored.
func (*Writer) MarkRetired ¶ added in v1.0.363
func (s *Writer) MarkRetired()
MarkRetired records that the owner has folded this Writer's cumulative counters into its own accumulator and will stop reading them.
Call it BEFORE Close. Sealing is what ends the fold, so a loss landing after the seal but before this mark is in neither the fold nor the late counter — the one ordering that loses a loss outright.
func (*Writer) Panics ¶ added in v1.0.190
Panics reports how many lines were lost to a recovered panic in the drain goroutine (CHAOS-24). Always 0 in a healthy process; a non-zero value means a delivery bug is being contained rather than crashing the gateway.
func (*Writer) Sealed ¶ added in v1.0.363
Sealed reports whether the drain goroutine has exited and published this Writer's cumulative snapshot. It does NOT mean the counters stop moving: a caller holding a stale handle still records its losses here, which is what keeps the episode state (is it failing NOW, since when, why) honest. What it means is that FinalStats is available, and that a consumer folding these totals elsewhere must switch to it.
A zero-value (synchronous) Writer has no drain goroutine and is never sealed; nothing folds its totals either.
func (*Writer) SetDeliveryObserver ¶ added in v1.0.363
SetDeliveryObserver publishes an optional observer notified on the drain goroutine whenever a line is DROPPED, and once more when a delivery ends a failure episode. A nil fn clears it.
This is the same seam, for the same reason, as SetPanicObserver above: this package is a stdlib-only leaf per its header contract and cannot log, alert or hold a timer, so the freshness plane lives in package main (syslog_health.go) and is driven from here.
The asymmetry is deliberate and is a cost decision. The observer is NOT called on an ordinary successful delivery: that is the steady state of a gateway forwarding one request-log line per proxied request, and a callback there would tax the happy path to observe a fault that is not happening. On the failure side the cost is irrelevant — the line is already lost — and per-drop notification is what lets the plane decide degradation on a DURATION without polling and without a goroutine of its own.
An observer must be cheap, must not block, and must never call back into this Writer (send, Close, Stats are all reachable from the drain goroutine's own stack) — the rule audit.SetWriteFailureObserver carries for the same reason. It is panic-contained so a bad observer can never take down delivery.
func (*Writer) SetPanicObserver ¶ added in v1.0.203
SetPanicObserver publishes an optional observer notified synchronously, on the drain goroutine, whenever deliverGuarded recovers a panic. This package is a stdlib-only leaf with no logging dependency (see the package doc), so without an observer a recovered panic is visible only through Panics() — package main wires this to the process log (mirrors fileutil's and internal/audit's SetWriteFailureObserver, the same leaf-package-can't-log seam applied to a second chokepoint). A nil fn clears it. The observer runs AFTER deliverLine's own deferred mutex unlock has already fired during unwind, so it never needs s.mu, and is itself panic-contained so a bad observer can never take down delivery.
func (*Writer) Stats ¶ added in v1.0.363
Stats snapshots the delivery counters.
Read order is deliberate and is the only consistency guarantee offered: the FAILURE side is read before the SUCCESS side, so a snapshot taken across a concurrent delivery can report a stale failure next to a fresh success (harmless — reports healthy slightly late) but can never report a fresh success next to a stale failure (which would report a dark feed as delivering). A lock is deliberately not taken: Stats is reached from /metrics, /healthz and the diagnostics row, and none of them may contend with the drain goroutine's socket writes.
func (*Writer) WriteAudit ¶
WriteAudit sends a structured audit entry as a JSON syslog message at severity=5 (notice), which most SIEMs map to a security-relevant priority. The entry is only JSON-marshalled, so any serializable value is accepted.
func (*Writer) WriteProbe ¶ added in v1.0.363
func (s *Writer) WriteProbe(msg string) (<-chan ProbeOutcome, bool)
WriteProbe enqueues one message and returns a channel that receives the delivery outcome OF THAT MESSAGE, once, from the drain goroutine.
Returns ok=false when the line could not even be queued (writer closed, or the collector is so far behind that the queue is full) — already counted as a drop, and an outcome in its own right. A zero-value Writer has no drain goroutine, so it reports the synchronous result directly.
The caller must bound its own wait: a wedged collector can hold the drain in a write deadline, and nothing here promises when the answer arrives.
func (*Writer) WriteRequest ¶
WriteRequest sends a structured request-log entry as a JSON syslog message at PRI=14 (facility=1 user-level, severity=6 informational).