smon/notification/script.go
2024-06-02 10:59:06 +02:00

71 lines
1.3 KiB
Go

package notification
import (
// External
werr "git.gibonuddevalla.se/go/wrappederror"
// Standard
"encoding/json"
"log/slog"
"os/exec"
"strconv"
"strings"
)
type Script struct {
Filename string
Prio int
AcknowledgeURL string
logger *slog.Logger
}
func NewScript(config []byte, prio int, ackURL string) (instance *Script, err error) {
instance = new(Script)
err = json.Unmarshal(config, &instance)
if err != nil {
err = werr.Wrap(err).WithCode("002-0001").WithData(config)
return
}
instance.Prio = prio
instance.AcknowledgeURL = ackURL
return instance, nil
}
func (script *Script) SetLogger(l *slog.Logger) {
script.logger = l
}
func (script *Script) GetType() string {
return "SCRIPT"
}
func (script *Script) GetPrio() int {
return script.Prio
}
func (script Script) Send(problemID int, msg []byte) (err error) {
var errbuf strings.Builder
cmd := exec.Command(script.Filename, strconv.Itoa(problemID), script.AcknowledgeURL, string(msg))
cmd.Stderr = &errbuf
err = cmd.Run()
if err != nil {
script.logger.Error("notification", "type", "script", "error", err)
err = werr.Wrap(err).WithData(
struct {
Filename string
ProblemID int
Msg string
StdErr string
}{
script.Filename,
problemID,
string(msg),
errbuf.String(),
},
).Log()
}
return
}