-
Notifications
You must be signed in to change notification settings - Fork 4
/
galera.go
93 lines (83 loc) · 2.42 KB
/
galera.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"time"
)
type Galera struct {
Conf ConfGalera
Status Status
lg log.Logger
}
type ConfGalera struct {
Enabled bool
Interval int
User string
Pass string
Host string
Port int
Socket string
Local_state int
Sst_method string
}
// You do not want to change these queries, to avoid injections
const wsrep_local_state_query = "show global status where variable_name = ?"
const wsrep_sst_method_query = "show global variables where variable_name = ?"
func (c *ConfGalera) getConnectionString() string {
if c.User == "" {
c.User = "root"
}
if c.Host == "" {
c.Host = "localhost"
}
if c.Port == 0 {
c.Port = 3306
}
protocol := fmt.Sprintf("tcp(%s:%d)", c.Host, c.Port)
if c.Socket != "" {
protocol = fmt.Sprintf("unix(%s)", c.Socket)
}
if c.Pass == "" {
return fmt.Sprintf("%s@%s/", c.User, protocol)
} else {
return fmt.Sprintf("%s:%s@%s/", c.User, c.Pass, protocol)
}
}
func (g *Galera) check() {
for ; ; time.Sleep(time.Duration(g.Conf.Interval) * time.Second) {
var wsrep_sst_method string
var wsrep_local_state int
var varName string
db, err := sql.Open("mysql", fmt.Sprintf("%s?timeout=%ds&readTimeout=%ds", g.Conf.getConnectionString(), g.Conf.Interval/2+1, g.Conf.Interval/2+1))
if err != nil {
g.lg.Println("Timeout while connecting to mysql", err.Error())
g.Status.PartOfCluster = false
g.Status.Timestamp = time.Now()
db.Close()
continue
}
err = db.QueryRow(wsrep_local_state_query, "wsrep_local_state").Scan(&varName, &wsrep_local_state)
if err != nil {
g.lg.Println("Error querying "+wsrep_local_state_query+": ", err.Error())
g.Status.PartOfCluster = false
} else {
err = db.QueryRow(wsrep_sst_method_query, "wsrep_sst_method").Scan(&varName, &wsrep_sst_method)
if err != nil {
g.lg.Println("Error querying "+wsrep_sst_method_query+": ", err.Error())
g.Status.PartOfCluster = false
} else {
if wsrep_local_state == g.Conf.Local_state && wsrep_sst_method == g.Conf.Sst_method {
g.Status.PartOfCluster = true
} else {
g.lg.Printf("wsrep_local_state is %d, but should be %d", wsrep_local_state, g.Conf.Local_state)
g.lg.Printf("wsrep_sst_method is %s, but should be %s", wsrep_sst_method, g.Conf.Sst_method)
g.Status.PartOfCluster = false
}
}
}
g.Status.Timestamp = time.Now()
db.Close()
}
}