-
Notifications
You must be signed in to change notification settings - Fork 0
/
settings.go
126 lines (109 loc) · 2.6 KB
/
settings.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
package settings
import (
"fmt"
"os"
"github.com/rancher/rancher/pkg/settings"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/config"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1"
)
func Register(context *config.ScaledContext) error {
sp := &settingsProvider{
settings: context.Management.Settings(""),
settingsLister: context.Management.Settings("").Controller().Lister(),
}
if err := settings.SetProvider(sp); err != nil {
return err
}
return nil
}
type settingsProvider struct {
settings v3.SettingInterface
settingsLister v3.SettingLister
fallback map[string]string
}
func (s *settingsProvider) Get(name string) string {
value := os.Getenv(settings.GetEnvKey(name))
if value != "" {
return value
}
obj, err := s.settingsLister.Get("", name)
if err != nil {
return s.fallback[name]
}
if obj.Value == "" {
return obj.Default
}
return obj.Value
}
func (s *settingsProvider) Set(name, value string) error {
envValue := os.Getenv(settings.GetEnvKey(name))
if envValue != "" {
return fmt.Errorf("setting %s can not be set because it is from environment variable", name)
}
obj, err := s.settings.Get(name, v1.GetOptions{})
if err != nil {
return err
}
obj.Value = value
_, err = s.settings.Update(obj)
return err
}
func (s *settingsProvider) SetIfUnset(name, value string) error {
obj, err := s.settings.Get(name, v1.GetOptions{})
if err != nil {
return err
}
if obj.Value != "" {
return nil
}
obj.Value = value
_, err = s.settings.Update(obj)
return err
}
func (s *settingsProvider) SetAll(settingsMap map[string]settings.Setting) error {
fallback := map[string]string{}
for name, setting := range settingsMap {
key := settings.GetEnvKey(name)
value := os.Getenv(key)
obj, err := s.settings.Get(setting.Name, v1.GetOptions{})
if errors.IsNotFound(err) {
newSetting := &v3.Setting{
ObjectMeta: v1.ObjectMeta{
Name: setting.Name,
},
Default: setting.Default,
}
if value != "" {
newSetting.Value = value
}
fallback[newSetting.Name] = newSetting.Value
_, err := s.settings.Create(newSetting)
if err != nil {
return err
}
} else if err != nil {
return err
} else {
update := false
if obj.Default != setting.Default {
obj.Default = setting.Default
update = true
}
if value != "" && obj.Value != value {
obj.Value = value
update = true
}
fallback[obj.Name] = obj.Value
if update {
_, err := s.settings.Update(obj)
if err != nil {
return err
}
}
}
}
s.fallback = fallback
return nil
}