master
go 79 lines 2.04 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package mysql
4
5 import (
6 "context"
7
8 "github.com/blang/semver/v4"
9 )
10
11 const (
12 queryShowReplicaStatus = "SHOW REPLICA STATUS;"
13 queryShowSlaveStatus = "SHOW SLAVE STATUS;"
14 queryShowAllSlavesStatus = "SHOW ALL SLAVES STATUS;"
15 )
16
17 func (c *Collector) collectSlaveStatus(ctx context.Context) error {
18 // https://mariadb.com/docs/reference/es/sql-statements/SHOW_ALL_SLAVES_STATUS/
19 mariaDBMinVer := semver.Version{Major: 10, Minor: 2, Patch: 0}
20 mysqlMinVer := semver.Version{Major: 8, Minor: 0, Patch: 22}
21 var q string
22 if c.isMariaDB && c.version.GTE(mariaDBMinVer) {
23 q = queryShowAllSlavesStatus
24 } else if !c.isMariaDB && c.version.GTE(mysqlMinVer) {
25 q = queryShowReplicaStatus
26 } else {
27 q = queryShowSlaveStatus
28 }
29 c.Debugf("executing query: '%s'", q)
30
31 type slaveStatusRow struct {
32 name string
33 behindMaster int64
34 sqlRunning int64
35 ioRunning int64
36 }
37 row := slaveStatusRow{}
38
39 _, err := c.collectQuery(ctx, q, func(column, value string, lineEnd bool) {
40 switch column {
41 case "Connection_name", "Channel_Name":
42 row.name = value
43 case "Seconds_Behind_Master", "Seconds_Behind_Source":
44 row.behindMaster = parseInt(value)
45 case "Slave_SQL_Running", "Replica_SQL_Running":
46 row.sqlRunning = parseInt(convertSlaveSQLRunning(value))
47 case "Slave_IO_Running", "Replica_IO_Running":
48 row.ioRunning = parseInt(convertSlaveIORunning(value))
49 }
50 if lineEnd {
51 c.mx.setReplication("seconds_behind_master", row.name, row.behindMaster)
52 c.mx.setReplication("slave_sql_running", row.name, row.sqlRunning)
53 c.mx.setReplication("slave_io_running", row.name, row.ioRunning)
54
55 // Explicit row reset keeps per-row lifecycle obvious in callback flow.
56 row = slaveStatusRow{}
57 }
58 })
59 return err
60 }
61
62 func convertSlaveSQLRunning(value string) string {
63 switch value {
64 case "Yes":
65 return "1"
66 default:
67 return "0"
68 }
69 }
70
71 func convertSlaveIORunning(value string) string {
72 // NOTE: There is 'Connecting' state and probably others
73 switch value {
74 case "Yes":
75 return "1"
76 default:
77 return "0"
78 }
79 }