Skip to content

Commit

Permalink
Notifier: Webex
Browse files Browse the repository at this point in the history
Cisco's Webex has been one of the most requested notifiers on Grafana for a while now, please see: grafana/grafana#11750 (comment)

Given it's straightforward implementation, low maintance overhead and request demand, I think it's worth including this directly in the Alertmanager.
  • Loading branch information
gotjosh committed Nov 8, 2022
1 parent 33bba95 commit e7143a2
Show file tree
Hide file tree
Showing 7 changed files with 310 additions and 2 deletions.
4 changes: 2 additions & 2 deletions asset/assets_vfsdata.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions cmd/alertmanager/main.go
Expand Up @@ -58,6 +58,7 @@ import (
"github.com/prometheus/alertmanager/notify/sns"
"github.com/prometheus/alertmanager/notify/telegram"
"github.com/prometheus/alertmanager/notify/victorops"
"github.com/prometheus/alertmanager/notify/webex"
"github.com/prometheus/alertmanager/notify/webhook"
"github.com/prometheus/alertmanager/notify/wechat"
"github.com/prometheus/alertmanager/provider/mem"
Expand Down Expand Up @@ -177,6 +178,9 @@ func buildReceiverIntegrations(nc *config.Receiver, tmpl *template.Template, log
for i, c := range nc.DiscordConfigs {
add("discord", i, c, func(l log.Logger) (notify.Notifier, error) { return discord.New(c, tmpl, l) })
}
for i, c := range nc.WebexConfigs {
add("webex", i, c, func(l log.Logger) (notify.Notifier, error) { return webex.New(c, tmpl, l) })
}

if errs.Len() > 0 {
return nil, &errs
Expand Down
12 changes: 12 additions & 0 deletions config/config.go
Expand Up @@ -251,6 +251,9 @@ func resolveFilepaths(baseDir string, cfg *Config) {
for _, cfg := range receiver.DiscordConfigs {
cfg.HTTPConfig.SetDirectory(baseDir)
}
for _, cfg := range receiver.WebexConfigs {
cfg.HTTPConfig.SetDirectory(baseDir)
}
}
}

Expand Down Expand Up @@ -513,6 +516,14 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
return fmt.Errorf("no discord webhook URL provided")
}
}
for _, webex := range rcv.WebexConfigs {
if webex.HTTPConfig == nil {
webex.HTTPConfig = c.Global.HTTPConfig
}
if webex.WebhookURL == nil {
return fmt.Errorf("no webex webhook URL provided")
}
}

names[rcv.Name] = struct{}{}
}
Expand Down Expand Up @@ -878,6 +889,7 @@ type Receiver struct {
VictorOpsConfigs []*VictorOpsConfig `yaml:"victorops_configs,omitempty" json:"victorops_configs,omitempty"`
SNSConfigs []*SNSConfig `yaml:"sns_configs,omitempty" json:"sns_configs,omitempty"`
TelegramConfigs []*TelegramConfig `yaml:"telegram_configs,omitempty" json:"telegram_configs,omitempty"`
WebexConfigs []*WebexConfig `yaml:"webex_configs,omitempty" json:"webex_configs,omitempty"`
}

// UnmarshalYAML implements the yaml.Unmarshaler interface for Receiver.
Expand Down
25 changes: 25 additions & 0 deletions config/notifiers.go
Expand Up @@ -33,6 +33,14 @@ var (
},
}

// DefaultWebexConfig defines default values for Webex configurations.
DefaultWebexConfig = WebexConfig{
NotifierConfig: NotifierConfig{
VSendResolved: true,
},
Message: `{{ template "webex.default.message" . }}`,
}

// DefaultDiscordConfig defines default values for Discord configurations.
DefaultDiscordConfig = DiscordConfig{
NotifierConfig: NotifierConfig{
Expand Down Expand Up @@ -166,6 +174,23 @@ func (nc *NotifierConfig) SendResolved() bool {
return nc.VSendResolved
}

// WebexConfig configures notifications via Webex.
type WebexConfig struct {
NotifierConfig `yaml:",inline" json:",inline"`
HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"`
WebhookURL *SecretURL `yaml:"webhook_url,omitempty" json:"webhook_url,omitempty"`

Message string `yaml:"message,omitempty" json:"message,omitempty"`
RoomID string `yaml:"room_id,omitempty" json:"room_id,omitempty"`
}

// UnmarshalYAML implements the yaml.Unmarshaler interface.
func (c *WebexConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
*c = DefaultWebexConfig
type plain WebexConfig
return unmarshal((*plain)(c))
}

// DiscordConfig configures notifications via Discord.
type DiscordConfig struct {
NotifierConfig `yaml:",inline" json:",inline"`
Expand Down
116 changes: 116 additions & 0 deletions notify/webex/webex.go
@@ -0,0 +1,116 @@
// Copyright 2022 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package webex

import (
"bytes"
"context"
"encoding/json"
"net/http"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
commoncfg "github.com/prometheus/common/config"

"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
)

const (
// maxMessageSize represents the maximum message length that Webex supports.
maxMessageSize = 7439
)

type Notifier struct {
conf *config.WebexConfig
tmpl *template.Template
logger log.Logger
client *http.Client
retrier *notify.Retrier
webhookURL *config.SecretURL
}

// New returns a new Webex notifier.
func New(c *config.WebexConfig, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) {
client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "webex", httpOpts...)
if err != nil {
return nil, err
}

n := &Notifier{
conf: c,
tmpl: t,
logger: l,
client: client,
retrier: &notify.Retrier{},
webhookURL: c.WebhookURL,
}

return n, nil
}

type webhook struct {
Message string `json:"markdown"`
RoomID string `json:"roomId,omitempty"`
}

// Notify implements the Notifier interface.
func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
key, err := notify.ExtractGroupKey(ctx)
if err != nil {
return false, err
}

level.Debug(n.logger).Log("incident", key)

data := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)
tmpl := notify.TmplText(n.tmpl, data, &err)
if err != nil {
return false, err
}

message := tmpl(n.conf.Message)
if err != nil {
return false, err
}

message, truncated := notify.Truncate(message, maxMessageSize)
if truncated {
level.Debug(n.logger).Log("msg", "message truncated due to exceeding maximum allowed length by webex", "truncated_message", message)
}

w := webhook{
Message: message,
RoomID: n.conf.RoomID,
}

var payload bytes.Buffer
if err = json.NewEncoder(&payload).Encode(w); err != nil {
return false, err
}

resp, err := notify.PostJSON(ctx, n.client, n.webhookURL.String(), &payload)
if err != nil {
return true, notify.RedactURL(err)
}

shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
if err != nil {
return shouldRetry, err
}

return false, nil
}
140 changes: 140 additions & 0 deletions notify/webex/webex_test.go
@@ -0,0 +1,140 @@
// Copyright 2022 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package webex

