Browse Source

code cleanup, improvements to loading api keys

master
Christopher Ramey 3 years ago
parent
commit
fcdff1039f
  1. 52
      config/config.go
  2. 94
      config/parser.go
  3. 7
      go.mod
  4. 2
      go.sum

52
config/config.go

@ -3,26 +3,19 @@ package config
import ( import (
"fmt" "fmt"
"git.binarythought.com/cdramey/alrm/alarm" "git.binarythought.com/cdramey/alrm/alarm"
"github.com/denisbrodbeck/machineid"
"os"
"time" "time"
) )
type Config struct { type Config struct {
Groups map[string]*Group
Alarms map[string]alarm.Alarm
Interval time.Duration
Listen string
Path string
APIKey string
}
func NewConfig() *Config {
return &Config{
// Default check interval, 30 seconds
Interval: time.Second * 30,
// Default listen address
Listen: "127.0.0.1:8282",
}
Groups map[string]*Group
Alarms map[string]alarm.Alarm
Interval time.Duration
DebugLevel int
Listen string
Path string
APIKey string
APIKeyFile string
} }
func (c *Config) NewAlarm(name string, typename string) (alarm.Alarm, error) { func (c *Config) NewAlarm(name string, typename string) (alarm.Alarm, error) {
@ -68,18 +61,29 @@ func (c *Config) SetInterval(val string) error {
} }
func ReadConfig(fn string, debuglvl int) (*Config, error) { func ReadConfig(fn string, debuglvl int) (*Config, error) {
parser := &Parser{DebugLevel: debuglvl}
config, err := parser.Parse(fn)
if err != nil {
cfg := &Config{
// Default check interval, 30 seconds
Interval: time.Second * 30,
// Default listen address
Listen: "127.0.0.1:8282",
DebugLevel: debuglvl,
Path: fn,
// API keyfile defaults to alrmrc.key
APIKeyFile: fn + ".key",
}
pr := &parser{config: cfg}
if err := pr.parse(); err != nil {
return nil, err return nil, err
} }
if config.APIKey == "" {
key, err := machineid.ProtectedID("alrm")
if cfg.APIKey == "" {
b, err := os.ReadFile(cfg.APIKeyFile)
if err != nil { if err != nil {
return nil, fmt.Errorf("could not generate machine id for api key")
return nil, err
} }
config.APIKey = key
cfg.APIKey = string(b)
} }
return config, nil
return cfg, nil
} }

94
config/parser.go

@ -17,8 +17,8 @@ const (
PR_ALARM PR_ALARM
) )
type Parser struct {
DebugLevel int
type parser struct {
config *Config
states []int states []int
lastHost *Host lastHost *Host
lastGroup *Group lastGroup *Group
@ -27,12 +27,10 @@ type Parser struct {
lastAlarmName string lastAlarmName string
} }
func (p *Parser) Parse(fn string) (*Config, error) {
config := NewConfig()
config.Path = fn
tok, err := NewTokenizer(fn)
func (p *parser) parse() error {
tok, err := NewTokenizer(p.config.Path)
if err != nil { if err != nil {
return nil, err
return err
} }
defer tok.Close() defer tok.Close()
@ -49,34 +47,36 @@ func (p *Parser) Parse(fn string) (*Config, error) {
case "alarm": case "alarm":
p.setState(PR_ALARM) p.setState(PR_ALARM)
default: default:
return nil, fmt.Errorf("invalid token in %s, line %d: \"%s\"",
fn, tok.Line(), tk)
return fmt.Errorf("invalid token in %s, line %d: \"%s\"",
p.config.Path, tok.Line(), tk)
} }
case PR_SET: case PR_SET:
key := strings.ToLower(tk) key := strings.ToLower(tk)
if !tok.Scan() { if !tok.Scan() {
return nil, fmt.Errorf("empty value name for set in %s, line %d",
fn, tok.Line())
return fmt.Errorf("empty value name for set in %s, line %d",
p.config.Path, tok.Line())
} }
value := tok.Text() value := tok.Text()
switch key { switch key {
case "interval": case "interval":
err := config.SetInterval(value)
err := p.config.SetInterval(value)
if err != nil { if err != nil {
return nil, fmt.Errorf(
return fmt.Errorf(
"invalid duration for interval in %s, line %d: \"%s\"", "invalid duration for interval in %s, line %d: \"%s\"",
fn, tok.Line(), value,
p.config.Path, tok.Line(), value,
) )
} }
case "listen": case "listen":
config.Listen = value
case "apikey":
config.APIKey = value
p.config.Listen = value
case "api.key":
p.config.APIKey = value
case "api.keyfile":
p.config.APIKeyFile = value
default: default:
return nil, fmt.Errorf("unknown key for set in %s, line %d: \"%s\"",
fn, tok.Line(), tk,
return fmt.Errorf("unknown key for set in %s, line %d: \"%s\"",
p.config.Path, tok.Line(), tk,
) )
} }
p.prevState() p.prevState()
@ -96,10 +96,10 @@ func (p *Parser) Parse(fn string) (*Config, error) {
case PR_GROUP: case PR_GROUP:
if p.lastGroup == nil { if p.lastGroup == nil {
p.lastGroup, err = config.NewGroup(tk)
p.lastGroup, err = p.config.NewGroup(tk)
if err != nil { if err != nil {
return nil, fmt.Errorf("%s in %s, line %d",
err.Error(), fn, tok.Line(),
return fmt.Errorf("%s in %s, line %d",
err.Error(), p.config.Path, tok.Line(),
) )
} }
continue continue
@ -117,10 +117,10 @@ func (p *Parser) Parse(fn string) (*Config, error) {
case PR_HOST: case PR_HOST:
// If a host has no group, inherit the host name // If a host has no group, inherit the host name
if p.lastGroup == nil { if p.lastGroup == nil {
p.lastGroup, err = config.NewGroup(tk)
p.lastGroup, err = p.config.NewGroup(tk)
if err != nil { if err != nil {
return nil, fmt.Errorf("%s in %s, line %d",
err.Error(), fn, tok.Line(),
return fmt.Errorf("%s in %s, line %d",
err.Error(), p.config.Path, tok.Line(),
) )
} }
} }
@ -128,8 +128,8 @@ func (p *Parser) Parse(fn string) (*Config, error) {
if p.lastHost == nil { if p.lastHost == nil {
p.lastHost, err = p.lastGroup.NewHost(tk) p.lastHost, err = p.lastGroup.NewHost(tk)
if err != nil { if err != nil {
return nil, fmt.Errorf("%s in %s, line %d",
err.Error(), fn, tok.Line(),
return fmt.Errorf("%s in %s, line %d",
err.Error(), p.config.Path, tok.Line(),
) )
} }
continue continue
@ -138,8 +138,8 @@ func (p *Parser) Parse(fn string) (*Config, error) {
switch strings.ToLower(tk) { switch strings.ToLower(tk) {
case "address": case "address":
if !tok.Scan() { if !tok.Scan() {
return nil, fmt.Errorf("empty address for host in %s, line %d",
fn, tok.Line())
return fmt.Errorf("empty address for host in %s, line %d",
p.config.Path, tok.Line())
} }
p.lastHost.Address = tok.Text() p.lastHost.Address = tok.Text()
@ -155,15 +155,15 @@ func (p *Parser) Parse(fn string) (*Config, error) {
if p.lastCheck == nil { if p.lastCheck == nil {
p.lastCheck, err = p.lastHost.NewCheck(tk) p.lastCheck, err = p.lastHost.NewCheck(tk)
if err != nil { if err != nil {
return nil, fmt.Errorf("%s in %s, line %d",
err.Error(), fn, tok.Line())
return fmt.Errorf("%s in %s, line %d",
err.Error(), p.config.Path, tok.Line())
} }
continue continue
} }
cont, err := p.lastCheck.Parse(tk) cont, err := p.lastCheck.Parse(tk)
if err != nil { if err != nil {
return nil, fmt.Errorf("%s in %s, line %d",
err.Error(), fn, tok.Line())
return fmt.Errorf("%s in %s, line %d",
err.Error(), p.config.Path, tok.Line())
} }
if !cont { if !cont {
p.lastCheck = nil p.lastCheck = nil
@ -178,18 +178,18 @@ func (p *Parser) Parse(fn string) (*Config, error) {
continue continue
} }
p.lastAlarm, err = config.NewAlarm(p.lastAlarmName, tk)
p.lastAlarm, err = p.config.NewAlarm(p.lastAlarmName, tk)
if err != nil { if err != nil {
return nil, fmt.Errorf("%s in %s, line %d",
err.Error(), fn, tok.Line())
return fmt.Errorf("%s in %s, line %d",
err.Error(), p.config.Path, tok.Line())
} }
p.lastAlarmName = "" p.lastAlarmName = ""
continue continue
} }
cont, err := p.lastAlarm.Parse(tk) cont, err := p.lastAlarm.Parse(tk)
if err != nil { if err != nil {
return nil, fmt.Errorf("%s in %s, line %d",
err.Error(), fn, tok.Line())
return fmt.Errorf("%s in %s, line %d",
err.Error(), p.config.Path, tok.Line())
} }
if !cont { if !cont {
p.lastAlarm = nil p.lastAlarm = nil
@ -198,23 +198,23 @@ func (p *Parser) Parse(fn string) (*Config, error) {
} }
default: default:
return nil, fmt.Errorf("unknown parser state: %d", p.state())
return fmt.Errorf("unknown parser state: %d", p.state())
} }
} }
if err := tok.Err(); err != nil { if err := tok.Err(); err != nil {
return nil, err
return err
} }
return config, nil
return nil
} }
func (p *Parser) state() int {
func (p *parser) state() int {
if len(p.states) < 1 { if len(p.states) < 1 {
return PR_NONE return PR_NONE
} }
return p.states[len(p.states)-1] return p.states[len(p.states)-1]
} }
func (p *Parser) setState(state int) {
func (p *parser) setState(state int) {
switch state { switch state {
case PR_SET, PR_MONITOR: case PR_SET, PR_MONITOR:
fallthrough fallthrough
@ -226,23 +226,23 @@ func (p *Parser) setState(state int) {
p.lastCheck = nil p.lastCheck = nil
} }
if p.DebugLevel > 1 {
if p.config.DebugLevel > 1 {
fmt.Printf("Parser state: %s", p.stateName()) fmt.Printf("Parser state: %s", p.stateName())
} }
p.states = append(p.states, state) p.states = append(p.states, state)
if p.DebugLevel > 1 {
if p.config.DebugLevel > 1 {
fmt.Printf(" -> %s\n", p.stateName()) fmt.Printf(" -> %s\n", p.stateName())
} }
} }
func (p *Parser) prevState() int {
func (p *parser) prevState() int {
if len(p.states) > 0 { if len(p.states) > 0 {
p.states = p.states[:len(p.states)-1] p.states = p.states[:len(p.states)-1]
} }
return p.state() return p.state()
} }
func (p *Parser) stateName() string {
func (p *parser) stateName() string {
switch p.state() { switch p.state() {
case PR_NONE: case PR_NONE:
return "PR_NONE" return "PR_NONE"

7
go.mod

@ -1,8 +1,5 @@
module git.binarythought.com/cdramey/alrm module git.binarythought.com/cdramey/alrm
go 1.15
go 1.16
require (
github.com/denisbrodbeck/machineid v1.0.1
golang.org/x/net v0.0.0-20201224014010-6772e930b67b
)
require golang.org/x/net v0.0.0-20201224014010-6772e930b67b

2
go.sum

@ -1,5 +1,3 @@
github.com/denisbrodbeck/machineid v1.0.1 h1:geKr9qtkB876mXguW2X6TU4ZynleN6ezuMSRhl4D7AQ=
github.com/denisbrodbeck/machineid v1.0.1/go.mod h1:dJUwb7PTidGDeYyUBmXZ2GphQBbjJCrnectwCyxcUSI=
golang.org/x/net v0.0.0-20201224014010-6772e930b67b h1:iFwSg7t5GZmB/Q5TjiEAsdoLDrdJRC1RiF2WhuV29Qw= golang.org/x/net v0.0.0-20201224014010-6772e930b67b h1:iFwSg7t5GZmB/Q5TjiEAsdoLDrdJRC1RiF2WhuV29Qw=
golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw=

Loading…
Cancel
Save