minitor-go/config.go

71 lines
1.5 KiB
Go
Raw Normal View History

2019-09-21 22:03:26 +00:00
package main
import (
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"os"
)
2019-10-02 23:09:11 +00:00
// Config type is contains all provided user configuration
2019-09-21 22:03:26 +00:00
type Config struct {
CheckInterval int64 `yaml:"check_interval"`
2019-10-02 16:37:29 +00:00
Monitors []*Monitor
Alerts map[string]*Alert
2019-09-21 22:03:26 +00:00
}
2019-10-02 23:09:11 +00:00
// IsValid checks config validity and returns true if valid
func (config Config) IsValid() (isValid bool) {
isValid = true
for _, monitor := range config.Monitors {
if !monitor.IsValid() {
log.Printf("ERROR: Invalid monitor configuration: %s", monitor.Name)
isValid = false
}
}
for _, alert := range config.Alerts {
if !alert.IsValid() {
log.Printf("ERROR: Invalid alert configuration: %s", alert.Name)
isValid = false
}
}
return
}
// Init performs extra initialization on top of loading the config from file
func (config *Config) Init() {
for name, alert := range config.Alerts {
alert.Name = name
alert.BuildTemplates()
}
}
// LoadConfig will read config from the given path and parse it
2019-09-21 22:03:26 +00:00
func LoadConfig(filePath string) (config Config) {
data, err := ioutil.ReadFile(filePath)
if err != nil {
panic(err)
}
// TODO: Decide if this is better expanded here, or only when executing
2019-10-02 23:09:11 +00:00
envExpanded := os.ExpandEnv(string(data))
err = yaml.Unmarshal([]byte(envExpanded), &config)
2019-09-21 22:03:26 +00:00
if err != nil {
2019-10-02 16:37:29 +00:00
log.Fatalf("ERROR: %v", err)
2019-09-21 22:03:26 +00:00
panic(err)
}
log.Printf("config:\n%v\n", config)
2019-10-02 23:09:11 +00:00
if !config.IsValid() {
panic("Cannot continue with invalid configuration")
}
// Finish initializing configuration
config.Init()
2019-09-21 22:03:26 +00:00
return config
}