github.com/newrelic/newrelic-client-go@v1.1.0/pkg/alerts/conditions.go (about) 1 package alerts 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/newrelic/newrelic-client-go/pkg/errors" 8 ) 9 10 // ConditionType specifies the condition type used when creating the alert condition. 11 type ConditionType string 12 13 var ( 14 // ConditionTypes enumerates the possible condition types for an alert condition. 15 ConditionTypes = struct { 16 APMApplicationMetric ConditionType 17 APMKeyTransactionMetric ConditionType 18 ServersMetric ConditionType 19 BrowserMetric ConditionType 20 MobileMetric ConditionType 21 }{ 22 APMApplicationMetric: "apm_app_metric", 23 APMKeyTransactionMetric: "apm_kt_metric", 24 ServersMetric: "servers_metric", 25 BrowserMetric: "browser_metric", 26 MobileMetric: "mobile_metric", 27 } 28 ) 29 30 // MetricType specifies the metric type used when creating the alert condition. 31 type MetricType string 32 33 var ( 34 // MetricTypes enumerates the possible metric types for an alert condition. 35 // Not all metric types are valid for all condition types. See the docuentation for more details. 36 MetricTypes = struct { 37 AjaxResponseTime MetricType 38 AjaxThroughput MetricType 39 Apdex MetricType 40 CPUPercentage MetricType 41 Database MetricType 42 DiskIOPercentage MetricType 43 DomProcessing MetricType 44 EndUserApdex MetricType 45 ErrorCount MetricType 46 ErrorPercentage MetricType 47 FullestDiskPercentage MetricType 48 Images MetricType 49 JSON MetricType 50 LoadAverageOneMinute MetricType 51 MemoryPercentage MetricType 52 MobileCrashRate MetricType 53 Network MetricType 54 NetworkErrorPercentage MetricType 55 PageRendering MetricType 56 PageViewThroughput MetricType 57 PageViewsWithJsErrors MetricType 58 RequestQueuing MetricType 59 ResponseTime MetricType 60 ResponseTimeBackground MetricType 61 ResponseTimeWeb MetricType 62 StatusErrorPercentage MetricType 63 Throughput MetricType 64 ThroughputBackground MetricType 65 ThroughputWeb MetricType 66 TotalPageLoad MetricType 67 UserDefined MetricType 68 ViewLoading MetricType 69 WebApplication MetricType 70 }{ 71 AjaxResponseTime: "ajax_response_time", 72 AjaxThroughput: "ajax_throughput", 73 Apdex: "apdex", 74 CPUPercentage: "cpu_percentage", 75 Database: "database", 76 DiskIOPercentage: "disk_io_percentage", 77 DomProcessing: "dom_processing", 78 EndUserApdex: "end_user_apdex", 79 ErrorCount: "error_count", 80 ErrorPercentage: "error_percentage", 81 FullestDiskPercentage: "fullest_disk_percentage", 82 Images: "images", 83 JSON: "json", 84 LoadAverageOneMinute: "load_average_one_minute", 85 MemoryPercentage: "memory_percentage", 86 MobileCrashRate: "mobile_crash_rate", 87 Network: "network", 88 NetworkErrorPercentage: "network_error_percentage", 89 PageRendering: "page_rendering", 90 PageViewThroughput: "page_view_throughput", 91 PageViewsWithJsErrors: "page_views_with_js_errors", 92 RequestQueuing: "request_queuing", 93 ResponseTime: "response_time", 94 ResponseTimeBackground: "response_time_background", 95 ResponseTimeWeb: "response_time_web", 96 StatusErrorPercentage: "status_error_percentage", 97 Throughput: "throughput", 98 ThroughputBackground: "throughput_background", 99 ThroughputWeb: "throughput_web", 100 TotalPageLoad: "total_page_load", 101 UserDefined: "user_defined", 102 ViewLoading: "view_loading", 103 WebApplication: "web_application", 104 } 105 ) 106 107 // OperatorType specifies the operator for alert condition terms. 108 type OperatorType string 109 110 var ( 111 // OperatorTypes enumerates the possible operator values for alert condition terms. 112 OperatorTypes = struct { 113 Above OperatorType 114 Below OperatorType 115 Equal OperatorType 116 }{ 117 Above: "above", 118 Below: "below", 119 Equal: "equal", 120 } 121 ) 122 123 // PriorityType specifies the priority for alert condition terms. 124 type PriorityType string 125 126 var ( 127 // PriorityTypes enumerates the possible priority values for alert condition terms. 128 PriorityTypes = struct { 129 Critical PriorityType 130 Warning PriorityType 131 }{ 132 Critical: "critical", 133 Warning: "warning", 134 } 135 ) 136 137 // TimeFunctionType specifies the time function to be used for alert condition terms. 138 type TimeFunctionType string 139 140 var ( 141 // TimeFunctionTypes enumerates the possible time function types for alert condition terms. 142 TimeFunctionTypes = struct { 143 All TimeFunctionType 144 Any TimeFunctionType 145 }{ 146 All: "all", 147 Any: "any", 148 } 149 ) 150 151 // ValueFunctionType specifies the value function to be used for returning custom metric data. 152 type ValueFunctionType string 153 154 var ( 155 // ValueFunctionTypes enumerates the possible value function types for custom metrics. 156 ValueFunctionTypes = struct { 157 Average ValueFunctionType 158 Min ValueFunctionType 159 Max ValueFunctionType 160 Total ValueFunctionType 161 SampleSize ValueFunctionType 162 SingleValue ValueFunctionType 163 }{ 164 Average: "average", 165 Min: "min", 166 Max: "max", 167 Total: "total", 168 SampleSize: "sample_size", 169 SingleValue: "single_value", 170 } 171 ) 172 173 // Condition represents a New Relic alert condition. 174 // TODO: custom unmarshal entities to ints? 175 type Condition struct { 176 ID int `json:"id,omitempty"` 177 Type ConditionType `json:"type,omitempty"` 178 Name string `json:"name,omitempty"` 179 Enabled bool `json:"enabled"` 180 Entities []string `json:"entities,omitempty"` 181 Metric MetricType `json:"metric,omitempty"` 182 RunbookURL string `json:"runbook_url"` 183 Terms []ConditionTerm `json:"terms,omitempty"` 184 UserDefined ConditionUserDefined `json:"user_defined,omitempty"` 185 Scope string `json:"condition_scope,omitempty"` 186 GCMetric string `json:"gc_metric,omitempty"` 187 ViolationCloseTimer int `json:"violation_close_timer,omitempty"` 188 } 189 190 // ConditionUserDefined represents user defined metrics for the New Relic alert condition. 191 type ConditionUserDefined struct { 192 Metric string `json:"metric,omitempty"` 193 ValueFunction ValueFunctionType `json:"value_function,omitempty"` 194 } 195 196 // ConditionTerm represents the terms of a New Relic alert condition. 197 type ConditionTerm struct { 198 Duration int `json:"duration,string,omitempty"` 199 Operator OperatorType `json:"operator,omitempty"` 200 Priority PriorityType `json:"priority,omitempty"` 201 Threshold float64 `json:"threshold,string"` 202 TimeFunction TimeFunctionType `json:"time_function,omitempty"` 203 } 204 205 // ListConditions returns alert conditions for a specified policy. 206 func (a *Alerts) ListConditions(policyID int) ([]*Condition, error) { 207 return a.ListConditionsWithContext(context.Background(), policyID) 208 } 209 210 // ListConditionsWithContext returns alert conditions for a specified policy. 211 func (a *Alerts) ListConditionsWithContext(ctx context.Context, policyID int) ([]*Condition, error) { 212 alertConditions := []*Condition{} 213 queryParams := listConditionsParams{ 214 PolicyID: policyID, 215 } 216 217 nextURL := a.config.Region().RestURL("/alerts_conditions.json") 218 219 for nextURL != "" { 220 response := alertConditionsResponse{} 221 resp, err := a.client.GetWithContext(ctx, nextURL, &queryParams, &response) 222 223 if err != nil { 224 return nil, err 225 } 226 227 alertConditions = append(alertConditions, response.Conditions...) 228 229 paging := a.pager.Parse(resp) 230 nextURL = paging.Next 231 } 232 233 return alertConditions, nil 234 } 235 236 // GetCondition gets an alert condition for a specified policy ID and condition ID. 237 func (a *Alerts) GetCondition(policyID int, id int) (*Condition, error) { 238 return a.GetConditionWithContext(context.Background(), policyID, id) 239 } 240 241 // GetConditionWithContext gets an alert condition for a specified policy ID and condition ID. 242 func (a *Alerts) GetConditionWithContext(ctx context.Context, policyID int, id int) (*Condition, error) { 243 conditions, err := a.ListConditionsWithContext(ctx, policyID) 244 if err != nil { 245 return nil, err 246 } 247 248 for _, condition := range conditions { 249 if condition.ID == id { 250 return condition, nil 251 } 252 } 253 254 return nil, errors.NewNotFoundf("no condition found for policy %d and condition ID %d", policyID, id) 255 } 256 257 // CreateCondition creates an alert condition for a specified policy. 258 func (a *Alerts) CreateCondition(policyID int, condition Condition) (*Condition, error) { 259 return a.CreateConditionWithContext(context.Background(), policyID, condition) 260 } 261 262 // CreateConditionWithContext creates an alert condition for a specified policy. 263 func (a *Alerts) CreateConditionWithContext(ctx context.Context, policyID int, condition Condition) (*Condition, error) { 264 reqBody := alertConditionRequestBody{ 265 Condition: condition, 266 } 267 resp := alertConditionResponse{} 268 269 url := fmt.Sprintf("/alerts_conditions/policies/%d.json", policyID) 270 _, err := a.client.PostWithContext(ctx, a.config.Region().RestURL(url), nil, &reqBody, &resp) 271 272 if err != nil { 273 return nil, err 274 } 275 276 return &resp.Condition, nil 277 } 278 279 // UpdateCondition updates an alert condition. 280 func (a *Alerts) UpdateCondition(condition Condition) (*Condition, error) { 281 return a.UpdateConditionWithContext(context.Background(), condition) 282 } 283 284 // UpdateConditionWithContext updates an alert condition. 285 func (a *Alerts) UpdateConditionWithContext(ctx context.Context, condition Condition) (*Condition, error) { 286 reqBody := alertConditionRequestBody{ 287 Condition: condition, 288 } 289 resp := alertConditionResponse{} 290 291 url := fmt.Sprintf("/alerts_conditions/%d.json", condition.ID) 292 _, err := a.client.PutWithContext(ctx, a.config.Region().RestURL(url), nil, &reqBody, &resp) 293 294 if err != nil { 295 return nil, err 296 } 297 298 return &resp.Condition, nil 299 } 300 301 // DeleteCondition deletes an alert condition. 302 func (a *Alerts) DeleteCondition(id int) (*Condition, error) { 303 return a.DeleteConditionWithContext(context.Background(), id) 304 } 305 306 // DeleteConditionWithContext deletes an alert condition. 307 func (a *Alerts) DeleteConditionWithContext(ctx context.Context, id int) (*Condition, error) { 308 resp := alertConditionResponse{} 309 url := fmt.Sprintf("/alerts_conditions/%d.json", id) 310 311 _, err := a.client.DeleteWithContext(ctx, a.config.Region().RestURL(url), nil, &resp) 312 313 if err != nil { 314 return nil, err 315 } 316 317 return &resp.Condition, nil 318 } 319 320 // DeleteConditionMutation deletes any type of alert condition via New Relic's NerdGraph API. 321 func (a *Alerts) DeleteConditionMutation( 322 accountID int, 323 conditionID string, 324 ) (string, error) { 325 return a.DeleteConditionMutationWithContext(context.Background(), accountID, conditionID) 326 } 327 328 // DeleteConditionMutationWithContext deletes any type of alert condition via New Relic's NerdGraph API. 329 func (a *Alerts) DeleteConditionMutationWithContext( 330 ctx context.Context, 331 accountID int, 332 conditionID string, 333 ) (string, error) { 334 resp := conditionDeleteResponse{} 335 vars := map[string]interface{}{ 336 "accountId": accountID, 337 "id": conditionID, 338 } 339 340 if err := a.client.NerdGraphQueryWithContext(ctx, deleteConditionMutation, vars, &resp); err != nil { 341 return "", err 342 } 343 344 return resp.AlertsConditionDelete.ID, nil 345 } 346 347 type listConditionsParams struct { 348 PolicyID int `url:"policy_id,omitempty"` 349 } 350 351 type alertConditionsResponse struct { 352 Conditions []*Condition `json:"conditions,omitempty"` 353 } 354 355 type alertConditionResponse struct { 356 Condition Condition `json:"condition,omitempty"` 357 } 358 359 type alertConditionRequestBody struct { 360 Condition Condition `json:"condition,omitempty"` 361 } 362 363 type conditionDeleteResponse struct { 364 AlertsConditionDelete struct { 365 ID string `json:"id,omitempty"` 366 } `json:"alertsConditionDelete"` 367 } 368 369 const ( 370 deleteConditionMutation = ` 371 mutation($accountId: Int!, $id: ID!) { 372 alertsConditionDelete(accountId: $accountId, id: $id) { 373 id 374 } 375 }` 376 )