import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"

"github.com/go-kit/log"
commoncfg "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/require"

"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/notify/test"
"github.com/prometheus/alertmanager/types"
)

func TestWebexRetry(t *testing.T) {
testWebhookURL, err := url.Parse("https://api.ciscospark.com/v1/message")
require.NoError(t, err)

notifier, err := New(
&config.WebexConfig{
HTTPConfig: &commoncfg.HTTPClientConfig{},
WebhookURL: &config.SecretURL{URL: testWebhookURL},
},
test.CreateTmpl(t),
log.NewNopLogger(),
)
require.NoError(t, err)

for statusCode, expected := range test.RetryTests(test.DefaultRetryCodes()) {
actual, _ := notifier.retrier.Check(statusCode, nil)
require.Equal(t, expected, actual, fmt.Sprintf("error on status %d", statusCode))
}
}

func TestWebexTemplating(t *testing.T) {
tc := []struct {
name string

cfg *config.WebexConfig
Message string
expJSON string

retry bool
errMsg string
}{
{
name: "with a valid message, it is formatted as expected",
cfg: &config.WebexConfig{
Message: `{{ template "webex.default.message" . }}`,
},
expJSON: `{"markdown":"\n\nAlerts Firing:\nLabels:\n - lbl1 = val1\n - lbl3 = val3\nAnnotations:\nSource: \nLabels:\n - lbl1 = val1\n - lbl2 = val2\nAnnotations:\nSource: \n\n\n\n"}`,
retry: false,
},
{
name: "with templating errors, it fails.",
cfg: &config.WebexConfig{
Message: "{{ ",
},
errMsg: "template: :1: unclosed action",
},
}

for _, tt := range tc {
t.Run(tt.name, func(t *testing.T) {
var out []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var err error
out, err = io.ReadAll(r.Body)
require.NoError(t, err)
}))
defer srv.Close()
u, _ := url.Parse(srv.URL)

tt.cfg.WebhookURL = &config.SecretURL{URL: u}
tt.cfg.HTTPConfig = &commoncfg.HTTPClientConfig{}
notifierWebex, err := New(tt.cfg, test.CreateTmpl(t), log.NewNopLogger())
require.NoError(t, err)

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
ctx = notify.WithGroupKey(ctx, "1")

ok, err := notifierWebex.Notify(ctx, []*types.Alert{
{
Alert: model.Alert{
Labels: model.LabelSet{
"lbl1": "val1",
"lbl3": "val3",
},
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
},
},
{
Alert: model.Alert{
Labels: model.LabelSet{
"lbl1": "val1",
"lbl2": "val2",
},
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
},
},
}...)

if tt.errMsg == "" {
require.NoError(t, err)
fmt.Println(string(out))
require.JSONEq(t, tt.expJSON, string(out))
} else {
require.Error(t, err)
require.Contains(t, err.Error(), tt.errMsg)
}

require.Equal(t, tt.retry, ok)
})
}
}
11 changes: 11 additions & 0 deletions template/default.tmpl
Expand Up @@ -124,3 +124,14 @@ Alerts Resolved:
{{ template "__text_alert_list" .Alerts.Resolved }}
{{ end }}
{{ end }}

{{ define "webex.default.message" }}{{ .CommonAnnotations.SortedPairs.Values | join " " }}
{{ if gt (len .Alerts.Firing) 0 }}
Alerts Firing:
{{ template "__text_alert_list" .Alerts.Firing }}
{{ end }}
{{ if gt (len .Alerts.Resolved) 0 }}
Alerts Resolved:
{{ template "__text_alert_list" .Alerts.Resolved }}
{{ end }}
{{ end }}

0 comments on commit e7143a2

Please sign in to comment.