354 lines
10 KiB
Go
354 lines
10 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
supervisorCgroup = "supervisor"
|
|
jailsCgroup = "jails"
|
|
// cpuQuota allows one CPU per run: quota and period in microseconds.
|
|
cpuQuota = "100000 100000"
|
|
// cgroupDrainTimeout bounds the wait for a killed cgroup to empty.
|
|
cgroupDrainTimeout = 5 * time.Second
|
|
cgroupDrainPoll = 5 * time.Millisecond
|
|
// moveAttempts bounds retries while processes appear in the root cgroup.
|
|
moveAttempts = 10
|
|
cgroupFileMode = 0o644
|
|
cgroupDirMode = 0o755
|
|
bytesPerKB = 1 << 10
|
|
)
|
|
|
|
var requiredControllers = []string{"cpu", "memory", "pids"}
|
|
|
|
// cgroupTree is the cgroup hierarchy owned by the runner:
|
|
//
|
|
// <root>/supervisor the runner process itself
|
|
// <root>/jails/<run> one cgroup per sandboxed run
|
|
//
|
|
// cgroup v2 forbids processes in a cgroup that delegates controllers to its
|
|
// children, so the runner first moves itself out of the root.
|
|
type cgroupTree struct {
|
|
root string
|
|
jails string
|
|
}
|
|
|
|
// prepareCgroups creates the hierarchy below root, enables the controllers,
|
|
// and removes run cgroups left by an earlier process.
|
|
func prepareCgroups(root string) (*cgroupTree, error) {
|
|
controllers, err := os.ReadFile(filepath.Join(root, "cgroup.controllers"))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("sandbox.prepareCgroups - read controllers: %w", err)
|
|
}
|
|
available := strings.Fields(string(controllers))
|
|
for _, controller := range requiredControllers {
|
|
if !slices.Contains(available, controller) {
|
|
return nil, fmt.Errorf("sandbox.prepareCgroups - controller %s is not delegated", controller)
|
|
}
|
|
}
|
|
supervisor := filepath.Join(root, supervisorCgroup)
|
|
if err := mkdirCgroup(supervisor); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := moveProcesses(root, supervisor); err != nil {
|
|
return nil, err
|
|
}
|
|
enable := "+" + strings.Join(requiredControllers, " +")
|
|
if err := writeCgroupFile(root, "cgroup.subtree_control", enable); err != nil {
|
|
return nil, err
|
|
}
|
|
tree := &cgroupTree{root: root, jails: filepath.Join(root, jailsCgroup)}
|
|
if err := mkdirCgroup(tree.jails); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := writeCgroupFile(tree.jails, "cgroup.subtree_control", enable); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := tree.removeLeftovers(); err != nil {
|
|
return nil, err
|
|
}
|
|
return tree, nil
|
|
}
|
|
|
|
func mkdirCgroup(path string) error {
|
|
if err := os.Mkdir(path, cgroupDirMode); err != nil && !errors.Is(err, fs.ErrExist) {
|
|
return fmt.Errorf("sandbox.mkdirCgroup - create %s: %w", filepath.Base(path), err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// moveProcesses moves every process of the from cgroup into the to cgroup.
|
|
func moveProcesses(from, to string) error {
|
|
for range moveAttempts {
|
|
pids, err := readPIDs(from)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(pids) == 0 {
|
|
return nil
|
|
}
|
|
for _, pid := range pids {
|
|
err := writeCgroupFile(to, "cgroup.procs", strconv.Itoa(pid))
|
|
if err != nil && !errors.Is(err, syscall.ESRCH) {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return errors.New("sandbox.moveProcesses - processes keep appearing in the root cgroup")
|
|
}
|
|
|
|
func readPIDs(cgroup string) ([]int, error) {
|
|
content, err := os.ReadFile(filepath.Join(cgroup, "cgroup.procs"))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("sandbox.readPIDs - read procs: %w", err)
|
|
}
|
|
var pids []int
|
|
for field := range strings.FieldsSeq(string(content)) {
|
|
pid, err := strconv.Atoi(field)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("sandbox.readPIDs - parse pid: %w", err)
|
|
}
|
|
pids = append(pids, pid)
|
|
}
|
|
return pids, nil
|
|
}
|
|
|
|
// removeLeftovers kills and removes run cgroups of an earlier process.
|
|
func (t *cgroupTree) removeLeftovers() error {
|
|
entries, err := os.ReadDir(t.jails)
|
|
if err != nil {
|
|
return fmt.Errorf("sandbox.cgroupTree.removeLeftovers - list: %w", err)
|
|
}
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() {
|
|
continue
|
|
}
|
|
run := &runCgroup{path: filepath.Join(t.jails, entry.Name())}
|
|
if err := run.remove(context.Background()); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// leftoverRuns returns the names of run cgroups that still exist.
|
|
func (t *cgroupTree) leftoverRuns() ([]string, error) {
|
|
entries, err := os.ReadDir(t.jails)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("sandbox.cgroupTree.leftoverRuns - list: %w", err)
|
|
}
|
|
var names []string
|
|
for _, entry := range entries {
|
|
if entry.IsDir() {
|
|
names = append(names, entry.Name())
|
|
}
|
|
}
|
|
return names, nil
|
|
}
|
|
|
|
// cgroupLimits are the controller values of one run cgroup.
|
|
type cgroupLimits struct {
|
|
memoryBytes int64
|
|
processes int
|
|
}
|
|
|
|
// runCgroup is the cgroup of one run. dir is an open descriptor of the
|
|
// directory for CLONE_INTO_CGROUP.
|
|
type runCgroup struct {
|
|
path string
|
|
dir *os.File
|
|
}
|
|
|
|
func (t *cgroupTree) create(ctx context.Context, name string, limits cgroupLimits) (*runCgroup, error) {
|
|
cleanupCtx := context.WithoutCancel(ctx)
|
|
path := filepath.Join(t.jails, name)
|
|
if err := os.Mkdir(path, cgroupDirMode); err != nil {
|
|
return nil, fmt.Errorf("sandbox.cgroupTree.create - create: %w", err)
|
|
}
|
|
run := &runCgroup{path: path}
|
|
settings := []struct{ file, value string }{
|
|
{"memory.max", strconv.FormatInt(limits.memoryBytes, 10)},
|
|
{"memory.swap.max", "0"},
|
|
{"pids.max", strconv.Itoa(limits.processes)},
|
|
{"cpu.max", cpuQuota},
|
|
}
|
|
for _, setting := range settings {
|
|
err := writeCgroupFile(path, setting.file, setting.value)
|
|
if errors.Is(err, fs.ErrNotExist) && setting.file == "memory.swap.max" {
|
|
// A kernel without swap accounting has no swap to limit.
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return nil, errors.Join(err, run.remove(cleanupCtx))
|
|
}
|
|
}
|
|
dir, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, errors.Join(fmt.Errorf("sandbox.cgroupTree.create - open: %w", err), run.remove(cleanupCtx))
|
|
}
|
|
run.dir = dir
|
|
return run, nil
|
|
}
|
|
|
|
// cgroupStats are the counters the supervisor reads during and after a run.
|
|
type cgroupStats struct {
|
|
cpuUsage time.Duration
|
|
oomKills int64
|
|
pidsLimits int64
|
|
}
|
|
|
|
func (c *runCgroup) stats() (cgroupStats, error) {
|
|
var stats cgroupStats
|
|
cpu, err := readKeyedFile(c.path, "cpu.stat")
|
|
if err != nil {
|
|
return stats, err
|
|
}
|
|
stats.cpuUsage = time.Duration(cpu["usage_usec"]) * time.Microsecond
|
|
memory, err := readKeyedFile(c.path, "memory.events")
|
|
if err != nil {
|
|
return stats, err
|
|
}
|
|
stats.oomKills = memory["oom_kill"] + memory["oom_group_kill"]
|
|
pids, err := readKeyedFile(c.path, "pids.events")
|
|
if err != nil {
|
|
return stats, err
|
|
}
|
|
stats.pidsLimits = pids["max"]
|
|
return stats, nil
|
|
}
|
|
|
|
// kill stops every process of the cgroup.
|
|
func (c *runCgroup) kill() error {
|
|
err := writeCgroupFile(c.path, "cgroup.kill", "1")
|
|
if !errors.Is(err, fs.ErrNotExist) {
|
|
return err
|
|
}
|
|
// Kernels before 5.14 have no cgroup.kill; signal each process instead.
|
|
pids, err := readPIDs(c.path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, pid := range pids {
|
|
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
|
|
return fmt.Errorf("sandbox.runCgroup.kill - signal: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// killExcept kills every process of the cgroup except keep. Killing the
|
|
// jailed processes but not nsjail lets nsjail reap its child and report how it
|
|
// ended; once the namespace's first process dies, the kernel kills the rest
|
|
// of the PID namespace.
|
|
func (c *runCgroup) killExcept(keep int) error {
|
|
pids, err := readPIDs(c.path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, pid := range pids {
|
|
if pid == keep {
|
|
continue
|
|
}
|
|
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
|
|
return fmt.Errorf("sandbox.runCgroup.killExcept - signal: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// remove kills what is left, waits until the cgroup is empty, and deletes it.
|
|
func (c *runCgroup) remove(ctx context.Context) error {
|
|
if c.dir != nil {
|
|
_ = c.dir.Close() // The descriptor only served CLONE_INTO_CGROUP.
|
|
c.dir = nil
|
|
}
|
|
if err := c.kill(); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
|
return err
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, cgroupDrainTimeout)
|
|
defer cancel()
|
|
for {
|
|
err := os.Remove(c.path)
|
|
if err == nil || errors.Is(err, fs.ErrNotExist) {
|
|
return nil
|
|
}
|
|
if !errors.Is(err, syscall.EBUSY) {
|
|
return fmt.Errorf("sandbox.runCgroup.remove - remove: %w", err)
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return fmt.Errorf("sandbox.runCgroup.remove - processes did not exit: %w", ctx.Err())
|
|
case <-time.After(cgroupDrainPoll):
|
|
}
|
|
}
|
|
}
|
|
|
|
func writeCgroupFile(dir, name, value string) error {
|
|
path := filepath.Join(dir, name)
|
|
// O_TRUNC is not allowed on cgroup files; each write is one operation.
|
|
file, err := os.OpenFile(path, os.O_WRONLY, cgroupFileMode)
|
|
if err != nil {
|
|
return fmt.Errorf("sandbox.writeCgroupFile - open %s: %w", name, err)
|
|
}
|
|
_, writeErr := file.WriteString(value)
|
|
closeErr := file.Close()
|
|
if writeErr != nil {
|
|
return fmt.Errorf("sandbox.writeCgroupFile - write %s: %w", name, writeErr)
|
|
}
|
|
if closeErr != nil {
|
|
return fmt.Errorf("sandbox.writeCgroupFile - close %s: %w", name, closeErr)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// readKeyedFile parses a flat "key value" cgroup file.
|
|
func readKeyedFile(dir, name string) (map[string]int64, error) {
|
|
content, err := os.ReadFile(filepath.Join(dir, name))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("sandbox.readKeyedFile - read %s: %w", name, err)
|
|
}
|
|
values := make(map[string]int64)
|
|
scanner := bufio.NewScanner(bytes.NewReader(content))
|
|
for scanner.Scan() {
|
|
key, value, found := strings.Cut(scanner.Text(), " ")
|
|
if !found {
|
|
continue
|
|
}
|
|
number, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
values[key] = number
|
|
}
|
|
return values, nil
|
|
}
|
|
|
|
// peakMemoryKB returns memory.peak in KiB, or 0 when the kernel has no
|
|
// such file. It is the exact high-water mark of every process of the run,
|
|
// nsjail included, plus file cache charged to the run. Unlike ru_maxrss it
|
|
// never includes the runner itself: Go starts nsjail through vfork, so the
|
|
// rusage of nsjail inherits the runner's resident set at exec.
|
|
func (c *runCgroup) peakMemoryKB() int64 {
|
|
content, err := os.ReadFile(filepath.Join(c.path, "memory.peak"))
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
peak, err := strconv.ParseInt(strings.TrimSpace(string(content)), 10, 64)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return peak / bytesPerKB
|
|
}
|