feat: 新增 proc wait,等待进程退出
- 每秒检查一次目标进程,存在则继续等待,直到消失为止 - 关键字在进程名与命令行中匹配(忽略大小写),多个关键字为逻辑与; --pid 可直接指定进程 ID(逗号分隔可多个) - 默认不超时,--timeout 限时(退出码 2 并列出残留 PID),--once 只检查一次 - 三平台实现:Linux 读 /proc(回退 ps)、macOS 用 ps、Windows 用 tasklist - ExitError 改为优先展示具体原因,不再只显示「命令以状态码 N 退出」 - 文档:README.proc.md 新增完整小节,主 README 补充示例与速查
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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/<pid>/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
|
||||
}
|
||||
@@ -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 <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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user