2020-02-16 18:59:02 +00:00
|
|
|
package provider
|
|
|
|
|
2020-02-21 21:15:05 +00:00
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
const alertsPath = "/api/v2/alerts"
|
|
|
|
|
|
|
|
var pool = sync.Pool{New: func() interface{} {
|
|
|
|
return &bytes.Buffer{}
|
|
|
|
}}
|
2020-02-16 18:59:02 +00:00
|
|
|
|
|
|
|
// AlertManager represents integration provider with Prometheus alert manager
|
2020-02-21 21:15:05 +00:00
|
|
|
type AlertManager struct {
|
|
|
|
alertURL string
|
|
|
|
argFunc AlertURLGenerator
|
|
|
|
client *http.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
// AlertURLGenerator returns URL to single alert by given name
|
2020-03-13 10:19:31 +00:00
|
|
|
type AlertURLGenerator func(group, name string) string
|
2020-02-21 21:15:05 +00:00
|
|
|
|
|
|
|
// NewAlertManager is a constructor for AlertManager
|
|
|
|
func NewAlertManager(alertManagerURL string, fn AlertURLGenerator, c *http.Client) *AlertManager {
|
|
|
|
return &AlertManager{
|
|
|
|
alertURL: strings.TrimSuffix(alertManagerURL, "/") + alertsPath,
|
|
|
|
argFunc: fn,
|
|
|
|
client: c,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-16 18:59:02 +00:00
|
|
|
// Send an alert or resolve message
|
2020-03-13 10:19:31 +00:00
|
|
|
func (am *AlertManager) Send(alerts []Alert) error {
|
2020-02-21 21:15:05 +00:00
|
|
|
b := pool.Get().(*bytes.Buffer)
|
|
|
|
b.Reset()
|
|
|
|
defer pool.Put(b)
|
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() }()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
b.Reset()
|
|
|
|
if _, err := io.Copy(b, resp.Body); err != nil {
|
|
|
|
logger.Errorf("unable to copy error response body to buffer %s", err)
|
|
|
|
}
|
|
|
|
return fmt.Errorf("invalid response from alertmanager %s", b)
|
|
|
|
}
|
2020-02-16 18:59:02 +00:00
|
|
|
return nil
|
|
|
|
}
|