fix: cap ARTEX container and tool resource use

This commit is contained in:
ji ruo committed 2026-11-27 15:20:52 +08:00
1 parent 253a8eeac3
commit ea4377ef9a
36 files changed
+1869 -64

No files matched your search

+29 -17
View File
@@ -6,6 +6,7 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"log"
@@ -19,6 +20,7 @@ import (
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/internal/httpidentity"
"github.com/Autumn-27/artex/internal/toolguard"
"github.com/Autumn-27/norma/permission"
actool "github.com/Autumn-27/norma/tool"
)
@@ -336,15 +338,14 @@ func (s *Server) runCommandTool(ctx context.Context, execRaw json.RawMessage, pa
return actool.Errorf("command 为空"), nil
}
cmd := renderTemplate(spec.Command, params, shellQuote)
// 复用 Bash 也在用的底层 run(经 Bash CoreTool.Call):自动继承安全 floor/超时/
// 代理 env/输出溢出。工具与 Bash 平级、共用底层,不经过 Bash 这个工具让模型调。
bashIn, _ := json.Marshal(map[string]any{"command": cmd})
// 复用受资源上限保护的 Bash 底层 run:自动继承安全 floor / 内存与超时限制 /
// 代理 env / 输出溢出。工具与 Bash 平级、共用底层,不经过 Bash 这个工具让模型调。
payload := map[string]any{"command": cmd}
if spec.TimeoutMs > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeoutOr(spec.TimeoutMs, 120000))
defer cancel()
payload["timeout_ms"] = spec.TimeoutMs
}
return actool.NewBash().Call(ctx, bashIn, tc)
bashIn, _ := json.Marshal(payload)
return toolguard.NewBash().Call(ctx, bashIn, tc)
}
// ---------- script(仅 Python):临时文件 + stdin JSON + env ----------
@@ -367,16 +368,20 @@ func (s *Server) runScriptTool(ctx context.Context, key string, execRaw json.Raw
}
sessionEnv = tc.Env
}
body, err := execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, timeoutOr(spec.TimeoutMs, 120000))
body, err := execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, toolguard.FromEnv().ResolveTimeout(spec.TimeoutMs))
if err != nil {
return actool.Errorf(maskSecrets(err.Error())), nil
out := actool.Capture(tc, body)
if out != "" {
out += "\n\n"
}
return actool.Errorf(out + maskSecrets(err.Error())), nil
}
return actool.Text(actool.Capture(tc, body)), nil
}
// execPython writes the code to a temp .py under workDir/.tools, runs it via interp
// with the params JSON on stdin + scalar params mirrored to TOOL_<NAME> env, and
// returns combined stdout+stderr (with a timeout/exit note). Standalone + testable.
// returns combined stdout+stderr and any termination error.
func execPython(ctx context.Context, interp, key, code string, params map[string]any, workDir string, sessionEnv []string, timeout time.Duration) (string, error) {
toolsDir := filepath.Join(workDir, ".tools")
if err := os.MkdirAll(toolsDir, 0o755); err != nil {
@@ -396,7 +401,7 @@ func execPython(ctx context.Context, interp, key, code string, params map[string
runCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
c := exec.CommandContext(runCtx, interp, tmp)
c := exec.Command(interp, tmp)
c.Dir = workDir
c.Env = append(os.Environ(), sessionEnv...) // 会话代理 env
for k, v := range params { // 标量参数镜像成 TOOL_<NAME>
@@ -406,12 +411,19 @@ func execPython(ctx context.Context, interp, key, code string, params map[string
}
pj, _ := json.Marshal(params)
c.Stdin = bytes.NewReader(pj) // 参数 JSON 走 stdin
out, err := c.CombinedOutput()
body := string(out)
if runCtx.Err() == context.DeadlineExceeded {
body += "\n... [超时终止] ..."
} else if err != nil {
body += "\n[exit: " + err.Error() + "]"
res := toolguard.Run(runCtx, toolguard.FromEnv(), c)
body := res.Output
if res.OutputTruncated {
body += "\n\n[output truncated at capture limit]"
}
if res.MemoryKilled {
return body, errors.New(toolguard.FormatMemoryKilled(res.PeakMemoryBytes, res.MemoryLimitBytes, res.KilledByCgroup))
}
if res.TimedOut {
return body, fmt.Errorf("[command timed out (configured limit %s)]", timeout)
}
if res.Err != nil {
return body, fmt.Errorf("[exit: %w]", res.Err)
}
return body, nil
}
+30
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"os/exec"
"runtime"
"strings"
"testing"
"time"
@@ -185,3 +186,32 @@ func TestHTTPToolTruncatesLargeBody(t *testing.T) {
t.Fatalf("oversized http body was not truncated: len=%d", len(out))
}
}
func TestCustomCommandToolTimeout(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX shell syntax")
}
s := &Server{}
res, err := s.runCommandTool(context.Background(), []byte(`{"command":"sleep 10", "timeout_ms":100}`), nil, nil)
if err != nil || !res.IsError || !strings.Contains(res.Flatten(), "timed out") {
t.Fatalf("expected timeout, got %s, %v", res.Flatten(), err)
}
}
func TestExecPythonMemoryLimit(t *testing.T) {
if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
t.Skip("requires a process memory watchdog")
}
interp, err := exec.LookPath("python3")
if err != nil {
t.Skip("python3 unavailable")
}
t.Setenv("ARTEX_TOOL_MEMORY_LIMIT_MB", "16")
_, err = execPython(context.Background(), interp, "test", `import time
b = bytearray(b'x') * (48 * 1024 * 1024)
time.sleep(10)
`, nil, t.TempDir(), nil, 5*time.Second)
if err == nil || !strings.Contains(err.Error(), "memory limit exceeded") {
t.Fatalf("expected a memory limit error, got %v", err)
}
}
+33 -8
View File
@@ -4,6 +4,8 @@ import (
"encoding/json"
"net/http"
"time"
"github.com/Autumn-27/artex/internal/toolguard"
)
type metricValue struct {
@@ -12,15 +14,38 @@ type metricValue struct {
Percent float64 `json:"percent"`
}
type resourceLimitsInfo struct {
ContainerMemoryLimitBytes uint64 `json:"container_memory_limit_bytes"`
ContainerMemoryBounded bool `json:"container_memory_bounded"`
ContainerPidsLimit uint64 `json:"container_pids_limit"`
ToolMemoryLimitMB int `json:"tool_memory_limit_mb"`
ToolTimeoutSeconds int `json:"tool_timeout_seconds"`
ToolPidsLimit int `json:"tool_pids_limit"`
ToolCgroupAvailable bool `json:"tool_cgroup_available"`
ToolRSSWatchdogAvailable bool `json:"tool_rss_watchdog_available"`
}
type systemMetricsResponse struct {
Scope string `json:"scope"`
Supported bool `json:"supported"`
Timestamp time.Time `json:"timestamp"`
CPU metricValue `json:"cpu"`
Memory metricValue `json:"memory"`
Disk metricValue `json:"disk"`
DataDisk metricValue `json:"data_disk"`
Container bool `json:"container_metrics"`
Scope string `json:"scope"`
Supported bool `json:"supported"`
Timestamp time.Time `json:"timestamp"`
CPU metricValue `json:"cpu"`
Memory metricValue `json:"memory"`
Disk metricValue `json:"disk"`
DataDisk metricValue `json:"data_disk"`
Container bool `json:"container_metrics"`
Limits resourceLimitsInfo `json:"limits"`
}
func toolResourceLimits() resourceLimitsInfo {
cfg := toolguard.FromEnv()
return resourceLimitsInfo{
ToolMemoryLimitMB: cfg.MemoryLimitMB,
ToolTimeoutSeconds: int(cfg.Timeout / time.Second),
ToolPidsLimit: cfg.PidsLimit,
ToolCgroupAvailable: toolguard.CgroupV2Available(),
ToolRSSWatchdogAvailable: cfg.RSSWatchdogAvailable(),
}
}
func (s *Server) systemMetrics(w http.ResponseWriter, r *http.Request) {
+145 -22
View File
@@ -20,43 +20,166 @@ func systemMetricsSnapshot(s *Server) systemMetricsResponse {
s.metricsMu.Lock()
if !s.lastCPUAt.IsZero() && use >= s.lastCPUUse && limit > 0 {
elapsed := now.Sub(s.lastCPUAt).Seconds()
if elapsed > 0 { cpuPct = float64(use-s.lastCPUUse) / 1e6 / elapsed / limit * 100 }
if elapsed > 0 {
cpuPct = float64(use-s.lastCPUUse) / 1e6 / elapsed / limit * 100
}
}
s.lastCPUUse, s.lastCPUAt = use, now
s.metricsMu.Unlock()
}
memUsed, memTotal, memOK := cgroupMemory()
memoryDirs := cgroupControllerDirs("memory")
memoryLimit := cgroupLimit(memoryDirs, "memory.max", "memory.limit_in_bytes")
pidsLimit := cgroupLimit(cgroupControllerDirs("pids"), "pids.max", "pids.max")
memUsed, memOK := cgroupMemoryUsage(memoryDirs)
memTotal := memoryLimit
if memOK && memTotal == 0 {
memTotal = hostMemoryTotal()
}
root, data := diskMetric("/"), diskMetric(s.dataDir)
if data.TotalBytes == 0 { data = root }
if data.TotalBytes == 0 {
data = root
}
limits := toolResourceLimits()
limits.ContainerMemoryLimitBytes = memoryLimit
limits.ContainerMemoryBounded = memoryLimit > 0
limits.ContainerPidsLimit = pidsLimit
return systemMetricsResponse{Scope: "container", Supported: true, Timestamp: time.Now().UTC(), Container: cpuOK || memOK,
CPU: metricValue{Percent: clampPercent(cpuPct)}, Memory: metricValue{UsedBytes: memUsed, TotalBytes: memTotal, Percent: percent(memUsed, memTotal)}, Disk: root, DataDisk: data}
CPU: metricValue{Percent: clampPercent(cpuPct)}, Memory: metricValue{UsedBytes: memUsed, TotalBytes: memTotal, Percent: percent(memUsed, memTotal)}, Disk: root, DataDisk: data,
Limits: limits}
}
func cgroupCPU() (uint64, float64, bool) {
for _, dir := range []string{"/sys/fs/cgroup", "/sys/fs/cgroup/cpu"} {
b, err := os.ReadFile(filepath.Join(dir, "cpu.stat")); if err != nil { continue }
b, err := os.ReadFile(filepath.Join(dir, "cpu.stat"))
if err != nil {
continue
}
var use uint64
for _, line := range strings.Split(string(b), "\n") { f := strings.Fields(line); if len(f) == 2 && f[0] == "usage_usec" { use, _ = strconv.ParseUint(f[1], 10, 64) } }
for _, line := range strings.Split(string(b), "\n") {
f := strings.Fields(line)
if len(f) == 2 && f[0] == "usage_usec" {
use, _ = strconv.ParseUint(f[1], 10, 64)
}
}
limit := float64(runtime.NumCPU())
if q, err := os.ReadFile(filepath.Join(dir, "cpu.max")); err == nil { f := strings.Fields(string(q)); if len(f) == 2 && f[0] != "max" { quota, _ := strconv.ParseFloat(f[0], 64); period, _ := strconv.ParseFloat(f[1], 64); if period > 0 { limit = quota / period } } }
if use > 0 { return use, limit, true }
if q, err := os.ReadFile(filepath.Join(dir, "cpu.max")); err == nil {
f := strings.Fields(string(q))
if len(f) == 2 && f[0] != "max" {
quota, _ := strconv.ParseFloat(f[0], 64)
period, _ := strconv.ParseFloat(f[1], 64)
if period > 0 {
limit = quota / period
}
}
}
if use > 0 {
return use, limit, true
}
}
return 0, 0, false
}
func cgroupMemory() (uint64, uint64, bool) {
for _, dir := range []string{"/sys/fs/cgroup", "/sys/fs/cgroup/memory"} {
cur, ce := readUint(filepath.Join(dir, "memory.current")); max, me := readUint(filepath.Join(dir, "memory.max"))
if ce == nil && me == nil { return cur, max, max > 0 }
if ce == nil { if b, err := os.ReadFile(filepath.Join(dir, "memory.max")); err == nil && strings.TrimSpace(string(b)) == "max" { return cur, hostMemoryTotal(), true } }
cur, ce = readUint(filepath.Join(dir, "memory.usage_in_bytes")); max, me = readUint(filepath.Join(dir, "memory.limit_in_bytes"))
if ce == nil && me == nil && max < ^uint64(0)/2 { return cur, max, true }
}
return 0, 0, false
type controllerDirs struct {
root string
leaf string
v2 bool
}
func hostMemoryTotal() uint64 { b, err := os.ReadFile("/proc/meminfo"); if err != nil { return 0 }; for _, line := range strings.Split(string(b), "\n") { f := strings.Fields(line); if len(f) >= 2 && f[0] == "MemTotal:" { n, _ := strconv.ParseUint(f[1], 10, 64); return n * 1024 } }; return 0 }
func readUint(path string) (uint64, error) { b, err := os.ReadFile(path); if err != nil { return 0, err }; return strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64) }
func diskMetric(path string) metricValue { var st syscall.Statfs_t; if path == "" || syscall.Statfs(path, &st) != nil { return metricValue{} }; total, free := st.Blocks*uint64(st.Bsize), st.Bavail*uint64(st.Bsize); used := total-free; return metricValue{UsedBytes: used, TotalBytes: total, Percent: percent(used, total)} }
func percent(used, total uint64) float64 { if total == 0 { return 0 }; return clampPercent(float64(used)/float64(total)*100) }
func clampPercent(v float64) float64 { if v < 0 { return 0 }; if v > 100 { return 100 }; return v }
func cgroupControllerDirs(controller string) controllerDirs {
const mount = "/sys/fs/cgroup"
data, _ := os.ReadFile("/proc/self/cgroup")
for _, line := range strings.Split(string(data), "\n") {
f := strings.SplitN(line, ":", 3)
if len(f) != 3 || !strings.HasPrefix(f[2], "/") {
continue
}
if f[0] == "0" && f[1] == "" {
return controllerDirs{root: mount, leaf: filepath.Join(mount, filepath.Clean(f[2])), v2: true}
}
if strings.Contains(","+f[1]+",", ","+controller+",") {
root := filepath.Join(mount, controller)
return controllerDirs{root: root, leaf: filepath.Join(root, filepath.Clean(f[2]))}
}
}
return controllerDirs{}
}
func cgroupMemoryUsage(d controllerDirs) (uint64, bool) {
if d.leaf == "" {
return 0, false
}
name := "memory.usage_in_bytes"
if d.v2 {
name = "memory.current"
}
n, err := readUint(filepath.Join(d.leaf, name))
return n, err == nil
}
// The effective bound is the smallest finite limit from leaf to mount root.
func cgroupLimit(d controllerDirs, v2Name, v1Name string) uint64 {
if d.leaf == "" {
return 0
}
name := v1Name
if d.v2 {
name = v2Name
}
var limit uint64
for dir := d.leaf; ; dir = filepath.Dir(dir) {
n, err := readUint(filepath.Join(dir, name))
// v1 represents unlimited memory with a large page-aligned sentinel.
if err == nil && n > 0 && (d.v2 || name != "memory.limit_in_bytes" || n < 1<<62) && (limit == 0 || n < limit) {
limit = n
}
if dir == d.root || dir == filepath.Dir(dir) {
return limit
}
}
}
func hostMemoryTotal() uint64 {
b, err := os.ReadFile("/proc/meminfo")
if err != nil {
return 0
}
for _, line := range strings.Split(string(b), "\n") {
f := strings.Fields(line)
if len(f) >= 2 && f[0] == "MemTotal:" {
n, _ := strconv.ParseUint(f[1], 10, 64)
return n * 1024
}
}
return 0
}
func readUint(path string) (uint64, error) {
b, err := os.ReadFile(path)
if err != nil {
return 0, err
}
return strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64)
}
func diskMetric(path string) metricValue {
var st syscall.Statfs_t
if path == "" || syscall.Statfs(path, &st) != nil {
return metricValue{}
}
total, free := st.Blocks*uint64(st.Bsize), st.Bavail*uint64(st.Bsize)
used := total - free
return metricValue{UsedBytes: used, TotalBytes: total, Percent: percent(used, total)}
}
func percent(used, total uint64) float64 {
if total == 0 {
return 0
}
return clampPercent(float64(used) / float64(total) * 100)
}
func clampPercent(v float64) float64 {
if v < 0 {
return 0
}
if v > 100 {
return 100
}
return v
}
+41
View File
@@ -0,0 +1,41 @@
//go:build linux
package server
import (
"os"
"path/filepath"
"testing"
)
func TestCgroupEffectiveLimit(t *testing.T) {
root := t.TempDir()
parent := filepath.Join(root, "container")
leaf := filepath.Join(parent, "app")
if err := os.MkdirAll(leaf, 0o755); err != nil {
t.Fatal(err)
}
write := func(dir, name, value string) {
t.Helper()
if err := os.WriteFile(filepath.Join(dir, name), []byte(value), 0o600); err != nil {
t.Fatal(err)
}
}
write(leaf, "memory.max", "max\n")
write(parent, "memory.max", "1073741824\n")
write(root, "memory.max", "2147483648\n")
write(leaf, "pids.max", "48\n")
write(parent, "pids.max", "64\n")
d := controllerDirs{root: root, leaf: leaf, v2: true}
if got := cgroupLimit(d, "memory.max", "memory.limit_in_bytes"); got != 1<<30 {
t.Fatalf("expected parent's memory limit, got %d", got)
}
if got := cgroupLimit(d, "pids.max", "pids.max"); got != 48 {
t.Fatalf("expected the smaller leaf PID limit, got %d", got)
}
write(leaf, "memory.limit_in_bytes", "9223372036854771712\n")
d.v2 = false
if got := cgroupLimit(d, "memory.max", "memory.limit_in_bytes"); got != 0 {
t.Fatalf("v1 unlimited sentinel reported as a bound: %d", got)
}
}
+6
View File
@@ -8,6 +8,9 @@ import (
)
func TestSystemMetricsReturnsContainerAndDiskValues(t *testing.T) {
t.Setenv("ARTEX_TOOL_MEMORY_LIMIT_MB", "96")
t.Setenv("ARTEX_TOOL_TIMEOUT_S", "72")
t.Setenv("ARTEX_TOOL_PIDS_LIMIT", "48")
s := &Server{dataDir: t.TempDir()}
r := httptest.NewRequest("GET", "/api/system/metrics", nil)
w := httptest.NewRecorder()
@@ -22,6 +25,9 @@ func TestSystemMetricsReturnsContainerAndDiskValues(t *testing.T) {
if got.Scope == "" || got.Timestamp.IsZero() {
t.Fatalf("unexpected response metadata: %+v", got)
}
if got.Limits.ToolMemoryLimitMB != 96 || got.Limits.ToolTimeoutSeconds != 72 || got.Limits.ToolPidsLimit != 48 {
t.Fatalf("configured tool limits missing: %+v", got.Limits)
}
if runtime.GOOS != "linux" {
if got.Supported || got.Scope != "unsupported" {
t.Fatalf("unsupported platform returned metrics: %+v", got)
+6 -1
View File
@@ -5,5 +5,10 @@ package server
import "time"
func systemMetricsSnapshot(_ *Server) systemMetricsResponse {
return systemMetricsResponse{Scope: "unsupported", Supported: false, Timestamp: time.Now().UTC()}
return systemMetricsResponse{
Scope: "unsupported",
Supported: false,
Timestamp: time.Now().UTC(),
Limits: toolResourceLimits(),
}
}