// Package system wraps privileged host operations (commands, distro detection, // metrics, ports, systemd units). package system import ( "bufio" "bytes" "context" "errors" "fmt" "os" "os/exec" "time" ) // ErrUnsupported is returned when the host lacks a required facility. var ErrUnsupported = errors.New("当前系统不支持该操作") // Runner executes external commands with a hard timeout and bounded output. type Runner struct { Timeout time.Duration MaxLine int // maximum bytes retained per stream } // NewRunner returns a runner with production defaults. func NewRunner() *Runner { return &Runner{Timeout: 60 * time.Second, MaxLine: 512 * 1024} } // Result is the outcome of one command. type Result struct { Stdout string Stderr string Code int } // Run executes a command without a shell. Arguments are passed verbatim, so // callers never have to quote or escape user input. func (r *Runner) Run(ctx context.Context, name string, args ...string) (*Result, error) { return r.RunEnv(ctx, nil, name, args...) } // RunEnv is Run with extra environment variables (for example MYSQL_PWD). func (r *Runner) RunEnv(ctx context.Context, env []string, name string, args ...string) (*Result, error) { if r.Timeout > 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, r.Timeout) defer cancel() } cmd := exec.CommandContext(ctx, name, args...) if len(env) > 0 { cmd.Env = append(os.Environ(), env...) } out := newLimitBuffer(r.MaxLine) errb := newLimitBuffer(r.MaxLine) cmd.Stdout = out cmd.Stderr = errb err := cmd.Run() res := &Result{Stdout: out.String(), Stderr: errb.String()} if err == nil { return res, nil } var exitErr *exec.ExitError if errors.As(err, &exitErr) { res.Code = exitErr.ExitCode() return res, fmt.Errorf("%s 退出码 %d", name, res.Code) } if ctx.Err() != nil { return res, fmt.Errorf("命令 %s 超时: %w", name, ctx.Err()) } return res, err } // RunLong is Run with a caller supplied timeout (installs, builds, backups). func (r *Runner) RunLong(ctx context.Context, timeout time.Duration, name string, args ...string) (*Result, error) { clone := *r clone.Timeout = timeout return clone.Run(ctx, name, args...) } // Lookup reports whether a binary is available on PATH. func Lookup(name string) bool { _, err := exec.LookPath(name) return err == nil } // limitBuffer keeps the head and the tail of a long stream so that both the // context and the final error survive truncation. type limitBuffer struct { buf bytes.Buffer max int head int } func newLimitBuffer(max int) *limitBuffer { if max <= 0 { max = 256 * 1024 } return &limitBuffer{max: max, head: max / 3} } func (l *limitBuffer) Write(p []byte) (int, error) { n := len(p) if l.buf.Len()+n <= l.max { l.buf.Write(p) return n, nil } b := l.buf.Bytes() headPart := b if len(headPart) > l.head { headPart = headPart[:l.head] } tailPart := append(append([]byte{}, b[l.head:]...), p...) if len(tailPart) > l.max-l.head { tailPart = tailPart[len(tailPart)-(l.max-l.head):] } merged := make([]byte, 0, l.max+32) merged = append(merged, headPart...) merged = append(merged, []byte("\n...[输出过长已截断]...\n")...) merged = append(merged, tailPart...) l.buf.Reset() l.buf.Write(merged) return n, nil } func (l *limitBuffer) String() string { return l.buf.String() } // Tail returns the last n lines of a file with bounded memory usage. func Tail(path string, n int) ([]string, error) { if n <= 0 { n = 200 } f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() ring := make([]string, 0, n) sc := bufio.NewScanner(f) sc.Buffer(make([]byte, 64*1024), 4*1024*1024) for sc.Scan() { if len(ring) == n { copy(ring, ring[1:]) ring[n-1] = sc.Text() continue } ring = append(ring, sc.Text()) } if err := sc.Err(); err != nil { return nil, err } return ring, nil }