Codebase list golang-github-go-kit-kit / f8df147
sd/etcd: minor fixes to new TTL code - Don't embed Mutex, to avoid client code locking it - More safety checks on r.quit - Minor formatting and grammar fixes Peter Bourgon 6 years ago
2 changed file(s) with 24 addition(s) and 18 deletion(s). Raw diff Collapse all Expand all
157157 }
158158 var err error
159159 if s.TTL != nil {
160 _, err = c.keysAPI.Set(c.ctx, s.Key, s.Value, &etcd.SetOptions{PrevExist: etcd.PrevIgnore, TTL: s.TTL.ttl})
160 _, err = c.keysAPI.Set(c.ctx, s.Key, s.Value, &etcd.SetOptions{
161 PrevExist: etcd.PrevIgnore,
162 TTL: s.TTL.ttl,
163 })
161164 } else {
162165 _, err = c.keysAPI.Create(c.ctx, s.Key, s.Value)
163166 }
88 "github.com/go-kit/kit/log"
99 )
1010
11 const (
12 minHeartBeatTime = time.Millisecond * 500
13 )
11 const minHeartBeatTime = 500 * time.Millisecond
1412
1513 // Registrar registers service instance liveness information to etcd.
1614 type Registrar struct {
1715 client Client
1816 service Service
1917 logger log.Logger
18
19 quitmtx sync.Mutex
2020 quit chan struct{}
21 sync.Mutex
2221 }
2322
2423 // Service holds the instance identifying data you want to publish to etcd. Key
3837 ttl time.Duration // e.g. time.Second * 10
3938 }
4039
41 // NewTTLOption returns a TTLOption that contains proper ttl settings. param
42 // heartbeat is used to refresh lease of the key periodically by a loop goroutine,
43 // its value should be at least 500ms. param ttl definite the lease of the key,
44 // its value should be greater than heartbeat's.
45 // e.g. heartbeat: time.Second * 3, ttl: time.Second * 10.
40 // NewTTLOption returns a TTLOption that contains proper TTL settings. Heartbeat
41 // is used to refresh the lease of the key periodically; its value should be at
42 // least 500ms. TTL defines the lease of the key; its value should be
43 // significantly greater than heartbeat.
44 //
45 // Good default values might be 3s heartbeat, 10s TTL.
4646 func NewTTLOption(heartbeat, ttl time.Duration) *TTLOption {
4747 if heartbeat <= minHeartBeatTime {
4848 heartbeat = minHeartBeatTime
4949 }
5050 if ttl <= heartbeat {
51 ttl = heartbeat * 3
51 ttl = 3 * heartbeat
5252 }
5353 return &TTLOption{
5454 heartbeat: heartbeat,
8383 }
8484
8585 func (r *Registrar) loop() {
86 r.Lock()
86 r.quitmtx.Lock()
87 if r.quit != nil {
88 return // already running
89 }
8790 r.quit = make(chan struct{})
88 r.Unlock()
91 r.quitmtx.Unlock()
8992
9093 tick := time.NewTicker(r.service.TTL.heartbeat)
9194 defer tick.Stop()
92
9395 for {
9496 select {
95 case <-r.quit:
96 return
9797 case <-tick.C:
9898 if err := r.client.Register(r.service); err != nil {
9999 r.logger.Log("err", err)
100100 }
101 case <-r.quit:
102 return
101103 }
102104 }
103105 }
110112 } else {
111113 r.logger.Log("action", "deregister")
112114 }
113 r.Lock()
114 defer r.Unlock()
115
116 r.quitmtx.Lock()
117 defer r.quitmtx.Unlock()
115118 if r.quit != nil {
116119 close(r.quit)
117120 r.quit = nil