仰望星辰工作室

miaopanel

miaopanel/ internal/webserver/performance.go 11.0 KB · 389 行 原始文件
1package webserver
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8 "regexp"
9 "strconv"
10 "strings"
11 "time"
12
13 "github.com/miaopanel/miaopanel/internal/fsutil"
14)
15
16// Performance is the tunable subset of the nginx main configuration.
17type Performance struct {
18 WorkerProcesses string `json:"worker_processes"`
19 WorkerConnections int `json:"worker_connections"`
20 KeepaliveTimeout int `json:"keepalive_timeout"`
21 Gzip bool `json:"gzip"`
22 GzipMinLengthKB int `json:"gzip_min_length_kb"`
23 GzipCompLevel int `json:"gzip_comp_level"`
24 ClientMaxBodyMB int `json:"client_max_body_size_mb"`
25 ServerNamesHashBucket int `json:"server_names_hash_bucket_size"`
26 ClientHeaderBufferKB int `json:"client_header_buffer_size_kb"`
27 ClientBodyBufferKB int `json:"client_body_buffer_size_kb"`
28
29 ConfigPath string `json:"config_path"`
30 BackupPath string `json:"backup_path,omitempty"`
31 AppliedAt int64 `json:"applied_at,omitempty"`
32}
33
34const nginxPerfBackup = "nginx/performance"
35
36var workerProcessesRe = regexp.MustCompile(`(?m)^([ \t]*)worker_processes[ \t]+([^;]+);`)
37
38// ReadPerformance parses the main nginx.conf. Missing directives fall back to
39// the nginx defaults so the form always shows an effective value.
40func (m *Manager) ReadPerformance() (Performance, error) {
41 if !m.Available() {
42 return Performance{}, fmt.Errorf("nginx 未安装或未检测到配置,无法调整性能参数")
43 }
44 path := strings.TrimSpace(m.cfg.Nginx.Conf)
45 if path == "" {
46 return Performance{}, fmt.Errorf("未配置 nginx.conf 路径")
47 }
48 raw, err := os.ReadFile(path)
49 if err != nil {
50 return Performance{}, fmt.Errorf("读取 nginx.conf 失败: %w", err)
51 }
52 src := string(raw)
53 p := Performance{
54 WorkerProcesses: "auto",
55 WorkerConnections: 1024,
56 KeepaliveTimeout: 75,
57 Gzip: false,
58 GzipMinLengthKB: 20,
59 GzipCompLevel: 1,
60 ClientMaxBodyMB: 1,
61 ServerNamesHashBucket: 32,
62 ClientHeaderBufferKB: 1,
63 ClientBodyBufferKB: 8,
64 ConfigPath: path,
65 }
66 if v, ok := directiveValue(src, "worker_processes"); ok {
67 if v = strings.TrimSpace(v); v != "" {
68 p.WorkerProcesses = v
69 }
70 }
71 if body, ok := blockBody(src, "events"); ok {
72 if v, ok := directiveValue(body, "worker_connections"); ok {
73 if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && n > 0 {
74 p.WorkerConnections = n
75 }
76 }
77 }
78 if body, ok := blockBody(src, "http"); ok {
79 if v, ok := directiveValue(body, "keepalive_timeout"); ok {
80 if n, err := strconv.Atoi(strings.TrimSuffix(strings.TrimSpace(v), "s")); err == nil && n >= 0 {
81 p.KeepaliveTimeout = n
82 }
83 }
84 if v, ok := directiveValue(body, "gzip"); ok {
85 p.Gzip = strings.EqualFold(strings.TrimSpace(v), "on")
86 }
87 if v, ok := directiveValue(body, "gzip_min_length"); ok {
88 if n, err := parseSizeKB(v); err == nil {
89 p.GzipMinLengthKB = n
90 }
91 }
92 if v, ok := directiveValue(body, "gzip_comp_level"); ok {
93 if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
94 p.GzipCompLevel = n
95 }
96 }
97 if v, ok := directiveValue(body, "client_max_body_size"); ok {
98 if n, err := parseSizeMB(v); err == nil {
99 p.ClientMaxBodyMB = n
100 }
101 }
102 if v, ok := directiveValue(body, "server_names_hash_bucket_size"); ok {
103 if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
104 p.ServerNamesHashBucket = n
105 }
106 }
107 if v, ok := directiveValue(body, "client_header_buffer_size"); ok {
108 if n, err := parseSizeKB(v); err == nil {
109 p.ClientHeaderBufferKB = n
110 }
111 }
112 if v, ok := directiveValue(body, "client_body_buffer_size"); ok {
113 if n, err := parseSizeKB(v); err == nil {
114 p.ClientBodyBufferKB = n
115 }
116 }
117 }
118 return p, nil
119}
120
121// ApplyPerformance rewrites nginx.conf, validates it with nginx -t and reloads.
122// Any failure restores the exact previous bytes.
123func (m *Manager) ApplyPerformance(ctx context.Context, p Performance) (Performance, error) {
124 if err := p.validate(); err != nil {
125 return Performance{}, err
126 }
127 if !m.Available() {
128 return Performance{}, fmt.Errorf("nginx 未安装,无法调整性能参数")
129 }
130 path := strings.TrimSpace(m.cfg.Nginx.Conf)
131 raw, err := os.ReadFile(path)
132 if err != nil {
133 return Performance{}, fmt.Errorf("读取 nginx.conf 失败: %w", err)
134 }
135 patched, err := patchPerformance(string(raw), p)
136 if err != nil {
137 return Performance{}, err
138 }
139
140 m.applyMu.Lock()
141 defer m.applyMu.Unlock()
142
143 backupDir := filepath.Join(m.cfg.DataDir, "backups", filepath.FromSlash(nginxPerfBackup))
144 if err := os.MkdirAll(backupDir, 0o700); err != nil {
145 return Performance{}, fmt.Errorf("创建备份目录失败: %w", err)
146 }
147 backup := filepath.Join(backupDir, fmt.Sprintf("nginx.conf.%d.bak", time.Now().Unix()))
148 if err := os.WriteFile(backup, raw, 0o600); err != nil {
149 return Performance{}, fmt.Errorf("备份 nginx.conf 失败: %w", err)
150 }
151 if err := fsutil.WriteFileAtomic(path, []byte(patched), 0o644); err != nil {
152 return Performance{}, fmt.Errorf("写入 nginx.conf 失败: %w", err)
153 }
154
155 restore := func() {
156 if err := fsutil.WriteFileAtomic(path, raw, 0o644); err != nil {
157 // Nothing else can be done here; the backup path is returned in logs.
158 return
159 }
160 _, _ = m.Validate(context.WithoutCancel(ctx))
161 _ = m.Reload(context.WithoutCancel(ctx))
162 }
163
164 if out, err := m.Validate(ctx); err != nil {
165 restore()
166 return Performance{}, fmt.Errorf("nginx 配置校验失败,已回滚:%s", firstLine(out, err.Error()))
167 }
168 if err := m.Reload(ctx); err != nil {
169 restore()
170 return Performance{}, fmt.Errorf("重载 nginx 失败,已回滚:%v", err)
171 }
172 p.ConfigPath = path
173 p.BackupPath = backup
174 p.AppliedAt = time.Now().Unix()
175 return p, nil
176}
177
178func (p Performance) validate() error {
179 if !regexp.MustCompile(`^(auto|[1-9][0-9]{0,2})$`).MatchString(strings.TrimSpace(p.WorkerProcesses)) {
180 return fmt.Errorf("worker_processes 只能是 auto 或 1-999 的整数")
181 }
182 checks := []struct {
183 name string
184 val int
185 min int
186 max int
187 }{
188 {"worker_connections", p.WorkerConnections, 128, 1048576},
189 {"keepalive_timeout", p.KeepaliveTimeout, 0, 3600},
190 {"gzip_min_length", p.GzipMinLengthKB, 0, 10240},
191 {"gzip_comp_level", p.GzipCompLevel, 1, 9},
192 {"client_max_body_size", p.ClientMaxBodyMB, 1, 10240},
193 {"server_names_hash_bucket_size", p.ServerNamesHashBucket, 32, 16384},
194 {"client_header_buffer_size", p.ClientHeaderBufferKB, 1, 256},
195 {"client_body_buffer_size", p.ClientBodyBufferKB, 1, 256},
196 }
197 for _, c := range checks {
198 if c.val < c.min || c.val > c.max {
199 return fmt.Errorf("%s 需要在 %d-%d 之间", c.name, c.min, c.max)
200 }
201 }
202 if p.ServerNamesHashBucket&(p.ServerNamesHashBucket-1) != 0 {
203 return fmt.Errorf("server_names_hash_bucket_size 必须是 2 的幂(如 32/64/128)")
204 }
205 return nil
206}
207
208func patchPerformance(src string, p Performance) (string, error) {
209 out := src
210 worker := strings.TrimSpace(p.WorkerProcesses)
211 if m := workerProcessesRe.FindStringSubmatchIndex(out); m != nil {
212 out = out[:m[4]] + worker + out[m[5]:]
213 } else {
214 pos := 0
215 if open, _, ok := blockSpan(out, "events"); ok {
216 pos = open
217 }
218 out = out[:pos] + "worker_processes " + worker + ";\n\n" + out[pos:]
219 }
220
221 var err error
222 if out, err = setInBlock(out, "events", "worker_connections", strconv.Itoa(p.WorkerConnections)); err != nil {
223 return "", err
224 }
225 gzip := "off"
226 if p.Gzip {
227 gzip = "on"
228 }
229 httpValues := []struct{ name, value string }{
230 {"keepalive_timeout", strconv.Itoa(p.KeepaliveTimeout)},
231 {"gzip", gzip},
232 {"gzip_min_length", fmt.Sprintf("%dk", p.GzipMinLengthKB)},
233 {"gzip_comp_level", strconv.Itoa(p.GzipCompLevel)},
234 {"client_max_body_size", fmt.Sprintf("%dm", p.ClientMaxBodyMB)},
235 {"server_names_hash_bucket_size", strconv.Itoa(p.ServerNamesHashBucket)},
236 {"client_header_buffer_size", fmt.Sprintf("%dk", p.ClientHeaderBufferKB)},
237 {"client_body_buffer_size", fmt.Sprintf("%dk", p.ClientBodyBufferKB)},
238 }
239 for _, item := range httpValues {
240 if out, err = setInBlock(out, "http", item.name, item.value); err != nil {
241 return "", err
242 }
243 }
244 return out, nil
245}
246
247// blockSpan returns the byte offsets of the braces of the first top-level
248// "name { ... }" block, skipping comments and quoted strings.
249func blockSpan(src, name string) (int, int, bool) {
250 re := regexp.MustCompile(`(?m)^[ \t]*` + regexp.QuoteMeta(name) + `[ \t]*\{`)
251 loc := re.FindStringIndex(src)
252 if loc == nil {
253 return 0, 0, false
254 }
255 open := strings.Index(src[loc[0]:loc[1]], "{") + loc[0]
256 depth := 0
257 inComment := false
258 var quote byte
259 for i := open; i < len(src); i++ {
260 c := src[i]
261 if inComment {
262 if c == '\n' {
263 inComment = false
264 }
265 continue
266 }
267 if quote != 0 {
268 if c == '\\' {
269 i++
270 continue
271 }
272 if c == quote {
273 quote = 0
274 }
275 continue
276 }
277 switch c {
278 case '#':
279 inComment = true
280 case '\'', '"':
281 quote = c
282 case '{':
283 depth++
284 case '}':
285 depth--
286 if depth == 0 {
287 return open, i, true
288 }
289 }
290 }
291 return 0, 0, false
292}
293
294func blockBody(src, name string) (string, bool) {
295 open, close, ok := blockSpan(src, name)
296 if !ok {
297 return "", false
298 }
299 return src[open+1 : close], true
300}
301
302func directiveValue(src, name string) (string, bool) {
303 re := regexp.MustCompile(`(?m)^[ \t]*` + regexp.QuoteMeta(name) + `[ \t]+([^;]+);`)
304 m := re.FindStringSubmatch(src)
305 if m == nil {
306 return "", false
307 }
308 return strings.TrimSpace(m[1]), true
309}
310
311func setInBlock(src, block, name, value string) (string, error) {
312 open, close, ok := blockSpan(src, block)
313 if !ok {
314 return "", fmt.Errorf("nginx.conf 中找不到 %s {} 配置块", block)
315 }
316 body := src[open+1 : close]
317 re := regexp.MustCompile(`(?m)^([ \t]*)` + regexp.QuoteMeta(name) + `[ \t]+[^;]*;`)
318 if re.MatchString(body) {
319 body = re.ReplaceAllString(body, "${1}"+name+" "+value+";")
320 } else if strings.HasPrefix(body, "\n") {
321 body = "\n " + name + " " + value + ";" + body
322 } else {
323 body = " " + name + " " + value + ";" + body
324 }
325 return src[:open+1] + body + src[close:], nil
326}
327
328func parseSizeKB(v string) (int, error) {
329 n, unit, err := splitSize(strings.TrimSpace(strings.ToLower(v)))
330 if err != nil {
331 return 0, err
332 }
333 switch unit {
334 case "": // nginx treats a plain number as bytes
335 return (n + 1023) / 1024, nil
336 case "k":
337 return n, nil
338 case "m":
339 return n * 1024, nil
340 case "g":
341 return n * 1024 * 1024, nil
342 }
343 return 0, fmt.Errorf("未知大小单位 %q", unit)
344}
345
346func parseSizeMB(v string) (int, error) {
347 n, unit, err := splitSize(strings.TrimSpace(strings.ToLower(v)))
348 if err != nil {
349 return 0, err
350 }
351 switch unit {
352 case "":
353 return (n + 1048575) / 1048576, nil
354 case "k":
355 return (n + 1023) / 1024, nil
356 case "m":
357 return n, nil
358 case "g":
359 return n * 1024, nil
360 }
361 return 0, fmt.Errorf("未知大小单位 %q", unit)
362}
363
364func splitSize(v string) (int, string, error) {
365 if v == "" {
366 return 0, "", fmt.Errorf("缺少数值")
367 }
368 i := 0
369 for i < len(v) && (v[i] >= '0' && v[i] <= '9') {
370 i++
371 }
372 if i == 0 {
373 return 0, "", fmt.Errorf("数值格式不正确: %q", v)
374 }
375 n, err := strconv.Atoi(v[:i])
376 if err != nil {
377 return 0, "", err
378 }
379 return n, strings.TrimSpace(v[i:]), nil
380}
381
382func firstLine(out, fallback string) string {
383 for _, line := range strings.Split(out, "\n") {
384 if s := strings.TrimSpace(line); s != "" {
385 return s
386 }
387 }
388 return fallback
389}