diff --git a/background/process.go b/background/process.go index 9f30e0f..71a2449 100644 --- a/background/process.go +++ b/background/process.go @@ -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 @@ -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() @@ -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 { @@ -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 { @@ -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(): @@ -249,6 +329,11 @@ 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), @@ -256,6 +341,57 @@ func scanIntoLog(ctx context.Context, log slog.Logger, scanner *bufio.Scanner, b } } +// 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 { diff --git a/background/process_test.go b/background/process_test.go new file mode 100644 index 0000000..ce6962c --- /dev/null +++ b/background/process_test.go @@ -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()) + }) +} diff --git a/cli/docker.go b/cli/docker.go index 469bc69..e65de04 100644 --- a/cli/docker.go +++ b/cli/docker.go @@ -226,14 +226,18 @@ func dockerCmd() *cobra.Command { select { // Start sysbox-mgr and sysbox-fs in order to run // sysbox containers. - case err := <-background.New(ctx, log, "sysbox-mgr", "sysbox-mgr", sysboxArgs...).Run(): + case err := <-background.New(ctx, log, "sysbox-mgr", "sysbox-mgr", sysboxArgs...). + OnCriticalOutput(startupLogCriticalOutput(blog, "sysbox-mgr")). + Run(): if ctx.Err() == nil { blog.Info(sysboxErrMsg) //nolint log.Critical(ctx, "sysbox-mgr exited", slog.Error(err)) panic(err) } - case err := <-background.New(ctx, log, "sysbox-fs", "sysbox-fs").Run(): + case err := <-background.New(ctx, log, "sysbox-fs", "sysbox-fs"). + OnCriticalOutput(startupLogCriticalOutput(blog, "sysbox-fs")). + Run(): if ctx.Err() == nil { blog.Info(sysboxErrMsg) //nolint @@ -258,7 +262,8 @@ func dockerCmd() *cobra.Command { blog.Info("Waiting for sysbox processes to startup...") wrapCmd, wrapArgs := wrapDockerdCmd(dargs) - dockerd := background.New(ctx, log, dockerdBinName, wrapCmd, wrapArgs...) + dockerd := background.New(ctx, log, dockerdBinName, wrapCmd, wrapArgs...). + OnCriticalOutput(startupLogCriticalOutput(blog, "dockerd")) err = dockerd.Start() if err != nil { return xerrors.Errorf("start dockerd: %w", err) @@ -456,6 +461,18 @@ func dockerCmd() *cobra.Command { return cmd } +// startupLogCriticalOutput returns a handler that writes critical output of a +// background process to the workspace startup logs. Without it, failures such +// as dockerd running out of disk are only visible in the envbox container's +// logs. The lines are written at info level because a matching line does not +// mean envbox failed: envbox can recover, for example by restarting dockerd +// with the vfs storage driver. Error is reserved for envbox's own failures. +func startupLogCriticalOutput(blog buildlog.Logger, process string) func(line string) { + return func(line string) { + blog.Infof("%s: %s", process, line) + } +} + func runDockerCVM(ctx context.Context, log slog.Logger, client dockerutil.Client, blog buildlog.Logger, flags flags) (string, error) { fs := xunix.GetFS(ctx) err := xunix.SetOOMScore(ctx, "self", "-1000") diff --git a/integration/docker_test.go b/integration/docker_test.go index 61c961d..83f0b35 100644 --- a/integration/docker_test.go +++ b/integration/docker_test.go @@ -1,17 +1,20 @@ package integration_test import ( + "crypto/tls" "encoding/json" "fmt" "net" "os" "path/filepath" + "slices" "strconv" "strings" "testing" "time" dockertest "github.com/ory/dockertest/v3" + "github.com/ory/dockertest/v3/docker" "github.com/stretchr/testify/require" "github.com/coder/envbox/cli" @@ -73,6 +76,56 @@ func TestDocker(t *testing.T) { _ = runEnvbox() }) + // CriticalOutputInStartupLogs asserts that a dockerd startup failure that + // is only printed by dockerd itself reaches the workspace startup logs. + t.Run("CriticalOutputInStartupLogs", func(t *testing.T) { + t.Parallel() + + pool, err := dockertest.NewPool("") + require.NoError(t, err) + + coderListener, err := net.Listen("tcp", fmt.Sprintf("%s:0", integrationtest.DockerBridgeIP(t))) + require.NoError(t, err) + defer coderListener.Close() + coderAddr := tcpAddr(t, coderListener) + recorder := integrationtest.FakeBuildLogRecorder(t, coderListener, tls.Certificate{}) + + // Replace dockerd's data root with a tmpfs too small to start in. + var binds []docker.HostMount + for _, bind := range integrationtest.DefaultBinds(t, integrationtest.TmpDir(t)) { + if bind.Target != "/var/lib/docker" { + binds = append(binds, bind) + } + } + + _ = integrationtest.RunEnvbox(t, pool, &integrationtest.CreateDockerCVMConfig{ + Image: integrationtest.DockerdImage, + Username: "root", + Envs: []string{ + integrationtest.EnvVar(cli.EnvAgentToken, "faketoken"), + integrationtest.EnvVar(cli.EnvAgentURL, fmt.Sprintf("http://host.docker.internal:%d", coderAddr.Port)), + }, + OuterMounts: binds, + OuterTmpfs: map[string]string{"/var/lib/docker": "size=64k"}, + ExpectFailure: true, + }) + + isCritical := func(log string) bool { + return strings.HasPrefix(log, "dockerd: ") && strings.Contains(log, "no space left on device") + } + isFailure := func(log string) bool { + return strings.HasPrefix(log, "Failed to create Container-based Virtual Machine") + } + require.Eventually(t, func() bool { + logs := recorder.Logs() + return slices.ContainsFunc(logs, isCritical) && slices.ContainsFunc(logs, isFailure) + }, 30*time.Second, 100*time.Millisecond, "startup logs: %q", recorder.Logs()) + + // The dockerd output must arrive before envbox reports the failure. + logs := recorder.Logs() + require.Less(t, slices.IndexFunc(logs, isCritical), slices.IndexFunc(logs, isFailure), "startup logs: %q", logs) + }) + // EnvboxArgs validates that arguments passed to envbox function correctly. // Most cases should be covered with unit tests, the intent with this is to // test cases that do not garner a high degree of confidence from mocking diff --git a/integration/integrationtest/coder.go b/integration/integrationtest/coder.go index 326232e..7de9f66 100644 --- a/integration/integrationtest/coder.go +++ b/integration/integrationtest/coder.go @@ -31,6 +31,14 @@ func (b *BuildLogRecorder) ContainsLog(l string) bool { return false } +// Logs returns a copy of the recorded build logs in the order they were +// received. +func (b *BuildLogRecorder) Logs() []string { + b.mu.Lock() + defer b.mu.Unlock() + return append([]string(nil), b.logs...) +} + func (b *BuildLogRecorder) Len() int { b.mu.Lock() defer b.mu.Unlock() diff --git a/integration/integrationtest/docker.go b/integration/integrationtest/docker.go index b6f5ce4..4f63914 100644 --- a/integration/integrationtest/docker.go +++ b/integration/integrationtest/docker.go @@ -62,7 +62,12 @@ type CreateDockerCVMConfig struct { InnerEnvFilter []string Envs []string - OuterMounts []docker.HostMount + OuterMounts []docker.HostMount + // OuterTmpfs mounts tmpfs filesystems in the envbox container, keyed by + // path, with mount options such as "size=64k" as values. Use it instead + // of a tmpfs HostMount: docker.TempfsOptions has the wrong JSON key, so + // Docker ignores its size limit. + OuterTmpfs map[string]string AddFUSE bool AddTUN bool CPUs int @@ -104,6 +109,7 @@ func RunEnvbox(t *testing.T, pool *dockertest.Pool, conf *CreateDockerCVMConfig) Env: conf.Envs, }, func(host *docker.HostConfig) { host.Mounts = conf.OuterMounts + host.Tmpfs = conf.OuterTmpfs host.Privileged = true host.CPUPeriod = int64(dockerutil.DefaultCPUPeriod) host.CPUQuota = int64(conf.CPUs) * int64(dockerutil.DefaultCPUPeriod) @@ -257,8 +263,12 @@ func waitForCVM(t *testing.T, pool *dockertest.Pool, resource *dockertest.Resour } } require.NoError(t, scanner.Err()) - require.True(t, finished, "unexpected logger exit") - return true + if !finished { + // envbox can exit without an error record, for example when a + // background process calls log.Fatal. + t.Log("envbox exited before reporting success") + } + return finished } type ExecConfig struct {