Skip to content

Commit

Permalink
feat(prometheus#3920): add msteamsv2 receiver
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Schneider authored and sschne committed Sep 6, 2024
1 parent a6df704 commit 287735d
Show file tree
Hide file tree
Showing 8 changed files with 261 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.

12 changes: 12 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,9 @@ func resolveFilepaths(baseDir string, cfg *Config) {
for _, cfg := range receiver.MSTeamsConfigs {
cfg.HTTPConfig.SetDirectory(baseDir)
}
for _, cfg := range receiver.MSTeamsV2Configs {
cfg.HTTPConfig.SetDirectory(baseDir)
}
for _, cfg := range receiver.JiraConfigs {
cfg.HTTPConfig.SetDirectory(baseDir)
}
Expand Down Expand Up @@ -551,6 +554,14 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
return fmt.Errorf("no msteams webhook URL or URLFile provided")
}
}
for _, msteamsv2 := range rcv.MSTeamsV2Configs {
if msteamsv2.HTTPConfig == nil {
msteamsv2.HTTPConfig = c.Global.HTTPConfig
}
if msteamsv2.WebhookURL == nil && len(msteamsv2.WebhookURLFile) == 0 {
return fmt.Errorf("no msteamsv2 webhook URL or URLFile provided")
}
}
for _, jira := range rcv.JiraConfigs {
if jira.HTTPConfig == nil {
jira.HTTPConfig = c.Global.HTTPConfig
Expand Down Expand Up @@ -935,6 +946,7 @@ type Receiver struct {
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:"msteams_configs,omitempty"`
MSTeamsV2Configs []*MSTeamsV2Config `yaml:"msteamsv2_configs,omitempty" json:"msteamsv2_configs,omitempty"`
JiraConfigs []*JiraConfig `yaml:"jira_configs,omitempty" json:"jira_configs,omitempty"`
}

Expand Down
36 changes: 36 additions & 0 deletions config/notifiers.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,14 @@ var (
Text: `{{ template "msteams.default.text" . }}`,
}

DefaultMSTeamsV2Config = MSTeamsV2Config{
NotifierConfig: NotifierConfig{
VSendResolved: true,
},
Title: `{{ template "msteamsv2.default.title" . }}`,
Text: `{{ template "msteamsv2.default.text" . }}`,
}

DefaultJiraConfig = JiraConfig{
NotifierConfig: NotifierConfig{
VSendResolved: true,
Expand Down Expand Up @@ -836,6 +844,34 @@ func (c *MSTeamsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
return nil
}

type MSTeamsV2Config 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"`
WebhookURLFile string `yaml:"webhook_url_file,omitempty" json:"webhook_url_file,omitempty"`

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

func (c *MSTeamsV2Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
*c = DefaultMSTeamsV2Config
type plain MSTeamsV2Config
if err := unmarshal((*plain)(c)); err != nil {
return err
}

if c.WebhookURL == nil && c.WebhookURLFile == "" {
return fmt.Errorf("one of webhook_url or webhook_url_file must be configured")
}

if c.WebhookURL != nil && len(c.WebhookURLFile) > 0 {
return fmt.Errorf("at most one of webhook_url & webhook_url_file must be configured")
}

return nil
}

type JiraConfig struct {
NotifierConfig `yaml:",inline" json:",inline"`
HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"`
Expand Down
4 changes: 4 additions & 0 deletions config/receiver/receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/prometheus/alertmanager/notify/email"
"github.com/prometheus/alertmanager/notify/jira"
"github.com/prometheus/alertmanager/notify/msteams"
"github.com/prometheus/alertmanager/notify/msteamsv2"
"github.com/prometheus/alertmanager/notify/opsgenie"
"github.com/prometheus/alertmanager/notify/pagerduty"
"github.com/prometheus/alertmanager/notify/pushover"
Expand Down Expand Up @@ -93,6 +94,9 @@ func BuildReceiverIntegrations(nc config.Receiver, tmpl *template.Template, logg
for i, c := range nc.MSTeamsConfigs {
add("msteams", i, c, func(l log.Logger) (notify.Notifier, error) { return msteams.New(c, tmpl, l, httpOpts...) })
}
for i, c := range nc.MSTeamsV2Configs {
add("msteamsv2", i, c, func(l log.Logger) (notify.Notifier, error) { return msteamsv2.New(c, tmpl, l, httpOpts...) })
}
for i, c := range nc.JiraConfigs {
add("jira", i, c, func(l log.Logger) (notify.Notifier, error) { return jira.New(c, tmpl, l, httpOpts...) })
}
Expand Down
2 changes: 2 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,8 @@ email_configs:
[ - <email_config>, ... ]
msteams_configs:
[ - <msteams_config>, ... ]
msteamsv2_configs:
[ - <msteamsv2_config>, ... ]
jira_configs:
[ - <jira_config>, ... ]
opsgenie_configs:
Expand Down
192 changes: 192 additions & 0 deletions notify/msteamsv2/msteamsv2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// Copyright 2024 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 msteamsv2

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"

"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 = "Attention"
colorGreen = "Good"
colorGrey = "Warning"
)

type Notifier struct {
conf *config.MSTeamsV2Config
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)
}

// https://learn.microsoft.com/en-us/connectors/teams/?tabs=text1#adaptivecarditemschema
type Content struct {
Schema string `json:"$schema"`
Type string `json:"type"`
Version string `json:"version"`
Body []Body `json:"body"`
}

type Body struct {
Type string `json:"type"`
Text string `json:"text"`
Weight string `json:"weigth,omitempty"`
Size string `json:"size,omitempty"`
Wrap bool `json:"wrap,omitempty"`
Style string `json:"style,omitempty"`
Color string `json:"color,omitempty"`
}

type Attachment struct {
ContentType string `json:"contentType"`
ContentURL *string `json:"contentUrl"` // Use a pointer to handle null values
Content Content `json:"content"`
}

type teamsMessage struct {
Type string `json:"type"`
Attachments []Attachment `json:"attachments"`
}

// New returns a new notifier that uses the Microsoft Teams Power Platform connector.
func New(c *config.MSTeamsV2Config, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) {
client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "msteamsv2", 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
}

var url string
if n.conf.WebhookURL != nil {
url = n.conf.WebhookURL.String()
} else {
content, err := os.ReadFile(n.conf.WebhookURLFile)
if err != nil {
return false, fmt.Errorf("read webhook_url_file: %w", err)
}
url = strings.TrimSpace(string(content))
}

t := teamsMessage{
Type: "message",
Attachments: []Attachment{
{
ContentType: "application/vnd.microsoft.card.adaptive",
ContentURL: nil,
Content: Content{
Schema: "http://adaptivecards.io/schemas/adaptive-card.json",
Type: "AdaptiveCard",
Version: "1.2",
Body: []Body{
{
Type: "TextBlock",
Text: title,
Weight: "Bolder",
Size: "Medium",
Wrap: true,
Style: "heading",
Color: color,
},
{
Type: "TextBlock",
Text: text,
},
},
},
},
},
}

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

resp, err := n.postJSONFunc(ctx, n.client, url, &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
shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)
if err != nil {
return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)
}
return shouldRetry, err
}
1 change: 1 addition & 0 deletions notify/notify.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ func (m *Metrics) InitializeFor(receiver map[string][]Integration) {
"discord",
"webex",
"msteams",
"msteamsv2",
"jira",
} {
m.numNotifications.WithLabelValues(integration)
Expand Down
12 changes: 12 additions & 0 deletions template/default.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,18 @@ Alerts Resolved:
{{ end }}
{{ end }}

{{ define "msteamsv2.default.title" }}{{ template "__subject" . }}{{ end }}
{{ define "msteamsv2.default.text" }}
{{ if gt (len .Alerts.Firing) 0 }}
# Alerts Firing:
{{ template "__text_alert_list_markdown" .Alerts.Firing }}
{{ end }}
{{ if gt (len .Alerts.Resolved) 0 }}
# Alerts Resolved:
{{ template "__text_alert_list_markdown" .Alerts.Resolved }}
{{ end }}
{{ end }}

{{ define "jira.default.summary" }}{{ template "__subject" . }}{{ end }}
{{ define "jira.default.description" }}
{{ if gt (len .Alerts.Firing) 0 }}
Expand Down

0 comments on commit 287735d

Please sign in to comment.