kdnotify/handler/handler.go

86 lines
1.7 KiB
Go

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package handler
import (
"text/template"
"git.st8l.com/luxolus/kdnotify/config"
n "git.st8l.com/luxolus/kdnotify/schema/notify"
)
type VrrpHandler struct {
Config *config.WatchConfig
Cxt *config.LibCxt
}
type TemplateEnv struct {
Cxt any
Event MessageEvent
}
type MessageEvent struct {
Type string
State string
Instance string
}
func NewVrrp(cxt *config.LibCxt, cfg *config.WatchConfig) *VrrpHandler {
return &VrrpHandler{
Config: cfg,
Cxt: &config.LibCxt{
Logger: cxt.Logger.Named("handler"),
Context: cxt.Context,
},
}
}
func (h *VrrpHandler) ProcessVrrp(msg n.VrrpMessage) error {
log, matches := h.Cxt.Logger.Sugar(), 0
for _, rule := range h.Config.Rules {
if rule.Match(&msg) {
matches += 1
env := h.newTemplateEnv(&msg)
err := h.execTemplate(rule.Exec, &env)
if err != nil {
log.Warnw("failed to evaluate rule", "instance", msg.Instance, "error", err)
}
}
}
log.Debugw("processed VRRP message", "instance", msg.Instance, "rules", matches)
return nil
}
func (h *VrrpHandler) execTemplate(t *template.Template, env *TemplateEnv) error {
cmdline, err := runTemplate(t, env)
if err != nil {
return err
}
cmd, err := mkCmd(cmdline)
if err != nil {
return err
}
go execRuleCmd(cmd, h.Cxt.Logger)
return nil
}
func (h *VrrpHandler) newTemplateEnv(msg *n.VrrpMessage) TemplateEnv {
return TemplateEnv{
Cxt: h.Config.Context,
Event: MessageEvent{
Type: msg.Type.String(),
State: msg.State.String(),
Instance: msg.Instance,
},
}
}