-
Notifications
You must be signed in to change notification settings - Fork 44
/
service.go
86 lines (76 loc) · 2.11 KB
/
service.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
package calcium
import (
"context"
"sync"
"time"
"github.com/projecteru2/core/log"
"github.com/projecteru2/core/types"
"github.com/projecteru2/core/utils"
"github.com/cockroachdb/errors"
)
// WatchServiceStatus returns chan of available service address
func (c *Calcium) WatchServiceStatus(ctx context.Context) (<-chan types.ServiceStatus, error) {
id, ch := c.watcher.Subscribe(ctx)
_ = c.pool.Invoke(func() {
<-ctx.Done()
c.watcher.Unsubscribe(id)
})
return ch, nil
}
// RegisterService writes self service address in store
func (c *Calcium) RegisterService(ctx context.Context) (unregister func(), err error) {
serviceAddress, err := utils.GetOutboundAddress(c.config.Bind, c.config.ProbeTarget)
logger := log.WithFunc("calcium.RegisterService")
if err != nil {
logger.Error(ctx, err, "failed to get outbound address")
return nil, err
}
var (
expiry <-chan struct{}
unregisterService func()
)
for {
if expiry, unregisterService, err = c.registerService(ctx, serviceAddress); err == nil {
break
}
if errors.Is(err, types.ErrKeyExists) {
logger.Debugf(ctx, "service key exists: %+v", err)
time.Sleep(time.Second)
continue
}
logger.Error(ctx, err, "failed to first register service")
return nil, err
}
wg := &sync.WaitGroup{}
wg.Add(1)
ctx, cancel := context.WithCancel(ctx)
_ = c.pool.Invoke(func() {
defer func() {
unregisterService()
wg.Done()
}()
for {
select {
case <-expiry:
// The original one had been expired, we're going to register again.
if ne, us, err := c.registerService(ctx, serviceAddress); err != nil {
logger.Error(ctx, err, "failed to re-register service")
time.Sleep(c.config.GRPCConfig.ServiceHeartbeatInterval)
} else {
expiry = ne
unregisterService = us
}
case <-ctx.Done():
logger.Infof(ctx, "heartbeat done: %+v", ctx.Err())
return
}
}
})
return func() {
cancel()
wg.Wait()
}, nil
}
func (c *Calcium) registerService(ctx context.Context, addr string) (<-chan struct{}, func(), error) {
return c.store.RegisterService(ctx, addr, c.config.GRPCConfig.ServiceHeartbeatInterval)
}