/
manager.go
212 lines (184 loc) · 5.6 KB
/
manager.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
package conf
import (
"context"
"crypto/md5"
"encoding/json"
"github.com/spf13/viper"
"go.uber.org/fx"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/mimiro-io/objectstorage-datalayer/internal/security"
"github.com/bamzi/jobrunner"
"go.uber.org/zap"
"github.com/gojektech/heimdall/v6/httpclient"
)
type ConfigurationManager struct {
configLocation string
refreshInterval string
Datalayer *StorageConfig
logger *zap.SugaredLogger
State State
TokenProviders *security.TokenProviders
}
type State struct {
Timestamp int64
Digest [16]byte
}
func NewConfigurationManager(lc fx.Lifecycle, env *Env, providers *security.TokenProviders) *ConfigurationManager {
config := &ConfigurationManager{
configLocation: env.ConfigLocation,
refreshInterval: env.RefreshInterval,
Datalayer: &StorageConfig{},
TokenProviders: providers,
logger: env.Logger.Named("configuration"),
State: State{
Timestamp: time.Now().Unix(),
},
}
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
config.Init()
return nil
},
})
return config
}
func (conf *ConfigurationManager) Init() {
conf.logger.Infof("Starting the ConfigurationManager with refresh %s\n", conf.refreshInterval)
conf.load()
conf.logger.Info("Done loading the config")
jobrunner.Start()
err := jobrunner.Schedule(conf.refreshInterval, conf)
if err != nil {
conf.logger.Warn("Could not start configuration reload job")
}
}
func (conf *ConfigurationManager) Run() {
conf.load()
}
func (conf *ConfigurationManager) load() {
var configContent []byte
var err error
if strings.Index(conf.configLocation, "file://") == 0 {
configContent, err = conf.loadFile(conf.configLocation)
} else if strings.Index(conf.configLocation, "http") == 0 {
c, err := conf.loadUrl(conf.configLocation)
if err != nil {
conf.logger.Warn("Unable to parse json into config. Error is: "+err.Error()+". Please check file: "+conf.configLocation, err)
return
}
configContent, err = unpackContent(c)
} else {
conf.logger.Errorf("Config file location not supported: %s \n", conf.configLocation)
configContent, _ = conf.loadFile("file://resources/default-config.json")
}
if err != nil {
// means no file found
conf.logger.Infof("Could not find %s", conf.configLocation)
}
if configContent == nil {
// again means not found or no content
conf.logger.Infof("No values read for %s", conf.configLocation)
configContent = make([]byte, 0)
}
state := State{
Timestamp: time.Now().Unix(),
Digest: md5.Sum(configContent),
}
if state.Digest != conf.State.Digest {
config, err := conf.parse(configContent)
if err != nil {
conf.logger.Warn("Unable to parse json into config. Error is: "+err.Error()+". Please check file: "+conf.configLocation, err)
return
}
conf.Datalayer = conf.mapColumns(conf.injectSecrets(config))
conf.State = state
conf.logger.Info("Updated configuration with new values")
}
}
func (conf *ConfigurationManager) injectSecrets(config *StorageConfig) *StorageConfig {
updatedStorageBackend := []StorageBackend{}
for _, mapping := range config.StorageBackends {
secretFromProperties := mapping.Properties.Secret
if secretFromProperties != nil && *secretFromProperties != "" {
secretFromEnvironment := viper.GetString(*secretFromProperties)
if secretFromEnvironment != "" {
mapping.Properties.Secret = &secretFromEnvironment
}
}
updatedStorageBackend = append(updatedStorageBackend, mapping)
}
config.StorageBackends = updatedStorageBackend
return config
}
func (conf *ConfigurationManager) loadUrl(configEndpoint string) ([]byte, error) {
timeout := 10000 * time.Millisecond
client := httpclient.NewClient(httpclient.WithHTTPTimeout(timeout), httpclient.WithRetryCount(3))
req, err := http.NewRequest("GET", configEndpoint, nil) //
if err != nil {
return nil, err
}
provider, ok := conf.TokenProviders.Providers["auth0tokenprovider"]
if ok {
tokenProvider := provider.(security.TokenProvider)
bearer, err := tokenProvider.Token()
if err != nil {
conf.logger.Warnf("Token provider returned error: %w", err)
}
req.Header.Add("Authorization", bearer)
}
resp, err := client.Do(req)
if err != nil {
conf.logger.Error("Unable to open config url: "+configEndpoint, err)
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode == 200 {
return ioutil.ReadAll(resp.Body)
} else {
conf.logger.Infof("Endpoint returned %s", resp.Status)
return nil, err
}
}
type content struct {
Id string `json:"id"`
Data map[string]interface{} `json:"data"`
}
func unpackContent(themBytes []byte) ([]byte, error) {
unpacked := &content{}
err := json.Unmarshal(themBytes, unpacked)
if err != nil {
return nil, err
}
data := unpacked.Data
return json.Marshal(data)
}
func (conf *ConfigurationManager) loadFile(location string) ([]byte, error) {
configFileName := strings.ReplaceAll(location, "file://", "")
configFile, err := os.Open(configFileName)
if err != nil {
conf.logger.Error("Unable to open config file: "+configFileName, err)
return nil, err
}
defer configFile.Close()
return ioutil.ReadAll(configFile)
}
func (conf *ConfigurationManager) parse(config []byte) (*StorageConfig, error) {
configuration := &StorageConfig{}
err := json.Unmarshal(config, configuration)
return configuration, err
}
// mapColumns remaps the ColumnMapping into Column
func (conf *ConfigurationManager) mapColumns(config *StorageConfig) *StorageConfig {
layers := make(map[string]StorageBackend)
for _, t := range config.StorageBackends {
layers[t.Dataset] = t
}
config.StorageMapping = layers
return config
}