-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhealth.go
95 lines (89 loc) · 1.52 KB
/
health.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
package main
import (
"context"
"fmt"
"net"
"net/url"
"time"
)
func checkHealth(ctx context.Context, s string) (bool, error) {
u, err := url.Parse(s)
if err != nil {
return false, err
}
switch u.Scheme {
case "tcp":
var d net.Dialer
conn, err := d.DialContext(ctx, u.Scheme, u.Host)
if err != nil {
return false, err
}
defer conn.Close()
return true, nil
}
return false, nil
}
type HealthGroup struct {
URLs []string
All bool
Negate bool
Timeout time.Duration
Interval time.Duration
Retry uint64
}
func (g *HealthGroup) Wait(ctx context.Context) error {
ticker := time.NewTicker(g.Interval)
defer ticker.Stop()
var (
countOk uint64
countFail uint64
)
for {
var (
countHealthy uint64
countUnhealthy uint64
)
for _, u := range g.URLs {
func() {
hctx, cancel := context.WithTimeout(ctx, g.Timeout)
defer cancel()
ok, _ := checkHealth(hctx, u)
if ok {
countHealthy += 1
} else {
countUnhealthy += 1
}
}()
}
if g.Negate {
countHealthy, countUnhealthy = countUnhealthy, countHealthy
}
ok := countHealthy == uint64(len(g.URLs))
if !g.All {
ok = ok || countHealthy > 0
}
if ok {
countOk += 1
countFail = 0
} else {
countOk = 0
countFail += 1
}
if countOk > 0 {
return nil
}
if g.Retry > 0 && countFail >= g.Retry {
return fmt.Errorf("wait timeout")
}
select {
case <-ctx.Done():
return ctx.Err()
default:
}
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
}
}