This repository has been archived by the owner on Jul 6, 2023. It is now read-only.
/
registry.go
187 lines (157 loc) · 3.31 KB
/
registry.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
package registries
import (
"context"
"encoding/json"
"fmt"
"github.com/anqur/gbio/pkg/logging"
"github.com/anqur/gbio/pkg/registries"
"strings"
"sync"
"time"
etcd "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/concurrency"
"github.com/anqur/gbio/internal/endpoints"
)
const DefaultPrefix = "gbio-"
type Registry struct {
C *etcd.Config
Ctx context.Context
Prefix string
Tick time.Duration
cl *etcd.Client
tx *concurrency.Session
}
func New(c *etcd.Config) *Registry {
return &Registry{
C: c,
Ctx: context.Background(),
Prefix: DefaultPrefix,
Tick: 30 * time.Second,
}
}
func (r *Registry) dial() (err error) {
r.cl, err = etcd.New(*r.C)
if err != nil {
return
}
ttl := int(r.Tick.Seconds())
r.tx, err = concurrency.NewSession(r.cl, concurrency.WithTTL(ttl))
return
}
func (r *Registry) Register(addr string, eps []*endpoints.Endpoint) error {
if addr == "" || eps == nil {
return fmt.Errorf(
"%w: addr=%q, endpoints=%q",
registries.ErrEmptyEndpoints,
addr,
eps,
)
}
vals, err := json.Marshal(eps)
if err != nil {
return err
}
_, err = r.tx.
Client().
Put(
r.Ctx,
r.Prefix+addr,
string(vals),
etcd.WithLease(r.tx.Lease()),
)
return err
}
func (r *Registry) Close() error {
_ = r.tx.Close()
return r.cl.Close()
}
type (
NodeAddr string
NodeList []string
EndpointName string
)
type CachedRegistry struct {
*Registry
mu sync.RWMutex
Lb LB
nodes map[NodeAddr][]*endpoints.Endpoint
eps map[EndpointName]NodeList
}
func NewCached(c *etcd.Config) *CachedRegistry {
return &CachedRegistry{
Registry: New(c),
Lb: FirstLB(),
}
}
func (r *CachedRegistry) Close() error {
r.mu.RLock()
defer r.mu.RUnlock()
return r.Registry.Close()
}
func (r *CachedRegistry) Started() bool {
r.mu.RLock()
defer r.mu.RUnlock()
return r.cl != nil
}
func (r *CachedRegistry) Start() error {
if err := r.dial(); err != nil {
return err
}
r.fetchOnce()
go r.runFetch()
return nil
}
func (r *CachedRegistry) dial() (err error) {
r.mu.Lock()
defer r.mu.Unlock()
return r.Registry.dial()
}
func (r *CachedRegistry) fetchOnce() {
r.mu.Lock()
defer r.mu.Unlock()
resp, err := r.cl.Get(r.Ctx, r.Prefix, etcd.WithPrefix())
if err != nil {
logging.Error.Println("Fetch endpoints error:", err)
return
}
r.nodes = make(map[NodeAddr][]*endpoints.Endpoint)
r.eps = make(map[EndpointName]NodeList)
for _, kv := range resp.Kvs {
node := strings.TrimPrefix(string(kv.Key), r.Prefix)
var eps []*endpoints.Endpoint
if err := json.Unmarshal(kv.Value, &eps); err != nil {
logging.Error.Println("Unmarshal endpoints error:", err)
return
}
r.nodes[NodeAddr(node)] = eps
for _, ep := range eps {
n := EndpointName(ep.Name)
r.eps[n] = append(r.eps[n], node)
}
}
}
func (r *CachedRegistry) runFetch() {
for range time.Tick(r.Tick) {
r.fetchOnce()
}
}
func (r *CachedRegistry) pick(k EndpointName) (string, error) {
r.mu.RLock()
defer r.mu.RUnlock()
eps, ok := r.eps[k]
if !ok || len(eps) == 0 {
return "", fmt.Errorf("%w: %q", registries.ErrEndpointNotFound, k)
}
if len(eps) == 1 {
return eps[0], nil
}
return r.Lb.Pick(eps), nil
}
func (r *CachedRegistry) Lookup(k EndpointName) (string, error) {
if !r.Started() {
if err := r.Start(); err != nil {
return "", nil
}
}
return r.pick(k)
}