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