仰望星辰工作室

miaopanel

miaopanel/ internal/dbmanager/tuning.go 20.2 KB · 571 行 原始文件
1package dbmanager
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "regexp"
10 "strconv"
11 "strings"
12 "time"
13
14 "github.com/miaopanel/miaopanel/internal/fsutil"
15 "github.com/miaopanel/miaopanel/internal/system"
16)
17
18// Performance is the MySQL/MariaDB tuning form. Sizes are expressed in the unit
19// the UI shows, so the API stays readable; conversion to my.cnf units happens
20// in one place.
21type Performance struct {
22 Version string `json:"version"`
23 ConfigPath string `json:"config_path"`
24 ConfigManaged bool `json:"config_managed"`
25 MemoryTotal uint64 `json:"memory_total"`
26 EstimatedMaxMB float64 `json:"estimated_max_mb"`
27 QueryCacheSupported bool `json:"query_cache_supported"`
28
29 QueryCacheMB int `json:"query_cache_mb"`
30 TableOpenCache int `json:"table_open_cache"`
31 ThreadCacheSize int `json:"thread_cache_size"`
32 KeyBufferMB int `json:"key_buffer_mb"`
33 TmpTableMB int `json:"tmp_table_mb"`
34 InnoDBPoolMB int `json:"innodb_buffer_pool_mb"`
35 InnoDBLogBufferMB int `json:"innodb_log_buffer_mb"`
36 MaxConnections int `json:"max_connections"`
37 SortBufferKB int `json:"sort_buffer_kb"`
38 ReadBufferKB int `json:"read_buffer_kb"`
39 ReadRndBufferKB int `json:"read_rnd_buffer_kb"`
40 JoinBufferKB int `json:"join_buffer_kb"`
41 ThreadStackKB int `json:"thread_stack_kb"`
42 BinlogCacheKB int `json:"binlog_cache_kb"`
43 AppliedAt int64 `json:"applied_at,omitempty"`
44 RestartRequired bool `json:"restart_required,omitempty"`
45 EstimatedMaxDetail string `json:"estimated_max_detail,omitempty"`
46}
47
48var mysqlPerfVars = []string{
49 "version", "query_cache_size", "table_open_cache", "thread_cache_size",
50 "key_buffer_size", "tmp_table_size", "innodb_buffer_pool_size",
51 "innodb_log_buffer_size", "max_connections", "sort_buffer_size",
52 "read_buffer_size", "read_rnd_buffer_size", "join_buffer_size",
53 "thread_stack", "binlog_cache_size",
54}
55
56// Performance reads the effective values from the running server, so a value
57// edited in a distro config file is visible before the panel writes its own.
58func (s *Service) Performance(ctx context.Context) (Performance, error) {
59 if !s.Available() {
60 return Performance{}, errors.New("未检测到 mysql 客户端,请先安装 MySQL 或 MariaDB")
61 }
62 quoted := make([]string, 0, len(mysqlPerfVars))
63 for _, v := range mysqlPerfVars {
64 quoted = append(quoted, "'"+v+"'")
65 }
66 out, err := s.runSQL(ctx, "SHOW GLOBAL VARIABLES WHERE Variable_name IN ("+strings.Join(quoted, ",")+")")
67 if err != nil {
68 return Performance{}, err
69 }
70 vars := parseTSV(out)
71 if vars["version"] == "" {
72 if v, err := s.runSQL(ctx, "SELECT @@version"); err == nil {
73 vars["version"] = strings.TrimSpace(v)
74 }
75 }
76 p := Performance{
77 Version: vars["version"],
78 MemoryTotal: system.Collect("").Memory.Total,
79 QueryCacheSupported: vars["query_cache_size"] != "",
80 QueryCacheMB: bytesToMB(vars["query_cache_size"]),
81 TableOpenCache: atoi(vars["table_open_cache"]),
82 ThreadCacheSize: atoi(vars["thread_cache_size"]),
83 KeyBufferMB: bytesToMB(vars["key_buffer_size"]),
84 TmpTableMB: bytesToMB(vars["tmp_table_size"]),
85 InnoDBPoolMB: bytesToMB(vars["innodb_buffer_pool_size"]),
86 InnoDBLogBufferMB: bytesToMB(vars["innodb_log_buffer_size"]),
87 MaxConnections: atoi(vars["max_connections"]),
88 SortBufferKB: bytesToKB(vars["sort_buffer_size"]),
89 ReadBufferKB: bytesToKB(vars["read_buffer_size"]),
90 ReadRndBufferKB: bytesToKB(vars["read_rnd_buffer_size"]),
91 JoinBufferKB: bytesToKB(vars["join_buffer_size"]),
92 ThreadStackKB: bytesToKB(vars["thread_stack"]),
93 BinlogCacheKB: bytesToKB(vars["binlog_cache_size"]),
94 }
95 path, managed, err := tuningTarget()
96 if err == nil {
97 p.ConfigPath = path
98 p.ConfigManaged = managed
99 }
100 p.EstimatedMaxMB, p.EstimatedMaxDetail = estimateMaxMemory(p)
101 return p, nil
102}
103
104// SavePerformance writes a dedicated 99-miaopanel.cnf inside an includedir, so
105// distro files stay untouched. The caller must restart MySQL afterwards.
106func (s *Service) SavePerformance(ctx context.Context, p Performance) (Performance, error) {
107 if !s.Available() {
108 return Performance{}, errors.New("未检测到 mysql 客户端,请先安装 MySQL 或 MariaDB")
109 }
110 p.MemoryTotal = system.Collect("").Memory.Total
111 if err := p.validate(); err != nil {
112 return Performance{}, err
113 }
114 supported, err := s.queryCacheSupported(ctx)
115 if err != nil {
116 return Performance{}, err
117 }
118 if !supported {
119 if p.QueryCacheMB > 0 {
120 return Performance{}, errors.New("当前 MySQL 版本(8.0+)已移除查询缓存,请将 query_cache_size 设为 0")
121 }
122 p.QueryCacheMB = 0
123 }
124
125 path, managed, err := tuningTarget()
126 if err != nil {
127 return Performance{}, err
128 }
129 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
130 return Performance{}, fmt.Errorf("创建配置目录失败: %w", err)
131 }
132
133 // Keep the last known-good file for an automatic rollback on restart.
134 _ = os.MkdirAll(filepath.Dir(path), 0o755)
135 backup := path + ".mp.bak"
136 if raw, err := os.ReadFile(path); err == nil {
137 if err := os.WriteFile(backup, raw, 0o600); err != nil {
138 return Performance{}, fmt.Errorf("备份 MySQL 配置失败: %w", err)
139 }
140 }
141
142 body := renderMysqld(p, supported)
143 var data []byte
144 if managed {
145 data = []byte("# Managed by MiaoPanel — MySQL performance tuning.\n" +
146 "# Restart MySQL/MariaDB to apply.\n" + body)
147 } else {
148 raw, err := os.ReadFile(path)
149 if err != nil && !os.IsNotExist(err) {
150 return Performance{}, fmt.Errorf("读取 MySQL 配置失败: %w", err)
151 }
152 data = []byte(upsertMysqld(string(raw), body))
153 }
154 if err := fsutil.WriteFileAtomic(path, data, 0o644); err != nil {
155 return Performance{}, fmt.Errorf("写入 MySQL 配置失败: %w", err)
156 }
157 // On SELinux systems a file created under /etc can end up with a context
158 // mysqld is not allowed to read; restorecon is best effort and harmless
159 // when the command is absent.
160 _, _ = s.runner.Run(ctx, "restorecon", "-F", path)
161
162 p.ConfigPath = path
163 p.ConfigManaged = managed
164 if v := readVersion(ctx, s); v != "" {
165 p.Version = v
166 }
167 p.MemoryTotal = system.Collect("").Memory.Total
168 p.EstimatedMaxMB, p.EstimatedMaxDetail = estimateMaxMemory(p)
169 p.AppliedAt = time.Now().Unix()
170 p.RestartRequired = true
171 return p, nil
172}
173
174// Restart applies the config with an automatic rollback when the server fails
175// to start, which is the usual failure mode of a bad option file.
176func (s *Service) Restart(ctx context.Context) (string, error) {
177 name := ""
178 for _, candidate := range []string{"mysql", "mariadb", "mysqld"} {
179 res, err := s.runner.Run(ctx, "systemctl", "is-active", candidate)
180 if err == nil && strings.TrimSpace(res.Stdout) == "active" {
181 name = candidate
182 break
183 }
184 }
185 if name == "" {
186 return "", errors.New("未检测到正在运行的 MySQL/MariaDB 服务")
187 }
188 res, err := s.runner.RunLong(ctx, 120*time.Second, "systemctl", "restart", name)
189 if err != nil {
190 msg := strings.TrimSpace(res.Stderr)
191 if msg == "" {
192 msg = err.Error()
193 }
194 path, _, _ := tuningTarget()
195 backup := path + ".mp.bak"
196 if raw, readErr := os.ReadFile(backup); readErr == nil {
197 _ = fsutil.WriteFileAtomic(path, raw, 0o644)
198 _, _ = s.runner.RunLong(context.WithoutCancel(ctx), 120*time.Second, "systemctl", "restart", name)
199 return "", fmt.Errorf("重启失败,已回滚到上一次配置:%s", msg)
200 }
201 _ = os.Remove(path)
202 _, _ = s.runner.RunLong(context.WithoutCancel(ctx), 120*time.Second, "systemctl", "restart", name)
203 return "", fmt.Errorf("重启失败,已删除本次写入的配置:%s", msg)
204 }
205 // This config is now known good: make it the rollback target.
206 if path, _, err := tuningTarget(); err == nil {
207 if raw, err := os.ReadFile(path); err == nil {
208 _ = os.WriteFile(path+".mp.bak", raw, 0o600)
209 }
210 }
211 return name, nil
212}
213
214func (p Performance) validate() error {
215 checks := []struct {
216 name string
217 val int
218 min int
219 max int
220 }{
221 {"query_cache_size", p.QueryCacheMB, 0, 4096},
222 {"table_open_cache", p.TableOpenCache, 1, 2000000},
223 {"thread_cache_size", p.ThreadCacheSize, 0, 10000},
224 {"key_buffer_size", p.KeyBufferMB, 0, 8192},
225 {"tmp_table_size", p.TmpTableMB, 1, 16384},
226 {"innodb_buffer_pool_size", p.InnoDBPoolMB, 16, 262144},
227 {"innodb_log_buffer_size", p.InnoDBLogBufferMB, 1, 2048},
228 {"max_connections", p.MaxConnections, 10, 100000},
229 {"sort_buffer_size", p.SortBufferKB, 16, 1048576},
230 {"read_buffer_size", p.ReadBufferKB, 16, 1048576},
231 {"read_rnd_buffer_size", p.ReadRndBufferKB, 16, 1048576},
232 {"join_buffer_size", p.JoinBufferKB, 16, 1048576},
233 {"thread_stack", p.ThreadStackKB, 64, 1024},
234 {"binlog_cache_size", p.BinlogCacheKB, 4, 1048576},
235 }
236 for _, c := range checks {
237 if c.val < c.min || c.val > c.max {
238 return fmt.Errorf("%s 需要在 %d-%d 之间", c.name, c.min, c.max)
239 }
240 }
241 if p.MaxConnections > 0 {
242 perConn := (p.SortBufferKB + p.ReadBufferKB + p.ReadRndBufferKB +
243 p.JoinBufferKB + p.ThreadStackKB + p.BinlogCacheKB) / 1024
244 est := p.InnoDBPoolMB + p.KeyBufferMB + p.QueryCacheMB + p.TmpTableMB +
245 p.InnoDBLogBufferMB + p.MaxConnections*perConn
246 if p.MemoryTotal > 0 && float64(est) > float64(p.MemoryTotal)/1048576*1.2 {
247 return fmt.Errorf("按当前参数估算最多占用 %d MB,已超过本机内存的 120%%,请降低连接数或缓冲区", est)
248 }
249 }
250 return nil
251}
252
253func renderMysqld(p Performance, queryCache bool) string {
254 var b strings.Builder
255 b.WriteString("\n[mysqld]\n")
256 lines := []struct{ key, val string }{
257 {"table_open_cache", strconv.Itoa(p.TableOpenCache)},
258 {"thread_cache_size", strconv.Itoa(p.ThreadCacheSize)},
259 {"key_buffer_size", fmt.Sprintf("%dM", p.KeyBufferMB)},
260 {"tmp_table_size", fmt.Sprintf("%dM", p.TmpTableMB)},
261 {"innodb_buffer_pool_size", fmt.Sprintf("%dM", p.InnoDBPoolMB)},
262 {"innodb_log_buffer_size", fmt.Sprintf("%dM", p.InnoDBLogBufferMB)},
263 {"max_connections", strconv.Itoa(p.MaxConnections)},
264 {"sort_buffer_size", fmt.Sprintf("%dK", p.SortBufferKB)},
265 {"read_buffer_size", fmt.Sprintf("%dK", p.ReadBufferKB)},
266 {"read_rnd_buffer_size", fmt.Sprintf("%dK", p.ReadRndBufferKB)},
267 {"join_buffer_size", fmt.Sprintf("%dK", p.JoinBufferKB)},
268 {"thread_stack", fmt.Sprintf("%dK", p.ThreadStackKB)},
269 {"binlog_cache_size", fmt.Sprintf("%dK", p.BinlogCacheKB)},
270 }
271 if queryCache {
272 queryType := "0"
273 if p.QueryCacheMB > 0 {
274 queryType = "1"
275 }
276 lines = append([]struct{ key, val string }{
277 {"query_cache_size", fmt.Sprintf("%dM", p.QueryCacheMB)},
278 {"query_cache_type", queryType},
279 }, lines...)
280 }
281 for _, l := range lines {
282 fmt.Fprintf(&b, "%s = %s\n", l.key, l.val)
283 }
284 return b.String()
285}
286
287// upsertMysqld patches a main my.cnf that has no includedir. Only keys inside
288// [mysqld] are touched; every other section is preserved byte for byte.
289func upsertMysqld(raw, body string) string {
290 header := regexp.MustCompile(`(?mi)^[ \t]*\[mysqld\][ \t]*$`)
291 loc := header.FindStringIndex(raw)
292 if loc == nil {
293 if !strings.HasSuffix(raw, "\n") && raw != "" {
294 raw += "\n"
295 }
296 return raw + body
297 }
298 // Body of the [mysqld] section ends at the next section header.
299 rest := raw[loc[1]:]
300 next := regexp.MustCompile(`(?m)^[ \t]*\[[^\]]+\][ \t]*$`).FindStringIndex(rest)
301 head := raw[:loc[1]]
302 tail := ""
303 if next != nil {
304 tail = rest[next[0]:]
305 }
306 section := raw[loc[1]:]
307 if next != nil {
308 section = section[:next[0]]
309 }
310 for _, line := range strings.Split(strings.TrimSpace(body), "\n") {
311 line = strings.TrimSpace(line)
312 if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "[") {
313 continue
314 }
315 key := strings.TrimSpace(strings.SplitN(line, "=", 2)[0])
316 value := strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
317 re := regexp.MustCompile(`(?mi)^[ \t]*` + regexp.QuoteMeta(key) + `[ \t]*=.*$`)
318 if re.MatchString(section) {
319 section = re.ReplaceAllString(section, key+" = "+value)
320 } else {
321 if !strings.HasSuffix(section, "\n") {
322 section += "\n"
323 }
324 section += key + " = " + value + "\n"
325 }
326 }
327 return head + section + tail
328}
329
330// tuningTarget prefers a numeric conf.d file so distro defaults are overridden
331// by load order. Falls back to patching the main file.
332func tuningTarget() (string, bool, error) {
333 // The app store's legacy MySQL (5.5/5.6/5.7) runs with
334 // --defaults-file=/www/server/mysql/my.cnf; distro paths are not read by
335 // that process, so tuning must target the legacy file when it is active.
336 if st, err := os.Stat("/www/server/mysql/current"); err == nil && st.IsDir() {
337 if st, err := os.Stat("/www/server/mysql/my.cnf"); err == nil && !st.IsDir() {
338 return "/www/server/mysql/my.cnf", false, nil
339 }
340 }
341 mains := []string{"/etc/mysql/my.cnf", "/etc/my.cnf"}
342 for _, main := range mains {
343 raw, err := os.ReadFile(main)
344 if err != nil {
345 continue
346 }
347 // Option files are read in order, so the LAST includedir wins. Writing
348 // there guarantees our 99- file overrides the distro's 50- defaults.
349 lastDir := ""
350 for _, line := range strings.Split(string(raw), "\n") {
351 line = strings.TrimSpace(line)
352 if !strings.HasPrefix(line, "!includedir") {
353 continue
354 }
355 dir := strings.TrimSpace(strings.TrimPrefix(line, "!includedir"))
356 if st, err := os.Stat(dir); err == nil && st.IsDir() {
357 lastDir = dir
358 }
359 }
360 if lastDir != "" {
361 return filepath.Join(lastDir, "99-miaopanel.cnf"), true, nil
362 }
363 return main, false, nil
364 }
365 for _, dir := range []string{
366 "/etc/mysql/mysql.conf.d", "/etc/mysql/mariadb.conf.d",
367 "/etc/mysql/conf.d", "/etc/my.cnf.d",
368 } {
369 if st, err := os.Stat(dir); err == nil && st.IsDir() {
370 return filepath.Join(dir, "99-miaopanel.cnf"), true, nil
371 }
372 }
373 return "/etc/my.cnf", false, nil
374}
375
376func (s *Service) queryCacheSupported(ctx context.Context) (bool, error) {
377 out, err := s.runSQL(ctx, "SHOW GLOBAL VARIABLES LIKE 'query_cache_size'")
378 if err != nil {
379 return false, err
380 }
381 return strings.TrimSpace(out) != "", nil
382}
383
384func readVersion(ctx context.Context, s *Service) string {
385 out, err := s.runSQL(ctx, "SELECT @@version")
386 if err != nil {
387 return ""
388 }
389 return strings.TrimSpace(out)
390}
391
392func estimateMaxMemory(p Performance) (float64, string) {
393 perConnKB := p.SortBufferKB + p.ReadBufferKB + p.ReadRndBufferKB +
394 p.JoinBufferKB + p.ThreadStackKB + p.BinlogCacheKB
395 perConnMB := float64(perConnKB) / 1024
396 est := float64(p.InnoDBPoolMB+p.KeyBufferMB+p.QueryCacheMB+p.TmpTableMB+p.InnoDBLogBufferMB) +
397 float64(p.MaxConnections)*perConnMB
398 detail := fmt.Sprintf("InnoDB %dMB + key %dMB + 查询缓存 %dMB + 临时表 %dMB + 连接 %d×%.1fMB",
399 p.InnoDBPoolMB, p.KeyBufferMB, p.QueryCacheMB, p.TmpTableMB, p.MaxConnections, perConnMB)
400 return est, detail
401}
402
403// Status is the "current state" tab.
404type Status struct {
405 Version string `json:"version"`
406 StartTime int64 `json:"start_time"`
407 Uptime int64 `json:"uptime"`
408 Connections int64 `json:"connections"`
409 BytesSent uint64 `json:"bytes_sent"`
410 BytesReceived uint64 `json:"bytes_received"`
411 QPS float64 `json:"qps"`
412 TPS float64 `json:"tps"`
413 ThreadsConnected int64 `json:"threads_connected"`
414 MaxUsedConnections int64 `json:"max_used_connections"`
415 MaxConnections int64 `json:"max_connections"`
416 ThreadCacheHit float64 `json:"thread_cache_hit"`
417 KeyBufferHit float64 `json:"key_buffer_hit"`
418 InnoDBBufferHit float64 `json:"innodb_buffer_hit"`
419 QueryCacheHit float64 `json:"query_cache_hit"`
420 QueryCacheEnabled bool `json:"query_cache_enabled"`
421 TmpDiskRatio float64 `json:"tmp_disk_ratio"`
422 OpenTables int64 `json:"open_tables"`
423 TableOpenCache int64 `json:"table_open_cache"`
424 ThreadCacheSize int64 `json:"thread_cache_size"`
425 KeyBufferMB int64 `json:"key_buffer_mb"`
426 TmpTableMB int64 `json:"tmp_table_mb"`
427 InnoDBPoolMB int64 `json:"innodb_buffer_pool_mb"`
428 QueryCacheMB int64 `json:"query_cache_mb"`
429 SortBufferKB int64 `json:"sort_buffer_kb"`
430 SelectScan int64 `json:"select_scan"`
431 SelectFullJoin int64 `json:"select_full_join"`
432 SortMergePasses int64 `json:"sort_merge_passes"`
433 BinlogFile string `json:"binlog_file"`
434 BinlogPosition int64 `json:"binlog_position"`
435 BinlogSupported bool `json:"binlog_supported"`
436}
437
438// Status reads SHOW GLOBAL STATUS and derives the hit ratios shown in the UI.
439func (s *Service) Status(ctx context.Context) (Status, error) {
440 if !s.Available() {
441 return Status{}, errors.New("未检测到 mysql 客户端,请先安装 MySQL 或 MariaDB")
442 }
443 out, err := s.runSQL(ctx, "SHOW GLOBAL STATUS")
444 if err != nil {
445 return Status{}, err
446 }
447 st := parseTSV(out)
448 varsOut, err := s.runSQL(ctx, "SHOW GLOBAL VARIABLES WHERE Variable_name IN ("+
449 "'max_connections','table_open_cache','query_cache_size','thread_cache_size',"+
450 "'key_buffer_size','tmp_table_size','innodb_buffer_pool_size','sort_buffer_size')")
451 if err != nil {
452 return Status{}, err
453 }
454 vars := parseTSV(varsOut)
455
456 uptime := atoi64(st["Uptime"])
457 questions := atoi64(st["Questions"])
458 commits := atoi64(st["Com_commit"]) + atoi64(st["Com_rollback"])
459 res := Status{
460 Version: readVersion(ctx, s),
461 Uptime: uptime,
462 Connections: atoi64(st["Connections"]),
463 BytesSent: atoi64u(st["Bytes_sent"]),
464 BytesReceived: atoi64u(st["Bytes_received"]),
465 ThreadsConnected: atoi64(st["Threads_connected"]),
466 MaxUsedConnections: atoi64(st["Max_used_connections"]),
467 MaxConnections: atoi64(vars["max_connections"]),
468 OpenTables: atoi64(st["Open_tables"]),
469 TableOpenCache: atoi64(vars["table_open_cache"]),
470 ThreadCacheSize: atoi64(vars["thread_cache_size"]),
471 KeyBufferMB: atoi64(vars["key_buffer_size"]) / 1048576,
472 TmpTableMB: atoi64(vars["tmp_table_size"]) / 1048576,
473 InnoDBPoolMB: atoi64(vars["innodb_buffer_pool_size"]) / 1048576,
474 QueryCacheMB: atoi64(vars["query_cache_size"]) / 1048576,
475 SortBufferKB: atoi64(vars["sort_buffer_size"]) / 1024,
476 SelectScan: atoi64(st["Select_scan"]),
477 SelectFullJoin: atoi64(st["Select_full_join"]),
478 SortMergePasses: atoi64(st["Sort_merge_passes"]),
479 QueryCacheEnabled: atoi64(vars["query_cache_size"]) > 0,
480 }
481 if uptime > 0 {
482 res.StartTime = time.Now().Unix() - uptime
483 res.QPS = float64(questions) / float64(uptime)
484 res.TPS = float64(commits) / float64(uptime)
485 }
486 if c := res.Connections; c > 0 {
487 res.ThreadCacheHit = rate(c-atoi64(st["Threads_created"]), c)
488 }
489 if v := atoi64(st["Key_read_requests"]); v > 0 {
490 res.KeyBufferHit = rate(v-atoi64(st["Key_reads"]), v)
491 }
492 if v := atoi64(st["Innodb_buffer_pool_read_requests"]); v > 0 {
493 res.InnoDBBufferHit = rate(v-atoi64(st["Innodb_buffer_pool_reads"]), v)
494 }
495 if res.QueryCacheEnabled {
496 hits := atoi64(st["Qcache_hits"])
497 total := hits + atoi64(st["Qcache_inserts"]) + atoi64(st["Qcache_not_cached"])
498 if total > 0 {
499 res.QueryCacheHit = float64(hits) / float64(total) * 100
500 }
501 }
502 if v := atoi64(st["Created_tmp_tables"]); v > 0 {
503 res.TmpDiskRatio = float64(atoi64(st["Created_tmp_disk_tables"])) / float64(v) * 100
504 }
505 if line, ok := s.binlogStatus(ctx); ok {
506 parts := strings.Split(line, "\t")
507 if len(parts) >= 2 {
508 res.BinlogSupported = true
509 res.BinlogFile = strings.TrimSpace(parts[0])
510 res.BinlogPosition = atoi64(parts[1])
511 }
512 }
513 return res, nil
514}
515
516func (s *Service) binlogStatus(ctx context.Context) (string, bool) {
517 for _, sql := range []string{"SHOW MASTER STATUS", "SHOW BINARY LOG STATUS"} {
518 if out, err := s.runSQL(ctx, sql); err == nil {
519 if line := strings.TrimSpace(out); line != "" {
520 return line, true
521 }
522 }
523 }
524 return "", false
525}
526
527func parseTSV(out string) map[string]string {
528 m := make(map[string]string)
529 for _, line := range strings.Split(out, "\n") {
530 line = strings.TrimRight(line, "\r")
531 if line == "" {
532 continue
533 }
534 parts := strings.SplitN(line, "\t", 2)
535 if len(parts) != 2 {
536 continue
537 }
538 m[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
539 }
540 return m
541}
542
543func rate(part, total int64) float64 {
544 if total <= 0 {
545 return 0
546 }
547 return float64(part) / float64(total) * 100
548}
549
550func atoi(s string) int {
551 n, _ := strconv.Atoi(strings.TrimSpace(s))
552 return n
553}
554
555func atoi64(s string) int64 {
556 n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
557 return n
558}
559
560func atoi64u(s string) uint64 {
561 n, _ := strconv.ParseUint(strings.TrimSpace(s), 10, 64)
562 return n
563}
564
565func bytesToMB(s string) int {
566 return int(atoi64(s) / 1048576)
567}
568
569func bytesToKB(s string) int {
570 return int(atoi64(s) / 1024)
571}