Skip to content

Commit d10f21f

Browse files
authored
Add msteams (#3324)
* Add msteams Signed-off-by: Jack Zhang <[email protected]> --------- Signed-off-by: Jack Zhang <[email protected]> Signed-off-by: Jack <[email protected]>
1 parent 9f683fc commit d10f21f

File tree

9 files changed

+407
-2
lines changed

9 files changed

+407
-2
lines changed

asset/assets_vfsdata.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

cmd/alertmanager/main.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import (
5151
"github.com/prometheus/alertmanager/notify"
5252
"github.com/prometheus/alertmanager/notify/discord"
5353
"github.com/prometheus/alertmanager/notify/email"
54+
"github.com/prometheus/alertmanager/notify/msteams"
5455
"github.com/prometheus/alertmanager/notify/opsgenie"
5556
"github.com/prometheus/alertmanager/notify/pagerduty"
5657
"github.com/prometheus/alertmanager/notify/pushover"
@@ -181,6 +182,9 @@ func buildReceiverIntegrations(nc config.Receiver, tmpl *template.Template, logg
181182
for i, c := range nc.WebexConfigs {
182183
add("webex", i, c, func(l log.Logger) (notify.Notifier, error) { return webex.New(c, tmpl, l) })
183184
}
185+
for i, c := range nc.MSTeamsConfigs {
186+
add("msteams", i, c, func(l log.Logger) (notify.Notifier, error) { return msteams.New(c, tmpl, l) })
187+
}
184188

185189
if errs.Len() > 0 {
186190
return nil, &errs

config/config.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,9 @@ func resolveFilepaths(baseDir string, cfg *Config) {
254254
for _, cfg := range receiver.WebexConfigs {
255255
cfg.HTTPConfig.SetDirectory(baseDir)
256256
}
257+
for _, cfg := range receiver.MSTeamsConfigs {
258+
cfg.HTTPConfig.SetDirectory(baseDir)
259+
}
257260
}
258261
}
259262

@@ -528,6 +531,14 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
528531
webex.APIURL = c.Global.WebexAPIURL
529532
}
530533
}
534+
for _, msteams := range rcv.MSTeamsConfigs {
535+
if msteams.HTTPConfig == nil {
536+
msteams.HTTPConfig = c.Global.HTTPConfig
537+
}
538+
if msteams.WebhookURL == nil {
539+
return fmt.Errorf("no msteams webhook URL provided")
540+
}
541+
}
531542

532543
names[rcv.Name] = struct{}{}
533544
}
@@ -896,6 +907,7 @@ type Receiver struct {
896907
SNSConfigs []*SNSConfig `yaml:"sns_configs,omitempty" json:"sns_configs,omitempty"`
897908
TelegramConfigs []*TelegramConfig `yaml:"telegram_configs,omitempty" json:"telegram_configs,omitempty"`
898909
WebexConfigs []*WebexConfig `yaml:"webex_configs,omitempty" json:"webex_configs,omitempty"`
910+
MSTeamsConfigs []*MSTeamsConfig `yaml:"msteams_configs,omitempty" json:"teams_configs,omitempty"`
899911
}
900912

901913
// UnmarshalYAML implements the yaml.Unmarshaler interface for Receiver.

config/notifiers.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,14 @@ var (
164164
Message: `{{ template "telegram.default.message" . }}`,
165165
ParseMode: "HTML",
166166
}
167+
168+
DefaultMSTeamsConfig = MSTeamsConfig{
169+
NotifierConfig: NotifierConfig{
170+
VSendResolved: true,
171+
},
172+
Title: `{{ template "msteams.default.title" . }}`,
173+
Text: `{{ template "msteams.default.text" . }}`,
174+
}
167175
)
168176

169177
// NotifierConfig contains base options common across all notifier configurations.
@@ -778,3 +786,18 @@ func (c *TelegramConfig) UnmarshalYAML(unmarshal func(interface{}) error) error
778786
}
779787
return nil
780788
}
789+
790+
type MSTeamsConfig struct {
791+
NotifierConfig `yaml:",inline" json:",inline"`
792+
HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"`
793+
WebhookURL *SecretURL `yaml:"webhook_url,omitempty" json:"webhook_url,omitempty"`
794+
795+
Title string `yaml:"title,omitempty" json:"title,omitempty"`
796+
Text string `yaml:"text,omitempty" json:"text,omitempty"`
797+
}
798+
799+
func (c *MSTeamsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
800+
*c = DefaultMSTeamsConfig
801+
type plain MSTeamsConfig
802+
return unmarshal((*plain)(c))
803+
}

