-
Notifications
You must be signed in to change notification settings - Fork 1
/
etcd_register.go
188 lines (156 loc) · 3.98 KB
/
etcd_register.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package discov
import (
"context"
"errors"
"fmt"
"go.etcd.io/etcd/clientv3"
"sync"
"time"
)
// EtcdSrvRecord is a service record to be registered to or
// unregistered from etcd.
type EtcdSrvRecord interface {
// Register registers the record to etcd.
// This method should be called when the service starts.
Register()
// Unregister unregisters the record from etcd.
// This method should be called when the service is closed.
Unregister(context.Context) error
// CatchRuntimeErrors catches runtime errors.
// Since the EtcdSrvRecord spawns goroutines to keep heartbeat
// to etcd after calling Register, some errors may occur at runtime.
CatchRuntimeErrors() <-chan error
}
// NewEtcdSrvRecord construct a service record.
func NewEtcdSrvRecord(cli *clientv3.Client, srvName, srvAddr string) (EtcdSrvRecord, error) {
if cli == nil {
return nil, errors.New("nil etcd client")
}
if srvName == "" {
return nil, errors.New("empty srv name")
}
if srvAddr == "" {
return nil, errors.New("empty srv addr")
}
if !isEtcdClientAvailable(cli) {
return nil, errors.New("unavailable etcd client")
}
r := &etcdSrvRecord{
cli: cli,
ctx: nil,
cancel: nil,
wg: sync.WaitGroup{},
errs: nil,
errsLock: sync.Mutex{},
srvName: srvName,
srvAddr: srvAddr,
srvTTL: time.Second * 3,
}
return r, nil
}
type etcdSrvRecord struct {
cli *clientv3.Client
// used as revoking checker, aliveKeeper and consumer
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
errs chan error // note: never close after initialization
errsLock sync.Mutex
srvName string
srvAddr string
srvTTL time.Duration
}
func (r *etcdSrvRecord) Register() {
r.ctx, r.cancel = context.WithCancel(context.Background())
r.initErrorChannel()
r.wg.Add(1)
go r.checker()
}
func (r *etcdSrvRecord) Unregister(ctx context.Context) error {
if r.cancel != nil {
r.cancel() // revokes checker, aliveKeeper and consumer
r.wg.Wait()
}
key := fmt.Sprintf("%s/%v", getEtcdKeyPrefix(r.srvName), r.srvAddr)
_, err := r.cli.Delete(ctx, key)
if err != nil {
return fmt.Errorf("etcd client delete key(%s): %v", key, err)
}
return nil
}
func (r *etcdSrvRecord) checker() {
defer r.wg.Done()
key := fmt.Sprintf("%s/%v", getEtcdKeyPrefix(r.srvName), r.srvAddr)
ticker := time.NewTicker(r.srvTTL)
for {
select {
case <-r.ctx.Done():
// revoke this goroutine
ticker.Stop()
return
case <-ticker.C:
}
ctx, cancel := context.WithTimeout(context.Background(), r.srvTTL)
resp, err := r.cli.Get(ctx, key)
if err != nil {
cancel()
r.pushErr(fmt.Errorf("CHECKER_ERROR: failed to get key: %v", err))
continue
}
if resp.Count <= 0 {
lease, err := r.cli.Grant(ctx, r.srvTTL.Milliseconds()/1000)
if err != nil {
cancel()
r.pushErr(fmt.Errorf("CHECKER_ERROR: failed to grant lease: %v", err))
continue
}
_, err = r.cli.Put(ctx, key, r.srvAddr, clientv3.WithLease(lease.ID))
if err != nil {
cancel()
r.pushErr(fmt.Errorf("CHECKER_ERROR: failed to put key: %v", err))
continue
}
ch, err := r.cli.KeepAlive(r.ctx, lease.ID) // aliveKeeper
if err != nil {
cancel()
r.pushErr(fmt.Errorf("CHECKER_ERROR: failed to keep alive: %v", err))
continue
}
r.wg.Add(1)
go r.consumer(ch)
}
cancel()
}
}
func (r *etcdSrvRecord) consumer(ch <-chan *clientv3.LeaseKeepAliveResponse) {
defer r.wg.Done()
for {
select {
case <-r.ctx.Done():
return
case _, ok := <-ch:
if !ok {
r.pushErr(errors.New("KEEP_ALIVE_RESP_CONSUMER_WARNING: underlying keep alive stream is interrupted"))
return
}
}
}
}
func (r *etcdSrvRecord) pushErr(err error) {
r.initErrorChannel()
select {
case r.errs <- err:
default: // channel is full, discard err
}
}
func (r *etcdSrvRecord) CatchRuntimeErrors() <-chan error {
r.initErrorChannel()
return r.errs
}
func (r *etcdSrvRecord) initErrorChannel() {
r.errsLock.Lock()
defer r.errsLock.Unlock()
if r.errs == nil {
r.errs = makeErrorChannel()
}
}