Debian Codegraph @

pkg/services/incident/opsgenie/opsgenie.go

raw
1 package opsgenie
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "net/url"
12 "time"
13
14 "github.com/nicholas-fedor/shoutrrr/pkg/format"
15 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
16 "github.com/nicholas-fedor/shoutrrr/pkg/types"
17 )
18
19 // Service provides OpsGenie as a notification service.
20 type Service struct {
21 standard.Standard
22
23 Config *Config
24 pkr format.PropKeyResolver
25 }
26
27 // alertEndpointTemplate is the OpsGenie API endpoint template for sending alerts.
28 const (
29 alertEndpointTemplate = "https://%s:%d/v2/alerts"
30 MaxMessageLength = 130 // MaxMessageLength is the maximum length of the alert message field in OpsGenie.
31 httpSuccessMax = 299 // httpSuccessMax is the maximum HTTP status code for a successful response.
32 defaultHTTPTimeout = 10 * time.Second // defaultHTTPTimeout is the default timeout for HTTP requests.
33 )
34
35 // ErrUnexpectedStatus indicates that OpsGenie returned an unexpected HTTP status code.
36 var ErrUnexpectedStatus = errors.New("OpsGenie notification returned unexpected HTTP status code")
37
38 // GetID returns the service identifier.
39 func (s *Service) GetID() string {
40 return Scheme
41 }
42
43 // Initialize configures the service with a URL and logger.
44 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
45 s.SetLogger(logger)
46 s.Config = &Config{}
47 s.pkr = format.NewPropKeyResolver(s.Config)
48
49 return s.Config.setURL(&s.pkr, serviceURL)
50 }
51
52 // Send delivers a notification message to OpsGenie.
53 // See: https://docs.opsgenie.com/docs/alert-api#create-alert
54 func (s *Service) Send(message string, params *types.Params) error {
55 config := s.Config
56 serviceURL := fmt.Sprintf(
57 alertEndpointTemplate,
58 config.Host,
59 config.Port,
60 )
61
62 payload, err := s.newAlertPayload(message, params)
63 if err != nil {
64 return err
65 }
66
67 return s.sendAlert(serviceURL, config.APIKey, &payload)
68 }
69
70 // newAlertPayload creates a new alert payload for OpsGenie based on the message and parameters.
71 func (s *Service) newAlertPayload(
72 message string,
73 params *types.Params,
74 ) (AlertPayload, error) {
75 if params == nil {
76 params = &types.Params{}
77 }
78
79 // Defensive copy
80 payloadFields := *s.Config
81
82 if err := s.pkr.UpdateConfigFromParams(&payloadFields, params); err != nil {
83 return AlertPayload{}, fmt.Errorf("updating payload fields from params: %w", err)
84 }
85
86 // Use `Message` for the title if available, or if the message is too long
87 // Use `Description` for the message in these scenarios
88 title := payloadFields.Title
89 description := message
90
91 if title == "" {
92 if len(message) > MaxMessageLength {
93 title = message[:MaxMessageLength]
94 } else {
95 title = message
96 description = ""
97 }
98 }
99
100 if payloadFields.Description != "" && description != "" {
101 description += "\n"
102 }
103
104 result := AlertPayload{
105 Message: title,
106 Alias: payloadFields.Alias,
107 Description: description + payloadFields.Description,
108 Responders: payloadFields.Responders,
109 VisibleTo: payloadFields.VisibleTo,
110 Actions: payloadFields.Actions,
111 Tags: payloadFields.Tags,
112 Details: payloadFields.Details,
113 Entity: payloadFields.Entity,
114 Source: payloadFields.Source,
115 Priority: payloadFields.Priority,
116 User: payloadFields.User,
117 Note: payloadFields.Note,
118 }
119
120 return result, nil
121 }
122
123 // sendAlert sends an alert to OpsGenie using the specified URL and API key.
124 func (s *Service) sendAlert(serviceURL, apiKey string, payload *AlertPayload) error {
125 jsonBody, err := json.Marshal(payload)
126 if err != nil {
127 return fmt.Errorf("marshaling alert payload to JSON: %w", err)
128 }
129
130 jsonBuffer := bytes.NewBuffer(jsonBody)
131
132 ctx, cancel := context.WithTimeout(
133 context.Background(),
134 defaultHTTPTimeout,
135 )
136 defer cancel()
137
138 req, err := http.NewRequestWithContext(
139 ctx,
140 http.MethodPost,
141 serviceURL,
142 jsonBuffer,
143 )
144 if err != nil {
145 return fmt.Errorf("creating HTTP request: %w", err)
146 }
147
148 req.Header.Add("Authorization", "GenieKey "+apiKey)
149 req.Header.Add("Content-Type", "application/json")
150
151 resp, err := http.DefaultClient.Do(req)
152 if err != nil {
153 return fmt.Errorf("failed to send notification to OpsGenie: %w", err)
154 }
155
156 defer func() { _ = resp.Body.Close() }()
157
158 if resp.StatusCode < http.StatusOK || resp.StatusCode > httpSuccessMax {
159 body, err := io.ReadAll(resp.Body)
160 if err != nil {
161 return fmt.Errorf(
162 "%w: %d, cannot read body: %w",
163 ErrUnexpectedStatus,
164 resp.StatusCode,
165 err,
166 )
167 }
168
169 return fmt.Errorf(
170 "%w: %d - %s",
171 ErrUnexpectedStatus,
172 resp.StatusCode,
173 body,
174 )
175 }
176
177 return nil
178 }