-
Notifications
You must be signed in to change notification settings - Fork 3
/
callback.go
69 lines (60 loc) · 1.31 KB
/
callback.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
package callback
import (
"context"
"encoding/json"
"github.com/coreos/etcd/clientv3"
"github.com/meitu/bifrost/commons/efunc"
"github.com/meitu/bifrost/push/conf"
)
type callback struct {
record *Record
ctx context.Context
cancel context.CancelFunc
cli *efunc.Watcher
}
func NewCallback(config *conf.Callback, ctx context.Context) (Callback, error) {
ecfg := clientv3.Config{
Endpoints: config.Etcd.Cluster,
Username: config.Etcd.Username,
Password: config.Etcd.Password,
}
cli, err := efunc.NewWatcher(ecfg, config.Service)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(ctx)
cb := &callback{
record: newRecord(),
ctx: ctx,
cancel: cancel,
cli: cli,
}
go cb.watch(config)
return cb, nil
}
type callbackNode struct {
Name string `json:"service"`
Nodes []string `json:"nodes"`
}
func (cb *callback) String() string {
if cb.record == nil {
return ""
}
mapclis := cb.GetClientAddr()
clusters := make([]callbackNode, 0, len(mapclis))
for k, cli := range mapclis {
var cls callbackNode
cls.Name = k
cls.Nodes = cli.r.ServerAddrs()
clusters = append(clusters, cls)
}
if rawcluster, err := json.Marshal(clusters); err == nil {
return string(rawcluster)
}
return ""
}
func (cb *callback) Close() error {
cb.cli.Close()
cb.cancel()
return nil
}