Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add msteams #3324

Merged
merged 5 commits into from
Jun 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ -51,6 +51,7 @@ import (
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/notify/discord"
"github.com/prometheus/alertmanager/notify/email"
"github.com/prometheus/alertmanager/notify/msteams"
"github.com/prometheus/alertmanager/notify/opsgenie"
"github.com/prometheus/alertmanager/notify/pagerduty"
"github.com/prometheus/alertmanager/notify/pushover"
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.MSTeamsConfigs {
add("msteams", i, c, func(l log.Logger) (notify.Notifier, error) { return msteams.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.MSTeamsConfigs {
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 _, msteams := range rcv.MSTeamsConfigs {
if msteams.HTTPConfig == nil {
msteams.HTTPConfig = c.Global.HTTPConfig
}
if msteams.WebhookURL == nil {
return fmt.Errorf("no msteams 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"`
MSTeamsConfigs []*MSTeamsConfig `yaml:"msteams_configs,omitempty" json:"teams_configs,omitempty"`
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we align the configuration name? I am wondering why we call msteams for yaml but teams for json.
@zhan9san @simonpasquier

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yeya24

Thanks for pointing it out. It has to be a typo.

I'll submit a PR to fix it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch!

}

// 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",
}

DefaultMSTeamsConfig = MSTeamsConfig{
NotifierConfig: NotifierConfig{
VSendResolved: true,
},
Title: `{{ template "msteams.default.title" . }}`,
Text: `{{ template "msteams.default.text" . }}`,
}
)

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

type MSTeamsConfig 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 *MSTeamsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
*c = DefaultMSTeamsConfig
type plain MSTeamsConfig
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 @@ -499,6 +499,8 @@ discord_configs:
[ - <discord_config>, ... ]
email_configs:
[ - <email_config>, ... ]
msteams_configs:
[ - <msteams_config>, ... ]
opsgenie_configs:
[ - <opsgenie_config>, ... ]
pagerduty_configs:
Expand Down Expand Up @@ -717,6 +719,27 @@ tls_config:
[ headers: { <string>: <tmpl_string>, ... } ]
```

### `<msteams_config>`

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.

```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 ]
```

### `<opsgenie_config>`

OpsGenie notifications are sent via the [OpsGenie API](https://docs.opsgenie.com/docs/alert-api).
Expand Down
136 changes: 136 additions & 0 deletions notify/msteams/msteams.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Copyright 2023 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 msteams

import (
"bytes"
"context"
"encoding/json"
"io"
"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.MSTeamsConfig
tmpl *template.Template
logger log.Logger
client *http.Client
retrier *notify.Retrier
webhookURL *config.SecretURL
postJSONFunc func(ctx context.Context, client *http.Client, url string, body io.Reader) (*http.Response, error)
}

// Message card reference can be found at 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"`
}

// New returns a new notifier that uses the Microsoft Teams Webhook API.
func New(c *config.MSTeamsConfig, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) {
client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "msteams", httpOpts...)
if err != nil {
return nil, err
}

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

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)

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
}

alerts := types.Alerts(as...)
color := colorGrey
switch alerts.Status() {
case model.AlertFiring:
color = colorRed
case 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 := n.postJSONFunc(ctx, n.client, n.webhookURL.String(), &payload)
if err != nil {
return true, notify.RedactURL(err)
}
defer notify.Drain(resp)

// https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#rate-limiting-for-connectors
simonpasquier marked this conversation as resolved.
Show resolved Hide resolved
shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
if err != nil {
return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)
}
return shouldRetry, err
}