-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (75 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
// pollEndpoint is a helper utility that waits for a http endpoint to be reachable and return with http.StatusOK
package main
import (
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"time"
ma "gx/ipfs/QmSWLfmj5frN9xVLMMN846dMDriy5wN5jeghUm7aTW3DAG/go-multiaddr"
logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
manet "gx/ipfs/QmVCNGTyD4EkvNYaAp253uMQ9Rjsjy2oGMvcdJJUoVRfja/go-multiaddr-net"
)
var (
host = flag.String("host", "/ip4/127.0.0.1/tcp/5001", "the multiaddr host to dial on")
endpoint = flag.String("ep", "/version", "which http endpoint path to hit")
tries = flag.Int("tries", 10, "how many tries to make before failing")
timeout = flag.Duration("tout", time.Second, "how long to wait between attempts")
verbose = flag.Bool("v", false, "verbose logging")
)
var log = logging.Logger("pollEndpoint")
func main() {
flag.Parse()
// extract address from host flag
addr, err := ma.NewMultiaddr(*host)
if err != nil {
log.Fatal("NewMultiaddr() failed: ", err)
}
p := addr.Protocols()
if len(p) < 2 {
log.Fatal("need two protocols in host flag (/ip/tcp): ", addr)
}
_, host, err := manet.DialArgs(addr)
if err != nil {
log.Fatal("manet.DialArgs() failed: ", err)
}
if *verbose { // lower log level
logging.SetDebugLogging()
}
// construct url to dial
var u url.URL
u.Scheme = "http"
u.Host = host
u.Path = *endpoint
// show what we got
start := time.Now()
log.Debug("starting at %s, tries: %d, timeout: %s, url: %s", start, *tries, *timeout, u)
for *tries > 0 {
err := checkOK(http.Get(u.String()))
if err == nil {
log.Debugf("ok - endpoint reachable with %d tries remaining, took %s", *tries, time.Since(start))
os.Exit(0)
}
log.Debug("get failed: ", err)
time.Sleep(*timeout)
*tries--
}
log.Error("failed.")
os.Exit(1)
}
func checkOK(resp *http.Response, err error) error {
if err == nil { // request worked
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return nil
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Fprintf(os.Stderr, "pollEndpoint: ioutil.ReadAll() Error: %s", err)
}
return fmt.Errorf("Response not OK. %d %s %q", resp.StatusCode, resp.Status, string(body))
}
return err
}