-
Notifications
You must be signed in to change notification settings - Fork 786
/
kv_init_service.go
63 lines (51 loc) · 1.46 KB
/
kv_init_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
package memberlist
import (
"context"
"sync"
"github.com/cortexproject/cortex/pkg/util/services"
)
// This service initialized memberlist.KV on first call to GetMemberlistKV, and starts it. On stop,
// KV is stopped too. If KV fails, error is reported from the service.
type KVInitService struct {
services.Service
// config used for initialization
cfg *KVConfig
// init function, to avoid multiple initializations.
init sync.Once
// state
kv *KV
err error
watcher *services.FailureWatcher
}
func NewKVInitService(cfg *KVConfig) *KVInitService {
kvinit := &KVInitService{
cfg: cfg,
watcher: services.NewFailureWatcher(),
}
kvinit.Service = services.NewBasicService(nil, kvinit.running, kvinit.stopping)
return kvinit
}
// This method will initialize Memberlist.KV on first call, and add it to service failure watcher.
func (kvs *KVInitService) GetMemberlistKV() (*KV, error) {
kvs.init.Do(func() {
kvs.kv = NewKV(*kvs.cfg)
kvs.watcher.WatchService(kvs.kv)
kvs.err = kvs.kv.StartAsync(context.Background())
})
return kvs.kv, kvs.err
}
func (kvs *KVInitService) running(ctx context.Context) error {
select {
case <-ctx.Done():
return nil
case err := <-kvs.watcher.Chan():
// Only happens if KV service was actually initialized in GetMemberlistKV and it fails.
return err
}
}
func (kvs *KVInitService) stopping(_ error) error {
if kvs.kv == nil {
return nil
}
return services.StopAndAwaitTerminated(context.Background(), kvs.kv)
}