package dbmanager import ( "context" "errors" "fmt" "os" "path/filepath" "regexp" "strconv" "strings" "time" "github.com/miaopanel/miaopanel/internal/fsutil" "github.com/miaopanel/miaopanel/internal/system" ) // Performance is the MySQL/MariaDB tuning form. Sizes are expressed in the unit // the UI shows, so the API stays readable; conversion to my.cnf units happens // in one place. type Performance struct { Version string `json:"version"` ConfigPath string `json:"config_path"` ConfigManaged bool `json:"config_managed"` MemoryTotal uint64 `json:"memory_total"` EstimatedMaxMB float64 `json:"estimated_max_mb"` QueryCacheSupported bool `json:"query_cache_supported"` QueryCacheMB int `json:"query_cache_mb"` TableOpenCache int `json:"table_open_cache"` ThreadCacheSize int `json:"thread_cache_size"` KeyBufferMB int `json:"key_buffer_mb"` TmpTableMB int `json:"tmp_table_mb"` InnoDBPoolMB int `json:"innodb_buffer_pool_mb"` InnoDBLogBufferMB int `json:"innodb_log_buffer_mb"` MaxConnections int `json:"max_connections"` SortBufferKB int `json:"sort_buffer_kb"` ReadBufferKB int `json:"read_buffer_kb"` ReadRndBufferKB int `json:"read_rnd_buffer_kb"` JoinBufferKB int `json:"join_buffer_kb"` ThreadStackKB int `json:"thread_stack_kb"` BinlogCacheKB int `json:"binlog_cache_kb"` AppliedAt int64 `json:"applied_at,omitempty"` RestartRequired bool `json:"restart_required,omitempty"` EstimatedMaxDetail string `json:"estimated_max_detail,omitempty"` } var mysqlPerfVars = []string{ "version", "query_cache_size", "table_open_cache", "thread_cache_size", "key_buffer_size", "tmp_table_size", "innodb_buffer_pool_size", "innodb_log_buffer_size", "max_connections", "sort_buffer_size", "read_buffer_size", "read_rnd_buffer_size", "join_buffer_size", "thread_stack", "binlog_cache_size", } // Performance reads the effective values from the running server, so a value // edited in a distro config file is visible before the panel writes its own. func (s *Service) Performance(ctx context.Context) (Performance, error) { if !s.Available() { return Performance{}, errors.New("未检测到 mysql 客户端,请先安装 MySQL 或 MariaDB") } quoted := make([]string, 0, len(mysqlPerfVars)) for _, v := range mysqlPerfVars { quoted = append(quoted, "'"+v+"'") } out, err := s.runSQL(ctx, "SHOW GLOBAL VARIABLES WHERE Variable_name IN ("+strings.Join(quoted, ",")+")") if err != nil { return Performance{}, err } vars := parseTSV(out) if vars["version"] == "" { if v, err := s.runSQL(ctx, "SELECT @@version"); err == nil { vars["version"] = strings.TrimSpace(v) } } p := Performance{ Version: vars["version"], MemoryTotal: system.Collect("").Memory.Total, QueryCacheSupported: vars["query_cache_size"] != "", QueryCacheMB: bytesToMB(vars["query_cache_size"]), TableOpenCache: atoi(vars["table_open_cache"]), ThreadCacheSize: atoi(vars["thread_cache_size"]), KeyBufferMB: bytesToMB(vars["key_buffer_size"]), TmpTableMB: bytesToMB(vars["tmp_table_size"]), InnoDBPoolMB: bytesToMB(vars["innodb_buffer_pool_size"]), InnoDBLogBufferMB: bytesToMB(vars["innodb_log_buffer_size"]), MaxConnections: atoi(vars["max_connections"]), SortBufferKB: bytesToKB(vars["sort_buffer_size"]), ReadBufferKB: bytesToKB(vars["read_buffer_size"]), ReadRndBufferKB: bytesToKB(vars["read_rnd_buffer_size"]), JoinBufferKB: bytesToKB(vars["join_buffer_size"]), ThreadStackKB: bytesToKB(vars["thread_stack"]), BinlogCacheKB: bytesToKB(vars["binlog_cache_size"]), } path, managed, err := tuningTarget() if err == nil { p.ConfigPath = path p.ConfigManaged = managed } p.EstimatedMaxMB, p.EstimatedMaxDetail = estimateMaxMemory(p) return p, nil } // SavePerformance writes a dedicated 99-miaopanel.cnf inside an includedir, so // distro files stay untouched. The caller must restart MySQL afterwards. func (s *Service) SavePerformance(ctx context.Context, p Performance) (Performance, error) { if !s.Available() { return Performance{}, errors.New("未检测到 mysql 客户端,请先安装 MySQL 或 MariaDB") } p.MemoryTotal = system.Collect("").Memory.Total if err := p.validate(); err != nil { return Performance{}, err } supported, err := s.queryCacheSupported(ctx) if err != nil { return Performance{}, err } if !supported { if p.QueryCacheMB > 0 { return Performance{}, errors.New("当前 MySQL 版本(8.0+)已移除查询缓存,请将 query_cache_size 设为 0") } p.QueryCacheMB = 0 } path, managed, err := tuningTarget() if err != nil { return Performance{}, err } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return Performance{}, fmt.Errorf("创建配置目录失败: %w", err) } // Keep the last known-good file for an automatic rollback on restart. _ = os.MkdirAll(filepath.Dir(path), 0o755) backup := path + ".mp.bak" if raw, err := os.ReadFile(path); err == nil { if err := os.WriteFile(backup, raw, 0o600); err != nil { return Performance{}, fmt.Errorf("备份 MySQL 配置失败: %w", err) } } body := renderMysqld(p, supported) var data []byte if managed { data = []byte("# Managed by MiaoPanel — MySQL performance tuning.\n" + "# Restart MySQL/MariaDB to apply.\n" + body) } else { raw, err := os.ReadFile(path) if err != nil && !os.IsNotExist(err) { return Performance{}, fmt.Errorf("读取 MySQL 配置失败: %w", err) } data = []byte(upsertMysqld(string(raw), body)) } if err := fsutil.WriteFileAtomic(path, data, 0o644); err != nil { return Performance{}, fmt.Errorf("写入 MySQL 配置失败: %w", err) } // On SELinux systems a file created under /etc can end up with a context // mysqld is not allowed to read; restorecon is best effort and harmless // when the command is absent. _, _ = s.runner.Run(ctx, "restorecon", "-F", path) p.ConfigPath = path p.ConfigManaged = managed if v := readVersion(ctx, s); v != "" { p.Version = v } p.MemoryTotal = system.Collect("").Memory.Total p.EstimatedMaxMB, p.EstimatedMaxDetail = estimateMaxMemory(p) p.AppliedAt = time.Now().Unix() p.RestartRequired = true return p, nil } // Restart applies the config with an automatic rollback when the server fails // to start, which is the usual failure mode of a bad option file. func (s *Service) Restart(ctx context.Context) (string, error) { name := "" for _, candidate := range []string{"mysql", "mariadb", "mysqld"} { res, err := s.runner.Run(ctx, "systemctl", "is-active", candidate) if err == nil && strings.TrimSpace(res.Stdout) == "active" { name = candidate break } } if name == "" { return "", errors.New("未检测到正在运行的 MySQL/MariaDB 服务") } res, err := s.runner.RunLong(ctx, 120*time.Second, "systemctl", "restart", name) if err != nil { msg := strings.TrimSpace(res.Stderr) if msg == "" { msg = err.Error() } path, _, _ := tuningTarget() backup := path + ".mp.bak" if raw, readErr := os.ReadFile(backup); readErr == nil { _ = fsutil.WriteFileAtomic(path, raw, 0o644) _, _ = s.runner.RunLong(context.WithoutCancel(ctx), 120*time.Second, "systemctl", "restart", name) return "", fmt.Errorf("重启失败,已回滚到上一次配置:%s", msg) } _ = os.Remove(path) _, _ = s.runner.RunLong(context.WithoutCancel(ctx), 120*time.Second, "systemctl", "restart", name) return "", fmt.Errorf("重启失败,已删除本次写入的配置:%s", msg) } // This config is now known good: make it the rollback target. if path, _, err := tuningTarget(); err == nil { if raw, err := os.ReadFile(path); err == nil { _ = os.WriteFile(path+".mp.bak", raw, 0o600) } } return name, nil } func (p Performance) validate() error { checks := []struct { name string val int min int max int }{ {"query_cache_size", p.QueryCacheMB, 0, 4096}, {"table_open_cache", p.TableOpenCache, 1, 2000000}, {"thread_cache_size", p.ThreadCacheSize, 0, 10000}, {"key_buffer_size", p.KeyBufferMB, 0, 8192}, {"tmp_table_size", p.TmpTableMB, 1, 16384}, {"innodb_buffer_pool_size", p.InnoDBPoolMB, 16, 262144}, {"innodb_log_buffer_size", p.InnoDBLogBufferMB, 1, 2048}, {"max_connections", p.MaxConnections, 10, 100000}, {"sort_buffer_size", p.SortBufferKB, 16, 1048576}, {"read_buffer_size", p.ReadBufferKB, 16, 1048576}, {"read_rnd_buffer_size", p.ReadRndBufferKB, 16, 1048576}, {"join_buffer_size", p.JoinBufferKB, 16, 1048576}, {"thread_stack", p.ThreadStackKB, 64, 1024}, {"binlog_cache_size", p.BinlogCacheKB, 4, 1048576}, } 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.MaxConnections > 0 { perConn := (p.SortBufferKB + p.ReadBufferKB + p.ReadRndBufferKB + p.JoinBufferKB + p.ThreadStackKB + p.BinlogCacheKB) / 1024 est := p.InnoDBPoolMB + p.KeyBufferMB + p.QueryCacheMB + p.TmpTableMB + p.InnoDBLogBufferMB + p.MaxConnections*perConn if p.MemoryTotal > 0 && float64(est) > float64(p.MemoryTotal)/1048576*1.2 { return fmt.Errorf("按当前参数估算最多占用 %d MB,已超过本机内存的 120%%,请降低连接数或缓冲区", est) } } return nil } func renderMysqld(p Performance, queryCache bool) string { var b strings.Builder b.WriteString("\n[mysqld]\n") lines := []struct{ key, val string }{ {"table_open_cache", strconv.Itoa(p.TableOpenCache)}, {"thread_cache_size", strconv.Itoa(p.ThreadCacheSize)}, {"key_buffer_size", fmt.Sprintf("%dM", p.KeyBufferMB)}, {"tmp_table_size", fmt.Sprintf("%dM", p.TmpTableMB)}, {"innodb_buffer_pool_size", fmt.Sprintf("%dM", p.InnoDBPoolMB)}, {"innodb_log_buffer_size", fmt.Sprintf("%dM", p.InnoDBLogBufferMB)}, {"max_connections", strconv.Itoa(p.MaxConnections)}, {"sort_buffer_size", fmt.Sprintf("%dK", p.SortBufferKB)}, {"read_buffer_size", fmt.Sprintf("%dK", p.ReadBufferKB)}, {"read_rnd_buffer_size", fmt.Sprintf("%dK", p.ReadRndBufferKB)}, {"join_buffer_size", fmt.Sprintf("%dK", p.JoinBufferKB)}, {"thread_stack", fmt.Sprintf("%dK", p.ThreadStackKB)}, {"binlog_cache_size", fmt.Sprintf("%dK", p.BinlogCacheKB)}, } if queryCache { queryType := "0" if p.QueryCacheMB > 0 { queryType = "1" } lines = append([]struct{ key, val string }{ {"query_cache_size", fmt.Sprintf("%dM", p.QueryCacheMB)}, {"query_cache_type", queryType}, }, lines...) } for _, l := range lines { fmt.Fprintf(&b, "%s = %s\n", l.key, l.val) } return b.String() } // upsertMysqld patches a main my.cnf that has no includedir. Only keys inside // [mysqld] are touched; every other section is preserved byte for byte. func upsertMysqld(raw, body string) string { header := regexp.MustCompile(`(?mi)^[ \t]*\[mysqld\][ \t]*$`) loc := header.FindStringIndex(raw) if loc == nil { if !strings.HasSuffix(raw, "\n") && raw != "" { raw += "\n" } return raw + body } // Body of the [mysqld] section ends at the next section header. rest := raw[loc[1]:] next := regexp.MustCompile(`(?m)^[ \t]*\[[^\]]+\][ \t]*$`).FindStringIndex(rest) head := raw[:loc[1]] tail := "" if next != nil { tail = rest[next[0]:] } section := raw[loc[1]:] if next != nil { section = section[:next[0]] } for _, line := range strings.Split(strings.TrimSpace(body), "\n") { line = strings.TrimSpace(line) if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "[") { continue } key := strings.TrimSpace(strings.SplitN(line, "=", 2)[0]) value := strings.TrimSpace(strings.SplitN(line, "=", 2)[1]) re := regexp.MustCompile(`(?mi)^[ \t]*` + regexp.QuoteMeta(key) + `[ \t]*=.*$`) if re.MatchString(section) { section = re.ReplaceAllString(section, key+" = "+value) } else { if !strings.HasSuffix(section, "\n") { section += "\n" } section += key + " = " + value + "\n" } } return head + section + tail } // tuningTarget prefers a numeric conf.d file so distro defaults are overridden // by load order. Falls back to patching the main file. func tuningTarget() (string, bool, error) { // The app store's legacy MySQL (5.5/5.6/5.7) runs with // --defaults-file=/www/server/mysql/my.cnf; distro paths are not read by // that process, so tuning must target the legacy file when it is active. if st, err := os.Stat("/www/server/mysql/current"); err == nil && st.IsDir() { if st, err := os.Stat("/www/server/mysql/my.cnf"); err == nil && !st.IsDir() { return "/www/server/mysql/my.cnf", false, nil } } mains := []string{"/etc/mysql/my.cnf", "/etc/my.cnf"} for _, main := range mains { raw, err := os.ReadFile(main) if err != nil { continue } // Option files are read in order, so the LAST includedir wins. Writing // there guarantees our 99- file overrides the distro's 50- defaults. lastDir := "" for _, line := range strings.Split(string(raw), "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "!includedir") { continue } dir := strings.TrimSpace(strings.TrimPrefix(line, "!includedir")) if st, err := os.Stat(dir); err == nil && st.IsDir() { lastDir = dir } } if lastDir != "" { return filepath.Join(lastDir, "99-miaopanel.cnf"), true, nil } return main, false, nil } for _, dir := range []string{ "/etc/mysql/mysql.conf.d", "/etc/mysql/mariadb.conf.d", "/etc/mysql/conf.d", "/etc/my.cnf.d", } { if st, err := os.Stat(dir); err == nil && st.IsDir() { return filepath.Join(dir, "99-miaopanel.cnf"), true, nil } } return "/etc/my.cnf", false, nil } func (s *Service) queryCacheSupported(ctx context.Context) (bool, error) { out, err := s.runSQL(ctx, "SHOW GLOBAL VARIABLES LIKE 'query_cache_size'") if err != nil { return false, err } return strings.TrimSpace(out) != "", nil } func readVersion(ctx context.Context, s *Service) string { out, err := s.runSQL(ctx, "SELECT @@version") if err != nil { return "" } return strings.TrimSpace(out) } func estimateMaxMemory(p Performance) (float64, string) { perConnKB := p.SortBufferKB + p.ReadBufferKB + p.ReadRndBufferKB + p.JoinBufferKB + p.ThreadStackKB + p.BinlogCacheKB perConnMB := float64(perConnKB) / 1024 est := float64(p.InnoDBPoolMB+p.KeyBufferMB+p.QueryCacheMB+p.TmpTableMB+p.InnoDBLogBufferMB) + float64(p.MaxConnections)*perConnMB detail := fmt.Sprintf("InnoDB %dMB + key %dMB + 查询缓存 %dMB + 临时表 %dMB + 连接 %d×%.1fMB", p.InnoDBPoolMB, p.KeyBufferMB, p.QueryCacheMB, p.TmpTableMB, p.MaxConnections, perConnMB) return est, detail } // Status is the "current state" tab. type Status struct { Version string `json:"version"` StartTime int64 `json:"start_time"` Uptime int64 `json:"uptime"` Connections int64 `json:"connections"` BytesSent uint64 `json:"bytes_sent"` BytesReceived uint64 `json:"bytes_received"` QPS float64 `json:"qps"` TPS float64 `json:"tps"` ThreadsConnected int64 `json:"threads_connected"` MaxUsedConnections int64 `json:"max_used_connections"` MaxConnections int64 `json:"max_connections"` ThreadCacheHit float64 `json:"thread_cache_hit"` KeyBufferHit float64 `json:"key_buffer_hit"` InnoDBBufferHit float64 `json:"innodb_buffer_hit"` QueryCacheHit float64 `json:"query_cache_hit"` QueryCacheEnabled bool `json:"query_cache_enabled"` TmpDiskRatio float64 `json:"tmp_disk_ratio"` OpenTables int64 `json:"open_tables"` TableOpenCache int64 `json:"table_open_cache"` ThreadCacheSize int64 `json:"thread_cache_size"` KeyBufferMB int64 `json:"key_buffer_mb"` TmpTableMB int64 `json:"tmp_table_mb"` InnoDBPoolMB int64 `json:"innodb_buffer_pool_mb"` QueryCacheMB int64 `json:"query_cache_mb"` SortBufferKB int64 `json:"sort_buffer_kb"` SelectScan int64 `json:"select_scan"` SelectFullJoin int64 `json:"select_full_join"` SortMergePasses int64 `json:"sort_merge_passes"` BinlogFile string `json:"binlog_file"` BinlogPosition int64 `json:"binlog_position"` BinlogSupported bool `json:"binlog_supported"` } // Status reads SHOW GLOBAL STATUS and derives the hit ratios shown in the UI. func (s *Service) Status(ctx context.Context) (Status, error) { if !s.Available() { return Status{}, errors.New("未检测到 mysql 客户端,请先安装 MySQL 或 MariaDB") } out, err := s.runSQL(ctx, "SHOW GLOBAL STATUS") if err != nil { return Status{}, err } st := parseTSV(out) varsOut, err := s.runSQL(ctx, "SHOW GLOBAL VARIABLES WHERE Variable_name IN ("+ "'max_connections','table_open_cache','query_cache_size','thread_cache_size',"+ "'key_buffer_size','tmp_table_size','innodb_buffer_pool_size','sort_buffer_size')") if err != nil { return Status{}, err } vars := parseTSV(varsOut) uptime := atoi64(st["Uptime"]) questions := atoi64(st["Questions"]) commits := atoi64(st["Com_commit"]) + atoi64(st["Com_rollback"]) res := Status{ Version: readVersion(ctx, s), Uptime: uptime, Connections: atoi64(st["Connections"]), BytesSent: atoi64u(st["Bytes_sent"]), BytesReceived: atoi64u(st["Bytes_received"]), ThreadsConnected: atoi64(st["Threads_connected"]), MaxUsedConnections: atoi64(st["Max_used_connections"]), MaxConnections: atoi64(vars["max_connections"]), OpenTables: atoi64(st["Open_tables"]), TableOpenCache: atoi64(vars["table_open_cache"]), ThreadCacheSize: atoi64(vars["thread_cache_size"]), KeyBufferMB: atoi64(vars["key_buffer_size"]) / 1048576, TmpTableMB: atoi64(vars["tmp_table_size"]) / 1048576, InnoDBPoolMB: atoi64(vars["innodb_buffer_pool_size"]) / 1048576, QueryCacheMB: atoi64(vars["query_cache_size"]) / 1048576, SortBufferKB: atoi64(vars["sort_buffer_size"]) / 1024, SelectScan: atoi64(st["Select_scan"]), SelectFullJoin: atoi64(st["Select_full_join"]), SortMergePasses: atoi64(st["Sort_merge_passes"]), QueryCacheEnabled: atoi64(vars["query_cache_size"]) > 0, } if uptime > 0 { res.StartTime = time.Now().Unix() - uptime res.QPS = float64(questions) / float64(uptime) res.TPS = float64(commits) / float64(uptime) } if c := res.Connections; c > 0 { res.ThreadCacheHit = rate(c-atoi64(st["Threads_created"]), c) } if v := atoi64(st["Key_read_requests"]); v > 0 { res.KeyBufferHit = rate(v-atoi64(st["Key_reads"]), v) } if v := atoi64(st["Innodb_buffer_pool_read_requests"]); v > 0 { res.InnoDBBufferHit = rate(v-atoi64(st["Innodb_buffer_pool_reads"]), v) } if res.QueryCacheEnabled { hits := atoi64(st["Qcache_hits"]) total := hits + atoi64(st["Qcache_inserts"]) + atoi64(st["Qcache_not_cached"]) if total > 0 { res.QueryCacheHit = float64(hits) / float64(total) * 100 } } if v := atoi64(st["Created_tmp_tables"]); v > 0 { res.TmpDiskRatio = float64(atoi64(st["Created_tmp_disk_tables"])) / float64(v) * 100 } if line, ok := s.binlogStatus(ctx); ok { parts := strings.Split(line, "\t") if len(parts) >= 2 { res.BinlogSupported = true res.BinlogFile = strings.TrimSpace(parts[0]) res.BinlogPosition = atoi64(parts[1]) } } return res, nil } func (s *Service) binlogStatus(ctx context.Context) (string, bool) { for _, sql := range []string{"SHOW MASTER STATUS", "SHOW BINARY LOG STATUS"} { if out, err := s.runSQL(ctx, sql); err == nil { if line := strings.TrimSpace(out); line != "" { return line, true } } } return "", false } func parseTSV(out string) map[string]string { m := make(map[string]string) for _, line := range strings.Split(out, "\n") { line = strings.TrimRight(line, "\r") if line == "" { continue } parts := strings.SplitN(line, "\t", 2) if len(parts) != 2 { continue } m[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) } return m } func rate(part, total int64) float64 { if total <= 0 { return 0 } return float64(part) / float64(total) * 100 } func atoi(s string) int { n, _ := strconv.Atoi(strings.TrimSpace(s)) return n } func atoi64(s string) int64 { n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64) return n } func atoi64u(s string) uint64 { n, _ := strconv.ParseUint(strings.TrimSpace(s), 10, 64) return n } func bytesToMB(s string) int { return int(atoi64(s) / 1048576) } func bytesToKB(s string) int { return int(atoi64(s) / 1024) }