/
discovery.go
105 lines (87 loc) · 2.07 KB
/
discovery.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
package discovery
import (
log "github.com/Sirupsen/logrus"
etcd "github.com/coreos/etcd/client"
ctx "golang.org/x/net/context"
"path"
"strings"
"time"
)
const (
DefaultHeartbeat = 2 * time.Minute
DefaultTTL = 2*time.Minute + 30*time.Second
)
var (
RegisterPath = "/srv/monitor"
Advertise string
Discovery string
Hearbeat time.Duration
TTL time.Duration
Cancel ctx.CancelFunc
)
func parse(endpoint string) []string {
parts := strings.Split(strings.TrimPrefix(endpoint, "etcd://"), ",")
for idx, p := range parts {
parts[idx] = "http://" + p
}
return parts
}
func NewDiscovery() (client etcd.Client) {
cfg := etcd.Config{
Endpoints: Endpoints(),
Transport: etcd.DefaultTransport,
HeaderTimeoutPerRequest: time.Second,
}
if cli, err := etcd.New(cfg); err != nil {
log.Fatal(err)
} else {
client = cli
}
return
}
func Endpoints() []string {
return parse(Discovery)
}
func upkeep(kAPI etcd.KeysAPI, iden string, opts *etcd.SetOptions) (err error) {
_, err = kAPI.Set(ctx.Background(), iden, Advertise, opts)
return
}
func Register(heartbeat time.Duration, ttl time.Duration) {
Hearbeat, TTL = heartbeat, ttl
// begin book keeping "THIS" montior unit
go func() {
var work ctx.Context
work, Cancel = ctx.WithCancel(ctx.Background())
client := NewDiscovery()
var (
iden = path.Join(RegisterPath, Advertise)
opts = etcd.SetOptions{TTL: ttl}
kAPI = etcd.NewKeysAPI(client)
f = log.Fields{"heartbeat": heartbeat, "ttl": ttl}
t = time.NewTicker(heartbeat)
)
defer t.Stop()
// Allow for implicit bootstrap on register
if err := upkeep(kAPI, iden, &opts); err != nil {
log.Error("1:", err)
} else {
log.WithFields(f).Info("uptime")
}
// Tick... Toc...
for {
select {
case <-t.C:
if err := upkeep(kAPI, iden, &opts); err != nil {
log.Error("2:", err)
opts.PrevExist = etcd.PrevIgnore
} else {
log.WithFields(f).Info("uptime")
opts.PrevExist = etcd.PrevExist
}
case <-work.Done():
log.WithFields(f).Info("abort")
return
}
}
}()
}