docs/configuration.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,8 @@ discord_configs:
499499
[ - <discord_config>, ... ]
500500
email_configs:
501501
[ - <email_config>, ... ]
502+
msteams_configs:
503+
[ - <msteams_config>, ... ]
502504
opsgenie_configs:
503505
[ - <opsgenie_config>, ... ]
504506
pagerduty_configs:
@@ -717,6 +719,27 @@ tls_config:
717719
[ headers: { <string>: <tmpl_string>, ... } ]
718720
```
719721

722+
### `<msteams_config>`
723+
724+
Microsoft Teams notifications are sent via the [Incoming Webhooks](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/what-are-webhooks-and-connectors) API endpoint.
725+
726+
```yaml
727+
# Whether to notify about resolved alerts.
728+
[ send_resolved: <boolean> | default = true ]
729+
730+
# The incoming webhook URL.
731+
[ webhook_url: <secret> ]
732+
733+
# Message title template.
734+
[ title: <tmpl_string> | default = '{{ template "teams.default.title" . }}' ]
735+
736+
# Message body template.
737+
[ text: <tmpl_string> | default = '{{ template "teams.default.text" . }}' ]
738+
739+
# The HTTP client's configuration.
740+
[ http_config: <http_config> | default = global.http_config ]
741+
```
742+
720743
### `<opsgenie_config>`
721744

722745
OpsGenie notifications are sent via the [OpsGenie API](https://docs.opsgenie.com/docs/alert-api).

notify/msteams/msteams.go

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
// Copyright 2023 Prometheus Team
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
package msteams
15+
16+
import (
17+
"bytes"
18+
"context"
19+
"encoding/json"
20+
"io"
21+
"net/http"
22+
23+
"github.com/go-kit/log"
24+
"github.com/go-kit/log/level"
25+
commoncfg "github.com/prometheus/common/config"
26+
"github.com/prometheus/common/model"
27+
28+
"github.com/prometheus/alertmanager/config"
29+
"github.com/prometheus/alertmanager/notify"
30+
"github.com/prometheus/alertmanager/template"
31+
"github.com/prometheus/alertmanager/types"
32+
)
33+
34+
const (
35+
colorRed = "8C1A1A"
36+
colorGreen = "2DC72D"
37+
colorGrey = "808080"
38+
)
39+
40+
type Notifier struct {
41+
conf *config.MSTeamsConfig
42+
tmpl *template.Template
43+
logger log.Logger
44+
client *http.Client
45+
retrier *notify.Retrier
46+
webhookURL *config.SecretURL
47+
postJSONFunc func(ctx context.Context, client *http.Client, url string, body io.Reader) (*http.Response, error)
48+
}
49+
50+
// Message card reference can be found at https://learn.microsoft.com/en-us/outlook/actionable-messages/message-card-reference.
51+
type teamsMessage struct {
52+
Context string `json:"@context"`
53+
Type string `json:"type"`
54+
Title string `json:"title"`
55+
Text string `json:"text"`
56+
ThemeColor string `json:"themeColor"`
57+
}
58+
59+
// New returns a new notifier that uses the Microsoft Teams Webhook API.
60+
func New(c *config.MSTeamsConfig, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) {
61+
client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "msteams", httpOpts...)
62+
if err != nil {
63+
return nil, err
64+
}
65+
66+
n := &Notifier{
67+
conf: c,
68+
tmpl: t,
69+
logger: l,
70+
client: client,
71+
retrier: &notify.Retrier{},
72+
webhookURL: c.WebhookURL,
73+
postJSONFunc: notify.PostJSON,
74+
}
75+
76+
return n, nil
77+
}
78+
79+
func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
80+
key, err := notify.ExtractGroupKey(ctx)
81+
if err != nil {
82+
return false, err
83+
}
84+
85+
level.Debug(n.logger).Log("incident", key)
86+
87+
data := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)
88+
tmpl := notify.TmplText(n.tmpl, data, &err)
89+
if err != nil {
90+
return false, err
91+
}
92+
93+
title := tmpl(n.conf.Title)
94+
if err != nil {
95+
return false, err
96+
}
97+
text := tmpl(n.conf.Text)
98+
if err != nil {
99+
return false, err
100+
}
101+
102+
alerts := types.Alerts(as...)
103+
color := colorGrey
104+
switch alerts.Status() {
105+
case model.AlertFiring:
106+
color = colorRed
107+
case model.AlertResolved:
108+
color = colorGreen
109+
}
110+
111+
t := teamsMessage{
112+
Context: "http://schema.org/extensions",
113+
Type: "MessageCard",
114+
Title: title,
115+
Text: text,
116+
ThemeColor: color,
117+
}
118+
119+
var payload bytes.Buffer
120+
if err = json.NewEncoder(&payload).Encode(t); err != nil {
121+
return false, err
122+
}
123+
124+
resp, err := n.postJSONFunc(ctx, n.client, n.webhookURL.String(), &payload)
125+
if err != nil {
126+
return true, notify.RedactURL(err)
127+
}
128+
defer notify.Drain(resp)
129+
130+
// https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#rate-limiting-for-connectors
131+
shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
132+
if err != nil {
133+
return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)
134+
}
135+
return shouldRetry, err
136+
}

0 commit comments

Comments
 (0)