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