github.com/newrelic/newrelic-client-go@v1.1.0/pkg/alerts/muting_rules.go (about)

     1  package alerts
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"time"
     8  )
     9  
    10  // MutingRule represents the alert suppression mechanism in the Alerts API.
    11  type MutingRule struct {
    12  	ID            int                      `json:"id,string,omitempty"`
    13  	AccountID     int                      `json:"accountId,omitempty"`
    14  	Condition     MutingRuleConditionGroup `json:"condition,omitempty"`
    15  	CreatedAt     string                   `json:"createdAt,omitempty"`
    16  	CreatedByUser ByUser                   `json:"createdByUser,omitempty"`
    17  	Description   string                   `json:"description,omitempty"`
    18  	Enabled       bool                     `json:"enabled"`
    19  	Name          string                   `json:"name,omitempty"`
    20  	UpdatedAt     string                   `json:"updatedAt,omitempty"`
    21  	UpdatedByUser ByUser                   `json:"updatedByUser,omitempty"`
    22  	Schedule      *MutingRuleSchedule      `json:"schedule,omitempty"`
    23  }
    24  
    25  // ByUser is a collection of the user information that created or updated the muting rule.
    26  type ByUser struct {
    27  	Email    string `json:"email"`
    28  	Gravatar string `json:"gravatar"`
    29  	ID       int    `json:"id"`
    30  	Name     string `json:"name"`
    31  }
    32  
    33  // MutingRuleConditionGroup is a collection of conditions for muting.
    34  type MutingRuleConditionGroup struct {
    35  	Conditions []MutingRuleCondition `json:"conditions"`
    36  	Operator   string                `json:"operator"`
    37  }
    38  
    39  // MutingRuleCondition is a single muting rule condition.
    40  type MutingRuleCondition struct {
    41  	Attribute string   `json:"attribute"`
    42  	Operator  string   `json:"operator"`
    43  	Values    []string `json:"values"`
    44  }
    45  
    46  // MutingRuleScheduleRepeat represents how frequently a MutingRule's schedule repeats.
    47  type MutingRuleScheduleRepeat string
    48  
    49  // MutingRuleScheduleRepeatTypes are intervals for MutingRulesScheduleRepeat.
    50  var MutingRuleScheduleRepeatTypes = struct {
    51  	// DAILY - Schedule repeats once per calendar day.
    52  	DAILY MutingRuleScheduleRepeat
    53  	// WEEKLY - Schedule repeats once per specified day per calendar week.
    54  	WEEKLY MutingRuleScheduleRepeat
    55  	// MONTHLY - Schedule repeats once per calendar month.
    56  	MONTHLY MutingRuleScheduleRepeat
    57  }{
    58  	DAILY:   "DAILY",
    59  	WEEKLY:  "WEEKLY",
    60  	MONTHLY: "MONTHLY",
    61  }
    62  
    63  // DayOfWeek is used to configure a WEEKLY scheduled MutingRule.
    64  type DayOfWeek string
    65  
    66  // DayOfWeekTypes are days of the week for DayOfWeek.
    67  var DayOfWeekTypes = struct {
    68  	MONDAY    DayOfWeek
    69  	TUESDAY   DayOfWeek
    70  	WEDNESDAY DayOfWeek
    71  	THURSDAY  DayOfWeek
    72  	FRIDAY    DayOfWeek
    73  	SATURDAY  DayOfWeek
    74  	SUNDAY    DayOfWeek
    75  }{
    76  	MONDAY:    "MONDAY",
    77  	TUESDAY:   "TUESDAY",
    78  	WEDNESDAY: "WEDNESDAY",
    79  	THURSDAY:  "THURSDAY",
    80  	FRIDAY:    "FRIDAY",
    81  	SATURDAY:  "SATURDAY",
    82  	SUNDAY:    "SUNDAY",
    83  }
    84  
    85  // NaiveDateTime wraps `time.Time` to remove the time zone offset when JSON marshaling.
    86  // NaiveDateTime is used for MutingRuleScheduleCreateInput and MutingRuleScheduleUpdateInput fields StartTime, EndTime, and EndRepeat.
    87  type NaiveDateTime struct {
    88  	time.Time
    89  }
    90  
    91  // MarshalJSON strips the UTC time zone offset from the NaiveDateTime when JSON marshaling.
    92  // If a non-UTC time zone offset is specified on the NaiveDateTime, an error will be thrown.
    93  func (t NaiveDateTime) MarshalJSON() ([]byte, error) {
    94  	if _, offset := t.Zone(); offset != 0 {
    95  		return nil, fmt.Errorf("time offset %d not allowed. You can call .UTC() on the time provided to reset the offset", offset)
    96  	}
    97  
    98  	return json.Marshal(t.Format("2006-01-02T15:04:05"))
    99  }
   100  
   101  // MutingRuleSchedule is the time window when the MutingRule should actively mute violations
   102  type MutingRuleSchedule struct {
   103  	StartTime        *time.Time                `json:"startTime,omitempty"`
   104  	EndTime          *time.Time                `json:"endTime,omitempty"`
   105  	TimeZone         string                    `json:"timeZone"`
   106  	Repeat           *MutingRuleScheduleRepeat `json:"repeat,omitempty"`
   107  	EndRepeat        *time.Time                `json:"endRepeat,omitempty"`
   108  	RepeatCount      *int                      `json:"repeatCount,omitempty"`
   109  	WeeklyRepeatDays *[]DayOfWeek              `json:"weeklyRepeatDays,omitempty"`
   110  }
   111  
   112  // MutingRuleScheduleCreateInput is the time window when the MutingRule should actively mute violations for Create
   113  type MutingRuleScheduleCreateInput struct {
   114  	StartTime        *NaiveDateTime            `json:"startTime,omitempty"`
   115  	EndTime          *NaiveDateTime            `json:"endTime,omitempty"`
   116  	TimeZone         string                    `json:"timeZone"`
   117  	Repeat           *MutingRuleScheduleRepeat `json:"repeat,omitempty"`
   118  	EndRepeat        *NaiveDateTime            `json:"endRepeat,omitempty"`
   119  	RepeatCount      *int                      `json:"repeatCount,omitempty"`
   120  	WeeklyRepeatDays *[]DayOfWeek              `json:"weeklyRepeatDays,omitempty"`
   121  }
   122  
   123  // MutingRuleScheduleUpdateInput is the time window when the MutingRule should actively mute violations for Update
   124  type MutingRuleScheduleUpdateInput struct {
   125  	StartTime        *NaiveDateTime            `json:"startTime"`
   126  	EndTime          *NaiveDateTime            `json:"endTime"`
   127  	TimeZone         *string                   `json:"timeZone"`
   128  	Repeat           *MutingRuleScheduleRepeat `json:"repeat"`
   129  	EndRepeat        *NaiveDateTime            `json:"endRepeat"`
   130  	RepeatCount      *int                      `json:"repeatCount"`
   131  	WeeklyRepeatDays *[]DayOfWeek              `json:"weeklyRepeatDays"`
   132  }
   133  
   134  // MutingRuleCreateInput is the input for creating muting rules.
   135  type MutingRuleCreateInput struct {
   136  	Condition   MutingRuleConditionGroup       `json:"condition"`
   137  	Description string                         `json:"description"`
   138  	Enabled     bool                           `json:"enabled"`
   139  	Name        string                         `json:"name"`
   140  	Schedule    *MutingRuleScheduleCreateInput `json:"schedule,omitempty"`
   141  }
   142  
   143  // MutingRuleUpdateInput is the input for updating a rule.
   144  type MutingRuleUpdateInput struct {
   145  	// Condition is is available from the API, but the json needs to be handled
   146  	// properly.
   147  
   148  	Condition   *MutingRuleConditionGroup      `json:"condition,omitempty"`
   149  	Description string                         `json:"description,omitempty"`
   150  	Enabled     bool                           `json:"enabled"`
   151  	Name        string                         `json:"name,omitempty"`
   152  	Schedule    *MutingRuleScheduleUpdateInput `json:"schedule"`
   153  }
   154  
   155  // ListMutingRules queries for all muting rules in a given account.
   156  func (a *Alerts) ListMutingRules(accountID int) ([]MutingRule, error) {
   157  	return a.ListMutingRulesWithContext(context.Background(), accountID)
   158  }
   159  
   160  // ListMutingRulesWithContext queries for all muting rules in a given account.
   161  func (a *Alerts) ListMutingRulesWithContext(ctx context.Context, accountID int) ([]MutingRule, error) {
   162  	vars := map[string]interface{}{
   163  		"accountID": accountID,
   164  	}
   165  
   166  	resp := alertMutingRuleListResponse{}
   167  
   168  	if err := a.client.NerdGraphQueryWithContext(ctx, alertsMutingRulesQuery, vars, &resp); err != nil {
   169  		return nil, err
   170  	}
   171  
   172  	return resp.Actor.Account.Alerts.MutingRules, nil
   173  }
   174  
   175  // GetMutingRule queries for a single muting rule matching the given ID.
   176  func (a *Alerts) GetMutingRule(accountID, ruleID int) (*MutingRule, error) {
   177  	return a.GetMutingRuleWithContext(context.Background(), accountID, ruleID)
   178  }
   179  
   180  // GetMutingRuleWithContext queries for a single muting rule matching the given ID.
   181  func (a *Alerts) GetMutingRuleWithContext(ctx context.Context, accountID, ruleID int) (*MutingRule, error) {
   182  	vars := map[string]interface{}{
   183  		"accountID": accountID,
   184  		"ruleID":    ruleID,
   185  	}
   186  
   187  	resp := alertMutingRulesGetResponse{}
   188  
   189  	if err := a.NerdGraphQueryWithContext(ctx, alertsMutingRulesGet, vars, &resp); err != nil {
   190  		return nil, err
   191  	}
   192  
   193  	return &resp.Actor.Account.Alerts.MutingRule, nil
   194  }
   195  
   196  // CreateMutingRule is the mutation to create a muting rule for the given account and input.
   197  func (a *Alerts) CreateMutingRule(accountID int, rule MutingRuleCreateInput) (*MutingRule, error) {
   198  	return a.CreateMutingRuleWithContext(context.Background(), accountID, rule)
   199  }
   200  
   201  // CreateMutingRuleWithContext is the mutation to create a muting rule for the given account and input.
   202  func (a *Alerts) CreateMutingRuleWithContext(ctx context.Context, accountID int, rule MutingRuleCreateInput) (*MutingRule, error) {
   203  	vars := map[string]interface{}{
   204  		"accountID": accountID,
   205  		"rule":      rule,
   206  	}
   207  
   208  	resp := alertMutingRuleCreateResponse{}
   209  
   210  	if err := a.NerdGraphQueryWithContext(ctx, alertsMutingRulesCreate, vars, &resp); err != nil {
   211  		return nil, err
   212  	}
   213  
   214  	return &resp.AlertsMutingRuleCreate, nil
   215  }
   216  
   217  // UpdateMutingRule is the mutation to update an existing muting rule.
   218  func (a *Alerts) UpdateMutingRule(accountID int, ruleID int, rule MutingRuleUpdateInput) (*MutingRule, error) {
   219  	return a.UpdateMutingRuleWithContext(context.Background(), accountID, ruleID, rule)
   220  }
   221  
   222  // UpdateMutingRuleWithContext is the mutation to update an existing muting rule.
   223  func (a *Alerts) UpdateMutingRuleWithContext(ctx context.Context, accountID int, ruleID int, rule MutingRuleUpdateInput) (*MutingRule, error) {
   224  	vars := map[string]interface{}{
   225  		"accountID": accountID,
   226  		"ruleID":    ruleID,
   227  		"rule":      rule,
   228  	}
   229  
   230  	resp := alertMutingRuleUpdateResponse{}
   231  
   232  	if err := a.NerdGraphQueryWithContext(ctx, alertsMutingRulesUpdate, vars, &resp); err != nil {
   233  		return nil, err
   234  	}
   235  
   236  	return &resp.AlertsMutingRuleUpdate, nil
   237  }
   238  
   239  // DeleteMutingRule is the mutation to delete an existing muting rule.
   240  func (a *Alerts) DeleteMutingRule(accountID int, ruleID int) error {
   241  	return a.DeleteMutingRuleWithContext(context.Background(), accountID, ruleID)
   242  }
   243  
   244  // DeleteMutingRuleWithContext is the mutation to delete an existing muting rule.
   245  func (a *Alerts) DeleteMutingRuleWithContext(ctx context.Context, accountID int, ruleID int) error {
   246  	vars := map[string]interface{}{
   247  		"accountID": accountID,
   248  		"ruleID":    ruleID,
   249  	}
   250  
   251  	resp := alertMutingRuleDeleteResponse{}
   252  
   253  	return a.NerdGraphQueryWithContext(ctx, alertsMutingRuleDelete, vars, &resp)
   254  }
   255  
   256  type alertMutingRuleCreateResponse struct {
   257  	AlertsMutingRuleCreate MutingRule `json:"alertsMutingRuleCreate"`
   258  }
   259  
   260  type alertMutingRuleUpdateResponse struct {
   261  	AlertsMutingRuleUpdate MutingRule `json:"alertsMutingRuleUpdate"`
   262  }
   263  
   264  type alertMutingRuleDeleteResponse struct {
   265  	AlertsMutingRuleDelete struct {
   266  		ID string `json:"id"`
   267  	} `json:"alertsMutingRuleDelete"`
   268  }
   269  
   270  type alertMutingRuleListResponse struct {
   271  	Actor struct {
   272  		Account struct {
   273  			Alerts struct {
   274  				MutingRules []MutingRule `json:"mutingRules"`
   275  			} `json:"alerts"`
   276  		} `json:"account"`
   277  	} `json:"actor"`
   278  }
   279  
   280  type alertMutingRulesGetResponse struct {
   281  	Actor struct {
   282  		Account struct {
   283  			Alerts struct {
   284  				MutingRule MutingRule `json:"mutingRule"`
   285  			} `json:"alerts"`
   286  		} `json:"account"`
   287  	} `json:"actor"`
   288  }
   289  
   290  const (
   291  	alertsMutingRulesQuery = `query($accountID: Int!) {
   292  		actor {
   293  			account(id: $accountID) {
   294  				alerts {
   295  					mutingRules {
   296  						id
   297  						name
   298  						description
   299  						enabled
   300  						condition {
   301  							operator
   302  							conditions {
   303  								attribute
   304  								operator
   305  								values
   306  							}
   307  						}
   308  					}
   309  				}
   310  			}
   311  		}
   312  	}`
   313  
   314  	alertsMutingRulesGet = `query($accountID: Int!, $ruleID: ID!) {
   315  		actor {
   316  			account(id: $accountID) {
   317  				alerts {
   318  					mutingRule(id: $ruleID) {` +
   319  		alertsMutingRuleFields +
   320  		`}}}}}`
   321  
   322  	alertsMutingRuleFields = `
   323  		accountId
   324  		condition {
   325  			conditions {
   326  				attribute
   327  				operator
   328  				values
   329  			}
   330  			operator
   331  		}
   332  		id
   333  		name
   334  		enabled
   335  		description
   336  		createdAt
   337  		createdByUser {
   338  			email
   339  			gravatar
   340  			id
   341  			name
   342  		}
   343  		updatedAt
   344  		updatedByUser {
   345  			email
   346  			gravatar
   347  			id
   348  			name
   349  		}
   350  		schedule {
   351  			startTime
   352  			endTime
   353  			timeZone
   354  			repeat
   355  			endRepeat
   356  			repeatCount
   357  			weeklyRepeatDays
   358  		}
   359  	`
   360  
   361  	alertsMutingRulesCreate = `mutation CreateRule($accountID: Int!, $rule: AlertsMutingRuleInput!) {
   362  		alertsMutingRuleCreate(accountId: $accountID, rule: $rule) {` +
   363  		alertsMutingRuleFields +
   364  
   365  		`}
   366  	}`
   367  
   368  	alertsMutingRulesUpdate = `mutation UpdateRule($accountID: Int!, $ruleID: ID!, $rule: AlertsMutingRuleUpdateInput!) {
   369  		alertsMutingRuleUpdate(accountId: $accountID, id: $ruleID, rule: $rule) {` +
   370  		alertsMutingRuleFields +
   371  		`}
   372  	}`
   373  
   374  	alertsMutingRuleDelete = `mutation DeleteRule($accountID: Int!, $ruleID: ID!) {
   375  		alertsMutingRuleDelete(accountId: $accountID, id: $ruleID) {
   376  			id
   377  		}
   378  	}`
   379  )