From c49953385fb65428a11e2cecb272802bde8f20dc Mon Sep 17 00:00:00 2001 From: yjjnls Date: Mon, 23 Nov 2026 07:23:25 +0800 Subject: [PATCH] fix(envd): raise oom_score_adj only when the inherited score is lower The process wrapper unconditionally ran `echo 100 > /proc/$$/oom_score_adj && exec ...` before every command. An unprivileged process may not lower its OOM score (proc(5)), so in a container that inherits a score above 100 (Docker `--oom-score-adj=993`, a Kubernetes Burstable pod) the write is rejected and the `&&` chain fails the spawn: every command fails with an `echo: I/O error`. Read /proc/self/oom_score_adj in envd -- children inherit it -- and prepend the write only when the inherited score is below the target. Raising is always permitted, and preserving a higher score assigned by the container runtime keeps its OOM protection intact. When the score cannot be read, fall back to the unconditional write, matching the previous behavior. --- .../services/process/handler/spawn_unix.go | 37 ++++++++++++-- .../process/handler/spawn_unix_test.go | 48 +++++++++++++++++++ 2 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 packages/envd/internal/services/process/handler/spawn_unix_test.go diff --git a/packages/envd/internal/services/process/handler/spawn_unix.go b/packages/envd/internal/services/process/handler/spawn_unix.go index 67b192f65ba..867e8571ad1 100644 --- a/packages/envd/internal/services/process/handler/spawn_unix.go +++ b/packages/envd/internal/services/process/handler/spawn_unix.go @@ -5,9 +5,11 @@ package handler import ( "context" "fmt" + "os" "os/exec" "os/user" "strconv" + "strings" "syscall" "github.com/rs/zerolog" @@ -20,11 +22,12 @@ import ( // newCommand builds the child for a start request: the user's command wrapped // in a shell that resets oom_score_adj, ioprio (ionice best-effort/4) and // nice, running with the user's credentials inside the request's cgroup. The -// oom_score_adj write is pure /proc and always applied; the priority helpers -// are used only where the image provides them. +// oom_score_adj write is pure /proc and only applied when it raises the +// inherited score; the priority helpers are used only where the image provides +// them. func newCommand(ctx context.Context, user *user.User, req *rpc.StartRequest, logger *zerolog.Logger, cgroupManager cgroups.Manager) (*exec.Cmd, *sysState, error) { niceDelta := defaultNice - currentNice() - oomWrapperScript := fmt.Sprintf(`echo %d > /proc/$$/oom_score_adj && exec %s"${@}"`, defaultOomScore, ioniceNicePrefix(defaultIoClass, defaultIoPrio, niceDelta, exec.LookPath)) + oomWrapperScript := oomScoreAdjPrefix(defaultOomScore, readOwnOomScoreAdj) + fmt.Sprintf(`exec %s"${@}"`, ioniceNicePrefix(defaultIoClass, defaultIoPrio, niceDelta, exec.LookPath)) wrapperArgs := append([]string{"-c", oomWrapperScript, "--", req.GetProcess().GetCmd()}, req.GetProcess().GetArgs()...) cmd := exec.CommandContext(ctx, "/bin/sh", wrapperArgs...) @@ -58,6 +61,34 @@ func newCommand(ctx context.Context, user *user.User, req *rpc.StartRequest, log return cmd, &sysState{}, nil } +// oomScoreAdjPrefix returns the shell prefix that raises the child's +// oom_score_adj to target before exec, or "" when the inherited score is +// already at least target. An unprivileged process may only raise its OOM +// score (proc(5)); lowering a score assigned by the container runtime fails, +// and the wrapper's "&&" would turn that into a failed spawn. Keeping the +// higher inherited score also preserves the runtime's OOM protection. If the +// current score cannot be read, the unconditional write is kept, matching the +// previous behavior; /proc/self/oom_score_adj is always readable on Linux. +// readOomScoreAdj is injected for testability; production passes +// readOwnOomScoreAdj. +func oomScoreAdjPrefix(target int, readOomScoreAdj func() (int, error)) string { + if current, err := readOomScoreAdj(); err == nil && current >= target { + return "" + } + + return fmt.Sprintf("echo %d > /proc/$$/oom_score_adj && ", target) +} + +// readOwnOomScoreAdj returns envd's oom_score_adj, which its children inherit. +func readOwnOomScoreAdj() (int, error) { + value, err := os.ReadFile("/proc/self/oom_score_adj") + if err != nil { + return 0, err + } + + return strconv.Atoi(strings.TrimSpace(string(value))) +} + // currentNice returns the nice value of the current process. func currentNice() int { prio, err := syscall.Getpriority(syscall.PRIO_PROCESS, 0) diff --git a/packages/envd/internal/services/process/handler/spawn_unix_test.go b/packages/envd/internal/services/process/handler/spawn_unix_test.go new file mode 100644 index 00000000000..bf8941a4647 --- /dev/null +++ b/packages/envd/internal/services/process/handler/spawn_unix_test.go @@ -0,0 +1,48 @@ +//go:build unix + +package handler + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" +) + +// The OOM score prefix must only raise the child's score: writing a lower +// value is denied to an unprivileged process and would abort the wrapper +// before exec, failing every command in a container whose score was raised +// above the target by the runtime (e.g. a Kubernetes Burstable pod). +func TestOomScoreAdjPrefix(t *testing.T) { + t.Parallel() + + const raise = "echo 100 > /proc/$$/oom_score_adj && " + + tests := []struct { + name string + read func() (int, error) + want string + }{ + {"protected envd score is raised", fixedOomScore(-1000), raise}, + {"default score is raised", fixedOomScore(0), raise}, + {"just below target is raised", fixedOomScore(defaultOomScore - 1), raise}, + {"target is kept", fixedOomScore(defaultOomScore), ""}, + {"score above target is kept", fixedOomScore(993), ""}, + {"unreadable score keeps the unconditional write", failedOomScore, raise}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, oomScoreAdjPrefix(defaultOomScore, tt.read)) + }) + } +} + +func fixedOomScore(value int) func() (int, error) { + return func() (int, error) { return value, nil } +} + +func failedOomScore() (int, error) { + return 0, errors.New("unreadable") +}