/
properties.go
645 lines (551 loc) · 18.2 KB
/
properties.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
package properties
import (
"encoding/json"
goflag "flag"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/Axway/agent-sdk/pkg/util"
"github.com/Axway/agent-sdk/pkg/util/errors"
"github.com/Axway/agent-sdk/pkg/util/log"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
)
// ErrInvalidSecretReference - Error for parsing properties with secret reference
var ErrInvalidSecretReference = errors.Newf(1411, "invalid secret reference - %s, please check the value for %s config")
// QA EnvVars
const qaEnforceDurationLowerLimit = "QA_ENFORCE_DURATION_LOWER_LIMIT"
const (
lowerLimitName = "%s-lowerLimit"
upperLimitName = "%s-upperLimit"
qaVarNameFormat = "qa.%s"
)
// SecretPropertyResolver - interface for resolving property values with secret references
type SecretPropertyResolver interface {
ResolveSecret(secretRef string) (string, error)
}
// Properties - Root Command Properties interface for all configs to use for adding and parsing values
type Properties interface {
// Methods for adding yaml properties and command flag
AddStringProperty(name string, defaultVal string, description string)
AddStringPersistentFlag(name string, defaultVal string, description string)
AddStringFlag(name string, description string)
AddDurationProperty(name string, defaultVal time.Duration, description string, options ...DurationOpt)
AddIntProperty(name string, defaultVal int, description string)
AddBoolProperty(name string, defaultVal bool, description string)
AddBoolFlag(name, description string)
AddStringSliceProperty(name string, defaultVal []string, description string)
AddObjectSliceProperty(name string, objectPropertyNames []string)
// Methods to get the configured properties
StringPropertyValue(name string) string
StringFlagValue(name string) (bool, string)
DurationPropertyValue(name string) time.Duration
IntPropertyValue(name string) int
BoolPropertyValue(name string) bool
BoolPropertyValueOrTrue(name string) bool // Use this method when the default value, no config given, is true
BoolFlagValue(name string) bool
StringSlicePropertyValue(name string) []string
ObjectSlicePropertyValue(name string) []map[string]interface{}
// Methods to set a property
SetStringFlagValue(name string, value string)
// Log Properties
MaskValues(name string)
DebugLogProperties()
SetAliasKeyPrefix(aliasKeyPrefix string)
}
type durationOpts struct {
lower time.Duration
upper time.Duration
qaOverride bool
}
// DurationOpt are duration range options passed into AddDurationProperty
type DurationOpt func(prop *durationOpts)
// WithLowerLimit - lower limit of the duration range
func WithLowerLimit(lower time.Duration) DurationOpt {
return func(d *durationOpts) {
d.lower = lower
}
}
// WithUpperLimit - upper limit of the duration range
func WithUpperLimit(upper time.Duration) DurationOpt {
return func(d *durationOpts) {
d.upper = upper
}
}
// WithQAOverride - set to true to allow this setting to be overwritten with a qa env var
func WithQAOverride() DurationOpt {
return func(d *durationOpts) {
d.qaOverride = true
}
}
var aliasKeyPrefix string
type properties struct {
Properties
rootCmd *cobra.Command
envIntfArrayPropValues map[string][]map[string]interface{}
envIntfArrayPropertyKeys map[string]map[string]bool
secretResolver SecretPropertyResolver
flattenedProperties map[string]string
}
var expansionRegEx *regexp.Regexp
func init() {
expansionRegEx = regexp.MustCompile(`\$\{(\w+):(.*)\}|\$\{(\w+)\}`)
}
// NewProperties - Creates a new Properties struct
func NewProperties(rootCmd *cobra.Command) Properties {
cmdprops := &properties{
rootCmd: rootCmd,
envIntfArrayPropertyKeys: make(map[string]map[string]bool),
flattenedProperties: make(map[string]string),
}
return cmdprops
}
// NewPropertiesWithSecretResolver - Creates a new Properties struct with secret resolver for string property/flag
func NewPropertiesWithSecretResolver(rootCmd *cobra.Command, secretResolver SecretPropertyResolver) Properties {
cmdprops := &properties{
rootCmd: rootCmd,
envIntfArrayPropertyKeys: make(map[string]map[string]bool),
flattenedProperties: make(map[string]string),
secretResolver: secretResolver,
}
return cmdprops
}
// SetAliasKeyPrefix -
func SetAliasKeyPrefix(keyPrefix string) {
aliasKeyPrefix = keyPrefix
}
// GetAliasKeyPrefix -
func GetAliasKeyPrefix() string {
return aliasKeyPrefix
}
func (p *properties) bindOrPanic(key string, flg *flag.Flag) {
if err := viper.BindPFlag(key, flg); err != nil {
panic(err)
}
if aliasKeyPrefix != "" {
if err := viper.BindPFlag(aliasKeyPrefix+"."+key, flg); err != nil {
panic(err)
}
}
}
func (p *properties) AddObjectSliceProperty(envPrefix string, intfPropertyNames []string) {
envPrefix = strings.ReplaceAll(envPrefix, ".", "_")
envPrefix = strings.ToUpper(envPrefix)
if !strings.HasSuffix(envPrefix, "_") {
envPrefix += "_"
}
iPropNames := make(map[string]bool)
for _, propName := range intfPropertyNames {
iPropNames[propName] = true
}
p.envIntfArrayPropertyKeys[envPrefix] = iPropNames
}
func (p *properties) AddStringProperty(name string, defaultVal string, description string) {
if p.rootCmd != nil {
flagName := p.nameToFlagName(name)
p.rootCmd.Flags().String(flagName, defaultVal, description)
p.bindOrPanic(name, p.rootCmd.Flags().Lookup(flagName))
p.rootCmd.Flags().MarkHidden(flagName)
}
}
func (p *properties) AddStringPersistentFlag(flagName string, defaultVal string, description string) {
if p.rootCmd != nil {
flg := goflag.CommandLine.Lookup(flagName)
if flg == nil {
goflag.CommandLine.String(flagName, "", description)
flg = goflag.CommandLine.Lookup(flagName)
}
p.rootCmd.PersistentFlags().AddGoFlag(flg)
}
}
func (p *properties) AddStringFlag(flagName string, description string) {
if p.rootCmd != nil {
p.rootCmd.Flags().String(flagName, "", description)
}
}
func (p *properties) SetStringFlagValue(flagName string, value string) {
if p.rootCmd != nil {
p.rootCmd.Flags().Set(flagName, value)
}
}
func (p *properties) AddStringSliceProperty(name string, defaultVal []string, description string) {
if p.rootCmd != nil {
flagName := p.nameToFlagName(name)
p.rootCmd.Flags().StringSlice(flagName, defaultVal, description)
p.bindOrPanic(name, p.rootCmd.Flags().Lookup(flagName))
p.rootCmd.Flags().MarkHidden(flagName)
}
}
func (p *properties) AddDurationProperty(name string, defaultVal time.Duration, description string, options ...DurationOpt) {
if p.rootCmd != nil {
flagName := p.nameToFlagName(name)
opts := &durationOpts{
lower: time.Second * 30,
}
// validate if WithLowerLimit and WithUpperLimit were called
for _, option := range options {
option(opts)
}
p.configureUpperAndLowerLimits(defaultVal, opts, flagName)
if opts.qaOverride {
qaName := fmt.Sprintf(qaVarNameFormat, name)
qaFlagName := p.nameToFlagName(qaName)
p.rootCmd.Flags().Duration(qaFlagName, -1*time.Second, "")
p.bindOrPanic(qaName, p.rootCmd.Flags().Lookup(qaFlagName))
p.rootCmd.Flags().MarkHidden(qaFlagName)
}
p.rootCmd.Flags().Duration(flagName, defaultVal, description)
p.bindOrPanic(name, p.rootCmd.Flags().Lookup(flagName))
p.rootCmd.Flags().MarkHidden(flagName)
}
}
func (p *properties) configureUpperAndLowerLimits(defaultVal time.Duration, limits *durationOpts, flagName string) {
lowerLimitFlag := fmt.Sprintf(lowerLimitName, flagName)
upperLimitFlag := fmt.Sprintf(upperLimitName, flagName)
// set lower limit
if defaultVal < limits.lower {
panic(fmt.Errorf("default value (%s) can not be smaller than lower limit (%s) for %s", defaultVal, limits.lower, flagName))
}
p.rootCmd.Flags().Duration(lowerLimitFlag, limits.lower, "value %s is lower than the supported lower limit (%s) for configuration %s")
p.rootCmd.Flags().MarkHidden(lowerLimitFlag)
// set upper limit if greater than zero
if limits.upper > 0 {
p.rootCmd.Flags().Duration(upperLimitFlag, limits.upper, "value %s is higher than the supported higher limit (%s) for configuration %s")
p.rootCmd.Flags().MarkHidden(upperLimitFlag)
// check for valid upper and lower limits
if limits.upper < limits.lower {
panic(fmt.Errorf("upper limit (%s) can not be smaller than lower limit (%s) for %s", limits.upper, limits.lower, flagName))
}
if defaultVal > limits.upper {
panic(fmt.Errorf("default value (%s) can not be larger than upper limit (%s) for %s", defaultVal, limits.upper, flagName))
}
}
}
func (p *properties) AddIntProperty(name string, defaultVal int, description string) {
if p.rootCmd != nil {
flagName := p.nameToFlagName(name)
p.rootCmd.Flags().Int(flagName, defaultVal, description)
p.bindOrPanic(name, p.rootCmd.Flags().Lookup(flagName))
p.rootCmd.Flags().MarkHidden(flagName)
}
}
func (p *properties) AddBoolProperty(name string, defaultVal bool, description string) {
if p.rootCmd != nil {
flagName := p.nameToFlagName(name)
p.rootCmd.Flags().Bool(flagName, defaultVal, description)
p.bindOrPanic(name, p.rootCmd.Flags().Lookup(flagName))
p.rootCmd.Flags().MarkHidden(flagName)
}
}
func (p *properties) AddBoolFlag(flagName string, description string) {
if p.rootCmd != nil {
p.rootCmd.Flags().Bool(flagName, false, description)
}
}
func (p *properties) StringSlicePropertyValue(name string) []string {
val := viper.Get(name)
// special check to differentiate between yaml and commandline parsing. For commandline, must
// turn it into an array ourselves
switch val := val.(type) {
case string:
p.addPropertyToFlatMap(name, val)
return p.convertStringToSlice(fmt.Sprintf("%v", viper.Get(name)))
default:
return viper.GetStringSlice(name)
}
}
func (p *properties) convertStringToSlice(value string) []string {
slc := strings.Split(value, ",")
for i := range slc {
slc[i] = strings.TrimSpace(slc[i])
}
return slc
}
func (p *properties) parseStringValueForKey(key string) string {
s := strings.TrimSpace(viper.GetString(key))
if strings.Index(s, "$") == 0 {
matches := expansionRegEx.FindAllSubmatch([]byte(s), -1)
if len(matches) > 0 {
expSlice := matches[0]
if len(expSlice) > 2 {
s = p.parseSlice(s, expSlice)
}
}
}
return s
}
func (p *properties) parseSlice(s string, expSlice [][]byte) string {
rtnS := s
envVar := string(expSlice[1])
defaultVal := ""
if envVar == "" {
if len(expSlice) >= 4 {
envVar = strings.Trim(string(expSlice[3]), "\"")
}
} else {
if len(expSlice) >= 3 {
defaultVal = strings.Trim(string(expSlice[2]), "\"")
}
}
if envVar != "" {
rtnS = os.Getenv(envVar)
if rtnS == "" && defaultVal != "" {
rtnS = defaultVal
}
}
return rtnS
}
func (p *properties) parseStringValue(key string) string {
var s string
if aliasKeyPrefix != "" {
s = p.parseStringValueForKey(aliasKeyPrefix + "." + key)
}
// If no alias or no value parsed for alias key
if s == "" {
s = p.parseStringValueForKey(key)
}
return s
}
func (p *properties) resolveSecretReference(cfgName, cfgValue string) string {
if p.secretResolver != nil {
secretValue, err := p.secretResolver.ResolveSecret(cfgValue)
if err != nil {
// only log the error and return empty string,
// validation on config triggers the agent to return error to root command
log.Error(ErrInvalidSecretReference.FormatError(err.Error(), cfgName))
cfgValue = ""
}
if secretValue != "" {
cfgValue = secretValue
}
}
return cfgValue
}
func (p *properties) StringPropertyValue(name string) string {
s := p.parseStringValue(name)
s = p.resolveSecretReference(name, s)
p.addPropertyToFlatMap(name, s)
return s
}
func (p *properties) StringFlagValue(name string) (bool, string) {
flag := p.rootCmd.Flag(name)
if flag == nil || flag.Value.String() == "" {
return false, ""
}
fv := flag.Value.String()
fv = p.resolveSecretReference(name, fv)
p.addPropertyToFlatMap(name, fv)
return true, fv
}
func (p *properties) DurationPropertyValue(name string) time.Duration {
s := p.parseStringValue(name)
d, _ := time.ParseDuration(s)
// check if the duration has a qa equivalent that should be used
if qaVal := p.getQADuration(name); qaVal > 0 {
return qaVal
}
if !isDurationLowerLimitEnforced() {
return d
}
flagName := p.nameToFlagName(name)
flag := p.rootCmd.Flag(flagName)
lowerLimit, upperLimit := p.getDurationLimits(flagName)
defaultVal, _ := time.ParseDuration(flag.DefValue)
if lowerLimit > 0 && d < lowerLimit {
d = defaultVal
log.Warnf("Configuration %s has been set to the default value of %s. Please update this value greater than the lower limit of %s", name, d, lowerLimit)
} else if upperLimit > 0 && d > upperLimit {
d = defaultVal
log.Warnf("Configuration %s has been set to the default value of %s. Please update this value lower than the upper limit of %s", name, d, upperLimit)
}
p.addPropertyToFlatMap(name, s)
return d
}
// getQADuration - returns the qa variables duration
func (p *properties) getQADuration(name string) time.Duration {
qaName := fmt.Sprintf(qaVarNameFormat, name)
qaVal := -1 * time.Second
if s := p.parseStringValue(qaName); s != "" {
qaVal, _ = time.ParseDuration(s)
}
return qaVal
}
// getDurationLimits - returns the duration limits, negative number returned for unset
func (p *properties) getDurationLimits(flagName string) (time.Duration, time.Duration) {
lowerLimitFlag := p.rootCmd.Flag(fmt.Sprintf(lowerLimitName, flagName))
upperLimitFlag := p.rootCmd.Flag(fmt.Sprintf(upperLimitName, flagName))
lowerLimit := -1 * time.Second
upperLimit := -1 * time.Second
if lowerLimitFlag != nil {
lowerLimit, _ = time.ParseDuration(lowerLimitFlag.Value.String())
}
if upperLimitFlag != nil {
upperLimit, _ = time.ParseDuration(upperLimitFlag.Value.String())
}
return lowerLimit, upperLimit
}
func (p *properties) IntPropertyValue(name string) int {
s := p.parseStringValue(name)
i, _ := strconv.Atoi(s)
p.addPropertyToFlatMap(name, s)
return i
}
func (p *properties) BoolPropertyValue(name string) bool {
return p.boolPropertyValue(name, false)
}
func (p *properties) BoolPropertyValueOrTrue(name string) bool {
return p.boolPropertyValue(name, true)
}
func (p *properties) boolPropertyValue(name string, defVal bool) bool {
s := p.parseStringValue(name)
if s == "" {
return defVal
}
b, _ := strconv.ParseBool(s)
p.addPropertyToFlatMap(name, s)
return b
}
func (p *properties) BoolFlagValue(name string) bool {
flag := p.rootCmd.Flag(name)
if flag == nil {
return false
}
if flag.Value.String() == "true" {
return true
}
return false
}
func (p *properties) nameToFlagName(name string) (flagName string) {
parts := strings.Split(name, ".")
flagName = parts[0]
for _, part := range parts[1:] {
flagName += strings.Title(part)
}
return
}
// String array containing any sensitive data that needs to be masked with "*" (asterisks)
// Add any sensitive data here using flattened key format
var maskValues = make([]string, 0)
func (p *properties) addPropertyToFlatMap(key, value string) {
for _, maskValue := range maskValues {
match, _ := regexp.MatchString("\\b"+strings.TrimSpace(maskValue)+"\\b", key)
if match {
value = util.MaskValue(value)
}
}
p.flattenedProperties[key] = value
}
func (p *properties) MaskValues(maskedKeys string) {
maskValues = strings.Split(maskedKeys, ",")
}
func (p *properties) DebugLogProperties() {
data, _ := json.MarshalIndent(p.flattenedProperties, "", " ")
log.Debugf("%s\n", data)
}
// enforce the lower limit by default
func isDurationLowerLimitEnforced() bool {
if val := os.Getenv(qaEnforceDurationLowerLimit); val != "" {
ret, err := strconv.ParseBool(val)
if err != nil {
log.Errorf("Invalid value %s for env variable %s", val, qaEnforceDurationLowerLimit)
return true
}
return ret
}
return true
}
// ObjectSlicePropertyValue
func (p *properties) ObjectSlicePropertyValue(name string) []map[string]interface{} {
p.readEnv()
name = strings.ReplaceAll(name, ".", "_")
name = strings.ToUpper(name)
if !strings.HasSuffix(name, "_") {
name += "_"
}
return p.envIntfArrayPropValues[name]
}
func (p *properties) readEnv() {
if p.envIntfArrayPropValues != nil {
return
}
p.envIntfArrayPropValues = make(map[string][]map[string]interface{})
envVarsMap := p.parseEnvPropertiesFlatMap()
for prefix, eVals := range envVarsMap {
propValues, ok := p.envIntfArrayPropValues[prefix]
if !ok {
propValues = make([]map[string]interface{}, 0)
}
for _, val := range eVals {
v := p.convertFlatMap(val)
propValues = append(propValues, v)
}
p.envIntfArrayPropValues[prefix] = propValues
}
}
func (p *properties) convertFlatMap(flatMap map[string]string) map[string]interface{} {
m := make(map[string]interface{})
for key, val := range flatMap {
ok := strings.Contains(key, ".")
if !ok {
m[key] = val
} else {
k := strings.Split(key, ".")
p.setChildMapProperty(m, k, val)
}
}
return m
}
func (p *properties) setChildMapProperty(parentMap map[string]interface{}, childKeys []string, val string) {
cm, ok := parentMap[childKeys[0]]
if !ok {
cm = make(map[string]interface{})
}
childMap, ok := cm.(map[string]interface{})
if ok {
if len(childKeys) > 2 {
p.setChildMapProperty(childMap, childKeys[1:], val)
} else {
childMap[childKeys[1]] = val
}
parentMap[childKeys[0]] = cm
}
}
func (p *properties) parseEnvPropertiesFlatMap() map[string]map[string]map[string]string {
envVarsMap := make(map[string]map[string]map[string]string)
for _, element := range os.Environ() {
variable := strings.SplitN(element, "=", 2)
name := variable[0]
val := variable[1]
for prefix, iPropNames := range p.envIntfArrayPropertyKeys {
p.fillEnvVarsMap(name, val, prefix, iPropNames, envVarsMap)
}
}
return envVarsMap
}
func (p *properties) fillEnvVarsMap(name string, val string, prefix string, iPropNames map[string]bool, envVarsMap map[string]map[string]map[string]string) {
if strings.HasPrefix(name, prefix) {
n := strings.ReplaceAll(name, prefix, "")
elements := strings.Split(name, "_")
lastSuffix := elements[len(elements)-1]
_, ok := envVarsMap[prefix]
if !ok {
envVarsMap[prefix] = make(map[string]map[string]string)
}
m, ok := envVarsMap[prefix][lastSuffix]
if !ok {
m = make(map[string]string)
}
for pName := range iPropNames {
propName := strings.ReplaceAll(pName, ".", "_")
propName = strings.ToUpper(propName)
if strings.HasPrefix(n, propName) {
m[pName] = val
envVarsMap[prefix][lastSuffix] = m
}
}
}
}