Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 138 additions & 2 deletions background/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,48 @@ type Process struct {
userKilled *int64
waitCh chan error
mu sync.Mutex

onCriticalOutput func(line string)
}

const (
// maxCriticalLines caps how many critical lines a single run of a
// process forwards to its OnCriticalOutput handler.
maxCriticalLines = 10
// criticalFlushTimeout bounds how long reporting a process exit waits for
// the OnCriticalOutput handler to finish with already forwarded lines.
criticalFlushTimeout = 5 * time.Second
)

// criticalOutputPatterns are lowercase substrings of child output that point
// at an actionable startup failure. Keep this list short: every match is
// shown to the user in the workspace startup logs.
var criticalOutputPatterns = []string{
// Disk exhaustion, from dockerd or sysbox.
"no space left on device",
// dockerd prints this to stderr before its logger is set up, so the
// line has no level= field.
"failed to start daemon",
// sysbox-mgr and sysbox-fs startup errors.
"failed to create sysbox-mgr",
"failed to start sysbox-mgr",
"failed to start sysbox-fs",
// logrus fatal level, used by dockerd, sysbox-mgr, and sysbox-fs right
// before they exit.
"level=fatal",
}

// IsCriticalOutput reports whether a line of child process output describes
// a failure that should be shown to the user, rather than only written to the
// envbox container's logs.
func IsCriticalOutput(line string) bool {
line = strings.ToLower(line)
for _, pattern := range criticalOutputPatterns {
if strings.Contains(line, pattern) {
return true
}
}
return false
}

// New returns an instantiated daemon. binName is the expected
Expand All @@ -51,6 +93,21 @@ func New(ctx context.Context, log slog.Logger, binName, cmd string, args ...stri
}
}

// OnCriticalOutput registers fn to receive lines of the process's output for
// which IsCriticalOutput is true. Each run of the process forwards a line at
// most once and at most maxCriticalLines lines in total. fn runs on its own
// goroutine so a slow fn never blocks the process. The channel returned by
// Wait does not report an exit until fn has returned for every forwarded
// line, or until criticalFlushTimeout passes. Call it before Start or Run;
// the handler also applies after Restart.
func (d *Process) OnCriticalOutput(fn func(line string)) *Process {
d.mu.Lock()
defer d.mu.Unlock()

d.onCriticalOutput = fn
return d
}

