Skip to content
Open
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
37 changes: 34 additions & 3 deletions packages/envd/internal/services/process/handler/spawn_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ package handler
import (
"context"
"fmt"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"syscall"

"github.com/rs/zerolog"
Expand All @@ -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...)

Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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")
}