/
file_based_client.go
348 lines (302 loc) · 10 KB
/
file_based_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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package dynamicconfig
import (
"errors"
"fmt"
"io/ioutil"
"os"
"sync/atomic"
"time"
"gopkg.in/yaml.v2"
"github.com/uber/cadence/common/log"
"github.com/uber/cadence/common/log/tag"
)
var _ Client = (*fileBasedClient)(nil)
const (
minPollInterval = time.Second * 5
fileMode = 0644 // used for update config file
)
type constrainedValue struct {
Value interface{}
Constraints map[string]interface{}
}
// FileBasedClientConfig is the config for the file based dynamic config client.
// It specifies where the config file is stored and how often the config should be
// updated by checking the config file again.
type FileBasedClientConfig struct {
Filepath string `yaml:"filepath"`
PollInterval time.Duration `yaml:"pollInterval"`
}
type fileBasedClient struct {
values atomic.Value
lastUpdatedTime time.Time
config *FileBasedClientConfig
doneCh chan struct{}
logger log.Logger
}
// NewFileBasedClient creates a file based client.
func NewFileBasedClient(config *FileBasedClientConfig, logger log.Logger, doneCh chan struct{}) (Client, error) {
if err := validateConfig(config); err != nil {
return nil, err
}
client := &fileBasedClient{
config: config,
doneCh: doneCh,
logger: logger,
}
if err := client.update(); err != nil {
return nil, err
}
go func() {
ticker := time.NewTicker(client.config.PollInterval)
for {
select {
case <-ticker.C:
err := client.update()
if err != nil {
client.logger.Error("Failed to update dynamic config", tag.Error(err))
}
case <-client.doneCh:
ticker.Stop()
return
}
}
}()
return client, nil
}
func (fc *fileBasedClient) GetValue(name Key, defaultValue interface{}) (interface{}, error) {
return fc.getValueWithFilters(name, nil, defaultValue)
}
func (fc *fileBasedClient) GetValueWithFilters(name Key, filters map[Filter]interface{}, defaultValue interface{}) (interface{}, error) {
return fc.getValueWithFilters(name, filters, defaultValue)
}
func (fc *fileBasedClient) GetIntValue(name Key, filters map[Filter]interface{}, defaultValue int) (int, error) {
val, err := fc.getValueWithFilters(name, filters, defaultValue)
if err != nil {
return defaultValue, err
}
if intVal, ok := val.(int); ok {
return intVal, nil
}
return defaultValue, errors.New("value type is not int")
}
func (fc *fileBasedClient) GetFloatValue(name Key, filters map[Filter]interface{}, defaultValue float64) (float64, error) {
val, err := fc.getValueWithFilters(name, filters, defaultValue)
if err != nil {
return defaultValue, err
}
if floatVal, ok := val.(float64); ok {
return floatVal, nil
} else if intVal, ok := val.(int); ok {
return float64(intVal), nil
}
return defaultValue, errors.New("value type is not float64")
}
func (fc *fileBasedClient) GetBoolValue(name Key, filters map[Filter]interface{}, defaultValue bool) (bool, error) {
val, err := fc.getValueWithFilters(name, filters, defaultValue)
if err != nil {
return defaultValue, err
}
if boolVal, ok := val.(bool); ok {
return boolVal, nil
}
return defaultValue, errors.New("value type is not bool")
}
func (fc *fileBasedClient) GetStringValue(name Key, filters map[Filter]interface{}, defaultValue string) (string, error) {
val, err := fc.getValueWithFilters(name, filters, defaultValue)
if err != nil {
return defaultValue, err
}
if stringVal, ok := val.(string); ok {
return stringVal, nil
}
return defaultValue, errors.New("value type is not string")
}
func (fc *fileBasedClient) GetMapValue(
name Key, filters map[Filter]interface{}, defaultValue map[string]interface{},
) (map[string]interface{}, error) {
val, err := fc.getValueWithFilters(name, filters, defaultValue)
if err != nil {
return defaultValue, err
}
if mapVal, ok := val.(map[string]interface{}); ok {
return mapVal, nil
}
return defaultValue, errors.New("value type is not map")
}
func (fc *fileBasedClient) GetDurationValue(
name Key, filters map[Filter]interface{}, defaultValue time.Duration,
) (time.Duration, error) {
val, err := fc.getValueWithFilters(name, filters, defaultValue)
if err != nil {
return defaultValue, err
}
durationString, ok := val.(string)
if !ok {
return defaultValue, errors.New("value type is not string")
}
durationVal, err := time.ParseDuration(durationString)
if err != nil {
return defaultValue, fmt.Errorf("failed to parse duration: %v", err)
}
return durationVal, nil
}
func (fc *fileBasedClient) UpdateValue(name Key, value interface{}) error {
keyName := keys[name]
currentValues := make(map[string][]*constrainedValue)
confContent, err := ioutil.ReadFile(fc.config.Filepath)
if err != nil {
return fmt.Errorf("failed to read dynamic config file %v: %v", fc.config.Filepath, err)
}
if err = yaml.Unmarshal(confContent, currentValues); err != nil {
return fmt.Errorf("failed to decode dynamic config %v", err)
}
cVal := &constrainedValue{
Value: value,
}
currentValues[keyName] = []*constrainedValue{cVal}
newBytes, _ := yaml.Marshal(currentValues)
err = ioutil.WriteFile(fc.config.Filepath, newBytes, fileMode)
if err != nil {
return fmt.Errorf("failed to write config file, err: %v", err)
}
return fc.storeValues(currentValues)
}
func (fc *fileBasedClient) update() error {
defer func() {
fc.lastUpdatedTime = time.Now()
}()
newValues := make(map[string][]*constrainedValue)
info, err := os.Stat(fc.config.Filepath)
if err != nil {
return fmt.Errorf("failed to get status of dynamic config file: %v", err)
}
if !info.ModTime().After(fc.lastUpdatedTime) {
return nil
}
confContent, err := ioutil.ReadFile(fc.config.Filepath)
if err != nil {
return fmt.Errorf("failed to read dynamic config file %v: %v", fc.config.Filepath, err)
}
if err = yaml.Unmarshal(confContent, newValues); err != nil {
return fmt.Errorf("failed to decode dynamic config %v", err)
}
return fc.storeValues(newValues)
}
func (fc *fileBasedClient) storeValues(newValues map[string][]*constrainedValue) error {
// yaml will unmarshal map into map[interface{}]interface{} instead of map[string]interface{}
// manually convert key type to string for all values here
// We don't need to convert constraints as their type can't be map. If user does use a map as filter
// value, it won't match anyway.
for _, s := range newValues {
for _, cv := range s {
var err error
cv.Value, err = convertKeyTypeToString(cv.Value)
if err != nil {
return err
}
}
}
fc.values.Store(newValues)
fc.logger.Info("Updated dynamic config")
return nil
}
func (fc *fileBasedClient) getValueWithFilters(key Key, filters map[Filter]interface{}, defaultValue interface{}) (interface{}, error) {
keyName := keys[key]
values := fc.values.Load().(map[string][]*constrainedValue)
found := false
for _, constrainedValue := range values[keyName] {
if len(constrainedValue.Constraints) == 0 {
// special handling for default value (value without any constraints)
defaultValue = constrainedValue.Value
found = true
continue
}
if match(constrainedValue, filters) {
return constrainedValue.Value, nil
}
}
if !found {
return defaultValue, notFoundError
}
return defaultValue, nil
}
// match will return true if the constraints matches the filters or any subsets
func match(v *constrainedValue, filters map[Filter]interface{}) bool {
if len(v.Constraints) > len(filters) {
return false
}
for constrain, constrainedValue := range v.Constraints {
constrainKey := parseFilter(constrain)
if filters[constrainKey] == nil || filters[constrainKey] != constrainedValue {
return false
}
}
return true
}
func convertKeyTypeToString(v interface{}) (interface{}, error) {
switch v := v.(type) {
case map[interface{}]interface{}:
return convertKeyTypeToStringMap(v)
case []interface{}:
return convertKeyTypeToStringSlice(v)
default:
return v, nil
}
}
func convertKeyTypeToStringMap(m map[interface{}]interface{}) (map[string]interface{}, error) {
stringKeyMap := make(map[string]interface{})
for key, value := range m {
stringKey, ok := key.(string)
if !ok {
return nil, fmt.Errorf("type of key %v is not string", key)
}
convertedValue, err := convertKeyTypeToString(value)
if err != nil {
return nil, err
}
stringKeyMap[stringKey] = convertedValue
}
return stringKeyMap, nil
}
func convertKeyTypeToStringSlice(s []interface{}) ([]interface{}, error) {
stringKeySlice := make([]interface{}, len(s))
for idx, value := range s {
convertedValue, err := convertKeyTypeToString(value)
if err != nil {
return nil, err
}
stringKeySlice[idx] = convertedValue
}
return stringKeySlice, nil
}
func validateConfig(config *FileBasedClientConfig) error {
if config == nil {
return errors.New("no config found for file based dynamic config client")
}
if _, err := os.Stat(config.Filepath); err != nil {
return fmt.Errorf("error checking dynamic config file at path %s, error: %v", config.Filepath, err)
}
if config.PollInterval < minPollInterval {
return fmt.Errorf("poll interval should be at least %v", minPollInterval)
}
return nil
}