2024-11-26 13:37:13 -06:00
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
2025-08-20 23:00:10 -07:00
|
|
|
"log"
|
2024-11-26 13:37:13 -06:00
|
|
|
"net/http"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type pdAlert struct {
|
|
|
|
|
RoutingKey string `json:"routing_key"`
|
|
|
|
|
EventAction string `json:"event_action"`
|
|
|
|
|
Payload pdPayload `json:"payload"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type pdPayload struct {
|
|
|
|
|
Summary string `json:"summary"`
|
|
|
|
|
Source string `json:"source"`
|
|
|
|
|
Severity string `json:"severity"`
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-20 23:18:40 -07:00
|
|
|
type pdResponse struct {
|
|
|
|
|
DedupKey string `json:"dedup_key"`
|
|
|
|
|
Message string `json:"message"`
|
|
|
|
|
Status string `json:"status"`
|
|
|
|
|
}
|
|
|
|
|
|
2024-11-26 13:37:13 -06:00
|
|
|
type pdClient struct {
|
|
|
|
|
c *http.Client
|
|
|
|
|
routingKey string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func newPDClient(routingKey string) *pdClient {
|
|
|
|
|
return &pdClient{
|
|
|
|
|
c: &http.Client{},
|
|
|
|
|
routingKey: routingKey,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (pd *pdClient) sendAlert(msg string) error {
|
|
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
|
err := json.NewEncoder(buf).Encode(pdAlert{
|
|
|
|
|
RoutingKey: pd.routingKey,
|
|
|
|
|
EventAction: "trigger",
|
|
|
|
|
Payload: pdPayload{
|
|
|
|
|
Summary: msg,
|
|
|
|
|
Source: "p",
|
|
|
|
|
Severity: "critical",
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
2024-11-26 14:37:24 -06:00
|
|
|
return err
|
2024-11-26 13:37:13 -06:00
|
|
|
}
|
|
|
|
|
|
2025-08-20 23:00:10 -07:00
|
|
|
log.Printf("[->pagerduty] %s", buf.String())
|
|
|
|
|
|
2024-11-26 13:37:13 -06:00
|
|
|
req, err := http.NewRequest("POST", "https://events.pagerduty.com/v2/enqueue", buf)
|
|
|
|
|
if err != nil {
|
2024-11-26 14:37:24 -06:00
|
|
|
return err
|
2024-11-26 13:37:13 -06:00
|
|
|
}
|
|
|
|
|
|
2024-11-26 14:37:24 -06:00
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
|
|
2024-11-26 13:37:13 -06:00
|
|
|
resp, err := pd.c.Do(req)
|
|
|
|
|
if err != nil {
|
2024-11-26 14:37:24 -06:00
|
|
|
return err
|
2024-11-26 13:37:13 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
body, _ := io.ReadAll(resp.Body)
|
|
|
|
|
|
|
|
|
|
if resp.StatusCode != 202 {
|
2024-11-26 14:37:24 -06:00
|
|
|
return fmt.Errorf("%s", string(body))
|
2024-11-26 13:37:13 -06:00
|
|
|
}
|
|
|
|
|
|
2025-08-20 23:00:10 -07:00
|
|
|
log.Printf("[<-pagerduty] %s", string(body))
|
|
|
|
|
|
2025-08-20 23:18:40 -07:00
|
|
|
pdResp := pdResponse{}
|
|
|
|
|
err = json.Unmarshal(body, &pdResp)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if pdResp.Status != "success" {
|
|
|
|
|
return fmt.Errorf("%s: %s", pdResp.Status, pdResp.Message)
|
|
|
|
|
}
|
|
|
|
|
|
2024-11-26 13:37:13 -06:00
|
|
|
return nil
|
|
|
|
|
}
|