Debian Codegraph @

pkg/services/incident/pagerduty/pagerduty.go

raw
1 package pagerduty
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "strings"
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 PagerDuty as a notification service.
20 type Service struct {
21 standard.Standard
22
23 Config *Config
24 pkr format.PropKeyResolver
25 httpClient types.HTTPClient
26 }
27
28 const (
29 eventEndpointTemplate = "https://%s:%d/v2/enqueue"
30 defaultHTTPTimeout = 30 * time.Second // defaultHTTPTimeout is the default timeout for HTTP requests.
31 maxMessageLength = 1024 // maxMessageLength is the maximum permitted length of the summary property.
32
33 contextTypeLink = "link"
34 contextTypeImage = "image"
35 )
36
37 // GetID returns the service identifier.
38 func (s *Service) GetID() string {
39 return Scheme
40 }
41
42 // Initialize loads ServiceConfig from serviceURL and sets logger for this Service.
43 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
44 s.SetLogger(logger)
45 s.Config = &Config{}
46 s.pkr = format.NewPropKeyResolver(s.Config)
47
48 if err := s.setDefaults(); err != nil {
49 return err
50 }
51
52 if err := s.Config.setURL(&s.pkr, serviceURL); err != nil {
53 return err
54 }
55
56 if s.httpClient == nil {
57 // Initialize HTTP client with timeout
58 s.httpClient = &http.Client{
59 Timeout: defaultHTTPTimeout,
60 }
61 }
62
63 return nil
64 }
65
66 // Send a notification message to PagerDuty
67 // See: https://developer.pagerduty.com/docs/events-api-v2-overview
68 func (s *Service) Send(message string, params *types.Params) error {
69 return s.SendWithContext(context.Background(), message, params)
70 }
71
72 // SendWithContext sends a notification message to PagerDuty with context support
73 // See: https://developer.pagerduty.com/docs/events-api-v2-overview
74 func (s *Service) SendWithContext(
75 ctx context.Context,
76 message string,
77 params *types.Params,
78 ) error {
79 config := s.Config
80 endpointURL := fmt.Sprintf(eventEndpointTemplate, config.Host, config.Port)
81
82 payload, err := s.newEventPayload(message, params)
83 if err != nil {
84 return err
85 }
86
87 return s.sendAlert(ctx, endpointURL, &payload)
88 }
89
90 // ServiceTimeout returns the HTTP timeout used for a PagerDuty send.
91 func (*Service) ServiceTimeout(*types.Params) time.Duration {
92 return defaultHTTPTimeout
93 }
94
95 // SetHTTPClient allows users to provide a custom HTTP client for enterprise environments
96 // requiring proxies, custom TLS configurations, etc.
97 func (s *Service) SetHTTPClient(client types.HTTPClient) {
98 if client == nil {
99 s.httpClient = &http.Client{Timeout: defaultHTTPTimeout}
100
101 return
102 }
103
104 s.httpClient = client
105 }
106
107 func (s *Service) newEventPayload(
108 message string,
109 params *types.Params,
110 ) (EventPayload, error) {
111 if params == nil {
112 params = &types.Params{}
113 }
114
115 // Defensive copy
116 payloadFields := *s.Config
117
118 if err := s.pkr.UpdateConfigFromParams(&payloadFields, params); err != nil {
119 return EventPayload{}, fmt.Errorf("failed to update config from params: %w", err)
120 }
121
122 // Validate severity
123 if err := validateSeverity(payloadFields.Severity); err != nil {
124 return EventPayload{}, err
125 }
126
127 // Validate event action
128 if err := validateEventAction(payloadFields.Action); err != nil {
129 return EventPayload{}, err
130 }
131
132 // The maximum permitted length of this property is 1024 characters.
133 runes := []rune(message)
134 if len(runes) > maxMessageLength {
135 message = string(runes[:maxMessageLength])
136 }
137
138 result := EventPayload{
139 Payload: Payload{
140 Summary: message,
141 Severity: payloadFields.Severity,
142 Source: payloadFields.Source,
143 },
144 RoutingKey: payloadFields.IntegrationKey,
145 EventAction: payloadFields.Action,
146 }
147
148 // Add optional dedup_key if provided
149 if payloadFields.DedupKey != "" {
150 result.DedupKey = payloadFields.DedupKey
151 }
152
153 // Add optional fields if provided
154 if payloadFields.Details != "" {
155 var details any
156 if err := json.Unmarshal([]byte(payloadFields.Details), &details); err != nil {
157 return EventPayload{}, fmt.Errorf(
158 "failed to unmarshal details %q: %w",
159 payloadFields.Details,
160 err,
161 )
162 }
163
164 result.Details = details
165 }
166
167 if payloadFields.Client != "" {
168 result.Client = payloadFields.Client
169 }
170
171 if payloadFields.ClientURL != "" {
172 result.ClientURL = payloadFields.ClientURL
173 }
174
175 if payloadFields.Contexts != "" {
176 contexts, err := parseContexts(payloadFields.Contexts)
177 if err != nil {
178 return EventPayload{}, fmt.Errorf("failed to parse contexts: %w", err)
179 }
180
181 result.Contexts = contexts
182 }
183
184 return result, nil
185 }
186
187 // sendAlert sends an alert payload to the specified PagerDuty endpoint URL.
188 func (s *Service) sendAlert(ctx context.Context, endpoint string, payload *EventPayload) error {
189 // Marshal the payload into JSON format
190 jsonBody, err := json.Marshal(payload)
191 if err != nil {
192 return fmt.Errorf("failed to marshal payload: %w", err)
193 }
194
195 jsonBuffer := bytes.NewBuffer(jsonBody)
196
197 // Create a new HTTP POST request with the JSON body
198 req, err := http.NewRequestWithContext(
199 ctx,
200 http.MethodPost,
201 endpoint,
202 jsonBuffer,
203 )
204 if err != nil {
205 return fmt.Errorf("failed to create HTTP request: %w", err)
206 }
207
208 // Set the Content-Type header to application/json
209 req.Header.Add("Content-Type", "application/json")
210
211 // Use the custom HTTP client
212 if s.httpClient == nil {
213 return errServiceNotInitialized
214 }
215
216 // Send the HTTP request to PagerDuty
217 resp, err := s.httpClient.Do(req)
218 if err != nil {
219 return fmt.Errorf("failed to send notification to PagerDuty: %w", err)
220 }
221
222 defer func() { _ = resp.Body.Close() }()
223
224 // Check if the response status indicates success (2xx)
225 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
226 // Parse error response body for better error reporting
227 errorMsg := fmt.Sprintf("HTTP %d", resp.StatusCode)
228 if resp.Body != nil {
229 bodyBytes, err := io.ReadAll(resp.Body)
230 if err == nil && len(bodyBytes) > 0 {
231 // Try to parse as PagerDuty error response
232 var errorResponse struct {
233 Status string `json:"status"`
234 Message string `json:"message"`
235 Error string `json:"error"`
236 Errors []string `json:"errors"`
237 }
238 if jsonErr := json.Unmarshal(bodyBytes, &errorResponse); jsonErr == nil {
239 switch {
240 case errorResponse.Message != "":
241 errorMsg = errorResponse.Message
242 case errorResponse.Error != "":
243 errorMsg = errorResponse.Error
244 case len(errorResponse.Errors) > 0:
245 errorMsg = strings.Join(errorResponse.Errors, "; ")
246 }
247 } else {
248 // Fallback to raw body if JSON parsing fails
249 errorMsg = string(bodyBytes)
250 }
251 }
252 }
253
254 return fmt.Errorf("%w: %s", errPagerDutyNotificationFailed, errorMsg)
255 }
256
257 return nil
258 }
259
260 func (s *Service) setDefaults() error {
261 if err := s.pkr.SetDefaultProps(s.Config); err != nil {
262 return fmt.Errorf("failed to set default props: %w", err)
263 }
264
265 return nil
266 }
267
268 // parseContexts parses contexts from either a JSON array format or legacy comma-separated string format.
269 // It first attempts to unmarshal the input as a JSON array of PagerDutyContext objects.
270 // If JSON unmarshaling fails, it falls back to parsing the legacy string format like "type:src,type2:src2".
271 // Legacy format supports:
272 // - "link:http://example.com" -> {Type: "link", Href: "http://example.com"}
273 // - "image:http://example.com/img.png" -> {Type: "image", Src: "http://example.com/img.png"}.
274 func parseContexts(contextsStr string) ([]PagerDutyContext, error) {
275 if contextsStr == "" {
276 return nil, nil
277 }
278
279 // First, attempt to parse as JSON array
280 var result []PagerDutyContext
281 if err := json.Unmarshal([]byte(contextsStr), &result); err == nil {
282 // Validate Type field and required fields for each context in JSON format
283 for _, ctx := range result {
284 if ctx.Type != contextTypeLink && ctx.Type != contextTypeImage {
285 return nil, fmt.Errorf("%w: found %q", errInvalidContextType, ctx.Type)
286 }
287
288 if ctx.Type == contextTypeLink && ctx.Href == "" {
289 return nil, fmt.Errorf("%w: %+v", errMissingHrefForLinkContext, ctx)
290 }
291
292 if ctx.Type == contextTypeImage && ctx.Src == "" {
293 return nil, fmt.Errorf("%w: %+v", errMissingSrcForImageContext, ctx)
294 }
295 }
296
297 return result, nil
298 }
299
300 // Fall back to legacy comma-separated parsing
301 // Split the input string by commas to get individual context entries
302 contexts := strings.Split(contextsStr, ",")
303 result = make([]PagerDutyContext, 0, len(contexts))
304
305 for _, ctx := range contexts {
306 // Trim whitespace from each context entry
307 ctx = strings.TrimSpace(ctx)
308 if ctx == "" {
309 continue
310 }
311
312 const expectedParts = 2
313
314 // Split each context by colon to separate type and value, limiting to 2 parts
315 parts := strings.SplitN(ctx, ":", expectedParts)
316 if len(parts) != expectedParts {
317 return nil, fmt.Errorf("%w: %q", errInvalidContextFormat, ctx)
318 }
319
320 // Trim whitespace from type and value parts
321 contextType := strings.TrimSpace(parts[0])
322 value := strings.TrimSpace(parts[1])
323
324 // Validate that neither type nor value is empty after trimming
325 if contextType == "" || value == "" {
326 return nil, fmt.Errorf("%w: %q", errEmptyContextTypeOrValue, ctx)
327 }
328
329 var ctxVar PagerDutyContext
330
331 // Map context types to appropriate PagerDutyContext fields
332 switch contextType {
333 case "link":
334 // Create a link context with href
335 //nolint:exhaustruct_v5 // link type only needs Type+Href
336 ctxVar = PagerDutyContext{Type: "link", Href: value}
337 case "image":
338 // Create an image context with src
339 //nolint:exhaustruct_v5 // image type only needs Type+Src
340 ctxVar = PagerDutyContext{Type: "image", Src: value}
341 case "text":
342 // Skip text contexts
343 continue
344 default:
345 return nil, fmt.Errorf(
346 "%w: unsupported context type %q",
347 errInvalidContextFormat,
348 contextType,
349 )
350 }
351
352 // Add the parsed context to the result slice
353 result = append(result, ctxVar)
354 }
355
356 return result, nil
357 }
358
359 // validateSeverity checks if the provided severity is one of the allowed values.
360 func validateSeverity(severity string) error {
361 validSeverities := map[string]bool{
362 "critical": true,
363 "error": true,
364 "warning": true,
365 "info": true,
366 }
367
368 if !validSeverities[severity] {
369 return errInvalidSeverity
370 }
371
372 return nil
373 }
374
375 // validateEventAction checks if the provided event action is one of the allowed values.
376 func validateEventAction(action string) error {
377 validActions := map[string]bool{
378 "trigger": true,
379 "acknowledge": true,
380 "resolve": true,
381 }
382
383 if !validActions[action] {
384 return errInvalidEventAction
385 }
386
387 return nil
388 }