forked from philchia/agollo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
245 lines (203 loc) · 5.5 KB
/
client.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package agollo
import (
"context"
"encoding/json"
"fmt"
"net/http"
)
// Client for apollo
type Client struct {
conf *Conf
updateChan chan *ChangeEvent
caches *namespaceCache
releaseKeyRepo *cache
longPoller poller
requester requester
ctx context.Context
cancel context.CancelFunc
}
// result of query config
type result struct {
// AppID string `json:"appId"`
// Cluster string `json:"cluster"`
NamespaceName string `json:"namespaceName"`
Configurations map[string]string `json:"configurations"`
ReleaseKey string `json:"releaseKey"`
}
// NewClient create client from conf
func NewClient(conf *Conf) *Client {
client := &Client{
conf: conf,
caches: newNamespaceCahce(),
releaseKeyRepo: newCache(),
requester: newHTTPRequester(&http.Client{Timeout: queryTimeout}),
}
client.longPoller = newLongPoller(conf, longPoolInterval, client.handleNamespaceUpdate)
client.ctx, client.cancel = context.WithCancel(context.Background())
return client
}
// Start sync config
func (c *Client) Start() error {
// preload all config to local first
if err := c.preload(); err != nil {
return err
}
// start fetch update
go c.longPoller.start()
return nil
}
// handleNamespaceUpdate sync config for namespace, delivery changes to subscriber
func (c *Client) handleNamespaceUpdate(namespace string) error {
change, err := c.sync(namespace)
if err != nil || change == nil {
return err
}
c.deliveryChangeEvent(change)
return nil
}
// Stop sync config
func (c *Client) Stop() error {
c.longPoller.stop()
c.cancel()
// close(c.updateChan)
c.updateChan = nil
return nil
}
// fetchAllCinfig fetch from remote, if failed load from local file
func (c *Client) preload() error {
if err := c.longPoller.preload(); err != nil {
fmt.Printf("Long poller preload failed: %v\n", err)
return c.loadLocal(c.getDumpFileName())
}
return nil
}
// loadLocal load caches from local file
func (c *Client) loadLocal(name string) error {
return c.caches.load(name)
}
// dump caches to file
func (c *Client) dump(name string) error {
return c.caches.dump(name)
}
// WatchUpdate get all updates
func (c *Client) WatchUpdate() <-chan *ChangeEvent {
if c.updateChan == nil {
c.updateChan = make(chan *ChangeEvent)
}
return c.updateChan
}
// OnConfigChange when config changed, run would be called
func (c *Client) OnConfigChange(run func(*ChangeEvent)) {
go func() {
events := c.WatchUpdate()
for {
select {
case e := <-events:
run(e)
}
}
}()
}
func (c *Client) mustGetCache(namespace string) *cache {
return c.caches.mustGetCache(namespace)
}
// GetStringValueWithNameSpace get value from given namespace
func (c *Client) GetStringValueWithNameSpace(namespace, key, defaultValue string) string {
cache := c.mustGetCache(namespace)
if ret, ok := cache.get(key); ok && ret != "" {
return ret
}
return defaultValue
}
// GetStringValue from default namespace
func (c *Client) GetStringValue(key, defaultValue string) string {
return c.GetStringValueWithNameSpace(defaultNamespace, key, defaultValue)
}
// GetNameSpaceContent get contents of namespace
func (c *Client) GetNameSpaceContent(namespace, defaultValue string) string {
return c.GetStringValueWithNameSpace(namespace, "content", defaultValue)
}
// GetAllKeys return all config keys in given namespace
func (c *Client) GetAllKeys(namespace string) []string {
var keys []string
cache := c.mustGetCache(namespace)
cache.kv.Range(func(key, value interface{}) bool {
str, ok := key.(string)
if ok {
keys = append(keys, str)
}
return true
})
return keys
}
// Unmarshal unmarshals the config into a struct
func (c *Client) Unmarshal(model interface{}) error {
return c.caches.decode(model)
}
// sync namespace config
func (c *Client) sync(namesapce string) (*ChangeEvent, error) {
releaseKey := c.getReleaseKey(namesapce)
url := configURL(c.conf, namesapce, releaseKey)
bts, err := c.requester.request(url)
if err != nil || len(bts) == 0 {
return nil, err
}
var result result
if err := json.Unmarshal(bts, &result); err != nil {
return nil, err
}
return c.handleResult(&result), nil
}
// deliveryChangeEvent push change to subscriber
func (c *Client) deliveryChangeEvent(change *ChangeEvent) {
if c.updateChan == nil {
return
}
select {
case <-c.ctx.Done():
case c.updateChan <- change:
}
}
// handleResult generate changes from query result, and update local cache
func (c *Client) handleResult(result *result) *ChangeEvent {
var ret = ChangeEvent{
Namespace: result.NamespaceName,
Changes: map[string]*Change{},
}
cache := c.mustGetCache(result.NamespaceName)
kv := cache.dump()
for k, v := range kv {
if _, ok := result.Configurations[k]; !ok {
cache.delete(k)
ret.Changes[k] = makeDeleteChange(k, v)
}
}
for k, v := range result.Configurations {
cache.set(k, v)
old, ok := kv[k]
if !ok {
ret.Changes[k] = makeAddChange(k, v)
continue
}
if old != v {
ret.Changes[k] = makeModifyChange(k, old, v)
}
}
c.setReleaseKey(result.NamespaceName, result.ReleaseKey)
// dump caches to file
c.dump(c.getDumpFileName())
if len(ret.Changes) == 0 {
return nil
}
return &ret
}
func (c *Client) getDumpFileName() string {
return fmt.Sprintf(".%s_%s", c.conf.AppID, c.conf.Cluster)
}
func (c *Client) getReleaseKey(namespace string) string {
releaseKey, _ := c.releaseKeyRepo.get(namespace)
return releaseKey
}
func (c *Client) setReleaseKey(namespace, releaseKey string) {
c.releaseKeyRepo.set(namespace, releaseKey)
}