mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-11-29 19:01:50 +08:00
fix: cap ARTEX container and tool resource use
This commit is contained in:
1 parent
253a8eeac3
commit
ea4377ef9a
36 files changed
+1869
-64
No files matched your search
@@ -0,0 +1,126 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
const (
|
||||
backgroundArg = "--artex-internal-background-tool"
|
||||
backgroundExe = "_ARTEX_BG_EXE"
|
||||
backgroundCommand = "_ARTEX_BG_COMMAND"
|
||||
backgroundTimeout = "_ARTEX_BG_TIMEOUT"
|
||||
backgroundCgroup = "_ARTEX_BG_CGROUP"
|
||||
outputLimitNote = "\n\n[output truncated at capture limit]"
|
||||
)
|
||||
|
||||
// The SDK's task manager only accepts a shell command, not an exec hook. Its
|
||||
// shell execs this binary in a lightweight helper mode, keeping the manager's
|
||||
// task ID, streaming output, notifications, and cancellation semantics.
|
||||
func runGuardedBashBackground(tc *actool.ToolContext, cfg Config, command string, timeout time.Duration) (actool.Result, error) {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return actool.Errorf("Error: failed to locate background helper: " + err.Error()), nil
|
||||
}
|
||||
var dir string
|
||||
scope := newCgroupScope(cfg.MemoryLimitBytes(), cfg.PidsLimit)
|
||||
if scope != nil {
|
||||
dir = scope.dir
|
||||
scope.CloseFD()
|
||||
}
|
||||
env := append([]string{}, tc.Env...)
|
||||
// Pass the command as data, not shell syntax in the trampoline.
|
||||
env = append(env, backgroundExe+"="+exe, backgroundCommand+"="+command,
|
||||
backgroundTimeout+"="+timeout.String(), backgroundCgroup+"="+dir,
|
||||
EnvToolMemoryLimitMB+"="+strconv.Itoa(cfg.MemoryLimitMB),
|
||||
EnvToolPidsLimit+"="+strconv.Itoa(cfg.PidsLimit))
|
||||
trampoline := `exec "$` + backgroundExe + `" ` + backgroundArg
|
||||
if runtime.GOOS == "windows" {
|
||||
trampoline = `& $env:` + backgroundExe + ` '` + backgroundArg + `'; exit $LASTEXITCODE`
|
||||
}
|
||||
desc := strings.TrimSpace(strings.ReplaceAll(command, "\n", " "))
|
||||
if len(desc) > 60 {
|
||||
desc = desc[:57] + "..."
|
||||
}
|
||||
mgr := tc.Tasks
|
||||
t, err := mgr.Spawn(actool.SpawnSpec{
|
||||
Command: trampoline, Kind: actool.KindBash, WorkingDir: tc.WorkingDir,
|
||||
Description: desc, Env: env,
|
||||
})
|
||||
if err != nil {
|
||||
if scope != nil {
|
||||
scope.Cleanup()
|
||||
}
|
||||
return actool.Errorf("Error: failed to start background command: " + err.Error()), nil
|
||||
}
|
||||
mgr.Background(t.ID)
|
||||
if scope != nil {
|
||||
go func(id string) {
|
||||
// The helper might be SIGKILLed by TaskStop; its parent therefore
|
||||
// owns the scope and cleans it up after the task exits.
|
||||
_, done := mgr.Wait(context.Background(), id, timeout)
|
||||
if !done {
|
||||
_, done = mgr.Wait(context.Background(), id, 5*time.Second)
|
||||
}
|
||||
if !done {
|
||||
mgr.Kill(id)
|
||||
}
|
||||
scope.Cleanup()
|
||||
}(t.ID)
|
||||
}
|
||||
return actool.Text(fmt.Sprintf(
|
||||
"Running in background as %s. Output file: %s\nUse TaskOutput{task_id:%q} or Read to read its output; you are notified when it completes.",
|
||||
t.ID, t.OutputPath, t.ID)), nil
|
||||
}
|
||||
|
||||
// BackgroundHelper handles the internal helper invocation before normal app
|
||||
// startup. The helper uses the task manager's cwd, environment, and output file.
|
||||
func BackgroundHelper(args []string) (exitCode int, handled bool) {
|
||||
if len(args) != 1 || args[0] != backgroundArg {
|
||||
return 0, false
|
||||
}
|
||||
command, dir := os.Getenv(backgroundCommand), os.Getenv(backgroundCgroup)
|
||||
timeout, err := time.ParseDuration(os.Getenv(backgroundTimeout))
|
||||
for _, name := range []string{backgroundExe, backgroundCommand, backgroundTimeout, backgroundCgroup} {
|
||||
_ = os.Unsetenv(name)
|
||||
}
|
||||
if command == "" || err != nil || timeout <= 0 {
|
||||
fmt.Fprintln(os.Stderr, "invalid background tool invocation")
|
||||
return 1, true
|
||||
}
|
||||
cfg := FromEnv()
|
||||
cfg.MaxOutputBytes -= 4096 // leave room for the error note below norma's task-file cap
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
shell, flags := platformShellCmd()
|
||||
cmd := exec.Command(shell, append(flags, command)...)
|
||||
group := os.Getpid()
|
||||
if runtime.GOOS == "windows" {
|
||||
group = 0 // Windows terminates the process tree by PID, without a Unix group.
|
||||
}
|
||||
res := run(ctx, cfg, cmd, openCgroupScope(dir), group, os.Stdout)
|
||||
if res.OutputTruncated {
|
||||
fmt.Fprintln(os.Stderr, outputLimitNote)
|
||||
}
|
||||
switch {
|
||||
case res.MemoryKilled:
|
||||
fmt.Fprintln(os.Stderr, FormatMemoryKilled(res.PeakMemoryBytes, res.MemoryLimitBytes, res.KilledByCgroup))
|
||||
return 1, true
|
||||
case res.TimedOut:
|
||||
fmt.Fprintln(os.Stderr, timeoutNote(timeout))
|
||||
return 1, true
|
||||
case res.ExitCode >= 0:
|
||||
return res.ExitCode, true
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "[failed to run: %v]\n", res.Err)
|
||||
return 1, true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/norma/permission"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
// NewBash keeps the SDK permission floor but runs commands through ARTEX's guard.
|
||||
func NewBash() actool.CoreTool {
|
||||
base := actool.NewBash()
|
||||
schema := maps.Clone(base.InputSchema())
|
||||
props := maps.Clone(schema["properties"].(map[string]any))
|
||||
if _, ok := props["run_in_background"]; ok {
|
||||
props["run_in_background"] = map[string]any{"type": "boolean", "description": "Run asynchronously; read output with TaskOutput and stop it with TaskStop. The same memory and time limits apply."}
|
||||
}
|
||||
props["timeout_ms"] = map[string]any{"type": "integer", "description": "Command timeout in milliseconds (operator-configured default, normally 120000)."}
|
||||
schema["properties"] = props
|
||||
return actool.Build(actool.Spec{
|
||||
Name: base.Name(),
|
||||
Description: base.Description(),
|
||||
Prompt: strings.Replace(base.Prompt(), "A timeout (default 120s, max 600s) applies.", "Commands are terminated at their timeout instead of moving to the background.", 1),
|
||||
Schema: schema,
|
||||
ReadOnly: base.IsReadOnly,
|
||||
Concurrent: base.IsConcurrencySafe,
|
||||
Permissions: base.CheckPermissions,
|
||||
Run: runGuardedBash,
|
||||
})
|
||||
}
|
||||
|
||||
func runGuardedBash(ctx context.Context, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
|
||||
var in struct {
|
||||
Command string `json:"command"`
|
||||
TimeoutMS int `json:"timeout_ms"`
|
||||
RunInBackground bool `json:"run_in_background"`
|
||||
}
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return actool.Result{}, err
|
||||
}
|
||||
if strings.TrimSpace(in.Command) == "" {
|
||||
return actool.Errorf("Error: command is required"), nil
|
||||
}
|
||||
|
||||
// Custom command tools can invoke this handler directly, outside norma's
|
||||
// permission pipeline. Always enforce the same catastrophic-command floor.
|
||||
if dec := actool.NewBash().CheckPermissions(ctx, input, permission.Context{}); dec.Behavior == permission.Deny {
|
||||
return actool.Errorf(dec.Message), nil
|
||||
}
|
||||
cfg := FromEnv()
|
||||
timeout := cfg.ResolveTimeout(in.TimeoutMS)
|
||||
if in.RunInBackground && tc != nil && tc.Tasks != nil && !actool.BackgroundTasksDisabled() {
|
||||
return runGuardedBashBackground(tc, cfg, in.Command, timeout)
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
shell, flags := platformShellCmd()
|
||||
cmd := exec.Command(shell, append(flags, in.Command)...)
|
||||
if tc != nil {
|
||||
cmd.Dir = tc.WorkingDir
|
||||
if env := mergedEnv(tc.Env); env != nil {
|
||||
cmd.Env = env
|
||||
}
|
||||
}
|
||||
|
||||
res := Run(cctx, cfg, cmd)
|
||||
out := actool.Capture(tc, res.Output)
|
||||
if res.OutputTruncated {
|
||||
out += outputLimitNote
|
||||
}
|
||||
if res.MemoryKilled {
|
||||
if strings.TrimSpace(out) == "" {
|
||||
out = "(no output)"
|
||||
}
|
||||
return actool.Errorf(out + "\n\n" + FormatMemoryKilled(res.PeakMemoryBytes, res.MemoryLimitBytes, res.KilledByCgroup)), nil
|
||||
}
|
||||
if res.TimedOut {
|
||||
return actool.Errorf(out + timeoutNote(timeout)), nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return actool.Errorf("Error: " + ctx.Err().Error()), nil
|
||||
}
|
||||
if res.Err != nil {
|
||||
if res.ExitCode >= 0 {
|
||||
if strings.TrimSpace(out) == "" {
|
||||
out = "(no output)"
|
||||
}
|
||||
return actool.Errorf(fmt.Sprintf("%s\n\n[exit code %d]", out, res.ExitCode)), nil
|
||||
}
|
||||
return actool.Errorf(fmt.Sprintf("%s\n\n[failed to run: %v]", out, res.Err)), nil
|
||||
}
|
||||
if strings.TrimSpace(out) == "" {
|
||||
out = "(command produced no output)"
|
||||
}
|
||||
return actool.Text(out), nil
|
||||
}
|
||||
|
||||
func platformShellCmd() (string, []string) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return "powershell", []string{"-NoProfile", "-NonInteractive", "-Command"}
|
||||
}
|
||||
return "bash", []string{"-c"}
|
||||
}
|
||||
|
||||
func mergedEnv(extra []string) []string {
|
||||
if len(extra) == 0 {
|
||||
return nil
|
||||
}
|
||||
return append(os.Environ(), extra...)
|
||||
}
|
||||
|
||||
func timeoutNote(limit time.Duration) string {
|
||||
return fmt.Sprintf("\n\n[command timed out (configured limit %s)]", limit)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
func TestBashForeground(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("POSIX shell syntax")
|
||||
}
|
||||
tc := &actool.ToolContext{WorkingDir: t.TempDir(), Env: []string{"ARTEX_TEST_MARKER=from-session"}}
|
||||
res, _ := NewBash().Call(context.Background(), []byte(`{"command":"printf '%s %s' \"$ARTEX_TEST_MARKER\" \"$PWD\""}`), tc)
|
||||
cwd, err := filepath.EvalSymlinks(tc.WorkingDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError || res.Flatten() != "from-session "+cwd {
|
||||
t.Fatalf("cwd/env not passed: %s", res.Flatten())
|
||||
}
|
||||
res, _ = NewBash().Call(context.Background(), []byte(`{"command":"sleep 10", "timeout_ms":100}`), tc)
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "timed out") {
|
||||
t.Fatalf("missing timeout: %s", res.Flatten())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBashBackground(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("POSIX shell syntax")
|
||||
}
|
||||
t.Setenv("AGENT_CORE_DISABLE_BACKGROUND_TASKS", "")
|
||||
t.Setenv(EnvToolMemoryLimitMB, "0")
|
||||
t.Setenv(EnvToolPidsLimit, "0")
|
||||
mgr, err := actool.NewManager("artex-toolguard-" + filepath.Base(filepath.Dir(t.TempDir())))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(mgr.Cleanup)
|
||||
tc := &actool.ToolContext{Tasks: mgr, WorkingDir: t.TempDir(), Env: []string{"ARTEX_TEST_MARKER=background-session"}}
|
||||
invoke := func(command string, timeoutMS int) string {
|
||||
t.Helper()
|
||||
in, _ := json.Marshal(map[string]any{"command": command, "run_in_background": true, "timeout_ms": timeoutMS})
|
||||
res, err := NewBash().Call(context.Background(), in, tc)
|
||||
if err != nil || res.IsError {
|
||||
t.Fatalf("start background command: %s %v", res.Flatten(), err)
|
||||
}
|
||||
tasks := mgr.List()
|
||||
return tasks[len(tasks)-1].ID
|
||||
}
|
||||
id := invoke(`printf '%s\n' "$ARTEX_TEST_MARKER"; sleep 10`, 500)
|
||||
info, done := mgr.Wait(context.Background(), id, 5*time.Second)
|
||||
out, err := mgr.Output(id, 1024)
|
||||
if !done || info.Status != actool.TaskFailed || err != nil || !strings.Contains(out, "background-session") || !strings.Contains(out, "timed out") {
|
||||
t.Fatalf("background timeout not surfaced: %+v, output %q, error %v", info, out, err)
|
||||
}
|
||||
|
||||
id = invoke(`touch ready; sleep 2; touch survived`, 5000)
|
||||
waitUntil := time.Now().Add(3 * time.Second)
|
||||
for {
|
||||
if _, err := os.Stat(filepath.Join(tc.WorkingDir, "ready")); err == nil {
|
||||
break
|
||||
}
|
||||
if time.Now().After(waitUntil) {
|
||||
t.Fatal("background command did not start")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
mgr.Kill(id)
|
||||
if info, done := mgr.Wait(context.Background(), id, 5*time.Second); !done || info.Status != actool.TaskKilled {
|
||||
t.Fatalf("TaskStop did not stop helper: %+v", info)
|
||||
}
|
||||
// A stopped shell would otherwise write this file after its sleep.
|
||||
time.Sleep(2200 * time.Millisecond)
|
||||
if _, err := os.Stat(filepath.Join(tc.WorkingDir, "survived")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("TaskStop left the inner shell running: stat = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBashBackgroundMemory(t *testing.T) {
|
||||
if !watchdogAvailable() {
|
||||
t.Skip("requires a process memory watchdog")
|
||||
}
|
||||
t.Setenv("AGENT_CORE_DISABLE_BACKGROUND_TASKS", "")
|
||||
t.Setenv(EnvToolMemoryLimitMB, "16")
|
||||
t.Setenv(EnvToolPidsLimit, "0")
|
||||
mgr, err := actool.NewManager("artex-toolguard-memory-" + filepath.Base(filepath.Dir(t.TempDir())))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(mgr.Cleanup)
|
||||
tc := &actool.ToolContext{Tasks: mgr, WorkingDir: t.TempDir(), Env: []string{"ARTEX_TEST_GUARD_CHILD=memory", "ARTEX_TEST_EXECUTABLE=" + os.Args[0]}}
|
||||
res, err := NewBash().Call(context.Background(), []byte(`{"command":"\"$ARTEX_TEST_EXECUTABLE\" -test.run='^TestGuardChild$'", "run_in_background":true, "timeout_ms":5000}`), tc)
|
||||
if err != nil || res.IsError {
|
||||
t.Fatalf("start background command: %s %v", res.Flatten(), err)
|
||||
}
|
||||
info, done := mgr.Wait(context.Background(), mgr.List()[0].ID, 7*time.Second)
|
||||
out, err := mgr.Output(info.ID, 1024)
|
||||
if !done || info.Status != actool.TaskFailed || err != nil || !strings.Contains(out, "memory limit exceeded") {
|
||||
t.Fatalf("background memory limit not surfaced: %+v, output %q, error %v", info, out, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
)
|
||||
|
||||
// outputCapture keeps the first limit bytes and discards overflow. With a
|
||||
// streaming sink it forwards that bounded prefix without buffering it in RAM.
|
||||
type outputCapture struct {
|
||||
buf bytes.Buffer
|
||||
writer io.Writer
|
||||
remaining int
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func newOutputCapture(limit int, stream io.Writer) *outputCapture {
|
||||
c := &outputCapture{writer: stream, remaining: limit}
|
||||
if stream == nil {
|
||||
c.writer = &c.buf
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *outputCapture) Write(p []byte) (int, error) {
|
||||
n := min(c.remaining, len(p))
|
||||
if n > 0 {
|
||||
if _, err := c.writer.Write(p[:n]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.remaining -= n
|
||||
}
|
||||
c.truncated = c.truncated || n < len(p)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (c *outputCapture) output() string { return c.buf.String() }
|
||||
@@ -0,0 +1,240 @@
|
||||
//go:build linux
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
cgProbeOnce sync.Once
|
||||
cgParentDir string
|
||||
cgControllers map[string]bool
|
||||
cgAttachBlocked atomic.Bool
|
||||
cgScopeCounter atomic.Uint64
|
||||
)
|
||||
|
||||
// CgroupV2Available reports whether the process can create per-command Linux
|
||||
// cgroup v2 directories with the memory controller enabled.
|
||||
func CgroupV2Available() bool {
|
||||
probeCgroupV2()
|
||||
return cgParentDir != "" && !cgAttachBlocked.Load()
|
||||
}
|
||||
|
||||
func probeCgroupV2() {
|
||||
cgProbeOnce.Do(func() {
|
||||
candidates := candidateCgroupParents()
|
||||
for _, dir := range candidates {
|
||||
ctrls := readSubtreeControllers(dir)
|
||||
if !ctrls["memory"] && !ctrls["pids"] {
|
||||
continue
|
||||
}
|
||||
probeDir := filepath.Join(dir, fmt.Sprintf("artex-probe-%d-%d", os.Getpid(), cgScopeCounter.Add(1)))
|
||||
if err := os.Mkdir(probeDir, 0o755); err != nil {
|
||||
continue
|
||||
}
|
||||
control := "pids.max"
|
||||
if ctrls["memory"] {
|
||||
control = "memory.max"
|
||||
}
|
||||
err := os.WriteFile(filepath.Join(probeDir, control), []byte("max"), 0)
|
||||
_ = os.Remove(probeDir)
|
||||
if err == nil {
|
||||
cgParentDir = dir
|
||||
cgControllers = ctrls
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func candidateCgroupParents() []string {
|
||||
b, err := os.ReadFile("/proc/self/cgroup")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var rel string
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
if strings.HasPrefix(line, "0::") {
|
||||
rel = strings.TrimSpace(strings.TrimPrefix(line, "0::"))
|
||||
break
|
||||
}
|
||||
}
|
||||
if rel == "" {
|
||||
return nil
|
||||
}
|
||||
const cgRoot = "/sys/fs/cgroup"
|
||||
selfDir := filepath.Join(cgRoot, rel)
|
||||
within := func(parent, child string) bool {
|
||||
rel, err := filepath.Rel(parent, child)
|
||||
return err == nil && rel != ".." && !strings.HasPrefix(rel, "../")
|
||||
}
|
||||
if !within(cgRoot, selfDir) {
|
||||
return nil
|
||||
}
|
||||
// Never silently place a child in a sibling cgroup: this could escape
|
||||
// the service/container's existing memory and PID limits. For delegated
|
||||
// services an operator may explicitly select the enclosing subtree.
|
||||
if parent := os.Getenv(EnvToolCgroupParent); parent != "" {
|
||||
parent = filepath.Clean(parent)
|
||||
if within(cgRoot, parent) && within(parent, selfDir) {
|
||||
return []string{parent}
|
||||
}
|
||||
}
|
||||
return []string{selfDir}
|
||||
}
|
||||
|
||||
func readSubtreeControllers(dir string) map[string]bool {
|
||||
b, err := os.ReadFile(filepath.Join(dir, "cgroup.subtree_control"))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
m := map[string]bool{}
|
||||
for _, f := range strings.Fields(string(b)) {
|
||||
m[f] = true
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
type cgroupScope struct {
|
||||
dir string
|
||||
fd int
|
||||
active bool
|
||||
}
|
||||
|
||||
func newCgroupScope(limitBytes int64, pidsLimit int) *cgroupScope {
|
||||
if limitBytes <= 0 && pidsLimit <= 0 {
|
||||
return nil
|
||||
}
|
||||
if !CgroupV2Available() || (limitBytes > 0 && !cgControllers["memory"]) ||
|
||||
(limitBytes <= 0 && !cgControllers["pids"]) {
|
||||
return nil
|
||||
}
|
||||
dir := filepath.Join(cgParentDir, fmt.Sprintf("artex-cmd-%d-%d", os.Getpid(), cgScopeCounter.Add(1)))
|
||||
if err := os.Mkdir(dir, 0o755); err != nil {
|
||||
return nil
|
||||
}
|
||||
if limitBytes > 0 {
|
||||
if err := os.WriteFile(filepath.Join(dir, "memory.max"), []byte(strconv.FormatInt(limitBytes, 10)), 0o644); err != nil {
|
||||
_ = os.Remove(dir)
|
||||
return nil
|
||||
}
|
||||
// Best effort on kernels without swap accounting. Group-wide OOM
|
||||
// termination avoids leaving sibling workers running after a kill.
|
||||
_ = os.WriteFile(filepath.Join(dir, "memory.oom.group"), []byte("1"), 0)
|
||||
_ = os.WriteFile(filepath.Join(dir, "memory.swap.max"), []byte("0"), 0)
|
||||
}
|
||||
if pidsLimit > 0 && cgControllers["pids"] {
|
||||
_ = os.WriteFile(filepath.Join(dir, "pids.max"), []byte(strconv.Itoa(pidsLimit)), 0)
|
||||
}
|
||||
scope := openCgroupScope(dir)
|
||||
if scope == nil {
|
||||
_ = os.Remove(dir)
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
func openCgroupScope(dir string) *cgroupScope {
|
||||
if dir == "" {
|
||||
return nil
|
||||
}
|
||||
fd, err := syscall.Open(dir, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &cgroupScope{dir: dir, fd: fd}
|
||||
}
|
||||
|
||||
func startCommand(cmd *exec.Cmd, scope *cgroupScope) (*exec.Cmd, error) {
|
||||
if scope == nil {
|
||||
return cmd, cmd.Start()
|
||||
}
|
||||
// Start is single-use even on failure. Copy the unstarted command and
|
||||
// syscall attributes so a failed clone3 can fall back to normal exec.
|
||||
isolated := *cmd
|
||||
var attr syscall.SysProcAttr
|
||||
if cmd.SysProcAttr != nil {
|
||||
attr = *cmd.SysProcAttr
|
||||
}
|
||||
attr.UseCgroupFD, attr.CgroupFD = true, scope.fd
|
||||
isolated.SysProcAttr = &attr
|
||||
err := isolated.Start()
|
||||
if err == nil {
|
||||
scope.active = true
|
||||
return &isolated, nil
|
||||
}
|
||||
for _, unavailable := range []error{syscall.ENOSYS, syscall.EINVAL, syscall.EPERM, syscall.EACCES, syscall.EBUSY, syscall.EOPNOTSUPP} {
|
||||
if errors.Is(err, unavailable) {
|
||||
cmdErr := cmd.Start()
|
||||
if cmdErr == nil {
|
||||
cgAttachBlocked.Store(true)
|
||||
}
|
||||
return cmd, cmdErr
|
||||
}
|
||||
}
|
||||
return &isolated, err
|
||||
}
|
||||
|
||||
func (s *cgroupScope) CloseFD() {
|
||||
if s == nil || s.fd < 0 {
|
||||
return
|
||||
}
|
||||
_ = syscall.Close(s.fd)
|
||||
s.fd = -1
|
||||
}
|
||||
|
||||
func (s *cgroupScope) Kill() {
|
||||
if s == nil || s.dir == "" {
|
||||
return
|
||||
}
|
||||
// Linux >= 5.14: atomic cgroup kill.
|
||||
if err := os.WriteFile(filepath.Join(s.dir, "cgroup.kill"), []byte("1"), 0); err == nil {
|
||||
return
|
||||
}
|
||||
// Fallback for older kernels: SIGKILL every PID in cgroup.procs.
|
||||
if b, err := os.ReadFile(filepath.Join(s.dir, "cgroup.procs")); err == nil {
|
||||
for _, f := range strings.Fields(string(b)) {
|
||||
if pid, err := strconv.Atoi(f); err == nil && pid > 0 {
|
||||
_ = syscall.Kill(pid, syscall.SIGKILL)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *cgroupScope) OOMKilled() bool {
|
||||
if s == nil || s.dir == "" {
|
||||
return false
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(s.dir, "memory.events"))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return parseCgroupMemoryEventsOOM(b)
|
||||
}
|
||||
|
||||
func (s *cgroupScope) Cleanup() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.CloseFD()
|
||||
if s.dir == "" {
|
||||
return
|
||||
}
|
||||
s.Kill()
|
||||
for i := range 4 {
|
||||
if err := os.Remove(s.dir); err == nil || os.IsNotExist(err) {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Duration(i+1) * 15 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//go:build linux
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDelegatedCgroupLimitsAndCleanup(t *testing.T) {
|
||||
const limit = 24 << 20
|
||||
scope := newCgroupScope(limit, 128)
|
||||
if scope == nil {
|
||||
t.Skip("no delegated cgroup v2 subtree with the memory controller")
|
||||
}
|
||||
t.Cleanup(scope.Cleanup)
|
||||
if raw, err := os.ReadFile(filepath.Join(scope.dir, "memory.max")); err != nil || strings.TrimSpace(string(raw)) != "25165824" {
|
||||
t.Fatalf("memory.max = %q, %v", raw, err)
|
||||
}
|
||||
if cgControllers["pids"] {
|
||||
if raw, err := os.ReadFile(filepath.Join(scope.dir, "pids.max")); err != nil || strings.TrimSpace(string(raw)) != "128" {
|
||||
t.Fatalf("pids.max = %q, %v", raw, err)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
res := run(ctx, Config{MemoryLimitMB: 24}.withDefaults(), child("memory"), scope, 0, nil)
|
||||
if !scope.active {
|
||||
t.Skip("the environment blocked atomic cgroup attachment")
|
||||
}
|
||||
if !res.KilledByCgroup || !res.MemoryKilled || res.TimedOut {
|
||||
t.Fatalf("expected kernel OOM kill: %+v", res)
|
||||
}
|
||||
scope.Cleanup()
|
||||
if _, err := os.Stat(scope.dir); !os.IsNotExist(err) {
|
||||
t.Fatalf("cgroup remains after cleanup: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build !linux
|
||||
|
||||
package toolguard
|
||||
|
||||
import "os/exec"
|
||||
|
||||
func CgroupV2Available() bool { return false }
|
||||
|
||||
type cgroupScope struct {
|
||||
dir string
|
||||
active bool
|
||||
}
|
||||
|
||||
func newCgroupScope(_ int64, _ int) *cgroupScope { return nil }
|
||||
func openCgroupScope(_ string) *cgroupScope { return nil }
|
||||
func (*cgroupScope) CloseFD() {}
|
||||
func (*cgroupScope) Kill() {}
|
||||
func (*cgroupScope) OOMKilled() bool { return false }
|
||||
func (*cgroupScope) Cleanup() {}
|
||||
|
||||
func startCommand(cmd *exec.Cmd, _ *cgroupScope) (*exec.Cmd, error) {
|
||||
return cmd, cmd.Start()
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// Package toolguard enforces per-command memory, timeout, PID, and output bounds
|
||||
// for agent Bash commands and custom command/script tools.
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
EnvToolMemoryLimitMB = "ARTEX_TOOL_MEMORY_LIMIT_MB"
|
||||
EnvToolTimeoutS = "ARTEX_TOOL_TIMEOUT_S"
|
||||
EnvToolPidsLimit = "ARTEX_TOOL_PIDS_LIMIT"
|
||||
EnvToolCgroupParent = "ARTEX_TOOL_CGROUP_PARENT"
|
||||
|
||||
DefaultToolMemoryLimitMB = 2048
|
||||
DefaultToolTimeoutS = 120
|
||||
DefaultMaxToolTimeoutS = 600
|
||||
DefaultToolPidsLimit = 256
|
||||
DefaultPollInterval = 200 * time.Millisecond
|
||||
DefaultGrace = 1 * time.Second
|
||||
DefaultMaxOutputBytes = 50 << 20 // 50 MiB, matching norma's background task cap
|
||||
)
|
||||
|
||||
// Config controls per-command resource guards.
|
||||
type Config struct {
|
||||
MemoryLimitMB int // 0 disables per-command memory guard
|
||||
Timeout time.Duration // default command timeout
|
||||
MaxTimeout time.Duration // upper bound for per-call timeout_ms
|
||||
PidsLimit int // 0 disables per-command cgroup pids.max
|
||||
PollInterval time.Duration // RSS watchdog poll cadence
|
||||
Grace time.Duration // sustained over-limit duration before kill (spikes >=1.25x kill immediately)
|
||||
MaxOutputBytes int // hard cap on captured combined stdout+stderr
|
||||
}
|
||||
|
||||
// FromEnv reads the active guard configuration from environment variables,
|
||||
// falling back to safe defaults on unset or invalid values.
|
||||
func FromEnv() Config {
|
||||
memMB := parseNonNegLimit(os.Getenv(EnvToolMemoryLimitMB), DefaultToolMemoryLimitMB)
|
||||
timeoutS := parsePositiveInt(os.Getenv(EnvToolTimeoutS), DefaultToolTimeoutS)
|
||||
if int64(memMB) > math.MaxInt64/(1<<20) {
|
||||
memMB = DefaultToolMemoryLimitMB
|
||||
}
|
||||
if int64(timeoutS) > math.MaxInt64/int64(time.Second) {
|
||||
timeoutS = DefaultToolTimeoutS
|
||||
}
|
||||
pids := parseNonNegLimit(os.Getenv(EnvToolPidsLimit), DefaultToolPidsLimit)
|
||||
|
||||
maxTimeoutS := DefaultMaxToolTimeoutS
|
||||
if timeoutS > maxTimeoutS {
|
||||
maxTimeoutS = timeoutS
|
||||
}
|
||||
return Config{
|
||||
MemoryLimitMB: memMB,
|
||||
Timeout: time.Duration(timeoutS) * time.Second,
|
||||
MaxTimeout: time.Duration(maxTimeoutS) * time.Second,
|
||||
PidsLimit: pids,
|
||||
PollInterval: DefaultPollInterval,
|
||||
Grace: DefaultGrace,
|
||||
MaxOutputBytes: DefaultMaxOutputBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func (c Config) withDefaults() Config {
|
||||
if c.Timeout <= 0 {
|
||||
c.Timeout = DefaultToolTimeoutS * time.Second
|
||||
}
|
||||
if c.MaxTimeout < c.Timeout {
|
||||
c.MaxTimeout = c.Timeout
|
||||
}
|
||||
if c.MaxTimeout < DefaultMaxToolTimeoutS*time.Second {
|
||||
c.MaxTimeout = DefaultMaxToolTimeoutS * time.Second
|
||||
}
|
||||
if c.PollInterval <= 0 {
|
||||
c.PollInterval = DefaultPollInterval
|
||||
}
|
||||
if c.Grace < 0 {
|
||||
c.Grace = 0
|
||||
}
|
||||
if c.MaxOutputBytes <= 0 {
|
||||
c.MaxOutputBytes = DefaultMaxOutputBytes
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// MemoryLimitBytes returns the configured per-command memory cap in bytes,
|
||||
// or 0 when disabled.
|
||||
func (c Config) MemoryLimitBytes() int64 {
|
||||
if c.MemoryLimitMB <= 0 || int64(c.MemoryLimitMB) > math.MaxInt64/(1<<20) {
|
||||
return 0
|
||||
}
|
||||
return int64(c.MemoryLimitMB) * 1024 * 1024
|
||||
}
|
||||
|
||||
// ResolveTimeout computes the effective timeout for a Bash invocation given an
|
||||
// optional model-supplied timeout_ms.
|
||||
func (c Config) ResolveTimeout(requestedMS int) time.Duration {
|
||||
c = c.withDefaults()
|
||||
if requestedMS <= 0 {
|
||||
return c.Timeout
|
||||
}
|
||||
if int64(requestedMS) > int64(c.MaxTimeout/time.Millisecond) {
|
||||
return c.MaxTimeout
|
||||
}
|
||||
return time.Duration(requestedMS) * time.Millisecond
|
||||
}
|
||||
|
||||
// RSSWatchdogAvailable reports whether sampled per-command memory enforcement is enabled.
|
||||
func (c Config) RSSWatchdogAvailable() bool { return c.MemoryLimitBytes() > 0 && watchdogAvailable() }
|
||||
|
||||
// Summary formats the active resource limits for startup logs.
|
||||
func (c Config) Summary() string {
|
||||
c = c.withDefaults()
|
||||
mem := "disabled"
|
||||
if c.MemoryLimitMB > 0 {
|
||||
mem = fmt.Sprintf("%dMiB", c.MemoryLimitMB)
|
||||
}
|
||||
pids := "disabled"
|
||||
if c.PidsLimit > 0 {
|
||||
pids = strconv.Itoa(c.PidsLimit)
|
||||
}
|
||||
return fmt.Sprintf("memory=%s timeout=%ds pids=%s (cgroup_v2=%t, rss_watchdog=%t)",
|
||||
mem, int(c.Timeout/time.Second), pids, CgroupV2Available(), c.RSSWatchdogAvailable())
|
||||
}
|
||||
|
||||
func parseNonNegLimit(raw string, def int) int {
|
||||
v := strings.ToLower(strings.TrimSpace(raw))
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
switch v {
|
||||
case "0", "off", "false", "disabled", "none":
|
||||
return 0
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 0 {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func parsePositiveInt(raw string, def int) int {
|
||||
v := strings.TrimSpace(raw)
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n <= 0 {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestConfigFromEnv(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, memory, timeout, pids string
|
||||
wantMemory, wantPids int
|
||||
wantTime, wantMax time.Duration
|
||||
}{
|
||||
{"defaults", "", "", "", 2048, 256, 120 * time.Second, 600 * time.Second},
|
||||
{"override", "64", "700", "32", 64, 32, 700 * time.Second, 700 * time.Second},
|
||||
{"disabled", "0", "8", "off", 0, 0, 8 * time.Second, 600 * time.Second},
|
||||
{"invalid", "-5", "999999999999999999", "abc", 2048, 256, 120 * time.Second, 600 * time.Second},
|
||||
{"overflow", "999999999999999999", "0", "-5", 2048, 256, 120 * time.Second, 600 * time.Second},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv(EnvToolMemoryLimitMB, tc.memory)
|
||||
t.Setenv(EnvToolTimeoutS, tc.timeout)
|
||||
t.Setenv(EnvToolPidsLimit, tc.pids)
|
||||
c := FromEnv()
|
||||
if c.MemoryLimitBytes() != int64(tc.wantMemory)<<20 || c.PidsLimit != tc.wantPids ||
|
||||
c.ResolveTimeout(0) != tc.wantTime || c.ResolveTimeout(math.MaxInt) != tc.wantMax ||
|
||||
c.ResolveTimeout(125) != 125*time.Millisecond {
|
||||
t.Fatalf("unexpected settings: %+v", c)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//go:build darwin || freebsd || openbsd || netbsd
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func watchdogAvailable() bool { return true }
|
||||
|
||||
// readProcessTreeMemory samples the command's descendants and group, excluding
|
||||
// the guard helper itself for background commands.
|
||||
func readProcessTreeMemory(rootPID, groupID, excludePID int) (int64, []int, bool) {
|
||||
if rootPID <= 0 {
|
||||
return 0, nil, false
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "/bin/ps", "-axo", "pid=,ppid=,pgid=,rss=").Output()
|
||||
if err != nil {
|
||||
return 0, nil, false
|
||||
}
|
||||
var entries []procEntry
|
||||
byPID := make(map[int]int64, 64)
|
||||
rootAlive := false
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) < 4 {
|
||||
continue
|
||||
}
|
||||
pid, e1 := strconv.Atoi(f[0])
|
||||
ppid, e2 := strconv.Atoi(f[1])
|
||||
pgrp, e3 := strconv.Atoi(f[2])
|
||||
rssKB, e4 := strconv.ParseInt(f[3], 10, 64)
|
||||
if e1 != nil || e2 != nil || e3 != nil || e4 != nil || pid <= 0 {
|
||||
continue
|
||||
}
|
||||
if pid == rootPID || (pgrp == groupID && pid != excludePID) {
|
||||
rootAlive = true
|
||||
}
|
||||
rssBytes := rssKB * 1024
|
||||
entries = append(entries, procEntry{pid: pid, ppid: ppid, pgrp: pgrp})
|
||||
byPID[pid] = rssBytes
|
||||
}
|
||||
if !rootAlive {
|
||||
return 0, nil, false
|
||||
}
|
||||
pids := collectTreePIDs(rootPID, groupID, excludePID, entries)
|
||||
var total int64
|
||||
for _, pid := range pids {
|
||||
total += byPID[pid]
|
||||
}
|
||||
return total, pids, true
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
//go:build linux
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func watchdogAvailable() bool { return true }
|
||||
|
||||
// readProcessTreeMemory samples the command's descendants and group, excluding
|
||||
// the guard helper itself for background commands.
|
||||
func readProcessTreeMemory(rootPID, groupID, excludePID int) (int64, []int, bool) {
|
||||
if rootPID <= 0 {
|
||||
return 0, nil, false
|
||||
}
|
||||
dirs, err := os.ReadDir("/proc")
|
||||
if err != nil {
|
||||
return 0, nil, false
|
||||
}
|
||||
entries := make([]procEntry, 0, len(dirs))
|
||||
rootAlive := false
|
||||
for _, d := range dirs {
|
||||
if !d.IsDir() {
|
||||
continue
|
||||
}
|
||||
pid, err := strconv.Atoi(d.Name())
|
||||
if err != nil || pid <= 0 {
|
||||
continue
|
||||
}
|
||||
statBytes, err := os.ReadFile(filepath.Join("/proc", d.Name(), "stat"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ppid, pgrp, ok := parseProcStat(statBytes)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if pid == rootPID || (pgrp == groupID && pid != excludePID) {
|
||||
rootAlive = true
|
||||
}
|
||||
entries = append(entries, procEntry{pid: pid, ppid: ppid, pgrp: pgrp})
|
||||
}
|
||||
if !rootAlive {
|
||||
return 0, nil, false
|
||||
}
|
||||
pids := collectTreePIDs(rootPID, groupID, excludePID, entries)
|
||||
var total int64
|
||||
var anyRead bool
|
||||
for _, pid := range pids {
|
||||
pidStr := strconv.Itoa(pid)
|
||||
if b, err := os.ReadFile(filepath.Join("/proc", pidStr, "status")); err == nil {
|
||||
if n, ok := parseProcStatusBytes(b); ok {
|
||||
total += n
|
||||
anyRead = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return total, pids, anyRead
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !linux && !darwin && !freebsd && !openbsd && !netbsd
|
||||
|
||||
package toolguard
|
||||
|
||||
func watchdogAvailable() bool { return false }
|
||||
|
||||
func readProcessTreeMemory(_, _, _ int) (int64, []int, bool) {
|
||||
return 0, nil, false
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type procEntry struct {
|
||||
pid int
|
||||
ppid int
|
||||
pgrp int
|
||||
}
|
||||
|
||||
// collectTreePIDs returns every PID belonging to rootPID's process group or
|
||||
// descending from rootPID (or from any member of that process group).
|
||||
func collectTreePIDs(rootPID, groupID, excludePID int, entries []procEntry) []int {
|
||||
if rootPID <= 0 {
|
||||
return nil
|
||||
}
|
||||
children := make(map[int][]int, len(entries))
|
||||
seen := map[int]bool{rootPID: true}
|
||||
queue := []int{rootPID}
|
||||
for _, e := range entries {
|
||||
if e.pid <= 0 {
|
||||
continue
|
||||
}
|
||||
children[e.ppid] = append(children[e.ppid], e.pid)
|
||||
if e.pgrp == groupID && e.pid != excludePID && !seen[e.pid] {
|
||||
seen[e.pid] = true
|
||||
queue = append(queue, e.pid)
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(queue); i++ {
|
||||
cur := queue[i]
|
||||
for _, ch := range children[cur] {
|
||||
if !seen[ch] {
|
||||
seen[ch] = true
|
||||
queue = append(queue, ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
return queue
|
||||
}
|
||||
|
||||
// parseProcStat parses Linux /proc/<pid>/stat, returning (ppid, pgrp, ok).
|
||||
// The process name inside parentheses may contain spaces or ')', so we locate
|
||||
// the last ')' before splitting the trailing fields.
|
||||
func parseProcStat(data []byte) (ppid, pgrp int, ok bool) {
|
||||
idx := bytes.LastIndexByte(data, ')')
|
||||
if idx < 0 || idx+2 >= len(data) {
|
||||
return 0, 0, false
|
||||
}
|
||||
fields := strings.Fields(string(data[idx+1:]))
|
||||
// fields[0] = state, fields[1] = ppid, fields[2] = pgrp
|
||||
if len(fields) < 3 {
|
||||
return 0, 0, false
|
||||
}
|
||||
pp, err1 := strconv.Atoi(fields[1])
|
||||
pg, err2 := strconv.Atoi(fields[2])
|
||||
if err1 != nil || err2 != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
return pp, pg, true
|
||||
}
|
||||
|
||||
// parseProcStatusBytes parses Linux /proc/<pid>/status and returns
|
||||
// (VmRSS + VmSwap) in bytes.
|
||||
func parseProcStatusBytes(data []byte) (int64, bool) {
|
||||
var rssKB, swapKB int64
|
||||
var sawRSS bool
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
switch {
|
||||
case strings.HasPrefix(line, "VmRSS:"):
|
||||
if v, ok := parseKBField(line); ok {
|
||||
rssKB = v
|
||||
sawRSS = true
|
||||
}
|
||||
case strings.HasPrefix(line, "VmSwap:"):
|
||||
if v, ok := parseKBField(line); ok {
|
||||
swapKB = v
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sawRSS {
|
||||
return 0, false
|
||||
}
|
||||
return (rssKB + swapKB) * 1024, true
|
||||
}
|
||||
|
||||
func parseKBField(line string) (int64, bool) {
|
||||
f := strings.Fields(line)
|
||||
if len(f) < 2 {
|
||||
return 0, false
|
||||
}
|
||||
n, err := strconv.ParseInt(f[1], 10, 64)
|
||||
if err != nil || n < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
// parseCgroupMemoryEventsOOM reports whether a Linux cgroup v2 memory.events
|
||||
// payload shows any kernel OOM kill event.
|
||||
func parseCgroupMemoryEventsOOM(data []byte) bool {
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) == 2 && f[0] == "oom_kill" {
|
||||
if n, err := strconv.ParseInt(f[1], 10, 64); err == nil && n > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build !windows
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func setProcessGroup(cmd *exec.Cmd) {
|
||||
if cmd.SysProcAttr == nil {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{}
|
||||
}
|
||||
cmd.SysProcAttr.Setpgid = true
|
||||
}
|
||||
|
||||
func killProcessGroup(process *os.Process) {
|
||||
_ = syscall.Kill(-process.Pid, syscall.SIGKILL)
|
||||
}
|
||||
|
||||
func killProcessIDs(pids []int) {
|
||||
for _, pid := range pids {
|
||||
_ = syscall.Kill(pid, syscall.SIGKILL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build windows
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func setProcessGroup(_ *exec.Cmd) {}
|
||||
|
||||
func killProcessGroup(p *os.Process) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
_ = exec.CommandContext(ctx, "taskkill", "/T", "/F", "/PID", strconv.Itoa(p.Pid)).Run()
|
||||
_ = p.Kill()
|
||||
}
|
||||
|
||||
func killProcessIDs(_ []int) {}
|
||||
@@ -0,0 +1,173 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RunResult holds the outcome of a guarded subprocess execution.
|
||||
type RunResult struct {
|
||||
Output string
|
||||
OutputTruncated bool
|
||||
ExitCode int
|
||||
TimedOut bool
|
||||
MemoryKilled bool
|
||||
KilledByCgroup bool
|
||||
PeakMemoryBytes int64
|
||||
MemoryLimitBytes int64
|
||||
Err error
|
||||
}
|
||||
|
||||
// Run executes a one-shot subprocess and cleans up its process group when done.
|
||||
// The caller supplies the deadline, if any. cmd must not have been started.
|
||||
func Run(ctx context.Context, cfg Config, cmd *exec.Cmd) RunResult {
|
||||
cfg = cfg.withDefaults()
|
||||
scope := newCgroupScope(cfg.MemoryLimitBytes(), cfg.PidsLimit)
|
||||
if scope != nil {
|
||||
defer scope.Cleanup()
|
||||
}
|
||||
return run(ctx, cfg, cmd, scope, 0, nil)
|
||||
}
|
||||
|
||||
// group is zero for foreground commands. A background helper runs its command
|
||||
// within its own existing process group, so norma's TaskStop can kill both.
|
||||
func run(ctx context.Context, cfg Config, cmd *exec.Cmd, scope *cgroupScope, group int, stream io.Writer) RunResult {
|
||||
res := RunResult{ExitCode: -1, MemoryLimitBytes: cfg.MemoryLimitBytes()}
|
||||
if err := ctx.Err(); err != nil {
|
||||
res.Err, res.TimedOut = err, errors.Is(err, context.DeadlineExceeded)
|
||||
return res
|
||||
}
|
||||
if group == 0 {
|
||||
setProcessGroup(cmd)
|
||||
}
|
||||
|
||||
// Own the combined output pipe so Wait observes the direct child exiting,
|
||||
// even if a descendant still has stdout/stderr open.
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
res.Err = err
|
||||
return res
|
||||
}
|
||||
defer r.Close()
|
||||
defer w.Close()
|
||||
cmd.Stdout, cmd.Stderr = w, w
|
||||
cmd.WaitDelay = time.Second // also bounds os/exec's stdin pump, if present
|
||||
cmd, err = startCommand(cmd, scope)
|
||||
if scope != nil {
|
||||
scope.CloseFD()
|
||||
}
|
||||
if err != nil {
|
||||
res.Err = err
|
||||
return res
|
||||
}
|
||||
_ = w.Close()
|
||||
|
||||
capture := newOutputCapture(cfg.MaxOutputBytes, stream)
|
||||
drained := make(chan struct{})
|
||||
go func() {
|
||||
_, _ = io.Copy(capture, r)
|
||||
close(drained)
|
||||
}()
|
||||
waited := make(chan error, 1)
|
||||
go func() { waited <- cmd.Wait() }()
|
||||
|
||||
root := cmd.Process.Pid
|
||||
groupID := root
|
||||
if group != 0 {
|
||||
groupID = group
|
||||
}
|
||||
// When delegated memory.max is active, the kernel enforces the bound and
|
||||
// we do not need to walk /proc. Fall back to the sampled watchdog otherwise.
|
||||
var samples <-chan time.Time
|
||||
if res.MemoryLimitBytes > 0 && (scope == nil || !scope.active) && watchdogAvailable() {
|
||||
ticker := time.NewTicker(cfg.PollInterval)
|
||||
defer ticker.Stop()
|
||||
samples = ticker.C
|
||||
}
|
||||
kill := func(exited bool) {
|
||||
if scope != nil && scope.active {
|
||||
scope.Kill()
|
||||
}
|
||||
if group == 0 {
|
||||
if runtime.GOOS == "windows" && exited {
|
||||
return
|
||||
}
|
||||
killProcessGroup(cmd.Process)
|
||||
} else if scope == nil || !scope.active {
|
||||
// Do not kill the background helper itself: it still needs to
|
||||
// print the resource-limit error to the task's output file.
|
||||
_, pids, _ := readProcessTreeMemory(root, groupID, group)
|
||||
killProcessIDs(pids)
|
||||
_ = cmd.Process.Kill()
|
||||
}
|
||||
}
|
||||
|
||||
var overSince time.Time
|
||||
wait:
|
||||
for {
|
||||
select {
|
||||
case res.Err = <-waited:
|
||||
kill(true) // one-shot commands must not leave workers behind
|
||||
break wait
|
||||
case <-ctx.Done():
|
||||
res.TimedOut = errors.Is(ctx.Err(), context.DeadlineExceeded)
|
||||
kill(false)
|
||||
<-waited
|
||||
res.Err = ctx.Err()
|
||||
break wait
|
||||
case now := <-samples:
|
||||
used, pids, ok := readProcessTreeMemory(root, groupID, group)
|
||||
if !ok || used <= res.MemoryLimitBytes {
|
||||
overSince = time.Time{}
|
||||
continue
|
||||
}
|
||||
res.PeakMemoryBytes = max(res.PeakMemoryBytes, used)
|
||||
if overSince.IsZero() {
|
||||
overSince = now
|
||||
}
|
||||
if used-res.MemoryLimitBytes >= res.MemoryLimitBytes/4 || now.Sub(overSince) >= cfg.Grace {
|
||||
res.MemoryKilled = true
|
||||
if group == 0 {
|
||||
// Include freshly observed descendants that changed process groups.
|
||||
killProcessIDs(pids)
|
||||
}
|
||||
kill(false)
|
||||
res.Err = <-waited
|
||||
break wait
|
||||
}
|
||||
}
|
||||
}
|
||||
res.KilledByCgroup = scope != nil && scope.active && scope.OOMKilled()
|
||||
res.MemoryKilled = res.MemoryKilled || res.KilledByCgroup
|
||||
if res.MemoryKilled {
|
||||
res.TimedOut = false
|
||||
}
|
||||
res.ExitCode = cmd.ProcessState.ExitCode()
|
||||
|
||||
// Bound drain time even if an untracked process inherited the output pipe.
|
||||
drainTimer := time.NewTimer(time.Second)
|
||||
defer drainTimer.Stop()
|
||||
select {
|
||||
case <-drained:
|
||||
case <-drainTimer.C:
|
||||
_ = r.Close()
|
||||
<-drained
|
||||
}
|
||||
res.Output, res.OutputTruncated = capture.output(), capture.truncated
|
||||
return res
|
||||
}
|
||||
|
||||
// FormatMemoryKilled returns a model-actionable termination reason.
|
||||
func FormatMemoryKilled(peakBytes, limitBytes int64, byCgroup bool) string {
|
||||
const mib = 1 << 20
|
||||
if byCgroup {
|
||||
return fmt.Sprintf("[command killed: memory limit exceeded (cgroup cap %d MiB; reduce memory usage or adjust %s)]", limitBytes/mib, EnvToolMemoryLimitMB)
|
||||
}
|
||||
return fmt.Sprintf("[command killed: memory limit exceeded (sampled %.1f MiB, limit %d MiB; reduce memory usage or adjust %s)]", float64(peakBytes)/mib, limitBytes/mib, EnvToolMemoryLimitMB)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
if code, handled := BackgroundHelper(os.Args[1:]); handled {
|
||||
os.Exit(code)
|
||||
}
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestGuardChild(t *testing.T) {
|
||||
// Use a fixed-size child workload, never a machine-wide stress test.
|
||||
switch os.Getenv("ARTEX_TEST_GUARD_CHILD") {
|
||||
case "memory":
|
||||
b := make([]byte, 48<<20)
|
||||
for i := 0; i < len(b); i += os.Getpagesize() {
|
||||
b[i] = 1
|
||||
}
|
||||
fmt.Println("allocated")
|
||||
time.Sleep(10 * time.Second)
|
||||
runtime.KeepAlive(b)
|
||||
case "output":
|
||||
fmt.Fprint(os.Stdout, "stdout")
|
||||
fmt.Fprint(os.Stderr, "stderr")
|
||||
os.Exit(7)
|
||||
case "sleep":
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func child(mode string) *exec.Cmd {
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestGuardChild$")
|
||||
cmd.Env = append(os.Environ(), "ARTEX_TEST_GUARD_CHILD="+mode)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func TestRunOutputAndExitCode(t *testing.T) {
|
||||
res := Run(context.Background(), Config{MaxOutputBytes: 8}, child("output"))
|
||||
if res.Output != "stdoutst" || !res.OutputTruncated || res.ExitCode != 7 || res.Err == nil {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDoesNotStartCancelledCommand(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
cmd := child("output")
|
||||
res := Run(ctx, Config{}, cmd)
|
||||
if cmd.Process != nil || !errors.Is(res.Err, context.Canceled) {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTimeout(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
res := Run(ctx, Config{}, child("sleep"))
|
||||
if !res.TimedOut || res.MemoryKilled || !errors.Is(res.Err, context.DeadlineExceeded) {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWatchdogLimitsDescendantMemory(t *testing.T) {
|
||||
if !watchdogAvailable() {
|
||||
t.Skip("no process memory watchdog on this platform")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.Command("bash", "-c", `"$1" -test.run='^TestGuardChild$' & wait`, "guard-test", os.Args[0])
|
||||
cmd.Env = append(os.Environ(), "ARTEX_TEST_GUARD_CHILD=memory")
|
||||
cfg := Config{MemoryLimitMB: 16, PollInterval: 30 * time.Millisecond}.withDefaults()
|
||||
// Explicitly exercise the fallback even if this host has delegated cgroups.
|
||||
res := run(ctx, cfg, cmd, nil, 0, nil)
|
||||
if !res.MemoryKilled || res.KilledByCgroup || res.TimedOut || res.PeakMemoryBytes <= 16<<20 {
|
||||
t.Fatalf("expected watchdog to terminate the process tree: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDoesNotLeaveBackgroundChildren(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix process-group cleanup")
|
||||
}
|
||||
marker := filepath.Join(t.TempDir(), "child-survived")
|
||||
cmd := exec.Command("bash", "-c", `(sleep 0.4; touch "$1") & printf done`, "guard-test", marker)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
res := Run(ctx, Config{}, cmd)
|
||||
if res.Err != nil || res.Output != "done" {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
time.Sleep(550 * time.Millisecond)
|
||||
if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("command left descendants running: stat = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcParsing(t *testing.T) {
|
||||
if pp, pg, ok := parseProcStat([]byte("12 (name with ) inside) S 10 11 7")); !ok || pp != 10 || pg != 11 {
|
||||
t.Fatalf("unexpected stat parse: %d %d %t", pp, pg, ok)
|
||||
}
|
||||
if n, ok := parseProcStatusBytes([]byte("Name:\ttest\nVmRSS:\t400 kB\nVmSwap:\t20 kB\n")); !ok || n != 420*1024 {
|
||||
t.Fatalf("unexpected status parse: %d %t", n, ok)
|
||||
}
|
||||
if got := collectTreePIDs(11, 10, 10, []procEntry{
|
||||
{pid: 10, pgrp: 10}, {pid: 11, ppid: 10, pgrp: 10}, {pid: 12, ppid: 11, pgrp: 12},
|
||||
{pid: 13, ppid: 1, pgrp: 10}, {pid: 14, ppid: 1, pgrp: 14},
|
||||
}); !reflect.DeepEqual(got, []int{11, 13, 12}) {
|
||||
t.Fatalf("unexpected group: %v", got)
|
||||
}
|
||||
if !parseCgroupMemoryEventsOOM([]byte("oom 2\noom_kill 1\n")) || parseCgroupMemoryEventsOOM([]byte("oom 2\noom_kill 0\n")) {
|
||||
t.Fatal("only a positive oom_kill counter should be reported")
|
||||
}
|
||||
if note := FormatMemoryKilled(0, 16<<20, true); !strings.Contains(note, "memory limit exceeded") || !strings.Contains(note, "16 MiB") {
|
||||
t.Fatalf("unexpected cgroup error: %q", note)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user