// Start starts the daemon. It functions akin to ox/exec.Command.Start().
func (d *Process) Start() error {
d.mu.Lock()
Expand Down Expand Up @@ -121,12 +178,22 @@ func (d *Process) startProcess() error {

mw = io.MultiWriter(w, out)
cmd = d.cmd

// Restart reassigns these fields under d.mu, so the goroutines
// below must not read them directly.
ctx = d.ctx
binName = d.binName
onCritical = d.onCriticalOutput
)

cmd.SetStdout(mw)
cmd.SetStderr(mw)

go scanIntoLog(d.ctx, d.log, bufio.NewScanner(pr), d.binName)
scanDone := make(chan struct{})
go func() {
defer close(scanDone)
scanIntoLog(ctx, d.log, bufio.NewScanner(pr), binName, onCritical)
}()

err := d.cmd.Start()
if err != nil {
Expand All @@ -142,6 +209,16 @@ func (d *Process) startProcess() error {
err := cmd.Wait()
_ = psw.Flush()

// Wait returns only after all output has been copied into the
// pipe. Closing it lets scanIntoLog finish, so critical lines
// reach the handler before the exit is reported to callers.
_ = pw.Close()
select {
case <-scanDone:
case <-time.After(criticalFlushTimeout):
d.log.Warn(ctx, "timed out forwarding critical output", slog.F("process", binName))
}

// If the user killed the application the actual error returned
// from wait doesn't really matter.
if atomic.LoadInt64(userKilled) == 1 {
Expand Down Expand Up @@ -223,7 +300,10 @@ func isProcExited(fs afero.Fs, pid int, cmd string) (bool, error) {
return cmd != string(args[0]), nil
}

func scanIntoLog(ctx context.Context, log slog.Logger, scanner *bufio.Scanner, binaryName string) {
func scanIntoLog(ctx context.Context, log slog.Logger, scanner *bufio.Scanner, binaryName string, onCritical func(line string)) {
fwd := newCriticalForwarder(onCritical)
defer fwd.close()

for scanner.Scan() {
select {
case <-ctx.Done():
Expand All @@ -249,13 +329,69 @@ func scanIntoLog(ctx context.Context, log slog.Logger, scanner *bufio.Scanner, b
logFn = log.Error
}

if IsCriticalOutput(line) {
logFn = log.Error
fwd.forward(line)
}

logFn(ctx, "child log",
slog.F("process", binaryName),
slog.F("content", line),
)
}
}

// criticalForwarder delivers critical lines to a handler on a separate
// goroutine. forward and close must be called from a single goroutine.
type criticalForwarder struct {
lines chan string
seen map[string]struct{}
done chan struct{}
}

// newCriticalForwarder returns nil when fn is nil. The nil forwarder's
// methods are no-ops.
func newCriticalForwarder(fn func(line string)) *criticalForwarder {
if fn == nil {
return nil
}

f := &criticalForwarder{
lines: make(chan string, maxCriticalLines),
seen: make(map[string]struct{}),
done: make(chan struct{}),
}
go func() {
defer close(f.done)
for line := range f.lines {
fn(line)
}
}()
return f
}

func (f *criticalForwarder) forward(line string) {
if f == nil {
return
}
if _, ok := f.seen[line]; ok || len(f.seen) >= maxCriticalLines {
return
}
f.seen[line] = struct{}{}
// Never blocks: the buffer holds maxCriticalLines and no more than that
// are ever sent.
f.lines <- line
}

// close waits for the handler to finish with every forwarded line.
func (f *criticalForwarder) close() {
if f == nil {
return
}
close(f.lines)
<-f.done
}

var ErrUserKilled = xerrors.Errorf("daemon killed by user")

func i64ptr(i int64) *int64 {
Expand Down
166 changes: 166 additions & 0 deletions background/process_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package background_test

import (
"context"
"os"
"path/filepath"
"strconv"
"sync"
"testing"
"time"

"github.com/stretchr/testify/require"

"cdr.dev/slog/v3"
"cdr.dev/slog/v3/sloggers/slogtest"
"github.com/coder/envbox/background"
)

func TestIsCriticalOutput(t *testing.T) {
t.Parallel()

tests := []struct {
name string
line string
want bool
}{
{
// The line from the original report, emitted before dockerd's
// logger starts.
name: "DockerdNoSpace",
line: "failed to start daemon: Unable to get the TempDir under /var/lib/docker/100000.100000: mkdir /var/lib/docker/100000.100000/tmp: no space left on device",
want: true,
},
{
name: "SysboxFatal",
line: `time="2026-11-24 18:00:00" level=fatal msg="failed to start sysbox-mgr: some error"`,
want: true,
},
{
name: "SysboxFsStartError",
line: `level=error msg="failed to start sysbox-fs: ipc init"`,
want: true,
},
{
name: "CaseInsensitive",
line: "No Space Left On Device",
want: true,
},
{
name: "DockerdInfo",
line: `level=info msg="API listen on /var/run/docker.sock"`,
want: false,
},
{
name: "DockerdError",
line: `level=error msg="Handler for GET /v1.47/containers/foo/json returned error: No such container: foo"`,
want: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
require.Equal(t, tt.want, background.IsCriticalOutput(tt.line))
})
}
}

// testLogger ignores error logs, since critical child output is logged at the
// error level.
func testLogger(t *testing.T) slog.Logger {
return slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
}

// lineRecorder is a thread-safe OnCriticalOutput handler.
type lineRecorder struct {
mu sync.Mutex
lines []string
}

func (r *lineRecorder) record(line string) {
r.mu.Lock()
defer r.mu.Unlock()
r.lines = append(r.lines, line)
}

func (r *lineRecorder) get() []string {
r.mu.Lock()
defer r.mu.Unlock()
return append([]string(nil), r.lines...)
}

func TestProcessOnCriticalOutput(t *testing.T) {
t.Parallel()

t.Run("ForwardsCriticalLinesBeforeExit", func(t *testing.T) {
t.Parallel()

var rec lineRecorder
script := `
echo 'level=info msg="starting up"'
echo 'failed to start daemon: mkdir /var/lib/docker/tmp: no space left on device' >&2
echo 'regular output'
exit 1`
err := <-background.New(context.Background(), testLogger(t), "sh", "sh", "-c", script).
OnCriticalOutput(rec.record).
Run()
require.Error(t, err)

// Checked without waiting: the exit is only reported after the
// handler has received every forwarded line.
require.Equal(t, []string{
"failed to start daemon: mkdir /var/lib/docker/tmp: no space left on device",
}, rec.get())
})

t.Run("DedupesAndCaps", func(t *testing.T) {
t.Parallel()

var rec lineRecorder
script := `
for i in 1 2 3; do echo 'level=fatal msg="repeated"'; done
for i in $(seq 1 20); do echo "level=fatal msg=\"line $i\""; done`
err := <-background.New(context.Background(), testLogger(t), "sh", "sh", "-c", script).
OnCriticalOutput(rec.record).
Run()
require.NoError(t, err)

want := []string{`level=fatal msg="repeated"`}
for i := 1; len(want) < 10; i++ {
want = append(want, `level=fatal msg="line `+strconv.Itoa(i)+`"`)
}
require.Equal(t, want, rec.get())
})

t.Run("SlowHandlerDoesNotBlockProcess", func(t *testing.T) {
t.Parallel()

marker := filepath.Join(t.TempDir(), "done")
release := make(chan struct{})
var rec lineRecorder

// The process writes far more than a pipe buffer after the
// critical line, then creates the marker file. If the handler
// blocked output, the marker would never appear.
script := `
echo 'level=fatal msg="boom"'
head -c 1048576 /dev/zero | tr '\0' 'a' | fold -w 1024
touch "$1"`
p := background.New(context.Background(), testLogger(t), "sh", "sh", "-c", script, "sh", marker).
OnCriticalOutput(func(line string) {
<-release
rec.record(line)
})
require.NoError(t, p.Start())

require.Eventually(t, func() bool {
_, err := os.Stat(marker)
return err == nil
}, 10*time.Second, 10*time.Millisecond)

close(release)
require.NoError(t, <-p.Wait())
require.Equal(t, []string{`level=fatal msg="boom"`}, rec.get())
})
}
Loading
Loading