-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.go
245 lines (201 loc) · 5.82 KB
/
server.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package balancer
import (
"database/sql"
"fmt"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/go-gorp/gorp"
)
var mutex sync.Mutex
// Server server representation
type Server struct {
name string
health *ServerHealth
serverSettings ServerSettings
connection *gorp.DbMap
replicationConnection *gorp.DbMap
traceOn bool
isChecking int32
}
// GetName returns server's name
func (s *Server) GetName() string {
return s.name
}
// GetHealth returns server's health state
func (s *Server) GetHealth() *ServerHealth {
return s.health
}
// GetConnection returns server's connection
func (s *Server) GetConnection() *gorp.DbMap {
return s.connection
}
func (s *Server) connect(dsn string, traceOn bool, logger Logger) (*gorp.DbMap, error) {
conn, err := sql.Open("mysql", dsn)
if err != nil {
return nil, err
}
conn.SetMaxIdleConns(s.serverSettings.MaxIdleConns)
conn.SetMaxOpenConns(s.serverSettings.MaxOpenConns)
conn.SetConnMaxLifetime(s.serverSettings.MaxLifetimeConns)
if err := conn.Ping(); err != nil {
conn.Close()
return nil, err
}
connection := &gorp.DbMap{
Db: conn,
Dialect: gorp.MySQLDialect{},
}
if traceOn && logger != nil {
connection.TraceOn("[sql]", logger)
}
return connection, nil
}
// CheckHealth check server's health and set it's state
func (s *Server) CheckHealth(traceOn bool, logger Logger) {
var secondsBehindMaster, openConnections, runningConnections *int
// prevent concurrently checks on same server (slow queries/network)
if atomic.LoadInt32(&s.isChecking) == 1 {
return
}
atomic.StoreInt32(&s.isChecking, 1)
defer func() {
atomic.StoreInt32(&s.isChecking, 0)
}()
if err := s.connectReadUser(traceOn, logger); err != nil {
s.health.setDown(
err, false, secondsBehindMaster, openConnections, runningConnections,
)
return
}
if err := s.connectReplicationUser(traceOn, logger); err != nil {
s.health.setUP(
err, false, secondsBehindMaster, openConnections, runningConnections,
)
return
}
ioRunning := false
ioRunningResult, err := s.rawQuery("SHOW STATUS LIKE 'Slave_running'", logger)
if err == nil && strings.EqualFold(ioRunningResult["Value"], "ON") {
ioRunning = true
}
threadsConnectedResult, err := s.rawQuery("SHOW STATUS LIKE 'Threads_connected'", logger)
if err != nil {
s.health.setUP(
fmt.Errorf("failed acquiring MySQL thread connected status: %s", err),
ioRunning, secondsBehindMaster, openConnections, runningConnections,
)
return
}
threadsConnected := threadsConnectedResult["Value"]
tmp2, err := strconv.Atoi(threadsConnected)
if err != nil {
s.health.setUP(
fmt.Errorf("unexpected value for Threads_connected returned from MySQL: %s", err),
ioRunning, secondsBehindMaster, openConnections, runningConnections,
)
return
}
openConnections = &tmp2
threadsRunningResult, err := s.rawQuery("SHOW STATUS LIKE 'Threads_running'", logger)
if err != nil {
s.health.setUP(
fmt.Errorf("failed acquiring MySQL thread running status: %s", err),
ioRunning, secondsBehindMaster, openConnections, runningConnections,
)
return
}
threadsRunning := threadsRunningResult["Value"]
tmp3, err := strconv.Atoi(threadsRunning)
if err != nil {
s.health.setUP(
fmt.Errorf("unexpected value for Threads_running returned from MySQL: %s", err),
ioRunning, secondsBehindMaster, openConnections, runningConnections,
)
return
}
runningConnections = &tmp3
slaveStatusResult, err := s.rawQuery("SHOW SLAVE STATUS", logger)
if err != nil {
s.health.setUP(
err, ioRunning, secondsBehindMaster, openConnections, runningConnections,
)
return
}
rawSecondsBehindMaster := strings.TrimSpace(slaveStatusResult["Seconds_Behind_Master"])
if rawSecondsBehindMaster == "" || strings.ToLower(rawSecondsBehindMaster) == "null" {
s.health.setUP(
fmt.Errorf("empty or null value for Seconds_Behind_Master returned from MySQL: %s", err),
ioRunning, secondsBehindMaster, openConnections, runningConnections,
)
return
}
tmp, err := strconv.Atoi(rawSecondsBehindMaster)
if err != nil {
s.health.setUP(
fmt.Errorf("unexpected value for Seconds_Behind_Master returned from MySQL (conversion error): %s", err),
ioRunning, secondsBehindMaster, openConnections, runningConnections,
)
return
}
secondsBehindMaster = &tmp
s.health.setUP(nil, ioRunning, secondsBehindMaster, openConnections, runningConnections)
}
func (s *Server) connectReadUser(traceOn bool, logger Logger) error {
mutex.Lock()
defer mutex.Unlock()
if s.connection == nil {
conn, err := s.connect(s.serverSettings.DSN, traceOn, logger)
if err != nil {
return fmt.Errorf("could not connect to MySQL read user: %s", err.Error())
}
s.connection = conn
}
return nil
}
func (s *Server) connectReplicationUser(traceOn bool, logger Logger) error {
mutex.Lock()
defer mutex.Unlock()
if s.replicationConnection == nil {
conn, err := s.connect(s.serverSettings.ReplicationDSN, traceOn, logger)
if err != nil {
return fmt.Errorf("could not connect to MySQL replication user: %s", err.Error())
}
s.replicationConnection = conn
}
return nil
}
func (s *Server) rawQuery(query string, logger Logger) (map[string]string, error) {
rows, err := s.replicationConnection.Db.Query(query)
if err != nil {
return nil, err
}
if !rows.Next() {
return nil, sql.ErrNoRows
}
defer func() {
if err := rows.Close(); err != nil && logger != nil {
logger.Error(err)
}
}()
columns, err := rows.Columns()
if err != nil {
return nil, err
}
values := make([]interface{}, len(columns))
for i := range values {
var v sql.RawBytes
values[i] = &v
}
err = rows.Scan(values...)
if err != nil {
return nil, err
}
result := make(map[string]string)
for i, name := range columns {
bp := values[i].(*sql.RawBytes)
result[name] = string(*bp)
}
return result, nil
}