Skip to content

Commit

Permalink
Add msteams
Browse files Browse the repository at this point in the history
  • Loading branch information
zhan9san committed Apr 12, 2023
1 parent 9a8d1f9 commit 1d5b341
Show file tree
Hide file tree
Showing 8 changed files with 345 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
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import (
"github.com/prometheus/alertmanager/notify/pushover"
"github.com/prometheus/alertmanager/notify/slack"
"github.com/prometheus/alertmanager/notify/sns"
"github.com/prometheus/alertmanager/notify/teams"
"github.com/prometheus/alertmanager/notify/telegram"
"github.com/prometheus/alertmanager/notify/victorops"
"github.com/prometheus/alertmanager/notify/webex"
Expand Down Expand Up @@ -181,6 +182,9 @@ func buildReceiverIntegrations(nc config.Receiver, tmpl *template.Template, logg
for i, c := range nc.WebexConfigs {
add("webex", i, c, func(l log.Logger) (notify.Notifier, error) { return webex.New(c, tmpl, l) })
}
for i, c := range nc.TeamsConfigs {
add("teams", i, c, func(l log.Logger) (notify.Notifier, error) { return teams.New(c, tmpl, l) })
}

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

Expand Down Expand Up @@ -528,6 +531,14 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
webex.APIURL = c.Global.WebexAPIURL
}
}
for _, tc := range rcv.TeamsConfigs {
if tc.HTTPConfig == nil {
tc.HTTPConfig = c.Global.HTTPConfig
}
if tc.WebhookURL == nil {
return fmt.Errorf("no teams webhook URL provided")
}
}

names[rcv.Name] = struct{}{}
}
Expand Down Expand Up @@ -896,6 +907,7 @@ type Receiver struct {
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"`
TeamsConfigs []*TeamsConfig `yaml:"teams_configs,omitempty" json:"teams_configs,omitempty"`
}

// UnmarshalYAML implements the yaml.Unmarshaler interface for Receiver.
Expand Down
23 changes: 23 additions & 0 deletions config/notifiers.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,14 @@ var (
Message: `{{ template "telegram.default.message" . }}`,
ParseMode: "HTML",
}

DefaultTeamsConfig = TeamsConfig{
NotifierConfig: NotifierConfig{
VSendResolved: false,
},
Title: `{{ template "teams.default.title" . }}`,
Text: `{{ template "teams.default.text" . }}`,
}
)

// NotifierConfig contains base options common across all notifier configurations.
Expand Down Expand Up @@ -777,3 +785,18 @@ func (c *TelegramConfig) UnmarshalYAML(unmarshal func(interface{}) error) error
}
return nil
}

type TeamsConfig 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"`

Title string `yaml:"title,omitempty" json:"title,omitempty"`
Text string `yaml:"text,omitempty" json:"text,omitempty"`
}

func (c *TeamsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
*c = DefaultTeamsConfig
type plain TeamsConfig
return unmarshal((*plain)(c))
}
23 changes: 23 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,8 @@ slack_configs:
[ - <slack_config>, ... ]
sns_configs:
[ - <sns_config>, ... ]
teams_configs:
[ - <teams_config>, ... ]
telegram_configs:
[ - <telegram_config>, ... ]
victorops_configs:
Expand Down Expand Up @@ -1044,6 +1046,27 @@ attributes:
[ role_arn: <string> ]
```

### `<teams_config>`

Teams notifications are sent via the [Incoming Webhooks](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/what-are-webhooks-and-connectors).

```yaml
# Whether to notify about resolved alerts.
[ send_resolved: <boolean> | default = true ]

# The Incoming webhook URL.
[ webhook_url: <secret> ]

# Message title template.
[ title: <tmpl_string> | default = '{{ template "teams.default.title" . }}' ]

# Message body template.
[ text: <tmpl_string> | default = '{{ template "teams.default.text" . }}' ]

# The HTTP client's configuration.
[ http_config: <http_config> | default = global.http_config ]
```

### `<telegram_config>`

```yaml
Expand Down
130 changes: 130 additions & 0 deletions notify/teams/teams.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Copyright 2019 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 teams

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/common/model"

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

const (
colorRed = "8C1A1A"
colorGreen = "2DC72D"
colorGrey = "808080"
)

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

// Message card https://learn.microsoft.com/en-us/outlook/actionable-messages/message-card-reference
type teamsMessage struct {
Context string `json:"@context"`
Type string `json:"type"`
Title string `json:"title"`
Text string `json:"text"`
ThemeColor string `json:"themeColor"`
}

func New(c *config.TeamsConfig, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) {
client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "teams", 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
}

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)

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

title := tmpl(n.conf.Title)
if err != nil {
return false, err
}
text := tmpl(n.conf.Text)
if err != nil {
return false, err
}

color := colorGrey
if alerts.Status() == model.AlertFiring {
color = colorRed
}
if alerts.Status() == model.AlertResolved {
color = colorGreen
}

t := teamsMessage{
Context: "http://schema.org/extensions",
Type: "MessageCard",
Title: title,
Text: text,
ThemeColor: color,
}

var payload bytes.Buffer
if err = json.NewEncoder(&payload).Encode(t); 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
}
129 changes: 129 additions & 0 deletions notify/teams/teams_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// Copyright 2021 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 teams

import (
"context"
"encoding/json"
"fmt"
"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"
)

// This is a test URL that has been modified to not be valid.
var testWebhookURL, _ = url.Parse("https://example.webhook.office.com/webhookb2/xxxxxx/IncomingWebhook/xxx/xxx")

func TestTeamsRetry(t *testing.T) {
notifier, err := New(
&config.TeamsConfig{
WebhookURL: &config.SecretURL{URL: testWebhookURL},
HTTPConfig: &commoncfg.HTTPClientConfig{},
},
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("retry - error on status %d", statusCode))
}
}

func TestTeamsTemplating(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
out := make(map[string]interface{})
err := dec.Decode(&out)
if err != nil {
panic(err)
}
}))
defer srv.Close()
u, _ := url.Parse(srv.URL)

for _, tc := range []struct {
title string
cfg *config.TeamsConfig

retry bool
errMsg string
}{
{
title: "full-blown message",
cfg: &config.TeamsConfig{
Title: `{{ template "teams.default.title" . }}`,
Text: `{{ template "teams.default.text" . }}`,
},
retry: false,
},
{
title: "title with templating errors",
cfg: &config.TeamsConfig{
Title: "{{ ",
},
errMsg: "template: :1: unclosed action",
},
{
title: "message with templating errors",
cfg: &config.TeamsConfig{
Title: `{{ template "teams.default.title" . }}`,
Text: "{{ ",
},
errMsg: "template: :1: unclosed action",
},
} {
t.Run(tc.title, func(t *testing.T) {
tc.cfg.WebhookURL = &config.SecretURL{URL: u}
tc.cfg.HTTPConfig = &commoncfg.HTTPClientConfig{}
pd, err := New(tc.cfg, test.CreateTmpl(t), log.NewNopLogger())
require.NoError(t, err)

ctx := context.Background()
ctx = notify.WithGroupKey(ctx, "1")

ok, err := pd.Notify(ctx, []*types.Alert{
{
Alert: model.Alert{
Labels: model.LabelSet{
"lbl1": "val1",
},
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
},
},
}...)
if tc.errMsg == "" {
require.NoError(t, err)
} else {
require.Error(t, err)
require.Contains(t, err.Error(), tc.errMsg)
}
require.Equal(t, tc.retry, ok)
})
}
}

0 comments on commit 1d5b341

Please sign in to comment.