-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhealthcheck.go
81 lines (64 loc) · 1.65 KB
/
healthcheck.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
// Sends "/info" request to the localhosted core,
// if info['state'] == 'Synced!' returns 0, otherwise returns 1.
// Gets config path from CONFIG env variable
// Loads HTTP_PORT from CONFIG file, otherwise sets it to 8080.
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"gopkg.in/ini.v1"
)
const (
defaultConfigPath = "/config.ini"
healthyState = "Synced!"
defaultCorePort = 8080
stateEndpoint = "http://localhost:%d/info"
)
func main() {
configPath := os.Getenv("CONFIG")
if configPath == "" {
configPath = defaultConfigPath
}
corePort := getCorePort(configPath)
state, err := coreState(fmt.Sprintf(stateEndpoint, corePort))
if err != nil {
log.Fatalf("failed to get core info: %v", err)
}
if !strings.EqualFold(state, healthyState) {
log.Fatalf("node is in bad state: %s", state)
}
log.Printf("node is in good state")
}
func coreState(coreUrl string) (string, error) {
response, err := http.Get(coreUrl)
if err != nil {
return "", fmt.Errorf("failed to get info: %v", err)
}
defer response.Body.Close()
return stateFromResponse(response.Body)
}
func getCorePort(configPath string) int {
cfg, err := ini.LoadSources(ini.LoadOptions{
SkipUnrecognizableLines: true,
}, configPath)
if err != nil {
return defaultCorePort
}
return cfg.Section("").Key("HTTP_PORT").MustInt(defaultCorePort)
}
func stateFromResponse(r io.Reader) (string, error) {
var coreResponse struct {
Info struct {
State string
}
}
if err := json.NewDecoder(r).Decode(&coreResponse); err != nil {
return "", fmt.Errorf("failed to decode core response: %v", err)
}
return coreResponse.Info.State, nil
}