Skip to content

Commit

Permalink
feat: ms teams initial version (#5)
Browse files Browse the repository at this point in the history
* feat: ms teams initial version

* fix: solved issues found during ms teams testing

* fix: added retry code for ms teams sender
  • Loading branch information
mindhash committed Aug 8, 2023
1 parent 266c4f0 commit 795374c
Show file tree
Hide file tree
Showing 7 changed files with 306 additions and 10 deletions.
16 changes: 16 additions & 0 deletions api/v1/config_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/notify/msteams"
"github.com/prometheus/alertmanager/notify/pagerduty"
"github.com/prometheus/alertmanager/notify/slack"
"github.com/prometheus/alertmanager/notify/webhook"
Expand Down Expand Up @@ -245,6 +246,21 @@ func (api *API) testReceiver(w http.ResponseWriter, req *http.Request) {
api.respondError(w, apiError{err: err, typ: errorInternal}, fmt.Sprintf("failed to send test message to channel (%s)", receiver.Name))
return
}
} else if receiver.MSTeamsConfigs != nil {
msteamsConfig := receiver.MSTeamsConfigs[0]
msteamsConfig.HTTPConfig = &commoncfg.HTTPClientConfig{}
notifier, err := msteams.New(msteamsConfig, tmpl, api.logger)
if err != nil {
api.respondError(w, apiError{err: err, typ: errorInternal}, "failed to prepare message for select config")
return
}
ctx := getCtx(receiver.Name)
dummyAlert := getDummyAlert()
_, err = notifier.Notify(ctx, &dummyAlert)
if err != nil {
api.respondError(w, apiError{err: err, typ: errorInternal}, fmt.Sprintf("failed to send test message to channel (%s)", receiver.Name))
return
}
} else if receiver.PagerdutyConfigs != nil {
pc := receiver.PagerdutyConfigs[0]
pc.HTTPConfig = &commoncfg.HTTPClientConfig{}
Expand Down
4 changes: 4 additions & 0 deletions cmd/alertmanager/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import (
"github.com/prometheus/alertmanager/nflog"
"github.com/prometheus/alertmanager/notify"
"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 @@ -172,6 +173,9 @@ func buildReceiverIntegrations(nc *config.Receiver, tmpl *template.Template, log
for i, c := range nc.SNSConfigs {
add("sns", i, c, func(l log.Logger) (notify.Notifier, error) { return sns.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
13 changes: 13 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,9 @@ func resolveFilepaths(baseDir string, cfg *Config) {
for _, cfg := range receiver.SNSConfigs {
cfg.HTTPConfig.SetDirectory(baseDir)
}
for _, cfg := range receiver.MSTeamsConfigs {
cfg.HTTPConfig.SetDirectory(baseDir)
}
}
}

Expand Down Expand Up @@ -563,6 +566,15 @@ func (c *Config) Validate() error {
sns.HTTPConfig = c.Global.HTTPConfig
}
}
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 @@ -1035,6 +1047,7 @@ type Receiver struct {
PushoverConfigs []*PushoverConfig `yaml:"pushover_configs,omitempty" json:"pushover_configs,omitempty"`
VictorOpsConfigs []*VictorOpsConfig `yaml:"victorops_configs,omitempty" json:"victorops_configs,omitempty"`
SNSConfigs []*SNSConfig `yaml:"sns_configs,omitempty" json:"sns_configs,omitempty"`
MSTeamsConfigs []*MSTeamsConfig `yaml:"msteams_configs,omitempty" json:"msteams_configs,omitempty"`
}

func (c *Receiver) Validate() error {
Expand Down
26 changes: 25 additions & 1 deletion config/notifiers.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@ package config
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
"regexp"
"strings"
"time"

"github.com/pkg/errors"

commoncfg "github.com/prometheus/common/config"
"github.com/prometheus/common/sigv4"
)
Expand Down Expand Up @@ -137,6 +138,14 @@ var (
Subject: `{{ template "sns.default.subject" . }}`,
Message: `{{ template "sns.default.message" . }}`,
}

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 @@ -700,3 +709,18 @@ func (c *SNSConfig) 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))
}
138 changes: 138 additions & 0 deletions notify/msteams/msteams.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// 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"
"fmt"
"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{RetryCodes: []int{429}},
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
retry, err := n.retrier.Check(resp.StatusCode, resp.Body)
if err != nil {
reasonErr := notify.NewErrorWithReason(notify.GetFailureReason(resp.StatusCode, fmt.Sprintf("%v", err.Error())), err)
return retry, reasonErr
}
return false, nil
}
Loading

0 comments on commit 795374c

Please sign in to comment.