-
Notifications
You must be signed in to change notification settings - Fork 85
/
config.go
216 lines (178 loc) · 6.26 KB
/
config.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
package config
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
"github.com/bacalhau-project/bacalhau/pkg/config/migrations"
"github.com/bacalhau-project/bacalhau/pkg/config/types"
)
const (
environmentVariablePrefix = "BACALHAU"
inferConfigTypes = true
automaticEnvVar = true
// user key files
Libp2pPrivateKeyFileName = "libp2p_private_key"
UserPrivateKeyFileName = "user_id.pem"
// compute paths
ComputeStoragesPath = "executor_storages"
PluginsPath = "plugins"
// requester paths
AutoCertCachePath = "autocert-cache"
// update check paths
UpdateCheckStatePath = "update.json"
// auth paths
TokensPath = "tokens.json"
)
var (
environmentVariableReplace = strings.NewReplacer(".", "_")
configDecoderHook = viper.DecodeHook(mapstructure.TextUnmarshallerHookFunc())
)
const (
configType = "yaml"
configName = "config"
configFileMode = 0666
)
func Init(path string) (types.BacalhauConfig, error) {
// derive the default config for the specified environment.
defaultConfig := ForEnvironment()
// set default values for path dependent config.
defaultConfig.User.KeyPath = filepath.Join(path, UserPrivateKeyFileName)
defaultConfig.User.Libp2pKeyPath = filepath.Join(path, Libp2pPrivateKeyFileName)
defaultConfig.Node.ExecutorPluginPath = filepath.Join(path, PluginsPath)
defaultConfig.Node.ComputeStoragePath = filepath.Join(path, ComputeStoragesPath)
defaultConfig.Update.CheckStatePath = filepath.Join(path, UpdateCheckStatePath)
defaultConfig.Auth.TokensPath = filepath.Join(path, TokensPath)
// initialize the configuration with default values.
return initConfig(path, WithDefaultConfig(defaultConfig))
}
func Load(path string) (types.BacalhauConfig, error) {
// derive the default config for the specified environment.
defaultConfig := ForEnvironment()
// set default values for path dependent config.
defaultConfig.User.KeyPath = filepath.Join(path, UserPrivateKeyFileName)
defaultConfig.User.Libp2pKeyPath = filepath.Join(path, Libp2pPrivateKeyFileName)
defaultConfig.Node.ExecutorPluginPath = filepath.Join(path, PluginsPath)
defaultConfig.Node.ComputeStoragePath = filepath.Join(path, ComputeStoragesPath)
defaultConfig.Update.CheckStatePath = filepath.Join(path, UpdateCheckStatePath)
defaultConfig.Auth.TokensPath = filepath.Join(path, TokensPath)
return initConfig(path, WithDefaultConfig(defaultConfig), WithFileHandler(ReadConfigHandler))
}
func Migrate(path string) error {
// check if the config file exists, if one is not found we don't need to migrate it
configPath := filepath.Join(path, "config.yaml")
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return nil
} else if err != nil {
return fmt.Errorf("failed to stat config file for migration: %w", err)
}
// open the config file
f, err := os.Open(configPath)
if err != nil {
return fmt.Errorf("failed to open config file at %q: %w", configPath, err)
}
// read it all and unmarshal into yaml
b, err := io.ReadAll(f)
if err != nil {
if err := f.Close(); err != nil {
log.Error().Err(err).Msg("failed to close config file after failing to read it.")
}
return fmt.Errorf("failed to read config file: %w", err)
}
// we can close the file now that we read everything.
if err := f.Close(); err != nil {
return fmt.Errorf("failed to close config file: %w", err)
}
var cfg types.BacalhauConfig
if err := yaml.Unmarshal(b, &cfg); err != nil {
return fmt.Errorf("failed to unmarshal config file: %w", err)
}
// get all the migrations we need to apply to it.
migs, err := migrations.GetMigrations()
if err != nil {
return fmt.Errorf("failed to load migration list: %w", err)
}
// apply the migrations
currentCfg := cfg
for _, m := range migs {
log.Info().Msgf("applying migration sequence %d", m.Sequence())
currentCfg, err = m.Migrate(currentCfg)
if err != nil {
return err
}
}
log.Info().Msgf("config migration complete")
// marshal the migrated config back to yaml
marshaledCfg, err := yaml.Marshal(currentCfg)
if err != nil {
return fmt.Errorf("failed to marshal migrated config: %w", err)
}
// open the file for writing and truncate it.
fw, err := os.OpenFile(configPath, os.O_WRONLY|os.O_TRUNC, configFileMode)
if err != nil {
return fmt.Errorf("failed to open config file for writing at %q: %w", configPath, err)
}
defer fw.Close()
// write the marshaled data back to the file
if _, err := fw.Write(marshaledCfg); err != nil {
return fmt.Errorf("failed to write migrated config to file: %w", err)
}
return nil
}
type Params struct {
FileName string
FileType string
FileHandler func(fileName string) error
DefaultConfig types.BacalhauConfig
}
func initConfig(path string, opts ...Option) (types.BacalhauConfig, error) {
params := &Params{
FileName: configName,
FileType: configType,
FileHandler: NoopConfigHandler,
DefaultConfig: ForEnvironment(),
}
for _, opt := range opts {
opt(params)
}
viper.AddConfigPath(path)
viper.SetConfigName(params.FileName)
viper.SetConfigType(params.FileType)
viper.SetEnvPrefix(environmentVariablePrefix)
viper.SetTypeByDefaultValue(inferConfigTypes)
viper.SetEnvKeyReplacer(environmentVariableReplace)
if err := SetDefault(params.DefaultConfig); err != nil {
return types.BacalhauConfig{}, nil
}
if err := params.FileHandler(filepath.Join(path, fmt.Sprintf("%s.%s", params.FileName, params.FileType))); err != nil {
return types.BacalhauConfig{}, err
}
if automaticEnvVar {
viper.AutomaticEnv()
}
var out types.BacalhauConfig
if err := viper.Unmarshal(&out, configDecoderHook); err != nil {
return types.BacalhauConfig{}, err
}
return out, nil
}
// Reset clears all configuration, useful for testing.
func Reset() {
viper.Reset()
}
// Getenv wraps os.Getenv and retrieves the value of the environment variable named by the config key.
// It returns the value, which will be empty if the variable is not present.
func Getenv(key string) string {
return os.Getenv(KeyAsEnvVar(key))
}
// KeyAsEnvVar returns the environment variable corresponding to a config key
func KeyAsEnvVar(key string) string {
return strings.ToUpper(
fmt.Sprintf("%s_%s", environmentVariablePrefix, environmentVariableReplace.Replace(key)),
)
}