-
Notifications
You must be signed in to change notification settings - Fork 82
/
main.go
94 lines (83 loc) · 2.01 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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
func waitFor(timeout time.Duration, blocks int, url string, ch chan<- error) {
cli := http.Client{
Timeout: time.Second * 1,
}
end := time.After(timeout)
for {
select {
case <-time.After(time.Second * 5):
resp, err := cli.Get(fmt.Sprintf("%s/status", url))
if err != nil {
log.Printf("%s\n", err.Error())
continue
}
if resp.StatusCode == http.StatusOK {
status := &ChainStatus{}
err = json.NewDecoder(resp.Body).Decode(&status)
_ = resp.Body.Close()
if err != nil {
log.Printf("%s: error decoding response %s\n", url, err.Error())
continue
}
if block, err := strconv.Atoi(status.Result.SyncInfo.LatestBlockHeight); err == nil && block > blocks {
log.Printf("%s: chain is ready \n", url)
ch <- nil
return
}
log.Printf("%s latest block: %s \n", url, status.Result.SyncInfo.LatestBlockHeight)
}
case <-end:
ch <- fmt.Errorf("timed out waiting for %s", url)
return
}
}
}
func exists(path string) bool {
_, err := os.Stat(path)
return !errors.Is(err, os.ErrNotExist)
}
func main() {
checkFile := os.Getenv("PLUGIN_CHECK_FILE")
if checkFile != "" && !exists(checkFile) {
log.Fatal("check file doesn't exists")
}
chains := strings.Split(os.Getenv("PLUGIN_CHAIN_LIST"), ",")
if len(chains) == 0 || len(os.Getenv("PLUGIN_CHAIN_LIST")) == 0 {
log.Fatal("must provide at least one chain")
}
timeout, err := strconv.Atoi(os.Getenv("PLUGIN_TIMEOUT"))
if err != nil {
log.Fatal("must provide a valid timeout")
}
numBlocks, err := strconv.Atoi(os.Getenv("PLUGIN_BLOCKS"))
if err != nil || numBlocks < 5 {
numBlocks = 5
}
ch := make(chan error, len(chains))
for _, c := range chains {
log.Printf("wait for %s %d", c, timeout)
go waitFor(time.Duration(timeout)*time.Second, numBlocks, c, ch)
}
jobs := len(chains)
for err := range ch {
if err != nil {
log.Fatal(err)
}
jobs--
if jobs == 0 {
return
}
}
}