2015-09-29 13:12:31 +00:00
|
|
|
package notify
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2015-09-30 12:54:13 +00:00
|
|
|
"github.com/prometheus/common/log"
|
2015-10-01 13:46:10 +00:00
|
|
|
"github.com/prometheus/common/model"
|
2015-09-29 13:12:31 +00:00
|
|
|
"golang.org/x/net/context"
|
|
|
|
"golang.org/x/net/context/ctxhttp"
|
|
|
|
|
|
|
|
"github.com/prometheus/alertmanager/config"
|
|
|
|
"github.com/prometheus/alertmanager/types"
|
|
|
|
)
|
|
|
|
|
2015-10-01 13:46:10 +00:00
|
|
|
const contentTypeJSON = "application/json"
|
|
|
|
|
2015-09-29 13:12:31 +00:00
|
|
|
func Build(confs []*config.NotificationConfig) map[string]Notifier {
|
|
|
|
// Create new notifiers. If the type is not implemented yet, fallback
|
|
|
|
// to logging notifiers.
|
|
|
|
res := map[string]Notifier{}
|
|
|
|
for _, nc := range confs {
|
|
|
|
var all Notifiers
|
|
|
|
|
|
|
|
for _, wc := range nc.WebhookConfigs {
|
2015-09-30 12:54:13 +00:00
|
|
|
all = append(all, &LogNotifier{
|
|
|
|
Log: log.With("notifier", "webhook"),
|
|
|
|
Notifier: NewWebhook(wc),
|
|
|
|
})
|
2015-09-29 13:12:31 +00:00
|
|
|
}
|
|
|
|
for range nc.EmailConfigs {
|
2015-09-30 12:54:13 +00:00
|
|
|
all = append(all, &LogNotifier{Log: log.With("name", nc.Name)})
|
2015-09-29 13:12:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
res[nc.Name] = all
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
|
|
|
type Webhook struct {
|
|
|
|
URL string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWebhook(conf *config.WebhookConfig) *Webhook {
|
|
|
|
return &Webhook{URL: conf.URL}
|
|
|
|
}
|
|
|
|
|
|
|
|
type WebhookMessage struct {
|
|
|
|
Version string `json:"version"`
|
2015-10-01 13:46:10 +00:00
|
|
|
Status model.AlertStatus `json:"status"`
|
|
|
|
Alerts model.Alerts `json:"alert"`
|
2015-09-29 13:12:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (w *Webhook) Notify(ctx context.Context, alerts ...*types.Alert) error {
|
2015-10-01 13:46:10 +00:00
|
|
|
as := types.Alerts(alerts...)
|
|
|
|
|
2015-09-29 13:12:31 +00:00
|
|
|
msg := &WebhookMessage{
|
|
|
|
Version: "1",
|
2015-10-01 13:46:10 +00:00
|
|
|
Status: as.Status(),
|
|
|
|
Alerts: as,
|
2015-09-29 13:12:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var buf bytes.Buffer
|
|
|
|
if err := json.NewEncoder(&buf).Encode(msg); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(fabxc): implement retrying as long as context is not canceled.
|
2015-10-01 13:46:10 +00:00
|
|
|
resp, err := ctxhttp.Post(ctx, http.DefaultClient, w.URL, contentTypeJSON, &buf)
|
2015-09-29 13:12:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
resp.Body.Close()
|
|
|
|
|
|
|
|
if resp.StatusCode/100 != 2 {
|
|
|
|
return fmt.Errorf("unexpected status code %v", resp.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|