2020-04-06 11:44:03 +00:00
|
|
|
package notifier
|
2020-02-16 18:59:02 +00:00
|
|
|
|
2020-02-21 21:15:05 +00:00
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
2020-04-06 11:44:03 +00:00
|
|
|
"io/ioutil"
|
2020-02-21 21:15:05 +00:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2020-02-16 18:59:02 +00:00
|
|
|
// AlertManager represents integration provider with Prometheus alert manager
|
2020-04-06 11:44:03 +00:00
|
|
|
// https://github.com/prometheus/alertmanager
|
2020-02-21 21:15:05 +00:00
|
|
|
type AlertManager struct {
|
|
|
|
alertURL string
|
|
|
|
argFunc AlertURLGenerator
|
|
|
|
client *http.Client
|
|
|
|
}
|
|
|
|
|
2020-02-16 18:59:02 +00:00
|
|
|
// Send an alert or resolve message
|
2020-04-06 11:44:03 +00:00
|
|
|
func (am *AlertManager) Send(alerts []Alert) error {
|
|
|
|
b := &bytes.Buffer{}
|
2020-03-13 10:19:31 +00:00
|
|
|
writeamRequest(b, alerts, am.argFunc)
|
2020-02-21 21:15:05 +00:00
|
|
|
resp, err := am.client.Post(am.alertURL, "application/json", b)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer func() { _ = resp.Body.Close() }()
|
2020-04-06 11:44:03 +00:00
|
|
|
|
2020-02-21 21:15:05 +00:00
|
|
|
if resp.StatusCode != http.StatusOK {
|
2020-04-06 11:44:03 +00: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 21:15:05 +00:00
|
|
|
}
|
2020-04-06 11:44:03 +00:00
|
|
|
return fmt.Errorf("invalid SC %d from %q; response body: %s", resp.StatusCode, am.alertURL, string(body))
|
2020-02-21 21:15:05 +00:00
|
|
|
}
|
2020-02-16 18:59:02 +00:00
|
|
|
return nil
|
|
|
|
}
|
2020-04-06 11:44:03 +00:00
|
|
|
|
|
|
|
// AlertURLGenerator returns URL to single alert by given name
|
2020-04-11 09:40:24 +00:00
|
|
|
type AlertURLGenerator func(group, id string) string
|
2020-04-06 11:44:03 +00: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,
|
|
|
|
}
|
|
|
|
}
|