Refactor Opsgenie alerting provider code

This commit is contained in:
TwiN 2021-12-09 21:18:25 -05:00
parent 36a3419aec
commit 2503d21522
2 changed files with 55 additions and 90 deletions

View File

@ -4,62 +4,54 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/TwiN/gatus/v3/alerting/alert"
"github.com/TwiN/gatus/v3/client"
"github.com/TwiN/gatus/v3/core"
"io" "io"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"github.com/TwiN/gatus/v3/alerting/alert"
"github.com/TwiN/gatus/v3/client"
"github.com/TwiN/gatus/v3/core"
) )
const ( const (
restAPI = "https://api.opsgenie.com/v2/alerts" restAPI = "https://api.opsgenie.com/v2/alerts"
) )
type opsgenieAlertCreateRequest struct {
Message string `json:"message"`
Priority string `json:"priority"`
Source string `json:"source"`
Entity string `json:"entity"`
Alias string `json:"alias"`
Description string `json:"description"`
Tags []string `json:"tags,omitempty"`
Details map[string]string `json:"details"`
}
type opsgenieAlertCloseRequest struct {
Source string `json:"source"`
Note string `json:"note"`
}
type AlertProvider struct { type AlertProvider struct {
// APIKey to use for
APIKey string `yaml:"api-key"` APIKey string `yaml:"api-key"`
//Priority define priority to be used in opsgenie alert payload // Priority to be used in Opsgenie alert payload
// defaults: P1 //
// default: P1
Priority string `yaml:"priority"` Priority string `yaml:"priority"`
//Source define source to be used in opsgenie alert payload // Source define source to be used in Opsgenie alert payload
// defaults: gatus //
// default: gatus
Source string `yaml:"source"` Source string `yaml:"source"`
//EntityPrefix is a prefix to be used in entity argument in opsgenie alert payload // EntityPrefix is a prefix to be used in entity argument in Opsgenie alert payload
// defaults: gatus- //
// default: gatus-
EntityPrefix string `yaml:"entity-prefix"` EntityPrefix string `yaml:"entity-prefix"`
//AliasPrefix is a prefix to be used in alias argument in opsgenie alert payload //AliasPrefix is a prefix to be used in alias argument in Opsgenie alert payload
// defaults: gatus-healthcheck- //
// default: gatus-healthcheck-
AliasPrefix string `yaml:"alias-prefix"` AliasPrefix string `yaml:"alias-prefix"`
//tags define tags to be used in opsgenie alert payload // Tags to be used in Opsgenie alert payload
// defaults: [] //
// default: []
Tags []string `yaml:"tags"` Tags []string `yaml:"tags"`
// DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type // DefaultAlert is the default alert configuration to use for endpoints with an alert of the appropriate type
DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"` DefaultAlert *alert.Alert `yaml:"default-alert,omitempty"`
} }
// IsValid returns whether the provider's configuration is valid
func (provider *AlertProvider) IsValid() bool { func (provider *AlertProvider) IsValid() bool {
return len(provider.APIKey) > 0 return len(provider.APIKey) > 0
} }
@ -69,19 +61,15 @@ func (provider *AlertProvider) IsValid() bool {
// Relevant: https://docs.opsgenie.com/docs/alert-api // Relevant: https://docs.opsgenie.com/docs/alert-api
func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error { func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
err := provider.createAlert(endpoint, alert, result, resolved) err := provider.createAlert(endpoint, alert, result, resolved)
if err != nil { if err != nil {
return err return err
} }
if resolved { if resolved {
err = provider.closeAlert(endpoint, alert) err = provider.closeAlert(endpoint, alert)
if err != nil { if err != nil {
return err return err
} }
} }
if alert.IsSendingOnResolved() { if alert.IsSendingOnResolved() {
if resolved { if resolved {
// The alert has been resolved and there's no error, so we can clear the alert's ResolveKey // The alert has been resolved and there's no error, so we can clear the alert's ResolveKey
@ -90,61 +78,46 @@ func (provider *AlertProvider) Send(endpoint *core.Endpoint, alert *alert.Alert,
alert.ResolveKey = provider.alias(buildKey(endpoint)) alert.ResolveKey = provider.alias(buildKey(endpoint))
} }
} }
return nil return nil
} }
func (provider *AlertProvider) createAlert(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error { func (provider *AlertProvider) createAlert(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) error {
payload := provider.buildCreateRequestBody(endpoint, alert, result, resolved) payload := provider.buildCreateRequestBody(endpoint, alert, result, resolved)
_, err := provider.sendRequest(restAPI, http.MethodPost, payload) _, err := provider.sendRequest(restAPI, http.MethodPost, payload)
return err return err
} }
func (provider *AlertProvider) closeAlert(endpoint *core.Endpoint, alert *alert.Alert) error { func (provider *AlertProvider) closeAlert(endpoint *core.Endpoint, alert *alert.Alert) error {
payload := provider.buildCloseRequestBody(endpoint, alert) payload := provider.buildCloseRequestBody(endpoint, alert)
url := restAPI + "/" + provider.alias(buildKey(endpoint)) + "/close?identifierType=alias" url := restAPI + "/" + provider.alias(buildKey(endpoint)) + "/close?identifierType=alias"
_, err := provider.sendRequest(url, http.MethodPost, payload) _, err := provider.sendRequest(url, http.MethodPost, payload)
return err return err
} }
func (provider *AlertProvider) sendRequest(url, method string, payload interface{}) (*http.Response, error) { func (provider *AlertProvider) sendRequest(url, method string, payload interface{}) (*http.Response, error) {
body, err := json.Marshal(payload) body, err := json.Marshal(payload)
if err != nil { if err != nil {
return nil, fmt.Errorf("fail to build alert payload: %v", payload) return nil, fmt.Errorf("fail to build alert payload: %v", payload)
} }
request, err := http.NewRequest(method, url, bytes.NewBuffer(body)) request, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil { if err != nil {
return nil, err return nil, err
} }
request.Header.Set("Content-Type", "application/json") request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", "GenieKey "+provider.APIKey) request.Header.Set("Authorization", "GenieKey "+provider.APIKey)
res, err := client.GetHTTPClient(nil).Do(request) res, err := client.GetHTTPClient(nil).Do(request)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if res.StatusCode > 399 { if res.StatusCode > 399 {
rBody, _ := io.ReadAll(res.Body) rBody, _ := io.ReadAll(res.Body)
return nil, fmt.Errorf("call to provider alert returned status code %d: %s", res.StatusCode, string(rBody)) return nil, fmt.Errorf("call to provider alert returned status code %d: %s", res.StatusCode, string(rBody))
} }
return res, nil return res, nil
} }
func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) opsgenieAlertCreateRequest { func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, alert *alert.Alert, result *core.Result, resolved bool) alertCreateRequest {
var message, description, results string var message, description, results string
if resolved { if resolved {
message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.Name, alert.GetDescription()) message = fmt.Sprintf("RESOLVED: %s - %s", endpoint.Name, alert.GetDescription())
description = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.Name, alert.SuccessThreshold) description = fmt.Sprintf("An alert for *%s* has been resolved after passing successfully %d time(s) in a row", endpoint.Name, alert.SuccessThreshold)
@ -152,12 +125,9 @@ func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, a
message = fmt.Sprintf("%s - %s", endpoint.Name, alert.GetDescription()) message = fmt.Sprintf("%s - %s", endpoint.Name, alert.GetDescription())
description = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", endpoint.Name, alert.FailureThreshold) description = fmt.Sprintf("An alert for *%s* has been triggered due to having failed %d time(s) in a row", endpoint.Name, alert.FailureThreshold)
} }
if endpoint.Group != "" { if endpoint.Group != "" {
message = fmt.Sprintf("[%s] %s", endpoint.Group, message) message = fmt.Sprintf("[%s] %s", endpoint.Group, message)
} }
for _, conditionResult := range result.ConditionResults { for _, conditionResult := range result.ConditionResults {
var prefix string var prefix string
if conditionResult.Success { if conditionResult.Success {
@ -167,9 +137,7 @@ func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, a
} }
results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition) results += fmt.Sprintf("%s - `%s`\n", prefix, conditionResult.Condition)
} }
description = description + "\n" + results description = description + "\n" + results
key := buildKey(endpoint) key := buildKey(endpoint)
details := map[string]string{ details := map[string]string{
"endpoint:url": endpoint.URL, "endpoint:url": endpoint.URL,
@ -179,18 +147,15 @@ func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, a
"result:dns_code": result.DNSRCode, "result:dns_code": result.DNSRCode,
"result:errors": strings.Join(result.Errors, ","), "result:errors": strings.Join(result.Errors, ","),
} }
for k, v := range details { for k, v := range details {
if v == "" { if v == "" {
delete(details, k) delete(details, k)
} }
} }
if result.HTTPStatus > 0 { if result.HTTPStatus > 0 {
details["result:http_status"] = strconv.Itoa(result.HTTPStatus) details["result:http_status"] = strconv.Itoa(result.HTTPStatus)
} }
return alertCreateRequest{
return opsgenieAlertCreateRequest{
Message: message, Message: message,
Description: description, Description: description,
Source: provider.source(), Source: provider.source(),
@ -202,8 +167,8 @@ func (provider *AlertProvider) buildCreateRequestBody(endpoint *core.Endpoint, a
} }
} }
func (provider *AlertProvider) buildCloseRequestBody(endpoint *core.Endpoint, alert *alert.Alert) opsgenieAlertCloseRequest { func (provider *AlertProvider) buildCloseRequestBody(endpoint *core.Endpoint, alert *alert.Alert) alertCloseRequest {
return opsgenieAlertCloseRequest{ return alertCloseRequest{
Source: buildKey(endpoint), Source: buildKey(endpoint),
Note: fmt.Sprintf("RESOLVED: %s - %s", endpoint.Name, alert.GetDescription()), Note: fmt.Sprintf("RESOLVED: %s - %s", endpoint.Name, alert.GetDescription()),
} }
@ -211,21 +176,17 @@ func (provider *AlertProvider) buildCloseRequestBody(endpoint *core.Endpoint, al
func (provider *AlertProvider) source() string { func (provider *AlertProvider) source() string {
source := provider.Source source := provider.Source
if source == "" { if source == "" {
return "gatus" return "gatus"
} }
return source return source
} }
func (provider *AlertProvider) alias(key string) string { func (provider *AlertProvider) alias(key string) string {
alias := provider.AliasPrefix alias := provider.AliasPrefix
if alias == "" { if alias == "" {
alias = "gatus-healthcheck-" alias = "gatus-healthcheck-"
} }
return alias + key return alias + key
} }
@ -234,34 +195,46 @@ func (provider *AlertProvider) entity(key string) string {
if alias == "" { if alias == "" {
alias = "gatus-" alias = "gatus-"
} }
return alias + key return alias + key
} }
func (provider *AlertProvider) priority() string { func (provider *AlertProvider) priority() string {
priority := provider.Priority priority := provider.Priority
if priority == "" { if priority == "" {
return "P1" return "P1"
} }
return priority return priority
} }
// GetDefaultAlert returns the provider's default alert configuration
func (provider AlertProvider) GetDefaultAlert() *alert.Alert { func (provider AlertProvider) GetDefaultAlert() *alert.Alert {
return provider.DefaultAlert return provider.DefaultAlert
} }
func buildKey(endpoint *core.Endpoint) string { func buildKey(endpoint *core.Endpoint) string {
name := toKebabCase(endpoint.Name) name := toKebabCase(endpoint.Name)
if endpoint.Group == "" { if endpoint.Group == "" {
return name return name
} }
return toKebabCase(endpoint.Group) + "-" + name return toKebabCase(endpoint.Group) + "-" + name
} }
func toKebabCase(val string) string { func toKebabCase(val string) string {
return strings.ToLower(strings.ReplaceAll(val, " ", "-")) return strings.ToLower(strings.ReplaceAll(val, " ", "-"))
} }
type alertCreateRequest struct {
Message string `json:"message"`
Priority string `json:"priority"`
Source string `json:"source"`
Entity string `json:"entity"`
Alias string `json:"alias"`
Description string `json:"description"`
Tags []string `json:"tags,omitempty"`
Details map[string]string `json:"details"`
}
type alertCloseRequest struct {
Source string `json:"source"`
Note string `json:"note"`
}

View File

@ -1,13 +1,14 @@
package opsgenie package opsgenie
import ( import (
"net/http"
"reflect"
"testing"
"github.com/TwiN/gatus/v3/alerting/alert" "github.com/TwiN/gatus/v3/alerting/alert"
"github.com/TwiN/gatus/v3/client" "github.com/TwiN/gatus/v3/client"
"github.com/TwiN/gatus/v3/core" "github.com/TwiN/gatus/v3/core"
"github.com/TwiN/gatus/v3/test" "github.com/TwiN/gatus/v3/test"
"net/http"
"reflect"
"testing"
) )
func TestAlertProvider_IsValid(t *testing.T) { func TestAlertProvider_IsValid(t *testing.T) {
@ -23,9 +24,7 @@ func TestAlertProvider_IsValid(t *testing.T) {
func TestAlertProvider_Send(t *testing.T) { func TestAlertProvider_Send(t *testing.T) {
defer client.InjectHTTPClient(nil) defer client.InjectHTTPClient(nil)
description := "my bad alert description" description := "my bad alert description"
scenarios := []struct { scenarios := []struct {
Name string Name string
Provider AlertProvider Provider AlertProvider
@ -79,7 +78,6 @@ func TestAlertProvider_Send(t *testing.T) {
for _, scenario := range scenarios { for _, scenario := range scenarios {
t.Run(scenario.Name, func(t *testing.T) { t.Run(scenario.Name, func(t *testing.T) {
client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper}) client.InjectHTTPClient(&http.Client{Transport: scenario.MockRoundTripper})
err := scenario.Provider.Send( err := scenario.Provider.Send(
&core.Endpoint{Name: "endpoint-name"}, &core.Endpoint{Name: "endpoint-name"},
&scenario.Alert, &scenario.Alert,
@ -103,9 +101,7 @@ func TestAlertProvider_Send(t *testing.T) {
func TestAlertProvider_buildCreateRequestBody(t *testing.T) { func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
t.Parallel() t.Parallel()
description := "alert description" description := "alert description"
scenarios := []struct { scenarios := []struct {
Name string Name string
Provider *AlertProvider Provider *AlertProvider
@ -113,7 +109,7 @@ func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
Endpoint *core.Endpoint Endpoint *core.Endpoint
Result *core.Result Result *core.Result
Resolved bool Resolved bool
want opsgenieAlertCreateRequest want alertCreateRequest
}{ }{
{ {
Name: "missing all params (unresolved)", Name: "missing all params (unresolved)",
@ -122,7 +118,7 @@ func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
Endpoint: &core.Endpoint{}, Endpoint: &core.Endpoint{},
Result: &core.Result{}, Result: &core.Result{},
Resolved: false, Resolved: false,
want: opsgenieAlertCreateRequest{ want: alertCreateRequest{
Message: " - ", Message: " - ",
Priority: "P1", Priority: "P1",
Source: "gatus", Source: "gatus",
@ -140,7 +136,7 @@ func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
Endpoint: &core.Endpoint{}, Endpoint: &core.Endpoint{},
Result: &core.Result{}, Result: &core.Result{},
Resolved: true, Resolved: true,
want: opsgenieAlertCreateRequest{ want: alertCreateRequest{
Message: "RESOLVED: - ", Message: "RESOLVED: - ",
Priority: "P1", Priority: "P1",
Source: "gatus", Source: "gatus",
@ -174,7 +170,7 @@ func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
}, },
}, },
Resolved: false, Resolved: false,
want: opsgenieAlertCreateRequest{ want: alertCreateRequest{
Message: "my supper app - " + description, Message: "my supper app - " + description,
Priority: "P1", Priority: "P1",
Source: "gatus", Source: "gatus",
@ -212,7 +208,7 @@ func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
}, },
}, },
Resolved: true, Resolved: true,
want: opsgenieAlertCreateRequest{ want: alertCreateRequest{
Message: "RESOLVED: my mega app - " + description, Message: "RESOLVED: my mega app - " + description,
Priority: "P5", Priority: "P5",
Source: "gatus-hc", Source: "gatus-hc",
@ -251,7 +247,7 @@ func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
}, },
}, },
Resolved: false, Resolved: false,
want: opsgenieAlertCreateRequest{ want: alertCreateRequest{
Message: "[end game] my app - " + description, Message: "[end game] my app - " + description,
Priority: "P1", Priority: "P1",
Source: "gatus", Source: "gatus",
@ -270,7 +266,6 @@ func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
}, },
}, },
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
actual := scenario actual := scenario
t.Run(actual.Name, func(t *testing.T) { t.Run(actual.Name, func(t *testing.T) {
@ -283,27 +278,24 @@ func TestAlertProvider_buildCreateRequestBody(t *testing.T) {
func TestAlertProvider_buildCloseRequestBody(t *testing.T) { func TestAlertProvider_buildCloseRequestBody(t *testing.T) {
t.Parallel() t.Parallel()
description := "alert description" description := "alert description"
scenarios := []struct { scenarios := []struct {
Name string Name string
Provider *AlertProvider Provider *AlertProvider
Alert *alert.Alert Alert *alert.Alert
Endpoint *core.Endpoint Endpoint *core.Endpoint
want opsgenieAlertCloseRequest want alertCloseRequest
}{ }{
{ {
Name: "Missing all values", Name: "Missing all values",
Provider: &AlertProvider{}, Provider: &AlertProvider{},
Alert: &alert.Alert{}, Alert: &alert.Alert{},
Endpoint: &core.Endpoint{}, Endpoint: &core.Endpoint{},
want: opsgenieAlertCloseRequest{ want: alertCloseRequest{
Source: "", Source: "",
Note: "RESOLVED: - ", Note: "RESOLVED: - ",
}, },
}, },
{ {
Name: "Basic values", Name: "Basic values",
Provider: &AlertProvider{}, Provider: &AlertProvider{},
@ -313,7 +305,7 @@ func TestAlertProvider_buildCloseRequestBody(t *testing.T) {
Endpoint: &core.Endpoint{ Endpoint: &core.Endpoint{
Name: "endpoint name", Name: "endpoint name",
}, },
want: opsgenieAlertCloseRequest{ want: alertCloseRequest{
Source: "endpoint-name", Source: "endpoint-name",
Note: "RESOLVED: endpoint name - alert description", Note: "RESOLVED: endpoint name - alert description",
}, },