This repository has been archived by the owner on Jul 3, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
101 lines (89 loc) · 2.21 KB
/
main.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
package main
import (
"database/sql"
"encoding/json"
"errors"
"flag"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"net/http"
"strconv"
)
var (
dsn string
Version = "0.0.2"
failSlaveNotRunning bool
)
func main() {
var port int
var showVersion bool
flag.IntVar(&port, "port", 5000, "http listen port number")
flag.StringVar(&dsn, "dsn", "root:@tcp(127.0.0.1:3306)/?charset=utf8", "MySQL DSN")
flag.BoolVar(&showVersion, "version", false, "show version")
flag.BoolVar(&failSlaveNotRunning, "fail-slave-not-ruuning", true, "returns 500 if the slave is not running");
flag.Parse()
if showVersion {
fmt.Printf("version %s\n", Version)
return
}
log.Printf("Listing port %d", port)
log.Printf("dsn %s", dsn)
http.HandleFunc("/", handler)
addr := fmt.Sprintf(":%d", port)
log.Fatal(http.ListenAndServe(addr, nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
db, err := sql.Open("mysql", dsn)
defer db.Close()
if err != nil {
serverError(w, err)
return
}
rows, err := db.Query("SHOW SLAVE STATUS")
if err != nil {
serverError(w, err)
return
}
if !rows.Next() {
serverError(w, errors.New("No slave status"))
return
}
defer rows.Close()
// カラム数と同じ要素数のsliceを用意して sql.RawBytes のポインタで初期化しておく
columns, _ := rows.Columns()
values := make([]interface{}, len(columns))
for i, _ := range values {
var v sql.RawBytes
values[i] = &v
}
err = rows.Scan(values...)
if err != nil {
serverError(w, err)
return
}
// 結果を返す用のmapに値を詰める
slaveInfo := make(map[string]interface{})
for i, name := range columns {
bp := values[i].(*sql.RawBytes)
vs := string(*bp)
vi, err := strconv.ParseInt(vs, 10, 64)
if err != nil {
slaveInfo[name] = vs
} else {
slaveInfo[name] = vi
}
}
if failSlaveNotRunning && slaveInfo["Seconds_Behind_Master"] == "" {
serverError(w, errors.New("Slave is not running."))
return
}
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
encoder.Encode(slaveInfo)
}
func serverError(w http.ResponseWriter, err error) {
log.Printf("error: %s", err)
code := http.StatusInternalServerError
http.Error(w, fmt.Sprintf("%s", err), code)
}