diff --git a/README.md b/README.md index 1830e4d..fe16109 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,8 @@ kopsc disk usage /var --depth 2 # 下钻一层(du -x --max-depth=2 -h | s kopsc disk usage --path /var # 同上,用命名参数指定路径 kopsc disk usage /var --dry-run # 预览(内置命令同样支持) kopsc proc nohup ./server # 后台运行命令,输出写日志(等价 nohup ./server > server.out 2>&1 &) +kopsc proc wait nginx # 每秒检查一次,等 nginx 退出后再继续 +kopsc proc wait java app.jar --timeout 60 # 多个关键字逻辑与;最多等 60 秒 kopsc list # 全部命令及当前平台可用性 kopsc explain docker.clearsafe # 匹配过程、全部候选及各自被选中/拒绝的原因 @@ -136,7 +138,7 @@ kopsc 的命令按用途分组,每组的完整说明(命令表、选项、 | **net** | 网络与端口:端口被谁占用、本机监听了哪些端口 | [README.net.md](README.net.md) | | **disk** | 磁盘与文件占用:哪个目录、哪个文件最占空间 | [README.disk.md](README.disk.md) | | **diagnose** | 容器 / Pod 状态根因诊断(自动识别 Docker 与 K8s) | [README.diagnose.md](README.diagnose.md) | -| **proc** | 本机进程:后台运行命令并写日志 | [README.proc.md](README.proc.md) | +| **proc** | 本机进程:后台运行命令并写日志、等待进程退出 | [README.proc.md](README.proc.md) | | **pkg** | 系统软件包:刷新包管理器索引 | [README.pkg.md](README.pkg.md) | 辅助命令(不涉及具体资源,直接用即可): @@ -161,6 +163,7 @@ kopsc 的命令按用途分组,每组的完整说明(命令表、选项、 | 查磁盘占用 | `kopsc disk usage`、`kopsc disk usage /var --depth 2` | | 排障 | `kopsc diagnose web` | | 后台跑服务 | `kopsc proc nohup ./server` | +| 等进程退出 | `kopsc proc wait nginx`、`kopsc proc wait --pid 1234 --timeout 30` | | 刷新软件源 | `kopsc pkg refreshindex` | ## 平台识别 diff --git a/README.proc.md b/README.proc.md index 12ca7d1..03453b2 100644 --- a/README.proc.md +++ b/README.proc.md @@ -2,10 +2,11 @@ > 返回 [README.md](README.md) -在后台运行命令并写日志,关掉终端也不会退出。 +在后台运行命令并写日志,关掉终端也不会退出;也可以等某个进程退出后再继续。 ```bash kopsc proc nohup ./server # 后台运行命令,输出写日志 +kopsc proc wait nginx # 等 nginx 退出后返回 ``` ## 后台运行(proc.nohup) @@ -38,3 +39,50 @@ kopsc proc nohup --dry-run ./server # 只打印判定依 | `-q`, `--quiet` | 不打印启动摘要(PID、日志路径) | | `-w`, `--wait` | 前台等待命令退出,回显其写入的日志内容并透传退出码 | | `--detach` / `--no-detach` | 默认脱离会话;`--no-detach` 保留当前会话(类似只加 `&`) | + +## 等待进程退出(proc.wait) + +`kopsc proc wait <关键字>... [--pid PID]...` 每秒检查一次目标进程是否还在: +存在就继续等,直到它消失为止。适合在脚本里等一个服务真正停下来, +替代 `while pgrep nginx; do sleep 1; done` 这类写法。 + +```bash +kopsc proc wait nginx # 等所有名字/命令行含 nginx 的进程退出 +kopsc proc wait nginx worker # 关键字逻辑与:两个都命中才算目标 +kopsc proc wait --pid 1234 # 等指定 PID 退出 +kopsc proc wait --pid 1234,5678 # 多个 PID(逗号分隔) +kopsc proc wait nginx --timeout 30 # 最多等 30 秒 +kopsc proc wait nginx --once # 只检查一次,不等待 +kopsc proc wait nginx --interval 500ms -q # 每 0.5 秒查一次,不打印进度 +``` + +### 匹配规则 + +- 关键字在**进程名与完整命令行**中匹配,忽略大小写: + `kopsc proc wait nginx` 能命中 `/usr/sbin/nginx -g daemon off;`。 +- 给多个关键字时是**逻辑与**:全部命中才算目标进程。 + 例如 `kopsc proc wait java myapp.jar` 只等「既是 java 进程、命令行里又含 myapp.jar」的那些。 +- `--pid` 与关键字可以同时给:任一方仍有进程存在,就继续等待。 +- Windows 的 `tasklist` 不提供命令行,关键字只能匹配进程名(如 `nginx.exe`)。 + +### 退出码 + +| 退出码 | 含义 | +| --- | --- | +| `0` | 目标进程已全部退出;或启动时本来就没有匹配的进程 | +| `2` | `--timeout` 到期时进程仍在运行,错误信息会列出残留的 PID | +| `1` | 参数错误,或无法列出进程(例如没有权限) | + +### 选项 + +| 选项 | 说明 | +| --- | --- | +| `<关键字>...` | 要等待的进程关键字,可多个(逻辑与) | +| `--pid`, `-p` | 直接指定进程 ID;可写多次或用逗号分隔,如 `--pid 1234,5678` | +| `--timeout` | 最长等待时间,默认不超时;可写 `30`(秒)或 `30s`、`1m` | +| `--interval` | 检查间隔,默认 1 秒 | +| `--once` | 只检查一次并打印结果,不等待 | +| `-q`, `--quiet` | 不打印进度与结束提示 | + +> 关键字请直接作为参数书写;若关键字以 `-` 开头,用 `--` 分隔,例如 `kopsc proc wait -- -weird`。 +> `--dry-run` 只打印判定依据,不会去查询进程。 diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 3ef47aa..8361a95 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -903,3 +903,34 @@ func TestExplainHelpDocumentsWaysAndExitCodes(t *testing.T) { } } } + +func TestProcWaitRequiresTargetThroughCLI(t *testing.T) { + app, _, stderr := testApp(centos("docker")) + // No keywords and no --pid: kopsc must explain what to type. + if code := app.Execute([]string{"proc", "wait"}); code == 0 { + t.Fatal("expected a non-zero exit code without a target") + } + if !strings.Contains(stderr.String(), "缺少要等待的进程") { + t.Errorf("stderr = %s", stderr.String()) + } +} + +func TestProcWaitRejectsBadPIDThroughCLI(t *testing.T) { + app, _, stderr := testApp(centos("docker")) + if code := app.Execute([]string{"proc", "wait", "--pid", "abc"}); code == 0 { + t.Fatal("expected a non-zero exit code for a bad PID") + } + if !strings.Contains(stderr.String(), "--pid 需要正整数") { + t.Errorf("stderr = %s", stderr.String()) + } +} + +func TestProcWaitDryRunDoesNotPoll(t *testing.T) { + app, stdout, stderr := testApp(centos("docker")) + if code := app.Execute([]string{"proc", "wait", "--dry-run", "nginx"}); code != 0 { + t.Fatalf("exit code = %d, stderr=%s", code, stderr.String()) + } + if !strings.Contains(stdout.String(), "[dry-run]") { + t.Errorf("dry-run output = %q", stdout.String()) + } +} diff --git a/internal/executor/builtin.go b/internal/executor/builtin.go index 0be44b0..8b3c408 100644 --- a/internal/executor/builtin.go +++ b/internal/executor/builtin.go @@ -45,6 +45,7 @@ var builtins = map[string]Builtin{ "net.pids": runNetPIDs, "net.ports": runNetPorts, "proc.nohup": runNohup, + "proc.wait": runProcWait, } // runDiagnose bridges the registry builtin to the diagnose package. diff --git a/internal/executor/executor.go b/internal/executor/executor.go index b5ecdf9..a49ce44 100644 --- a/internal/executor/executor.go +++ b/internal/executor/executor.go @@ -196,9 +196,22 @@ type ExitError struct { } func (e *ExitError) Error() string { + // When the error carries its own explanation (for example a timeout that + // lists what is still running), show it instead of the bare status code. + if e.Err != nil { + if msg := e.Err.Error(); msg != "" && !isExitStatus(msg) { + return msg + } + } return fmt.Sprintf("命令以状态码 %d 退出", e.Code) } +// isExitStatus reports whether msg is just an os/exec exit status, which adds +// nothing to kopsc's own wording. +func isExitStatus(msg string) bool { + return strings.HasPrefix(msg, "exit status ") || strings.HasPrefix(msg, "signal: ") +} + func (e *ExitError) Unwrap() error { return e.Err } // ExitCode maps an error to the process exit code kopsc should return. diff --git a/internal/executor/processlist.go b/internal/executor/processlist.go new file mode 100644 index 0000000..546ee4a --- /dev/null +++ b/internal/executor/processlist.go @@ -0,0 +1,178 @@ +package executor + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" +) + +// processInfo is one running process as kopsc sees it. +type processInfo struct { + PID int + Name string // executable name, e.g. "nginx" + Command string // full command line when available +} + +// Matches reports whether the process satisfies every keyword: a keyword hits +// when it appears in the process name or anywhere in its command line. All +// keywords must match (logical AND). +func (p processInfo) Matches(keywords []string) bool { + haystack := strings.ToLower(p.Name + " " + p.Command) + for _, kw := range keywords { + if !strings.Contains(haystack, strings.ToLower(kw)) { + return false + } + } + return true +} + +// processLister is how kopsc enumerates processes. It is a variable so the +// wait command can be tested without depending on the host's ps/proc. +var processLister = listProcesses + +// listProcesses returns every process visible to the current user, using the +// cheapest mechanism the platform offers. +func listProcesses(ctx context.Context) ([]processInfo, error) { + switch runtime.GOOS { + case "linux": + procs, err := listProcessesProc("/proc") + if err == nil { + return procs, nil + } + // A hardened container may hide /proc entries; fall through to ps. + return listProcessesPS(ctx) + case "windows": + return listProcessesTasklist(ctx) + default: + return listProcessesPS(ctx) + } +} + +// listProcessesProc reads /proc//comm and cmdline. Unreadable entries +// (other users' processes, kernel threads) are skipped rather than failing. +func listProcessesProc(procRoot string) ([]processInfo, error) { + entries, err := os.ReadDir(procRoot) + if err != nil { + return nil, err + } + + var procs []processInfo + for _, entry := range entries { + pid, err := strconv.Atoi(entry.Name()) + if err != nil { + continue + } + dir := filepath.Join(procRoot, entry.Name()) + + name := "" + if data, err := os.ReadFile(filepath.Join(dir, "comm")); err == nil { + name = strings.TrimSpace(string(data)) + } + command := "" + if data, err := os.ReadFile(filepath.Join(dir, "cmdline")); err == nil { + // cmdline is NUL-separated. + command = strings.TrimSpace(strings.ReplaceAll(string(data), "\x00", " ")) + } + if name == "" && command == "" { + continue + } + procs = append(procs, processInfo{PID: pid, Name: name, Command: command}) + } + if len(procs) == 0 { + return nil, fmt.Errorf("无法从 %s 读取任何进程", procRoot) + } + return procs, nil +} + +// listProcessesPS parses `ps -eo pid=,args=`, which works on macOS and on Linux +// hosts where /proc is unavailable. +func listProcessesPS(ctx context.Context) ([]processInfo, error) { + out, err := exec.CommandContext(ctx, "ps", "-eo", "pid=,args=").Output() + if err != nil { + return nil, fmt.Errorf("无法列出进程(ps -eo pid=,args= 执行失败: %v);"+ + "请确认 ps 可用且当前用户有权限", err) + } + return parsePS(string(out)), nil +} + +// parsePS parses rows of " 1234 /usr/sbin/nginx -g daemon off;". +func parsePS(out string) []processInfo { + var procs []processInfo + for _, line := range strings.Split(out, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + pidField, rest, _ := strings.Cut(line, " ") + pid, err := strconv.Atoi(pidField) + if err != nil { + continue + } + rest = strings.TrimSpace(rest) + name := rest + if i := strings.IndexByte(name, ' '); i >= 0 { + name = name[:i] + } + name = filepath.Base(name) + procs = append(procs, processInfo{PID: pid, Name: name, Command: rest}) + } + return procs +} + +// listProcessesTasklist parses `tasklist /fo csv /nh` on Windows. +func listProcessesTasklist(ctx context.Context) ([]processInfo, error) { + out, err := exec.CommandContext(ctx, "tasklist", "/fo", "csv", "/nh").Output() + if err != nil { + return nil, fmt.Errorf("无法列出进程(tasklist 执行失败: %v)", err) + } + return parseTasklist(string(out)), nil +} + +// parseTasklist parses CSV rows: "nginx.exe","1234","Console","1","12,345 K". +// tasklist does not report the command line, so keywords match the image name. +func parseTasklist(out string) []processInfo { + var procs []processInfo + for _, line := range strings.Split(out, "\n") { + fields := strings.Split(strings.TrimSpace(line), ",") + if len(fields) < 2 { + continue + } + name := strings.Trim(fields[0], `"`) + // The PID column may be quoted and is never comma-grouped. + pid, err := strconv.Atoi(strings.Trim(fields[1], `" `)) + if err != nil { + continue + } + procs = append(procs, processInfo{PID: pid, Name: name}) + } + return procs +} + +// processesMatching returns the processes that satisfy all keywords. +func processesMatching(procs []processInfo, keywords []string) []processInfo { + if len(keywords) == 0 { + return nil + } + var out []processInfo + for _, p := range procs { + if p.Matches(keywords) { + out = append(out, p) + } + } + return out +} + +// processesWithPID returns the process with the given PID, if it exists. +func processesWithPID(procs []processInfo, pid int) (processInfo, bool) { + for _, p := range procs { + if p.PID == pid { + return p, true + } + } + return processInfo{}, false +} diff --git a/internal/executor/procwait.go b/internal/executor/procwait.go new file mode 100644 index 0000000..3669a5f --- /dev/null +++ b/internal/executor/procwait.go @@ -0,0 +1,252 @@ +package executor + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "time" +) + +// waitOptions are the parsed arguments of `kopsc proc wait`. +type waitOptions struct { + keywords []string // must all match (logical AND) + pids []int // explicit PIDs to watch + interval time.Duration // poll period, 1s by default + timeout time.Duration // 0 means wait forever + once bool // check once and report, do not wait + quiet bool // do not print progress +} + +// runProcWait implements `kopsc proc wait`: poll until the matched processes +// are gone, so a script can block like `while pgrep nginx; do sleep 1; done` +// but with an explicit target and optional timeout. +// +// Exit codes: 0 when the processes have exited (or --once found none), +// 2 when --timeout expires first, 1 on usage or runtime errors. +func runProcWait(ctx context.Context, req BuiltinRequest) error { + opts, err := parseProcWaitArgs(req.Args) + if err != nil { + return err + } + if len(opts.keywords) == 0 && len(opts.pids) == 0 { + return errors.New("缺少要等待的进程;用法: kopsc proc wait <关键字...> [--pid ]") + } + + describe := describeWaitTarget(opts) + start := time.Now() + + remaining, err := findWaiting(ctx, opts) + if err != nil { + return err + } + if len(remaining) == 0 { + if !opts.once { + fmt.Fprintf(req.Stdout, "%s 当前没有运行\n", describe) + } + return nil + } + if !opts.quiet { + fmt.Fprintf(req.Stdout, "等待 %s 退出(共 %d 个进程): %s\n", describe, len(remaining), summarizeProcesses(remaining)) + } + if opts.once { + return nil + } + + var timeout <-chan time.Time + if opts.timeout > 0 { + timer := time.NewTimer(opts.timeout) + defer timer.Stop() + timeout = timer.C + } + + ticker := time.NewTicker(opts.interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return ctx.Err() + case <-timeout: + left, _ := findWaiting(ctx, opts) + return &ExitError{Code: 2, Err: fmt.Errorf( + "等待超时(%s):%s 仍在运行: %s", opts.timeout, describe, summarizeProcesses(left))} + case <-ticker.C: + left, err := findWaiting(ctx, opts) + if err != nil { + return err + } + if len(left) == 0 { + if !opts.quiet { + fmt.Fprintf(req.Stdout, "%s 已退出(等待 %s)\n", describe, time.Since(start).Round(time.Second)) + } + return nil + } + } + } +} + +// findWaiting returns the processes that still satisfy the wait target. +func findWaiting(ctx context.Context, opts waitOptions) ([]processInfo, error) { + procs, err := processLister(ctx) + if err != nil { + return nil, err + } + + var remaining []processInfo + seen := map[int]bool{} + for _, pid := range opts.pids { + ref, ok := processesWithPID(procs, pid) + if ok { + remaining = append(remaining, ref) + seen[pid] = true + } + } + for _, ref := range processesMatching(procs, opts.keywords) { + if !seen[ref.PID] { + remaining = append(remaining, ref) + } + } + return remaining, nil +} + +// describeWaitTarget renders what is being waited for, for the progress lines. +func describeWaitTarget(opts waitOptions) string { + var parts []string + if len(opts.keywords) > 0 { + if len(opts.keywords) == 1 { + parts = append(parts, "进程 "+opts.keywords[0]) + } else { + parts = append(parts, "进程 "+strings.Join(opts.keywords, " 且 ")) + } + } + if len(opts.pids) > 0 { + ids := make([]string, len(opts.pids)) + for i, pid := range opts.pids { + ids[i] = strconv.Itoa(pid) + } + parts = append(parts, "PID "+strings.Join(ids, ",")) + } + return strings.Join(parts, ",") +} + +// summarizeProcesses renders "1234(nginx), 5678(nginx: worker)" for messages, +// keeping the line readable when many processes match. +func summarizeProcesses(procs []processInfo) string { + const max = 5 + parts := make([]string, 0, max) + for i, p := range procs { + if i == max { + parts = append(parts, fmt.Sprintf("…共 %d 个", len(procs))) + break + } + name := p.Name + if name == "" { + name = "?" + } + parts = append(parts, fmt.Sprintf("%d(%s)", p.PID, name)) + } + return strings.Join(parts, ", ") +} + +// parseProcWaitArgs parses kopsc's options; everything else is a keyword. +func parseProcWaitArgs(args []string) (waitOptions, error) { + opts := waitOptions{interval: time.Second} + positionalOnly := false + + for i := 0; i < len(args); i++ { + arg := args[i] + + if arg == "--" { + positionalOnly = true + continue + } + + if !positionalOnly && strings.HasPrefix(arg, "-") && arg != "-" { + name, value := arg, "" + if eq := strings.IndexByte(arg, '='); eq >= 0 && strings.HasPrefix(arg, "--") { + name, value = arg[:eq], arg[eq+1:] + } + takeValue := func() (string, error) { + if value != "" { + return value, nil + } + if i+1 >= len(args) { + return "", fmt.Errorf("%s 缺少参数", name) + } + i++ + return args[i], nil + } + + switch name { + case "--pid", "-p": + raw, err := takeValue() + if err != nil { + return opts, err + } + // Allow comma-separated lists: --pid 1234,5678 + for _, field := range strings.Split(raw, ",") { + pid, err := strconv.Atoi(strings.TrimSpace(field)) + if err != nil || pid <= 0 { + return opts, fmt.Errorf("--pid 需要正整数 PID,收到 %q", field) + } + opts.pids = append(opts.pids, pid) + } + case "--interval": + raw, err := takeValue() + if err != nil { + return opts, err + } + d, err := parseWaitDuration(raw) + if err != nil { + return opts, fmt.Errorf("--interval: %w", err) + } + opts.interval = d + case "--timeout": + raw, err := takeValue() + if err != nil { + return opts, err + } + d, err := parseWaitDuration(raw) + if err != nil { + return opts, fmt.Errorf("--timeout: %w", err) + } + opts.timeout = d + case "--once": + opts.once = true + case "-q", "--quiet": + opts.quiet = true + default: + return opts, fmt.Errorf("未知选项 %q;进程关键字请直接作为参数传入,或用 -- 分隔", arg) + } + continue + } + + opts.keywords = append(opts.keywords, arg) + } + + if opts.interval <= 0 { + return opts, errors.New("--interval 必须大于 0") + } + return opts, nil +} + +// parseWaitDuration accepts a Go duration ("1.5s", "500ms") or plain seconds +// ("30"), which is what most users type. +func parseWaitDuration(raw string) (time.Duration, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return 0, errors.New("缺少时长") + } + if secs, err := strconv.Atoi(raw); err == nil { + if secs < 0 { + return 0, fmt.Errorf("时长不能为负: %q", raw) + } + return time.Duration(secs) * time.Second, nil + } + d, err := time.ParseDuration(raw) + if err != nil || d <= 0 { + return 0, fmt.Errorf("无法识别时长 %q,可用 30(秒)或 30s、500ms、1m", raw) + } + return d, nil +} diff --git a/internal/executor/procwait_test.go b/internal/executor/procwait_test.go new file mode 100644 index 0000000..b076396 --- /dev/null +++ b/internal/executor/procwait_test.go @@ -0,0 +1,253 @@ +package executor + +import ( + "bytes" + "context" + "errors" + "strings" + "sync/atomic" + "testing" + "time" +) + +// fakeProcesses swaps the process lister for the duration of a test. Each call +// to the lister takes the next snapshot; the last one repeats. +func fakeProcesses(t *testing.T, snapshots ...[]processInfo) *int32 { + t.Helper() + var calls int32 + processLister = func(ctx context.Context) ([]processInfo, error) { + n := int(atomic.AddInt32(&calls, 1)) - 1 + if n >= len(snapshots) { + n = len(snapshots) - 1 + } + return snapshots[n], nil + } + t.Cleanup(func() { processLister = listProcesses }) + return &calls +} + +func TestParseProcWaitArgs(t *testing.T) { + opts, err := parseProcWaitArgs([]string{"nginx", "worker", "--pid", "1234,5678", "--timeout", "30", "--interval", "200ms", "--once", "-q"}) + if err != nil { + t.Fatalf("parse: %v", err) + } + if strings.Join(opts.keywords, ",") != "nginx,worker" { + t.Errorf("keywords = %v", opts.keywords) + } + if len(opts.pids) != 2 || opts.pids[0] != 1234 || opts.pids[1] != 5678 { + t.Errorf("pids = %v", opts.pids) + } + if opts.timeout != 30*time.Second || opts.interval != 200*time.Millisecond { + t.Errorf("timeout=%v interval=%v", opts.timeout, opts.interval) + } + if !opts.once || !opts.quiet { + t.Errorf("once=%v quiet=%v", opts.once, opts.quiet) + } + + // Keywords may start with a dash once "--" is seen. + opts, err = parseProcWaitArgs([]string{"--", "-weird"}) + if err != nil || len(opts.keywords) != 1 || opts.keywords[0] != "-weird" { + t.Fatalf("keywords after --: %v err=%v", opts.keywords, err) + } +} + +func TestParseProcWaitArgsRejectsBadInput(t *testing.T) { + tests := []struct { + args []string + want string + }{ + {[]string{"--pid"}, "--pid 缺少参数"}, + {[]string{"--pid", "abc"}, "--pid 需要正整数"}, + {[]string{"--pid", "0"}, "--pid 需要正整数"}, + {[]string{"--timeout", "abc"}, "--timeout"}, + {[]string{"--interval", "0"}, "--interval 必须大于 0"}, + {[]string{"--nope", "x"}, "未知选项"}, + } + for _, tc := range tests { + _, err := parseProcWaitArgs(tc.args) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("args %v: err = %v, want %q", tc.args, err, tc.want) + } + } +} + +func TestParseWaitDuration(t *testing.T) { + cases := map[string]time.Duration{ + "30": 30 * time.Second, + "30s": 30 * time.Second, + "500ms": 500 * time.Millisecond, + "2m": 2 * time.Minute, + } + for in, want := range cases { + got, err := parseWaitDuration(in) + if err != nil || got != want { + t.Errorf("parseWaitDuration(%q) = %v, %v; want %v", in, got, err, want) + } + } + for _, in := range []string{"", "-5", "abc"} { + if _, err := parseWaitDuration(in); err == nil { + t.Errorf("parseWaitDuration(%q) should fail", in) + } + } +} + +func TestProcessInfoMatchesAllKeywords(t *testing.T) { + p := processInfo{PID: 42, Name: "nginx", Command: "/usr/sbin/nginx -g daemon off;"} + cases := []struct { + keywords []string + want bool + }{ + {[]string{"nginx"}, true}, + {[]string{"NGINX"}, true}, // case-insensitive + {[]string{"daemon"}, true}, // matches the command line + {[]string{"nginx", "daemon"}, true}, // logical AND + {[]string{"nginx", "redis"}, false}, + {nil, true}, + } + for _, tc := range cases { + if got := p.Matches(tc.keywords); got != tc.want { + t.Errorf("Matches(%v) = %v, want %v", tc.keywords, got, tc.want) + } + } +} + +func TestProcWaitReturnsWhenProcessIsGone(t *testing.T) { + running := []processInfo{{PID: 42, Name: "nginx", Command: "nginx -g daemon off;"}} + gone := []processInfo{{PID: 1, Name: "init", Command: "init"}} + calls := fakeProcesses(t, running, running, gone) + + var out bytes.Buffer + start := time.Now() + err := runProcWait(context.Background(), BuiltinRequest{ + Args: []string{"nginx", "--interval", "10ms"}, + Stdout: &out, + }) + if err != nil { + t.Fatalf("wait: %v", err) + } + if time.Since(start) > 2*time.Second { + t.Errorf("wait took too long: %v", time.Since(start)) + } + if atomic.LoadInt32(calls) < 3 { + t.Errorf("expected at least 3 polls, got %d", *calls) + } + for _, want := range []string{"等待 进程 nginx 退出", "共 1 个进程", "42(nginx)", "已退出"} { + if !strings.Contains(out.String(), want) { + t.Errorf("output missing %q:\n%s", want, out.String()) + } + } +} + +func TestProcWaitAlreadyGoneIsImmediate(t *testing.T) { + fakeProcesses(t, []processInfo{{PID: 1, Name: "init"}}) + + var out bytes.Buffer + if err := runProcWait(context.Background(), BuiltinRequest{Args: []string{"nginx"}, Stdout: &out}); err != nil { + t.Fatalf("wait: %v", err) + } + if !strings.Contains(out.String(), "当前没有运行") { + t.Errorf("output = %q", out.String()) + } +} + +func TestProcWaitTimeoutExitsWithCodeTwo(t *testing.T) { + fakeProcesses(t, []processInfo{{PID: 42, Name: "nginx"}}) + + err := runProcWait(context.Background(), BuiltinRequest{ + Args: []string{"nginx", "--timeout", "60ms", "--interval", "10ms"}, + Stdout: &bytes.Buffer{}, + }) + if err == nil { + t.Fatal("expected a timeout error") + } + if code := ExitCode(err); code != 2 { + t.Fatalf("exit code = %d, want 2", code) + } + if !strings.Contains(err.Error(), "等待超时") || !strings.Contains(err.Error(), "nginx") { + t.Errorf("err = %v", err) + } +} + +func TestProcWaitByPID(t *testing.T) { + // PID 42 exists in the first snapshot only; the keyword never matches. + withPID := []processInfo{{PID: 42, Name: "some-proc"}, {PID: 7, Name: "other"}} + without := []processInfo{{PID: 7, Name: "other"}} + fakeProcesses(t, withPID, without) + + var out bytes.Buffer + if err := runProcWait(context.Background(), BuiltinRequest{ + Args: []string{"--pid", "42", "--interval", "10ms"}, + Stdout: &out, + }); err != nil { + t.Fatalf("wait: %v", err) + } + if !strings.Contains(out.String(), "PID 42") { + t.Errorf("output = %q", out.String()) + } +} + +func TestProcWaitOnceReportsDoNotWait(t *testing.T) { + calls := fakeProcesses(t, []processInfo{{PID: 42, Name: "nginx"}}) + + var out bytes.Buffer + if err := runProcWait(context.Background(), BuiltinRequest{Args: []string{"nginx", "--once"}, Stdout: &out}); err != nil { + t.Fatalf("wait: %v", err) + } + if atomic.LoadInt32(calls) != 1 { + t.Errorf("--once should poll exactly once, polled %d times", *calls) + } + if !strings.Contains(out.String(), "42(nginx)") { + t.Errorf("output = %q", out.String()) + } +} + +func TestProcWaitRequiresTarget(t *testing.T) { + fakeProcesses(t, nil) + err := runProcWait(context.Background(), BuiltinRequest{Stdout: &bytes.Buffer{}}) + if err == nil || !strings.Contains(err.Error(), "缺少要等待的进程") { + t.Fatalf("err = %v, want a missing-target error", err) + } +} + +func TestParsePS(t *testing.T) { + out := " 1234 /usr/sbin/nginx -g daemon off;\n" + + " 1 /sbin/init\n" + + " bad line\n" + procs := parsePS(out) + if len(procs) != 2 { + t.Fatalf("parsed %d processes, want 2: %+v", len(procs), procs) + } + if procs[0].PID != 1234 || procs[0].Name != "nginx" { + t.Errorf("first = %+v", procs[0]) + } + if !strings.Contains(procs[0].Command, "daemon off") { + t.Errorf("command not captured: %+v", procs[0]) + } + if procs[1].Name != "init" { + t.Errorf("second = %+v", procs[1]) + } +} + +func TestParseTasklist(t *testing.T) { + out := `"nginx.exe","1234","Console","1","12,345 K"` + "\n" + + `"postgres.exe","5678","Services","0","80,000 K"` + "\n" + procs := parseTasklist(out) + if len(procs) != 2 { + t.Fatalf("parsed %d, want 2: %+v", len(procs), procs) + } + if procs[0].PID != 1234 || procs[0].Name != "nginx.exe" { + t.Errorf("first = %+v", procs[0]) + } +} + +func TestProcWaitPropagatesListerError(t *testing.T) { + processLister = func(ctx context.Context) ([]processInfo, error) { + return nil, errors.New("ps 不可用") + } + t.Cleanup(func() { processLister = listProcesses }) + + err := runProcWait(context.Background(), BuiltinRequest{Args: []string{"nginx"}, Stdout: &bytes.Buffer{}}) + if err == nil || !strings.Contains(err.Error(), "ps 不可用") { + t.Fatalf("err = %v", err) + } +} diff --git a/internal/registry/builtin.go b/internal/registry/builtin.go index 3f2d39e..ef2588f 100644 --- a/internal/registry/builtin.go +++ b/internal/registry/builtin.go @@ -424,6 +424,34 @@ func Builtin() *Registry { }, }, }, + { + ID: "proc.wait", + Group: "proc", + Summary: "等待进程退出(关键字可多个,逻辑与;也可按 PID)", + Action: "每秒检查一次目标进程是否还在:存在就继续等,直到它消失为止。" + + "关键字在进程名与命令行中匹配(忽略大小写),多个关键字需全部命中(逻辑与);" + + "--pid 可直接指定进程 ID(逗号分隔可多个),与关键字同时给出时任一方仍存在都会继续等待。" + + "默认一直等到进程退出;--timeout 可限时,超时以退出码 2 结束;--once 只检查一次不等待。" + + "只读,不修改任何进程", + Usage: "<关键字>... [--pid PID]...", + Variants: []Variant{ + { + Match: Match{OS: "linux"}, + Builtin: "proc.wait", + Note: "Linux 内置实现(读 /proc,回退 ps)", + }, + { + Match: Match{OS: "darwin"}, + Builtin: "proc.wait", + Note: "macOS 内置实现(ps -eo pid=,args=)", + }, + { + Match: Match{OS: "windows"}, + Builtin: "proc.wait", + Note: "Windows 内置实现(tasklist,关键字只能匹配进程名)", + }, + }, + }, { ID: "pkg.refreshindex", Group: "pkg", diff --git a/internal/registry/registry_test.go b/internal/registry/registry_test.go index da6d421..d7ab90d 100644 --- a/internal/registry/registry_test.go +++ b/internal/registry/registry_test.go @@ -25,7 +25,7 @@ func TestBuiltinIDsStable(t *testing.T) { "docker.prunebuilder", "docker.prunevolumes", "docker.clearall", "docker.compose.up", "docker.compose.down", "docker.compose.ps", "docker.compose.logs", "diagnose", - "disk.usage", "net.pids", "net.ports", "proc.nohup", "pkg.refreshindex", + "disk.usage", "net.pids", "net.ports", "proc.nohup", "proc.wait", "pkg.refreshindex", } if got := reg.IDs(); !reflect.DeepEqual(got, want) { t.Fatalf("IDs() =\n%v\nwant\n%v", got, want) @@ -346,3 +346,30 @@ func TestMatchIsComparable(t *testing.T) { t.Fatal("Match should be a comparable plain struct value") } } + +func TestProcWaitIsBuiltinEverywhere(t *testing.T) { + reg := Builtin() + cmd, ok := reg.Lookup("proc.wait") + if !ok { + t.Fatal("proc.wait not found") + } + // The command is read-only: it must not demand --yes. + if cmd.RequiresYes { + t.Error("proc.wait only observes processes and must not require --yes") + } + if cmd.Usage == "" { + t.Error("proc.wait should document its arguments in Usage") + } + seen := map[string]bool{} + for _, v := range cmd.Variants { + if v.Builtin != "proc.wait" || len(v.Argv) != 0 { + t.Errorf("variant for %s should be the proc.wait builtin, got %+v", v.Match.OS, v) + } + seen[v.Match.OS] = true + } + for _, osName := range []string{"linux", "darwin", "windows"} { + if !seen[osName] { + t.Errorf("proc.wait lacks a %s variant", osName) + } + } +}