-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
95 lines (76 loc) · 2.3 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
package main
import (
"os"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
)
const binaryName = "hasap-alerts-handler"
// Config new config from yaml
func Config(flagSet *flag.FlagSet) (*viper.Viper, error) {
config := viper.New()
err := config.BindPFlags(flagSet)
if err != nil {
return nil, errors.Wrap(err, "could not bind config to CLI flags")
}
// try to get the "config" value from the bound "config" CLI flag
path := config.GetString("config")
if path != "" {
// try to manually load the configuration from the given path
err = loadConfigurationFromFile(config, path)
} else {
// otherwise try viper's auto-discovery
err = loadConfigurationAutomatically(config)
}
if err != nil {
return nil, errors.Wrap(err, "could not load configuration file")
}
setLogLevel(config.GetString("log-level"))
return config, nil
}
func loadConfigurationAutomatically(config *viper.Viper) error {
config.SetConfigName(binaryName)
config.AddConfigPath("/usr/etc/")
err := config.ReadInConfig()
if err == nil {
log.Info("Using config file: ", config.ConfigFileUsed())
return nil
}
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Infof("Could not discover configuration file: %s", err)
log.Info("Fallingback to default values.")
log.Warn("NO Alerts will be sent to alertmanager in case of failures. See alertmanagerIP variable for this")
return nil
}
return errors.Wrap(err, "could not load automatically discovered config file")
}
// loads configuration from an explicit file path
func loadConfigurationFromFile(config *viper.Viper, path string) error {
// we hard-code the config type to yaml, otherwise ReadConfig will not load the values
// see https://github.com/spf13/viper/issues/316
config.SetConfigType("yaml")
file, err := os.Open(path)
if err != nil {
return errors.Wrap(err, "could not open file")
}
defer file.Close()
err = config.ReadConfig(file)
if err != nil {
return errors.Wrap(err, "could not read file")
}
log.Info("Using config file: ", path)
return nil
}
func setLogLevel(level string) {
switch level {
case "error":
log.SetLevel(log.ErrorLevel)
case "warn":
log.SetLevel(log.WarnLevel)
case "info":
log.SetLevel(log.InfoLevel)
case "debug":
log.SetLevel(log.DebugLevel)
}
}