statping/notifiers/notifiers.go

78 lines
1.8 KiB
Go
Raw Normal View History

2020-03-04 10:29:00 +00:00
package notifiers
import (
"fmt"
2020-03-04 14:20:47 +00:00
"github.com/google/martian/log"
2020-03-04 10:29:00 +00:00
"github.com/hunterlong/statping/types/notifications"
"github.com/hunterlong/statping/utils"
2020-03-04 14:20:47 +00:00
"github.com/pkg/errors"
2020-03-04 10:29:00 +00:00
"strings"
)
var (
allowedVars = []string{"host", "username", "password", "port", "api_key", "api_secret", "var1", "var2"}
)
func checkNotifierForm(n notifications.Notifier) error {
notifier := n.Select()
for _, f := range notifier.Form {
contains := contains(f.DbField, allowedVars)
if !contains {
return fmt.Errorf("the DbField '%v' is not allowed, allowed vars: %v", f.DbField, allowedVars)
}
}
return nil
}
func contains(s string, arr []string) bool {
for _, v := range arr {
if strings.ToLower(s) == v {
return true
}
}
return false
}
// AddNotifier accept a Notifier interface to be added into the array
func AddNotifiers(notifiers ...notifications.Notifier) error {
for _, n := range notifiers {
2020-03-04 14:20:47 +00:00
log.Infof("Installing %s Notifier...", n.Select().Method)
2020-03-04 10:29:00 +00:00
if err := checkNotifierForm(n); err != nil {
2020-03-04 14:20:47 +00:00
return errors.Wrap(err, "error with notifier form fields")
2020-03-04 10:29:00 +00:00
}
if _, err := notifications.Init(n); err != nil {
2020-03-04 14:20:47 +00:00
return errors.Wrap(err, "error initiating notifier")
2020-03-04 10:29:00 +00:00
}
}
startAllNotifiers()
return nil
}
// startAllNotifiers will start the go routine for each loaded notifier
func startAllNotifiers() {
for _, comm := range notifications.AllCommunications {
if utils.IsType(comm, new(notifications.Notifier)) {
notify := comm.(notifications.Notifier)
if notify.Select().Enabled.Bool {
notify.Select().Close()
notify.Select().Start()
go notifications.Queue(notify)
}
}
}
}
func AttachNotifiers() error {
return AddNotifiers(
Command,
Discorder,
Emailer,
LineNotify,
Mobile,
Slacker,
Telegram,
Twilio,
Webhook,
)
}