Handle alert messages with newlines

Do not send to IRC messages with newlines, split in multiple messages
instead (see issue #15 ).

Signed-off-by: Luca Bigliardi <shammash@google.com>
This commit is contained in:
Luca Bigliardi 2021-11-26 12:16:45 +01:00
parent 33fe9e4ef8
commit f7034fa2c2
2 changed files with 39 additions and 8 deletions

View File

@ -50,7 +50,7 @@ func NewFormatter(config *Config) (*Formatter, error) {
}, nil }, nil
} }
func (f *Formatter) FormatMsg(ircChannel string, data interface{}) string { func (f *Formatter) FormatMsg(ircChannel string, data interface{}) []string {
output := bytes.Buffer{} output := bytes.Buffer{}
var msg string var msg string
if err := f.MsgTemplate.Execute(&output, data); err != nil { if err := f.MsgTemplate.Execute(&output, data); err != nil {
@ -63,22 +63,29 @@ func (f *Formatter) FormatMsg(ircChannel string, data interface{}) string {
} else { } else {
msg = output.String() msg = output.String()
} }
return msg
// Do not send to IRC messages with newlines, split in multiple messages instead.
newLinesSplit := func(r rune) bool {
return r == '\n' || r == '\r'
}
return strings.FieldsFunc(msg, newLinesSplit)
} }
func (f *Formatter) GetMsgsFromAlertMessage(ircChannel string, func (f *Formatter) GetMsgsFromAlertMessage(ircChannel string,
data *promtmpl.Data) []AlertMsg { data *promtmpl.Data) []AlertMsg {
msgs := []AlertMsg{} msgs := []AlertMsg{}
if f.MsgOnce { if f.MsgOnce {
msg := f.FormatMsg(ircChannel, data) for _, msg := range f.FormatMsg(ircChannel, data) {
msgs = append(msgs, msgs = append(msgs,
AlertMsg{Channel: ircChannel, Alert: msg}) AlertMsg{Channel: ircChannel, Alert: msg})
}
} else { } else {
for _, alert := range data.Alerts { for _, alert := range data.Alerts {
msg := f.FormatMsg(ircChannel, alert) for _, msg := range f.FormatMsg(ircChannel, alert) {
msgs = append(msgs, msgs = append(msgs,
AlertMsg{Channel: ircChannel, Alert: msg}) AlertMsg{Channel: ircChannel, Alert: msg})
} }
} }
}
return msgs return msgs
} }

View File

@ -109,3 +109,27 @@ func TestUrlFunctions(t *testing.T) {
CreateFormatterAndCheckOutput(t, &testingConfig, expectedAlertMsgs) CreateFormatterAndCheckOutput(t, &testingConfig, expectedAlertMsgs)
} }
func TestMultilineTemplates(t *testing.T) {
testingConfig := Config{
MsgTemplate: "Alert {{ .GroupLabels.alertname }}\nis\r{{ .Status }}",
MsgOnce: true,
}
expectedAlertMsgs := []AlertMsg{
AlertMsg{
Channel: "#somechannel",
Alert: "Alert airDown",
},
AlertMsg{
Channel: "#somechannel",
Alert: "is",
},
AlertMsg{
Channel: "#somechannel",
Alert: "resolved",
},
}
CreateFormatterAndCheckOutput(t, &testingConfig, expectedAlertMsgs)
}