refined alarm email, removed port requirement for smtp server, fixed bug with config loading

This commit is contained in:
Christopher Ramey 2021-01-20 18:49:32 -09:00
parent afcdef029e
commit 8c7822be97
4 changed files with 25 additions and 10 deletions

View File

@ -6,7 +6,7 @@ import (
type Alarm interface {
Parse(string) (bool, error)
Alarm() error
Alarm(string,string,string,error) error
}
func NewAlarm(name string, typename string) (Alarm, error) {

View File

@ -35,7 +35,7 @@ func NewAlarmEmail(name string) *AlarmEmail {
}
}
func (a *AlarmEmail) Alarm() error {
func (a *AlarmEmail) Alarm(grp string, host string, chk string, cerr error) error {
c, err := smtp.Dial(a.SMTP)
if err != nil {
return err
@ -68,7 +68,8 @@ func (a *AlarmEmail) Alarm() error {
msg := fmt.Sprintf("From: %s\r\n", a.From)
msg += fmt.Sprintf("To: %s\r\n", strings.Join(a.To, ";"))
msg += fmt.Sprintf("Subject: %s\r\n", "test subject")
msg += fmt.Sprintf("Subject: %s\r\n\r\n", "test subject")
msg += fmt.Sprintf("%s", cerr.Error())
_, err = fmt.Fprintf(m, "%s", msg)
if err != nil {
@ -113,6 +114,10 @@ func (a *AlarmEmail) Parse(tk string) (bool, error) {
if strings.TrimSpace(tk) == "" {
return false, fmt.Errorf("smtp server cannot be empty")
}
// If the smtp host doesn't contain a port, add the default
if !strings.Contains(tk, ":") {
tk += ":25"
}
a.SMTP = tk
a.state = TK_NONE

2
alrmrc
View File

@ -3,7 +3,7 @@ set interval 30s
alarm people email
to test1@localhost
to test2@localhost
smtp localhost:25
smtp localhost
from alrm@localhost
monitor group webservers

20
main.go
View File

@ -16,12 +16,14 @@ func main() {
flag.Usage = printUsage
flag.Parse()
if *cfgPath == "" {
if _, err := os.Stat("./alrmrc"); err == nil {
*cfgPath = "./alrmrc"
searchpaths := []string{"/etc/alrmrc", "./alrmrc"}
for _, sp := range searchpaths {
if _, err := os.Stat(sp); err == nil {
*cfgPath = sp
break
}
if _, err := os.Stat("/etc/alrmrc"); err == nil {
*cfgPath = "/etc/alrmrc"
}
if *cfgPath == "" {
fmt.Fprintf(os.Stderr, "cannot find configuration\n")
@ -32,12 +34,17 @@ func main() {
command := strings.ToLower(flag.Arg(0))
switch command {
case "config":
if *debuglvl > 0 {
fmt.Printf("checking config %s .. \n", *cfgPath)
}
cfg, err := config.ReadConfig(*cfgPath, *debuglvl)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
if *debuglvl > 0 {
o, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
@ -68,7 +75,10 @@ func main() {
os.Exit(1)
}
err = al.Alarm()
err = al.Alarm(
"test group", "test host", "test check",
fmt.Errorf("test alarm message"),
)
if err != nil {
fmt.Fprintf(os.Stderr, "alarm failed: %s\n", err.Error())
os.Exit(1)