仰望星辰工作室

miaopanel

miaopanel/ internal/system/exec.go 3.8 KB · 153 行 原始文件
1// Package system wraps privileged host operations (commands, distro detection,
2// metrics, ports, systemd units).
3package system
4
5import (
6 "bufio"
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "os"
12 "os/exec"
13 "time"
14)
15
16// ErrUnsupported is returned when the host lacks a required facility.
17var ErrUnsupported = errors.New("当前系统不支持该操作")
18
19// Runner executes external commands with a hard timeout and bounded output.
20type Runner struct {
21 Timeout time.Duration
22 MaxLine int // maximum bytes retained per stream
23}
24
25// NewRunner returns a runner with production defaults.
26func NewRunner() *Runner {
27 return &Runner{Timeout: 60 * time.Second, MaxLine: 512 * 1024}
28}
29
30// Result is the outcome of one command.
31type Result struct {
32 Stdout string
33 Stderr string
34 Code int
35}
36
37// Run executes a command without a shell. Arguments are passed verbatim, so
38// callers never have to quote or escape user input.
39func (r *Runner) Run(ctx context.Context, name string, args ...string) (*Result, error) {
40 return r.RunEnv(ctx, nil, name, args...)
41}
42
43// RunEnv is Run with extra environment variables (for example MYSQL_PWD).
44func (r *Runner) RunEnv(ctx context.Context, env []string, name string, args ...string) (*Result, error) {
45 if r.Timeout > 0 {
46 var cancel context.CancelFunc
47 ctx, cancel = context.WithTimeout(ctx, r.Timeout)
48 defer cancel()
49 }
50 cmd := exec.CommandContext(ctx, name, args...)
51 if len(env) > 0 {
52 cmd.Env = append(os.Environ(), env...)
53 }
54 out := newLimitBuffer(r.MaxLine)
55 errb := newLimitBuffer(r.MaxLine)
56 cmd.Stdout = out
57 cmd.Stderr = errb
58 err := cmd.Run()
59 res := &Result{Stdout: out.String(), Stderr: errb.String()}
60 if err == nil {
61 return res, nil
62 }
63 var exitErr *exec.ExitError
64 if errors.As(err, &exitErr) {
65 res.Code = exitErr.ExitCode()
66 return res, fmt.Errorf("%s 退出码 %d", name, res.Code)
67 }
68 if ctx.Err() != nil {
69 return res, fmt.Errorf("命令 %s 超时: %w", name, ctx.Err())
70 }
71 return res, err
72}
73
74// RunLong is Run with a caller supplied timeout (installs, builds, backups).
75func (r *Runner) RunLong(ctx context.Context, timeout time.Duration, name string, args ...string) (*Result, error) {
76 clone := *r
77 clone.Timeout = timeout
78 return clone.Run(ctx, name, args...)
79}
80
81// Lookup reports whether a binary is available on PATH.
82func Lookup(name string) bool {
83 _, err := exec.LookPath(name)
84 return err == nil
85}
86
87// limitBuffer keeps the head and the tail of a long stream so that both the
88// context and the final error survive truncation.
89type limitBuffer struct {
90 buf bytes.Buffer
91 max int
92 head int
93}
94
95func newLimitBuffer(max int) *limitBuffer {
96 if max <= 0 {
97 max = 256 * 1024
98 }
99 return &limitBuffer{max: max, head: max / 3}
100}
101
102func (l *limitBuffer) Write(p []byte) (int, error) {
103 n := len(p)
104 if l.buf.Len()+n <= l.max {
105 l.buf.Write(p)
106 return n, nil
107 }
108 b := l.buf.Bytes()
109 headPart := b
110 if len(headPart) > l.head {
111 headPart = headPart[:l.head]
112 }
113 tailPart := append(append([]byte{}, b[l.head:]...), p...)
114 if len(tailPart) > l.max-l.head {
115 tailPart = tailPart[len(tailPart)-(l.max-l.head):]
116 }
117 merged := make([]byte, 0, l.max+32)
118 merged = append(merged, headPart...)
119 merged = append(merged, []byte("\n...[输出过长已截断]...\n")...)
120 merged = append(merged, tailPart...)
121 l.buf.Reset()
122 l.buf.Write(merged)
123 return n, nil
124}
125
126func (l *limitBuffer) String() string { return l.buf.String() }
127
128// Tail returns the last n lines of a file with bounded memory usage.
129func Tail(path string, n int) ([]string, error) {
130 if n <= 0 {
131 n = 200
132 }
133 f, err := os.Open(path)
134 if err != nil {
135 return nil, err
136 }
137 defer f.Close()
138 ring := make([]string, 0, n)
139 sc := bufio.NewScanner(f)
140 sc.Buffer(make([]byte, 64*1024), 4*1024*1024)
141 for sc.Scan() {
142 if len(ring) == n {
143 copy(ring, ring[1:])
144 ring[n-1] = sc.Text()
145 continue
146 }
147 ring = append(ring, sc.Text())
148 }
149 if err := sc.Err(); err != nil {
150 return nil, err
151 }
152 return ring, nil
153}