Debian Codegraph @

pkg/services/incident/pagerduty/pagerduty.go

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