diff --git a/docs/en-US/tool-execution-governance.md b/docs/en-US/tool-execution-governance.md index 6e4ab5c3..f9e94ec9 100644 --- a/docs/en-US/tool-execution-governance.md +++ b/docs/en-US/tool-execution-governance.md @@ -224,6 +224,10 @@ Expected behavior: Each task has a distinct `runId`. Local commands and detached MCP workers retain ownership through context values. Managed `exec ... &` and Pi background execution return promptly but cannot outlive task cleanup. Unowned background launches are rejected. Cleanup seals process and worker admission, cancels workers, terminates processes and waits for reaping. Interrupt-and-continue retains ownership; SSE disconnection does not end the task. Failed cleanup retains the conversation slot and reports `cleanup_failed`; a 15-second sweep retries it. +Set `CS_CLEANUP_GRACE`, `CS_CLEANUP_KILL`, and `CS_CLEANUP_GUARD` to positive Go durations (for example, `10s`) to tune the graceful exit wait, post-SIGKILL wait, and isolation backend wait. Each defaults to 3 seconds when unset or invalid. + +On Linux, only-zombie process groups count as exited once the direct child has been reaped. With the process group watchdog, if cleanup times out and every surviving member is in uninterruptible sleep (D) with SIGKILL pending, the task reports `cleanup_unconfirmed` after local workers finish. The service log records the run ID and PGID. The kernel delivers the pending signal when the process can exit. The cgroup and Windows Job Object backends still require their own exit verification. + ### Kernel containment and crash recovery - **Linux with a delegated cgroup v2 root:** each task gets a cgroup with process, memory and optional CPU limits. Go uses `clone3(CLONE_INTO_CGROUP)` to assign membership at creation. A separate guardian uses `cgroup.kill` on owner pipe EOF and checks `populated=0`. Startup exclusively locks the delegated root and recovers stale task groups. `setsid` does not escape this scope. diff --git a/docs/zh-CN/tool-execution-governance.md b/docs/zh-CN/tool-execution-governance.md index df08afb3..dc68c972 100644 --- a/docs/zh-CN/tool-execution-governance.md +++ b/docs/zh-CN/tool-execution-governance.md @@ -228,9 +228,11 @@ PY - `exec ... &` 与 Pi 后台执行立即返回,但仍属于本轮任务;无任务归属的后台启动被拒绝。前台工具退出时清理遗留子进程,跨工具调用运行的任务应使用显式后台入口。 - 完成、失败、超时收尾、用户停止、服务正常关闭都会封闭启动入口、取消 worker、终止进程并等待回收。“中断并继续”保留本轮归属。 -- Unix 首先给进程组 3 秒退出宽限期,再强制终止并验证;内核隔离、守护进程退出与 worker 收尾各有有界等待。清理期间仍占用本轮任务;失败保留 `cleanup_failed`、进程组/worker ID,每 15 秒巡检重试。 +- Unix 先等待进程组主动退出,再强制终止并验证。环境变量 `CS_CLEANUP_GRACE`、`CS_CLEANUP_KILL`、`CS_CLEANUP_GUARD` 分别控制主动退出、SIGKILL 后回收和隔离后端的等待时间,接受正的 Go duration(例如 `10s`),未配置或无效时各用 3 秒。普通清理失败保留 `cleanup_failed` 和进程组/worker ID,每 15 秒巡检重试。 - 工具 worker 的登记与任务关闭互斥;即使 MCP 使用 `WithoutCancel`,任务也会等待其退出。旧轮次的延迟回调无法接管新轮次的进程或提交新 worker。 +Linux 上,直接子进程回收后,只剩僵尸进程的组视为已退出。使用进程组 watchdog 时,若清理超时且组内仍存活的成员均处于 D 态并已有待投递的 SIGKILL,等本地 worker 退出后,任务记为 `cleanup_unconfirmed`。服务日志记录 run ID 和 PGID,进程解除阻塞后由内核处理挂起的信号。cgroup 和 Windows Job Object 仍按后端自身的机制验证清理。 + ### 操作系统隔离和崩溃回收 | 平台 | 实现 | 崩溃回收与限制 | diff --git a/internal/handler/agent.go b/internal/handler/agent.go index 22c6ee37..f6206b0e 100644 --- a/internal/handler/agent.go +++ b/internal/handler/agent.go @@ -1725,7 +1725,9 @@ func (h *AgentHandler) CancelAgentLoop(c *gin.Context) { h.cancelRunningMCPToolsForConversation(req.ConversationID) h.tasks.AbortActiveAgentExecute(req.ConversationID, "") ok, err := h.tasks.CancelTask(req.ConversationID, cause) - if err != nil { + if errors.Is(err, security.ErrCleanupUnconfirmed) { + msg = taskCleanupMessage(err) + } else if err != nil { h.logger.Error("取消任务失败", zap.Error(err)) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return diff --git a/internal/handler/task_lifecycle.go b/internal/handler/task_lifecycle.go index e9987f73..2b7b31f6 100644 --- a/internal/handler/task_lifecycle.go +++ b/internal/handler/task_lifecycle.go @@ -1,11 +1,15 @@ package handler import ( - "cyberstrike-ai/internal/runlease" "errors" + "fmt" + "net/http" + + "cyberstrike-ai/internal/runlease" + "cyberstrike-ai/internal/security" + "github.com/gin-gonic/gin" "go.uber.org/zap" - "net/http" ) // ShutdownTasks stops local work before shared MCP clients and databases close. @@ -31,7 +35,8 @@ func (h *AgentHandler) taskFinishingEventSender(send func(string, string, interf if h.logger != nil { h.logger.Warn(taskCleanupMessage(err), zap.String("runId", runID), zap.Error(err)) } - send("error", taskCleanupMessage(err)+": "+err.Error(), map[string]interface{}{"errorType": taskCleanupStatus(err)}) + event := taskCleanupEvent(err) + send(event.Type, event.Message, event.Data) data = map[string]interface{}{"conversationId": conversationID, "runId": runID, "status": taskCleanupStatus(err), "cleanupError": err.Error()} } else { payload := map[string]interface{}{} @@ -67,15 +72,46 @@ func (h *AgentHandler) taskFinishingJSONResponder(c *gin.Context, conversationID } } +// A cleanup failure that can still resolve on retry takes precedence over +// an unconfirmed outcome. Preserve the details of both for diagnostics. +func taskCleanupResult(processErr, workerErr error) error { + localUnconfirmed := errors.Is(processErr, security.ErrCleanupUnconfirmed) + remoteUnconfirmed := errors.Is(workerErr, runlease.ErrUnconfirmed) + switch { + case processErr != nil && !localUnconfirmed && remoteUnconfirmed: + return fmt.Errorf("local cleanup: %w, remote state: %v", processErr, workerErr) + case localUnconfirmed && workerErr != nil && !remoteUnconfirmed: + return fmt.Errorf("local cleanup: %v, worker cleanup: %w", processErr, workerErr) + default: + return errors.Join(processErr, workerErr) + } +} + func taskCleanupStatus(err error) string { - if errors.Is(err, runlease.ErrUnconfirmed) { + if errors.Is(err, security.ErrCleanupUnconfirmed) || errors.Is(err, runlease.ErrUnconfirmed) { return "cleanup_unconfirmed" } return "cleanup_failed" } + func taskCleanupMessage(err error) string { - if errors.Is(err, runlease.ErrUnconfirmed) { + switch { + case errors.Is(err, security.ErrCleanupUnconfirmed) && errors.Is(err, runlease.ErrUnconfirmed): + return "本地残留进程处于不可中断状态,远端 MCP 停止状态待确认" + case errors.Is(err, security.ErrCleanupUnconfirmed): + return "本地残留进程处于不可中断状态,待主机解除阻塞后回收" + case errors.Is(err, runlease.ErrUnconfirmed): return "本地执行已结束,远端 MCP 停止状态待确认" + default: + return "任务资源清理失败,将自动重试" } - return "任务资源清理失败,将自动重试" +} + +func taskCleanupEvent(err error) StreamEvent { + status := taskCleanupStatus(err) + kind := "error" + if status == "cleanup_unconfirmed" { + kind = "warning" + } + return StreamEvent{Type: kind, Message: taskCleanupMessage(err) + ": " + err.Error(), Data: map[string]interface{}{"errorType": status}} } diff --git a/internal/handler/task_manager.go b/internal/handler/task_manager.go index 12b27d9d..565dc982 100644 --- a/internal/handler/task_manager.go +++ b/internal/handler/task_manager.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "sort" "strings" "sync" @@ -29,6 +28,11 @@ func shouldPersistAgentAgentTraceAfterRunError(baseCtx context.Context) bool { return true } +type taskCleanupAttempt struct { + done chan struct{} + err error +} + // AgentTask 描述正在运行的Agent任务 type AgentTask struct { RunID string `json:"runId"` @@ -36,7 +40,7 @@ type AgentTask struct { processes *security.ProcessScope workers *runlease.Scope IsolationBackend string `json:"isolationBackend,omitempty"` - finishing chan struct{} + finishing *taskCleanupAttempt stopping chan struct{} cancelRequested bool finalStatus string @@ -630,22 +634,16 @@ func (m *AgentTaskManager) FinishTaskRun(conversationID, runID, finalStatus stri } } if task.finishing != nil { - done := task.finishing + attempt := task.finishing m.mu.Unlock() - <-done - m.mu.RLock() - cleanupError := task.CleanupError - m.mu.RUnlock() - if cleanupError != "" { - return errors.New(cleanupError) - } - return nil + <-attempt.done + return attempt.err } if task.cancelRequested { finalStatus = "cancelled" } - done := make(chan struct{}) - task.finishing = done + attempt := &taskCleanupAttempt{done: make(chan struct{})} + task.finishing = attempt task.finalStatus = finalStatus task.Status = "cleaning" task.processes.Seal() @@ -671,14 +669,8 @@ func (m *AgentTaskManager) FinishTaskRun(conversationID, runID, finalStatus stri waitCtx, waitCancel := context.WithTimeout(context.Background(), 3*time.Second) workerErr := task.workers.Wait(waitCtx) waitCancel() - cleanupErr := errors.Join(processErr, workerErr) - if processErr != nil && errors.Is(workerErr, runlease.ErrUnconfirmed) { - // A simultaneous local failure must not be labelled as local completion. - cleanupErr = fmt.Errorf("local cleanup: %w; remote state: %v", processErr, workerErr) - } - // The local worker has returned, but remote notification cancellation is - // not an acknowledgement. Preserve an actionable history/tool status. - unconfirmed := processErr == nil && errors.Is(workerErr, runlease.ErrUnconfirmed) + cleanupErr := taskCleanupResult(processErr, workerErr) + unconfirmed := taskCleanupStatus(cleanupErr) == "cleanup_unconfirmed" if unconfirmed { finalStatus = "cleanup_unconfirmed" } @@ -687,15 +679,22 @@ func (m *AgentTaskManager) FinishTaskRun(conversationID, runID, finalStatus stri cleanupMessage = cleanupErr.Error() } if (cleanupErr == nil || unconfirmed) && bus != nil { - // Subscribers must receive completion only after local processes are reaped. - payload, _ := json.Marshal(StreamEvent{Type: "done", Data: map[string]interface{}{"conversationId": conversationID, "runId": runID, "status": finalStatus, "cleanupError": cleanupMessage}}) - bus.Publish(conversationID, append(append([]byte("data: "), payload...), '\n', '\n')) + // Publish the verified result or the explicit cleanup uncertainty. + publish := func(event StreamEvent) { + payload, _ := json.Marshal(event) + bus.Publish(conversationID, append(append([]byte("data: "), payload...), '\n', '\n')) + } + if unconfirmed { + publish(taskCleanupEvent(cleanupErr)) + } + publish(StreamEvent{Type: "done", Data: map[string]interface{}{"conversationId": conversationID, "runId": runID, "status": finalStatus, "cleanupError": cleanupMessage}}) bus.CloseConversation(conversationID) } m.mu.Lock() defer m.mu.Unlock() - defer close(done) + defer close(attempt.done) + attempt.err = cleanupErr if cleanupErr != nil && !unconfirmed { task.Status = "cleanup_failed" task.CleanupError = cleanupErr.Error() diff --git a/internal/handler/task_process_cleanup_test.go b/internal/handler/task_process_cleanup_test.go index f758edd2..5b7b4531 100644 --- a/internal/handler/task_process_cleanup_test.go +++ b/internal/handler/task_process_cleanup_test.go @@ -5,6 +5,7 @@ import ( "errors" "os/exec" "runtime" + "strings" "sync" "testing" "time" @@ -117,6 +118,9 @@ func TestTaskCleanupFailureRetainsOwnershipAndRetries(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("Unix shell") } + t.Setenv("CS_CLEANUP_GRACE", "25ms") + t.Setenv("CS_CLEANUP_KILL", "50ms") + t.Setenv("CS_CLEANUP_GUARD", "50ms") manager := NewAgentTaskManager() task, _ := manager.StartTask("conv", "job", nil) ctx := manager.BindProcessScope(context.Background(), "conv", task.RunID) @@ -201,6 +205,9 @@ func TestTaskWaitsForDetachedMCPWorker(t *testing.T) { func TestTaskReportsUnconfirmedRemoteCleanup(t *testing.T) { manager := NewAgentTaskManager() defer manager.Shutdown() + bus := NewTaskEventBus() + manager.SetTaskEventBus(bus) + _, events := bus.Subscribe("conv") task, _ := manager.StartTask("conv", "job", nil) ctx := manager.BindProcessScope(context.Background(), "conv", task.RunID) service := mcp.NewExecutionService(nil, nil) @@ -222,4 +229,39 @@ func TestTaskReportsUnconfirmedRemoteCleanup(t *testing.T) { if len(history) != 1 || history[0].Status != "cleanup_unconfirmed" || history[0].CleanupError == "" { t.Fatalf("missing retained warning: %+v", history) } + if warning, ok := <-events; !ok || !strings.Contains(string(warning), `"type":"warning"`) { + t.Fatalf("missing cleanup warning for SSE subscribers: %s", warning) + } + if done, ok := <-events; !ok || !strings.Contains(string(done), `"status":"cleanup_unconfirmed"`) { + t.Fatalf("missing cleanup status for SSE subscribers: %s", done) + } +} + +func TestTaskCleanupDistinguishesLocalAndRemoteUncertainty(t *testing.T) { + retryErr := context.DeadlineExceeded + for _, tc := range []struct { + name string + localErr error + workerErr error + wantStatus string + wantKind string + wantText string + }{ + {"local D state", security.ErrCleanupUnconfirmed, nil, "cleanup_unconfirmed", "warning", "本地残留进程"}, + {"remote MCP", nil, runlease.ErrUnconfirmed, "cleanup_unconfirmed", "warning", "远端 MCP"}, + {"local and remote", security.ErrCleanupUnconfirmed, runlease.ErrUnconfirmed, "cleanup_unconfirmed", "warning", "本地残留进程处于不可中断状态,远端 MCP"}, + {"worker still running", security.ErrCleanupUnconfirmed, retryErr, "cleanup_failed", "error", "将自动重试"}, + {"local cleanup failed", retryErr, runlease.ErrUnconfirmed, "cleanup_failed", "error", "将自动重试"}, + } { + t.Run(tc.name, func(t *testing.T) { + got := taskCleanupResult(tc.localErr, tc.workerErr) + event := taskCleanupEvent(got) + if taskCleanupStatus(got) != tc.wantStatus || event.Type != tc.wantKind || !strings.Contains(event.Message, tc.wantText) { + t.Fatalf("unexpected cleanup event: %+v", event) + } + if tc.wantStatus == "cleanup_failed" && !errors.Is(got, retryErr) { + t.Fatalf("retryable failure lost its cause: %v", got) + } + }) + } } diff --git a/internal/processguard/group_unix.go b/internal/processguard/group_unix.go index baa6afc3..efa9e7cd 100644 --- a/internal/processguard/group_unix.go +++ b/internal/processguard/group_unix.go @@ -107,19 +107,31 @@ func (g *unixGroup) Release(pid int) error { } func (g *unixGroup) Close(ctx context.Context) error { g.mu.Lock() - defer g.mu.Unlock() g.closed = true + pending := make([]int, 0, len(g.pids)) for pid := range g.pids { _ = syscall.Kill(-pid, syscall.SIGKILL) + pending = append(pending, pid) } - for { - for pid := range g.pids { - if syscall.Kill(-pid, 0) == syscall.ESRCH { - delete(g.pids, pid) + g.mu.Unlock() + for len(pending) != 0 { + remaining := pending[:0] + for _, pid := range pending { + g.mu.Lock() + _, owned := g.pids[pid] + g.mu.Unlock() + if !owned { + continue + } + if ProcessGroupExists(pid) { + remaining = append(remaining, pid) + } else if err := g.Release(pid); err != nil { + return err } } - if len(g.pids) == 0 { - return g.watcher.close() + pending = remaining + if len(pending) == 0 { + break } select { case <-ctx.Done(): @@ -127,6 +139,7 @@ func (g *unixGroup) Close(ctx context.Context) error { case <-time.After(10 * time.Millisecond): } } + return g.watcher.close() } func gatedChildMain(args []string) error { if len(args) != 2 { diff --git a/internal/processguard/proc_group_linux.go b/internal/processguard/proc_group_linux.go new file mode 100644 index 00000000..11c0e51c --- /dev/null +++ b/internal/processguard/proc_group_linux.go @@ -0,0 +1,130 @@ +package processguard + +import ( + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" +) + +type processStat struct { + group int + state byte + threads int +} + +func readProcessStat(dir string) (processStat, bool, error) { + data, err := os.ReadFile(filepath.Join(dir, "stat")) + if err != nil { + return processStat{}, false, err + } + // comm can contain spaces, parentheses and even newlines. + stat := string(data) + end := strings.LastIndexByte(stat, ')') + if end < 0 { + return processStat{}, false, nil + } + fields := strings.Fields(stat[end+1:]) + if len(fields) <= 17 || len(fields[0]) != 1 { + return processStat{}, false, nil + } + group, groupErr := strconv.Atoi(fields[2]) // field 5: pgrp + threads, threadErr := strconv.Atoi(fields[17]) // field 20: num_threads + return processStat{group, fields[0][0], threads}, groupErr == nil && threadErr == nil, nil +} + +func (p processStat) zombie() bool { + // A zombie thread-group leader can still have live sibling threads. + return p.state == 'Z' && p.threads == 1 +} + +func visitProcessGroup(root string, pgid int, visit func(int, string, processStat) bool) bool { + entries, err := os.ReadDir(root) + if err != nil { + return false + } + found := false + for _, entry := range entries { + pid, err := strconv.Atoi(entry.Name()) + if err != nil || pid <= 0 || !entry.IsDir() { + continue + } + dir := filepath.Join(root, entry.Name()) + stat, ok, err := readProcessStat(dir) + if errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ESRCH) { + continue // the process exited during the scan + } + if err != nil || !ok { + return false + } + if stat.group == pgid { + found = true + if !visit(pid, dir, stat) { + return false + } + } + } + return found +} + +func localProcFS() bool { + // A procfs mounted for another PID namespace reports different IDs. + self, err := os.Readlink("/proc/self") + return err == nil && self == strconv.Itoa(os.Getpid()) +} + +func processGroupOnlyZombies(pgid int) bool { + if !localProcFS() { + return false + } + // The group leader is usually still present while the guard polls. + stat, ok, _ := readProcessStat(filepath.Join("/proc", strconv.Itoa(pgid))) + if ok && stat.group == pgid && !stat.zombie() { + return false + } + return visitProcessGroup("/proc", pgid, func(_ int, _ string, stat processStat) bool { + return stat.zombie() + }) +} + +// ProcessGroupKillPending confirms all remaining live members are in D state +// with SIGKILL pending. An unreaped direct child must itself be blocked. +func ProcessGroupKillPending(pgid int, rootWaited bool) bool { + return localProcFS() && processGroupKillPending("/proc", pgid, rootWaited) +} + +func processGroupKillPending(root string, pgid int, rootWaited bool) bool { + blocked, rootBlocked := false, false + allExitedOrBlocked := visitProcessGroup(root, pgid, func(pid int, dir string, stat processStat) bool { + if stat.zombie() { + return true + } + if stat.state != 'D' || !hasPendingSIGKILL(dir) { + return false + } + blocked = true + rootBlocked = rootBlocked || pid == pgid + return true + }) + return allExitedOrBlocked && blocked && (rootWaited || rootBlocked) +} + +func hasPendingSIGKILL(dir string) bool { + data, err := os.ReadFile(filepath.Join(dir, "status")) + if err != nil { + return false + } + for line := range strings.SplitSeq(string(data), "\n") { + name, value, _ := strings.Cut(line, ":") + if name != "SigPnd" && name != "ShdPnd" { + continue + } + mask, err := strconv.ParseUint(strings.TrimSpace(value), 16, 64) + if err == nil && mask&(1<<(syscall.SIGKILL-1)) != 0 { + return true + } + } + return false +} diff --git a/internal/processguard/proc_group_linux_test.go b/internal/processguard/proc_group_linux_test.go new file mode 100644 index 00000000..8a953af0 --- /dev/null +++ b/internal/processguard/proc_group_linux_test.go @@ -0,0 +1,103 @@ +package processguard + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func TestWatchdogClosesWithZombieOnlyGroup(t *testing.T) { + group, err := newUnixGroup() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { closeTestGroup(t, group) }) + cmd, err := startTestCommand(group, "exit 0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cmd.Wait() }) + pid := cmd.Process.Pid + dir := filepath.Join("/proc", strconv.Itoa(pid)) + deadline := time.Now().Add(time.Second) + for { + stat, ok, err := readProcessStat(dir) + if err != nil { + t.Fatal(err) + } + if ok && stat.zombie() { + break + } + if time.Now().After(deadline) { + t.Fatalf("PID %d did not become a zombie", pid) + } + time.Sleep(5 * time.Millisecond) + } + if syscall.Kill(-pid, 0) != nil { + t.Fatal("fixture did not retain a process group") + } + if ProcessGroupExists(pid) { + t.Fatal("zombie-only group counted as live") + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := group.Close(ctx); err != nil { + t.Fatal(err) + } +} + +func TestProcessGroupKillPending(t *testing.T) { + for _, tc := range []struct { + name string + leader byte + member byte + threads int + signalMask string + rootWaited bool + want bool + }{ + {"blocked descendant", 'Z', 'D', 1, "00000100", true, true}, + {"blocked leader", 'D', 'Z', 1, "00000100", false, true}, + {"direct child not waited", 'Z', 'D', 1, "00000100", false, false}, + {"zombie leader has live threads", 'Z', 'D', 2, "00000100", true, false}, + {"stopped process", 'Z', 'T', 1, "00000100", true, false}, + {"sleeping process", 'Z', 'S', 1, "00000100", true, false}, + {"zombies only", 'Z', 'Z', 1, "00000100", true, false}, + {"different pending signal", 'Z', 'D', 1, "00004000", true, false}, + {"status unavailable", 'Z', 'D', 1, "", true, false}, + } { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + writeProcFixture(t, root, 100, 100, tc.leader, tc.threads, tc.signalMask) + writeProcFixture(t, root, 101, 100, tc.member, 1, tc.signalMask) + writeProcFixture(t, root, 200, 200, 'R', 1, "") + if got := processGroupKillPending(root, 100, tc.rootWaited); got != tc.want { + t.Errorf("processGroupKillPending = %v, want %v", got, tc.want) + } + }) + } +} + +func writeProcFixture(t *testing.T, root string, pid, pgid int, state byte, threads int, signalMask string) { + t.Helper() + dir := filepath.Join(root, strconv.Itoa(pid)) + if err := os.Mkdir(dir, 0700); err != nil { + t.Fatal(err) + } + stat := fmt.Sprintf("%d (command ) with newline\n) %c 1 %d%s %d 0\n", pid, state, pgid, strings.Repeat(" 0", 14), threads) + if err := os.WriteFile(filepath.Join(dir, "stat"), []byte(stat), 0600); err != nil { + t.Fatal(err) + } + if signalMask != "" { + status := "SigPnd:\t00000000\nShdPnd:\t" + signalMask + "\n" + if err := os.WriteFile(filepath.Join(dir, "status"), []byte(status), 0600); err != nil { + t.Fatal(err) + } + } +} diff --git a/internal/processguard/proc_group_other.go b/internal/processguard/proc_group_other.go new file mode 100644 index 00000000..b73e4a6f --- /dev/null +++ b/internal/processguard/proc_group_other.go @@ -0,0 +1,8 @@ +//go:build !linux + +package processguard + +func processGroupOnlyZombies(pgid int) bool { return false } + +// ProcessGroupKillPending is supported only with Linux procfs. +func ProcessGroupKillPending(pgid int, rootWaited bool) bool { return false } diff --git a/internal/processguard/proc_group_unix.go b/internal/processguard/proc_group_unix.go new file mode 100644 index 00000000..1bedfdeb --- /dev/null +++ b/internal/processguard/proc_group_unix.go @@ -0,0 +1,20 @@ +//go:build !windows + +package processguard + +import "syscall" + +// ProcessGroupExists reports whether the group can still have running members. +func ProcessGroupExists(pgid int) bool { + if pgid <= 0 { + return false + } + switch syscall.Kill(-pgid, 0) { + case syscall.ESRCH: + return false + case nil: + return !processGroupOnlyZombies(pgid) + default: + return true + } +} diff --git a/internal/security/procattr_unix.go b/internal/security/procattr_unix.go index 9969a2c4..ae8fc465 100644 --- a/internal/security/procattr_unix.go +++ b/internal/security/procattr_unix.go @@ -5,6 +5,8 @@ package security import ( "os/exec" "syscall" + + "cyberstrike-ai/internal/processguard" ) // prepareShellCmdSession 让 shell 子进程在独立会话中运行,便于超时/取消时整组 SIGKILL(含子进程)。 @@ -48,5 +50,5 @@ func stopProcessGroup(pid int, cmd *exec.Cmd) { } func processGroupExists(pid int) bool { - return pid > 0 && syscall.Kill(-pid, 0) != syscall.ESRCH + return processguard.ProcessGroupExists(pid) } diff --git a/internal/security/process_scope.go b/internal/security/process_scope.go index 48a7ca2c..f86ea3cc 100644 --- a/internal/security/process_scope.go +++ b/internal/security/process_scope.go @@ -4,7 +4,10 @@ import ( "context" "errors" "fmt" + "log/slog" + "os" "os/exec" + "sort" "sync" "time" @@ -15,6 +18,16 @@ import ( var ErrProcessScopeClosed = errors.New("task is ending; new processes are not allowed") var ErrBackgroundNeedsTask = errors.New("background commands require a managed task") +// ErrCleanupUnconfirmed means SIGKILL is pending on processes blocked in the kernel. +var ErrCleanupUnconfirmed = errors.New("local cleanup unconfirmed: processes in uninterruptible sleep (D) with SIGKILL pending") + +func cleanupDuration(name string) time.Duration { + if value, err := time.ParseDuration(os.Getenv(name)); err == nil && value > 0 { + return value + } + return 3 * time.Second +} + type processScopeKey struct{} // ProcessScope owns local commands for one task run, including background work. @@ -22,17 +35,27 @@ type processScopeKey struct{} // Start and Seal serialize under the same lock: no process can escape cleanup // by starting between the final snapshot and task completion. type ProcessScope struct { - ID string - mu sync.Mutex - closed bool - sessions map[*ShellSession]struct{} - guard processguard.Group - guardErr error - closeMu sync.Mutex + ID string + mu sync.Mutex + closed bool + sessions map[*ShellSession]struct{} + guard processguard.Group + guardErr error + closeMu sync.Mutex + blockedGroups []int // protected by closeMu + graceTimeout time.Duration + killTimeout time.Duration + guardTimeout time.Duration } func NewProcessScope() *ProcessScope { - return &ProcessScope{ID: uuid.NewString(), sessions: make(map[*ShellSession]struct{})} + return &ProcessScope{ + ID: uuid.NewString(), + sessions: make(map[*ShellSession]struct{}), + graceTimeout: cleanupDuration("CS_CLEANUP_GRACE"), + killTimeout: cleanupDuration("CS_CLEANUP_KILL"), + guardTimeout: cleanupDuration("CS_CLEANUP_GUARD"), + } } func WithProcessScope(ctx context.Context, scope *ProcessScope) context.Context { @@ -128,28 +151,57 @@ func (s *ProcessScope) Close() error { } s.mu.Unlock() if len(sessions) == 0 { - return s.closeGuard() + return s.cleanupResult(s.closeGuard()) } for _, session := range sessions { session.signal(false) } - if waitShellSessions(sessions, 3*time.Second) { - return s.closeGuard() + if waitShellSessions(sessions, s.graceTimeout) { + return s.cleanupResult(s.closeGuard()) } for _, session := range sessions { session.Terminate() } guardErr := s.closeGuard() - if waitShellSessions(sessions, 3*time.Second) { + waitShellSessions(sessions, s.killTimeout) + + // Only the watchdog backend is covered by the process group scan. A + // cgroup or Job Object can contain members outside the original group. + watchdogTimedOut := errors.Is(guardErr, context.DeadlineExceeded) && + s.IsolationBackend() == "process_group_watchdog" + var remaining []int + var releaseErr error + for _, session := range sessions { + if session.tryComplete() { + continue + } + if watchdogTimedOut { + deferred, err := session.deferKernelCleanup() + if deferred { + s.blockedGroups = append(s.blockedGroups, session.rootPID) + slog.Warn("Task process cleanup unconfirmed", "runId", s.ID, "pgid", session.rootPID) + continue + } + releaseErr = errors.Join(releaseErr, err) + } + remaining = append(remaining, session.rootPID) + } + if len(remaining) == 0 { + if watchdogTimedOut { + guardErr = s.closeGuard() + } + return s.cleanupResult(guardErr) + } + sort.Ints(remaining) + return errors.Join(fmt.Errorf("task %s: process cleanup timed out (process groups %v)", s.ID, remaining), guardErr, releaseErr) +} + +func (s *ProcessScope) cleanupResult(guardErr error) error { + if guardErr != nil || len(s.blockedGroups) == 0 { return guardErr } - remaining := make([]int, 0, len(sessions)) - for _, session := range sessions { - if !session.tryComplete() { - remaining = append(remaining, session.rootPID) - } - } - return fmt.Errorf("task %s: process cleanup timed out (process groups %v)", s.ID, remaining) + sort.Ints(s.blockedGroups) + return fmt.Errorf("task %s: %w (process groups %v)", s.ID, ErrCleanupUnconfirmed, s.blockedGroups) } func waitShellSessions(sessions []*ShellSession, timeout time.Duration) bool { @@ -199,7 +251,7 @@ func (s *ProcessScope) closeGuard() error { if s.guard == nil { return nil } - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), s.guardTimeout) defer cancel() return s.guard.Close(ctx) } diff --git a/internal/security/process_scope_test.go b/internal/security/process_scope_test.go index 16db0df7..ba526af2 100644 --- a/internal/security/process_scope_test.go +++ b/internal/security/process_scope_test.go @@ -194,3 +194,19 @@ func TestProcessScope_ForegroundExitKillsLeftoverChild(t *testing.T) { } requireProcessGone(t, pid) } + +func TestProcessScopeCleanupTimeoutConfiguration(t *testing.T) { + t.Setenv("CS_CLEANUP_GRACE", "125ms") + t.Setenv("CS_CLEANUP_KILL", "8s") + t.Setenv("CS_CLEANUP_GUARD", "10s") + scope := NewProcessScope() + if scope.graceTimeout != 125*time.Millisecond || scope.killTimeout != 8*time.Second || scope.guardTimeout != 10*time.Second { + t.Fatalf("unexpected cleanup waits: %v, %v, %v", scope.graceTimeout, scope.killTimeout, scope.guardTimeout) + } + for _, value := range []string{"", "invalid", "0s", "-1s"} { + t.Setenv("CS_CLEANUP_GRACE", value) + if got := NewProcessScope().graceTimeout; got != 3*time.Second { + t.Errorf("grace = %v with %q, want 3s", got, value) + } + } +} diff --git a/internal/security/shell_session.go b/internal/security/shell_session.go index a01b50c8..50a746e7 100644 --- a/internal/security/shell_session.go +++ b/internal/security/shell_session.go @@ -5,20 +5,23 @@ import ( "os/exec" "sync" "time" + + "cyberstrike-ai/internal/processguard" ) // ShellSession caches the process group while its command is alive. Signals // and Wait completion synchronize to avoid signalling already-released sessions. type ShellSession struct { - Cmd *exec.Cmd - rootPID int - scope *ProcessScope - done chan struct{} - waitOnce sync.Once - waitErr error - signalMu sync.Mutex - finished bool - waited bool + Cmd *exec.Cmd + rootPID int + scope *ProcessScope + done chan struct{} + waitOnce sync.Once + waitErr error + signalMu sync.Mutex + finished bool + waited bool + killPending bool } func StartShellSession(cmd *exec.Cmd) (*ShellSession, error) { @@ -37,7 +40,9 @@ func (s *ShellSession) Wait() error { s.waitErr = s.Cmd.Wait() s.signalMu.Lock() s.waited = true - terminateProcessGroup(s.rootPID, s.Cmd) + if !s.killPending { + terminateProcessGroup(s.rootPID, s.Cmd) + } s.signalMu.Unlock() // Usually the group disappears immediately. Retain ownership if the // kernel cannot confirm exit; task cleanup will retry and report it. @@ -55,7 +60,7 @@ func (s *ShellSession) signal(force bool) { } s.signalMu.Lock() defer s.signalMu.Unlock() - if s.finished { + if s.finished || s.killPending { return } if force { @@ -81,11 +86,11 @@ func (s *ShellSession) tryComplete() bool { if s.finished { return true } - if !s.waited || processGroupExists(s.rootPID) { + if !s.waited || (!s.killPending && processGroupExists(s.rootPID)) { return false } s.finished = true - if s.scope != nil { + if s.scope != nil && !s.killPending { s.scope.mu.Lock() if s.scope.guard != nil { if err := s.scope.guard.Release(s.rootPID); err != nil { @@ -100,3 +105,21 @@ func (s *ShellSession) tryComplete() bool { close(s.done) return true } + +// deferKernelCleanup relinquishes the PGID once the kernel has queued SIGKILL +// for every surviving member. Wait still reaps the direct child as it exits. +func (s *ShellSession) deferKernelCleanup() (bool, error) { + s.signalMu.Lock() + defer s.signalMu.Unlock() + if s.finished || !processguard.ProcessGroupKillPending(s.rootPID, s.waited) { + return false, nil + } + s.scope.mu.Lock() + defer s.scope.mu.Unlock() + if err := s.scope.guard.Release(s.rootPID); err != nil { + return false, err + } + s.killPending = true + delete(s.scope.sessions, s) + return true, nil +}