diff --git a/pkg/newlog/cmd/bufferedSocketWriter.go b/pkg/newlog/cmd/bufferedSocketWriter.go index 7222eb2a350..2f5ad808b78 100644 --- a/pkg/newlog/cmd/bufferedSocketWriter.go +++ b/pkg/newlog/cmd/bufferedSocketWriter.go @@ -7,27 +7,43 @@ import ( "fmt" "net" "slices" + "sync/atomic" "time" ) +// startupWait is how long after creation Write blocks on a full buffer +// instead of dropping. Vector creates its source sockets only once its +// topology is up, which takes about 20 s on an EVE-k boot, while the services +// and pillar log their startup; the backlog then drains faster than newlogd +// can refill it only if the writer waits. Blocking pushes back on the reader +// of memlogd, whose ring buffer holds those entries meanwhile. +const startupWait = 60 * time.Second + // BufferedSockWriter is a writer that buffers messages and writes them to a unix socket. // It uses a buffered channel to queue messages and attempts to reconnect if the connection is lost. type BufferedSockWriter struct { path string buffer chan []byte reconnect time.Duration - msgsDropped int // count of dropped messages due to full buffer or write errors - reportWhenCount int // count at which to report num dropped messages + msgsDropped atomic.Int64 // count of dropped messages due to full buffer or write errors + reportWhenCount int // count at which to report num dropped messages + waitDeadline time.Time // until then Write blocks on a full buffer } // NewBufferedSockWriter creates a new buffered socket writer that writes to the specified path. func NewBufferedSockWriter(path string, bufSize int, reconnect time.Duration) *BufferedSockWriter { + return newBufferedSockWriter(path, bufSize, reconnect, startupWait) +} + +// newBufferedSockWriter is NewBufferedSockWriter with the startup window in +// which Write blocks as a parameter. +func newBufferedSockWriter(path string, bufSize int, reconnect, waitFor time.Duration) *BufferedSockWriter { sw := &BufferedSockWriter{ path: path, buffer: make(chan []byte, bufSize), reconnect: reconnect, - msgsDropped: 0, reportWhenCount: 1, // initial report count + waitDeadline: time.Now().Add(waitFor), } go sw.run() return sw @@ -45,7 +61,7 @@ func (sw *BufferedSockWriter) run() { for msg := range sw.buffer { _, err := conn.Write(msg) if err != nil { - sw.msgsDropped++ + sw.msgsDropped.Add(1) log.Errorf("socket write failed: %v, reconnecting...", err) conn.Close() break // reconnect @@ -54,23 +70,34 @@ func (sw *BufferedSockWriter) run() { } } -// Write implements the io.Writer interface for bufferedSockWriter. +// Write implements the io.Writer interface for bufferedSockWriter. It drops +// the message if the buffer is full, except that during the startup window it +// waits for room until the window ends. func (sw *BufferedSockWriter) Write(p []byte) (int, error) { - // Don't block forever, drop if buffer full + msg := slices.Clone(p) select { - case sw.buffer <- slices.Clone(p): // copy buffer + case sw.buffer <- msg: return len(p), nil default: - sw.msgsDropped++ - return 0, fmt.Errorf("buffer full, dropping log") } + if wait := time.Until(sw.waitDeadline); wait > 0 { + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case sw.buffer <- msg: + return len(p), nil + case <-timer.C: + } + } + sw.msgsDropped.Add(1) + return 0, fmt.Errorf("buffer full, dropping log") } // ReportDroppedMsgs checks if the number of dropped msgs has reached the report threshold and then grows the threshold exponentially. func (sw *BufferedSockWriter) ReportDroppedMsgs() int { - if sw.msgsDropped == sw.reportWhenCount { + if dropped := int(sw.msgsDropped.Load()); dropped == sw.reportWhenCount { sw.reportWhenCount *= 2 // report every 2x the previous count - return sw.msgsDropped + return dropped } return 0 // no report needed } diff --git a/pkg/newlog/cmd/bufferedSocketWriter_test.go b/pkg/newlog/cmd/bufferedSocketWriter_test.go index 97c92a02d9d..b64fe4d5c22 100644 --- a/pkg/newlog/cmd/bufferedSocketWriter_test.go +++ b/pkg/newlog/cmd/bufferedSocketWriter_test.go @@ -4,7 +4,11 @@ package main import ( + "bufio" + "fmt" "math" + "net" + "path/filepath" "testing" "time" ) @@ -15,7 +19,7 @@ func TestReportDroppedMsgs(t *testing.T) { extra := 10 // Extra messages to write beyond the buffer size printedErrors := 0 // Counter for printed errors - sw := NewBufferedSockWriter("/tmp/test.sock", bufSize, 10*time.Second) + sw := newBufferedSockWriter("/tmp/test.sock", bufSize, 10*time.Second, 0) for i := 0; i < bufSize+extra; i++ { // Simulate writing messages to the buffer _, err := sw.Write([]byte("test message")) @@ -34,3 +38,87 @@ func TestReportDroppedMsgs(t *testing.T) { t.Logf("TestReportDroppedMsgs: successfully printed %d errors as expected", printedErrors) } } + +// TestWriteWaitsForFirstConnection checks that messages written while the +// socket does not exist yet are held back, not dropped, until it appears. +func TestWriteWaitsForFirstConnection(t *testing.T) { + bufSize := 5 + total := 50 + sockPath := filepath.Join(t.TempDir(), "source.sock") + sw := newBufferedSockWriter(sockPath, bufSize, 50*time.Millisecond, 10*time.Second) + + writeErr := make(chan error, 1) + go func() { + for i := 0; i < total; i++ { + if _, err := fmt.Fprintf(sw, "msg %d\n", i); err != nil { + writeErr <- fmt.Errorf("write %d: %w", i, err) + return + } + } + writeErr <- nil + }() + + time.Sleep(300 * time.Millisecond) + select { + case err := <-writeErr: + t.Fatalf("all writes returned before the socket existed: %v", err) + default: + } + + l, err := net.Listen("unix", sockPath) + if err != nil { + t.Fatal(err) + } + defer func() { _ = l.Close() }() + conn, err := l.Accept() + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + + scanner := bufio.NewScanner(conn) + for i := 0; i < total; i++ { + if err := conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatal(err) + } + if !scanner.Scan() { + t.Fatalf("got %d of %d messages: %v", i, total, scanner.Err()) + } + if want := fmt.Sprintf("msg %d", i); scanner.Text() != want { + t.Fatalf("message %d is %q, want %q", i, scanner.Text(), want) + } + } + if err := <-writeErr; err != nil { + t.Fatal(err) + } + if dropped := sw.msgsDropped.Load(); dropped != 0 { + t.Errorf("dropped %d messages", dropped) + } +} + +// TestWriteDropsAfterStartupWait checks that a full buffer drops once the +// startup window has ended, and from then on without waiting. +func TestWriteDropsAfterStartupWait(t *testing.T) { + bufSize := 3 + waitFor := 200 * time.Millisecond + sw := newBufferedSockWriter(filepath.Join(t.TempDir(), "none.sock"), bufSize, time.Hour, waitFor) + for i := 0; i < bufSize; i++ { + if _, err := sw.Write([]byte("x")); err != nil { + t.Fatalf("write %d: %v", i, err) + } + } + start := time.Now() + if _, err := sw.Write([]byte("x")); err == nil { + t.Fatal("write to a full buffer succeeded") + } + if waited := time.Since(start); waited < waitFor/2 { + t.Errorf("dropped after %v, within the startup window of %v", waited, waitFor) + } + start = time.Now() + if _, err := sw.Write([]byte("x")); err == nil { + t.Fatal("write to a full buffer succeeded") + } + if waited := time.Since(start); waited > waitFor/2 { + t.Errorf("waited %v to drop after the startup window", waited) + } +}