2020-04-06 13:44:03 +02:00
|
|
|
package notifier
|
2020-02-16 19:59:02 +01:00
|
|
|
|
2020-02-21 22:15:05 +01:00
|
|
|
import (
|
|
|
|
"bytes"
|
2020-05-10 18:58:17 +02:00
|
|
|
"context"
|
2020-02-21 22:15:05 +01:00
|
|
|
"fmt"
|
2020-04-06 13:44:03 +02:00
|
|
|
"io/ioutil"
|
2020-02-21 22:15:05 +01:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2020-02-16 19:59:02 +01:00
|
|
|
// AlertManager represents integration provider with Prometheus alert manager
|
2020-04-06 13:44:03 +02:00
|
|
|
// https://github.com/prometheus/alertmanager
|
2020-02-21 22:15:05 +01:00
|
|
|
type AlertManager struct {
|
|
|
|
alertURL string
|
|
|
|
argFunc AlertURLGenerator
|
|
|
|
client *http.Client
|
|
|
|
}
|
|
|
|
|
2020-02-16 19:59:02 +01:00
|
|
|
// Send an alert or resolve message
|
2020-05-10 18:58:17 +02:00
|
|
|
func (am *AlertManager) Send(ctx context.Context, alerts []Alert) error {
|
2020-04-06 13:44:03 +02:00
|
|
|
b := &bytes.Buffer{}
|
2020-03-13 11:19:31 +01:00
|
|
|
writeamRequest(b, alerts, am.argFunc)
|
2020-05-10 18:58:17 +02:00
|
|
|
|
|
|
|
req, err := http.NewRequest("POST", am.alertURL, b)
|
2020-02-21 22:15:05 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-05-10 18:58:17 +02:00
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
req = req.WithContext(ctx)
|
|
|
|
resp, err := am.client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-02-21 22:15:05 +01:00
|
|
|
defer func() { _ = resp.Body.Close() }()
|
2020-04-06 13:44:03 +02:00
|
|
|
|
2020-02-21 22:15:05 +01:00
|
|
|
if resp.StatusCode != http.StatusOK {
|
2020-04-06 13:44:03 +02:00
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to read response from %q: %s", am.alertURL, err)
|
2020-02-21 22:15:05 +01:00
|
|
|
}
|
2020-04-06 13:44:03 +02:00
|
|
|
return fmt.Errorf("invalid SC %d from %q; response body: %s", resp.StatusCode, am.alertURL, string(body))
|
2020-02-21 22:15:05 +01:00
|
|
|
}
|
2020-02-16 19:59:02 +01:00
|
|
|
return nil
|
|
|
|
}
|
2020-04-06 13:44:03 +02:00
|
|
|
|
|
|
|
// AlertURLGenerator returns URL to single alert by given name
|
2020-05-10 18:58:17 +02:00
|
|
|
type AlertURLGenerator func(group, alert string) string
|
2020-04-06 13:44:03 +02:00
|
|
|
|
|
|
|
const alertManagerPath = "/api/v2/alerts"
|
|
|
|
|
|
|
|
// NewAlertManager is a constructor for AlertManager
|
|
|
|
func NewAlertManager(alertManagerURL string, fn AlertURLGenerator, c *http.Client) *AlertManager {
|
|
|
|
return &AlertManager{
|
|
|
|
alertURL: strings.TrimSuffix(alertManagerURL, "/") + alertManagerPath,
|
|
|
|
argFunc: fn,
|
|
|
|
client: c,
|
|
|
|
}
|
|
|
|
}
|