alrm/config/config.go

86 lines
1.6 KiB
Go
Raw Normal View History

package config
import (
"fmt"
2021-02-03 05:59:31 -09:00
"git.binarythought.com/cdramey/alrm/alarm"
2021-02-20 17:08:27 -09:00
"github.com/denisbrodbeck/machineid"
"time"
)
type Config struct {
Groups map[string]*Group
Alarms map[string]alarm.Alarm
Interval time.Duration
Listen string
Path string
2021-02-20 17:08:27 -09:00
APIKey string
}
func NewConfig() *Config {
return &Config{
2021-01-17 05:24:13 -09:00
// Default check interval, 30 seconds
Interval: time.Second * 30,
// Default listen address
Listen: "127.0.0.1:8282",
2021-01-17 05:24:13 -09:00
}
}
func (c *Config) NewAlarm(name string, typename string) (alarm.Alarm, error) {
if c.Alarms == nil {
c.Alarms = make(map[string]alarm.Alarm)
}
if _, exists := c.Alarms[name]; exists {
return nil, fmt.Errorf("alarm %s already exists", name)
}
a, err := alarm.NewAlarm(name, typename)
if err != nil {
return nil, err
}
c.Alarms[name] = a
return a, nil
}
func (c *Config) NewGroup(name string) (*Group, error) {
if c.Groups == nil {
c.Groups = make(map[string]*Group)
}
if _, exists := c.Groups[name]; exists {
return nil, fmt.Errorf("group %s already exists", name)
}
group := &Group{Name: name}
c.Groups[name] = group
return group, nil
}
func (c *Config) SetInterval(val string) error {
interval, err := time.ParseDuration(val)
if err != nil {
return err
}
c.Interval = interval
return nil
}
func ReadConfig(fn string, debuglvl int) (*Config, error) {
parser := &Parser{DebugLevel: debuglvl}
config, err := parser.Parse(fn)
if err != nil {
return nil, err
}
2021-02-20 17:08:27 -09:00
if config.APIKey == "" {
key, err := machineid.ProtectedID("alrm")
if err != nil {
return nil, fmt.Errorf("could not generate machine id for api key")
}
config.APIKey = key
}
return config, nil
}