package webserver import ( "context" "fmt" "os" "path/filepath" "regexp" "strconv" "strings" "time" "github.com/miaopanel/miaopanel/internal/fsutil" ) // Performance is the tunable subset of the nginx main configuration. type Performance struct { WorkerProcesses string `json:"worker_processes"` WorkerConnections int `json:"worker_connections"` KeepaliveTimeout int `json:"keepalive_timeout"` Gzip bool `json:"gzip"` GzipMinLengthKB int `json:"gzip_min_length_kb"` GzipCompLevel int `json:"gzip_comp_level"` ClientMaxBodyMB int `json:"client_max_body_size_mb"` ServerNamesHashBucket int `json:"server_names_hash_bucket_size"` ClientHeaderBufferKB int `json:"client_header_buffer_size_kb"` ClientBodyBufferKB int `json:"client_body_buffer_size_kb"` ConfigPath string `json:"config_path"` BackupPath string `json:"backup_path,omitempty"` AppliedAt int64 `json:"applied_at,omitempty"` } const nginxPerfBackup = "nginx/performance" var workerProcessesRe = regexp.MustCompile(`(?m)^([ \t]*)worker_processes[ \t]+([^;]+);`) // ReadPerformance parses the main nginx.conf. Missing directives fall back to // the nginx defaults so the form always shows an effective value. func (m *Manager) ReadPerformance() (Performance, error) { if !m.Available() { return Performance{}, fmt.Errorf("nginx 未安装或未检测到配置,无法调整性能参数") } path := strings.TrimSpace(m.cfg.Nginx.Conf) if path == "" { return Performance{}, fmt.Errorf("未配置 nginx.conf 路径") } raw, err := os.ReadFile(path) if err != nil { return Performance{}, fmt.Errorf("读取 nginx.conf 失败: %w", err) } src := string(raw) p := Performance{ WorkerProcesses: "auto", WorkerConnections: 1024, KeepaliveTimeout: 75, Gzip: false, GzipMinLengthKB: 20, GzipCompLevel: 1, ClientMaxBodyMB: 1, ServerNamesHashBucket: 32, ClientHeaderBufferKB: 1, ClientBodyBufferKB: 8, ConfigPath: path, } if v, ok := directiveValue(src, "worker_processes"); ok { if v = strings.TrimSpace(v); v != "" { p.WorkerProcesses = v } } if body, ok := blockBody(src, "events"); ok { if v, ok := directiveValue(body, "worker_connections"); ok { if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && n > 0 { p.WorkerConnections = n } } } if body, ok := blockBody(src, "http"); ok { if v, ok := directiveValue(body, "keepalive_timeout"); ok { if n, err := strconv.Atoi(strings.TrimSuffix(strings.TrimSpace(v), "s")); err == nil && n >= 0 { p.KeepaliveTimeout = n } } if v, ok := directiveValue(body, "gzip"); ok { p.Gzip = strings.EqualFold(strings.TrimSpace(v), "on") } if v, ok := directiveValue(body, "gzip_min_length"); ok { if n, err := parseSizeKB(v); err == nil { p.GzipMinLengthKB = n } } if v, ok := directiveValue(body, "gzip_comp_level"); ok { if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil { p.GzipCompLevel = n } } if v, ok := directiveValue(body, "client_max_body_size"); ok { if n, err := parseSizeMB(v); err == nil { p.ClientMaxBodyMB = n } } if v, ok := directiveValue(body, "server_names_hash_bucket_size"); ok { if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil { p.ServerNamesHashBucket = n } } if v, ok := directiveValue(body, "client_header_buffer_size"); ok { if n, err := parseSizeKB(v); err == nil { p.ClientHeaderBufferKB = n } } if v, ok := directiveValue(body, "client_body_buffer_size"); ok { if n, err := parseSizeKB(v); err == nil { p.ClientBodyBufferKB = n } } } return p, nil } // ApplyPerformance rewrites nginx.conf, validates it with nginx -t and reloads. // Any failure restores the exact previous bytes. func (m *Manager) ApplyPerformance(ctx context.Context, p Performance) (Performance, error) { if err := p.validate(); err != nil { return Performance{}, err } if !m.Available() { return Performance{}, fmt.Errorf("nginx 未安装,无法调整性能参数") } path := strings.TrimSpace(m.cfg.Nginx.Conf) raw, err := os.ReadFile(path) if err != nil { return Performance{}, fmt.Errorf("读取 nginx.conf 失败: %w", err) } patched, err := patchPerformance(string(raw), p) if err != nil { return Performance{}, err } m.applyMu.Lock() defer m.applyMu.Unlock() backupDir := filepath.Join(m.cfg.DataDir, "backups", filepath.FromSlash(nginxPerfBackup)) if err := os.MkdirAll(backupDir, 0o700); err != nil { return Performance{}, fmt.Errorf("创建备份目录失败: %w", err) } backup := filepath.Join(backupDir, fmt.Sprintf("nginx.conf.%d.bak", time.Now().Unix())) if err := os.WriteFile(backup, raw, 0o600); err != nil { return Performance{}, fmt.Errorf("备份 nginx.conf 失败: %w", err) } if err := fsutil.WriteFileAtomic(path, []byte(patched), 0o644); err != nil { return Performance{}, fmt.Errorf("写入 nginx.conf 失败: %w", err) } restore := func() { if err := fsutil.WriteFileAtomic(path, raw, 0o644); err != nil { // Nothing else can be done here; the backup path is returned in logs. return } _, _ = m.Validate(context.WithoutCancel(ctx)) _ = m.Reload(context.WithoutCancel(ctx)) } if out, err := m.Validate(ctx); err != nil { restore() return Performance{}, fmt.Errorf("nginx 配置校验失败,已回滚:%s", firstLine(out, err.Error())) } if err := m.Reload(ctx); err != nil { restore() return Performance{}, fmt.Errorf("重载 nginx 失败,已回滚:%v", err) } p.ConfigPath = path p.BackupPath = backup p.AppliedAt = time.Now().Unix() return p, nil } func (p Performance) validate() error { if !regexp.MustCompile(`^(auto|[1-9][0-9]{0,2})$`).MatchString(strings.TrimSpace(p.WorkerProcesses)) { return fmt.Errorf("worker_processes 只能是 auto 或 1-999 的整数") } checks := []struct { name string val int min int max int }{ {"worker_connections", p.WorkerConnections, 128, 1048576}, {"keepalive_timeout", p.KeepaliveTimeout, 0, 3600}, {"gzip_min_length", p.GzipMinLengthKB, 0, 10240}, {"gzip_comp_level", p.GzipCompLevel, 1, 9}, {"client_max_body_size", p.ClientMaxBodyMB, 1, 10240}, {"server_names_hash_bucket_size", p.ServerNamesHashBucket, 32, 16384}, {"client_header_buffer_size", p.ClientHeaderBufferKB, 1, 256}, {"client_body_buffer_size", p.ClientBodyBufferKB, 1, 256}, } for _, c := range checks { if c.val < c.min || c.val > c.max { return fmt.Errorf("%s 需要在 %d-%d 之间", c.name, c.min, c.max) } } if p.ServerNamesHashBucket&(p.ServerNamesHashBucket-1) != 0 { return fmt.Errorf("server_names_hash_bucket_size 必须是 2 的幂(如 32/64/128)") } return nil } func patchPerformance(src string, p Performance) (string, error) { out := src worker := strings.TrimSpace(p.WorkerProcesses) if m := workerProcessesRe.FindStringSubmatchIndex(out); m != nil { out = out[:m[4]] + worker + out[m[5]:] } else { pos := 0 if open, _, ok := blockSpan(out, "events"); ok { pos = open } out = out[:pos] + "worker_processes " + worker + ";\n\n" + out[pos:] } var err error if out, err = setInBlock(out, "events", "worker_connections", strconv.Itoa(p.WorkerConnections)); err != nil { return "", err } gzip := "off" if p.Gzip { gzip = "on" } httpValues := []struct{ name, value string }{ {"keepalive_timeout", strconv.Itoa(p.KeepaliveTimeout)}, {"gzip", gzip}, {"gzip_min_length", fmt.Sprintf("%dk", p.GzipMinLengthKB)}, {"gzip_comp_level", strconv.Itoa(p.GzipCompLevel)}, {"client_max_body_size", fmt.Sprintf("%dm", p.ClientMaxBodyMB)}, {"server_names_hash_bucket_size", strconv.Itoa(p.ServerNamesHashBucket)}, {"client_header_buffer_size", fmt.Sprintf("%dk", p.ClientHeaderBufferKB)}, {"client_body_buffer_size", fmt.Sprintf("%dk", p.ClientBodyBufferKB)}, } for _, item := range httpValues { if out, err = setInBlock(out, "http", item.name, item.value); err != nil { return "", err } } return out, nil } // blockSpan returns the byte offsets of the braces of the first top-level // "name { ... }" block, skipping comments and quoted strings. func blockSpan(src, name string) (int, int, bool) { re := regexp.MustCompile(`(?m)^[ \t]*` + regexp.QuoteMeta(name) + `[ \t]*\{`) loc := re.FindStringIndex(src) if loc == nil { return 0, 0, false } open := strings.Index(src[loc[0]:loc[1]], "{") + loc[0] depth := 0 inComment := false var quote byte for i := open; i < len(src); i++ { c := src[i] if inComment { if c == '\n' { inComment = false } continue } if quote != 0 { if c == '\\' { i++ continue } if c == quote { quote = 0 } continue } switch c { case '#': inComment = true case '\'', '"': quote = c case '{': depth++ case '}': depth-- if depth == 0 { return open, i, true } } } return 0, 0, false } func blockBody(src, name string) (string, bool) { open, close, ok := blockSpan(src, name) if !ok { return "", false } return src[open+1 : close], true } func directiveValue(src, name string) (string, bool) { re := regexp.MustCompile(`(?m)^[ \t]*` + regexp.QuoteMeta(name) + `[ \t]+([^;]+);`) m := re.FindStringSubmatch(src) if m == nil { return "", false } return strings.TrimSpace(m[1]), true } func setInBlock(src, block, name, value string) (string, error) { open, close, ok := blockSpan(src, block) if !ok { return "", fmt.Errorf("nginx.conf 中找不到 %s {} 配置块", block) } body := src[open+1 : close] re := regexp.MustCompile(`(?m)^([ \t]*)` + regexp.QuoteMeta(name) + `[ \t]+[^;]*;`) if re.MatchString(body) { body = re.ReplaceAllString(body, "${1}"+name+" "+value+";") } else if strings.HasPrefix(body, "\n") { body = "\n " + name + " " + value + ";" + body } else { body = " " + name + " " + value + ";" + body } return src[:open+1] + body + src[close:], nil } func parseSizeKB(v string) (int, error) { n, unit, err := splitSize(strings.TrimSpace(strings.ToLower(v))) if err != nil { return 0, err } switch unit { case "": // nginx treats a plain number as bytes return (n + 1023) / 1024, nil case "k": return n, nil case "m": return n * 1024, nil case "g": return n * 1024 * 1024, nil } return 0, fmt.Errorf("未知大小单位 %q", unit) } func parseSizeMB(v string) (int, error) { n, unit, err := splitSize(strings.TrimSpace(strings.ToLower(v))) if err != nil { return 0, err } switch unit { case "": return (n + 1048575) / 1048576, nil case "k": return (n + 1023) / 1024, nil case "m": return n, nil case "g": return n * 1024, nil } return 0, fmt.Errorf("未知大小单位 %q", unit) } func splitSize(v string) (int, string, error) { if v == "" { return 0, "", fmt.Errorf("缺少数值") } i := 0 for i < len(v) && (v[i] >= '0' && v[i] <= '9') { i++ } if i == 0 { return 0, "", fmt.Errorf("数值格式不正确: %q", v) } n, err := strconv.Atoi(v[:i]) if err != nil { return 0, "", err } return n, strings.TrimSpace(v[i:]), nil } func firstLine(out, fallback string) string { for _, line := range strings.Split(out, "\n") { if s := strings.TrimSpace(line); s != "" { return s } } return fallback }