This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
111 lines (95 loc) · 2.5 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
102
103
104
105
106
107
108
109
110
111
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
cosmosClient "github.com/cosmos/cosmos-sdk/client"
rpcclient "github.com/tendermint/tendermint/rpc/client"
rpchttp "github.com/tendermint/tendermint/rpc/client/http"
libclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
)
const RPCTimeoutSeconds = 5
func newClient(addr string) (rpcclient.Client, error) {
httpClient, err := libclient.DefaultHTTPClient(addr)
if err != nil {
return nil, err
}
httpClient.Timeout = 10 * time.Second
rpcClient, err := rpchttp.NewWithClient(addr, "", httpClient)
if err != nil {
return nil, err
}
return rpcClient, nil
}
func getCosmosClient(rpcAddress string) (*cosmosClient.Context, error) {
client, err := newClient(rpcAddress)
if err != nil {
return nil, err
}
return &cosmosClient.Context{
Client: client,
Input: os.Stdin,
Output: os.Stdout,
}, nil
}
func inSync(client *cosmosClient.Context) bool {
node, err := client.GetNode()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting node: %v\n", err)
return false
}
statusCtx, statusCtxCancel := context.WithTimeout(context.Background(), time.Duration(time.Second*RPCTimeoutSeconds))
defer statusCtxCancel()
status, err := node.Status(statusCtx)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting status: %v\n", err)
return false
}
return !status.SyncInfo.CatchingUp
}
type InSyncResponse struct {
Address string `json:"address"`
InSync bool `json:"in_sync"`
}
func main() {
rpcAddress := os.Getenv("RPC_ADDRESS")
if rpcAddress == "" {
rpcAddress = "tcp://localhost:26657"
}
client, err := getCosmosClient(rpcAddress)
if err != nil {
panic(err)
}
inSyncResponse, err := json.Marshal(InSyncResponse{Address: rpcAddress, InSync: true})
if err != nil {
panic(err)
}
notInSyncResponse, err := json.Marshal(InSyncResponse{Address: rpcAddress, InSync: false})
if err != nil {
panic(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var status int
var response []byte
if inSync(client) {
status = http.StatusOK
response = inSyncResponse
} else {
status = http.StatusServiceUnavailable
response = notInSyncResponse
}
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(response)
})
port := os.Getenv("PORT")
if port == "" {
port = "1251"
}
listenAddr := fmt.Sprintf(":%s", port)
fmt.Printf("Health check for %s listening on port %s\n", rpcAddress, port)
panic(http.ListenAndServe(listenAddr, nil))
}