statusmon/cmd/config.go

115 lines
2.9 KiB
Go

package cmd
import (
"fmt"
"os"
"strings"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"statusmon/core"
"statusmon/utils"
)
// initConfig reads in config file and ENV variables if set.
func initConfig() {
theConfig := cfgFile
if cfgFile == "" {
theConfig = utils.GetConfigFile("statusmon")
}
viper.SetConfigType("yaml")
viper.SetConfigFile(theConfig)
viper.SetEnvPrefix("STATUSMON") // keys only work in upper case
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
viper.AutomaticEnv() // WARNING: OSEM_NOTIFIY_CONFIG will not be considered this way. but why should it..
// If a config file is found, read it in.
if _, err := os.Stat(theConfig); err == nil {
err := viper.ReadInConfig()
if err != nil {
log.Error("Error when reading config file:", err)
}
} else if cfgFile != "" {
log.Error("Specified config file not found!")
os.Exit(1)
}
validateConfig()
}
func validateConfig() {
if viper.GetString("notify") != "" {
if len(viper.GetStringSlice("healthchecks.default.notifications.options.recipients")) == 0 {
log.Warn("No default recipients set up for notifications!")
}
var conf = &core.TransportConfig{}
if err := viper.UnmarshalKey("healthchecks.default.notifications", conf); err != nil {
log.Error("invalid default notification configuration: ", err)
os.Exit(1)
}
// creating a notifier validates its configuration
_, err := core.GetNotifier(conf)
if err != nil {
log.Error(err)
os.Exit(1)
}
}
}
func getAvailableTargetIDs() []string {
checks := viper.GetStringMap("healthchecks")
res := []string{}
for key := range checks {
if key != "default" {
res = append(res, key)
}
}
return res
}
func getTargetConf(id string) (*core.Target, error) {
// config used when no configuration is present at all
target := &core.Target{Checks: []core.Check{}}
// override with default configuration from file
// considering the case that .events may be defined but empty
// to allow to define no events, and don't leak shorter lists into
// previous longer ones
if keyDefined("healthchecks.default.events") {
target.Checks = []core.Check{}
}
if err := viper.UnmarshalKey("healthchecks.default", target); err != nil {
return nil, err
}
if !keyDefined("healthchecks." + id + ".events") {
return nil, fmt.Errorf("target %s does not exist", id)
}
// override with per box configuration from file
if keyDefined("healthchecks." + id + ".events") {
target.Checks = []core.Check{}
}
// if err := viper.UnmarshalKey("healthchecks."+id, target); err != nil {
if err := viper.UnmarshalKey("healthchecks."+id, target); err != nil {
return nil, err
}
target.ID = id
return target, nil
}
// implement our own keyCheck, as viper.InConfig() does not work
func keyDefined(key string) bool {
allConfKeys := viper.AllKeys()
for _, k := range allConfKeys {
if k == key {
return true
}
}
return false
}