grafana/pkg/services/alerting/notifiers/opsgenie.go

247 lines
7.1 KiB
Go
Raw Normal View History

2016-12-06 14:48:13 -06:00
package notifiers
import (
Encryption: Refactor securejsondata.SecureJsonData to stop relying on global functions (#38865) * Encryption: Add support to encrypt/decrypt sjd * Add datasources.Service as a proxy to datasources db operations * Encrypt ds.SecureJsonData before calling SQLStore * Move ds cache code into ds service * Fix tlsmanager tests * Fix pluginproxy tests * Remove some securejsondata.GetEncryptedJsonData usages * Add pluginsettings.Service as a proxy for plugin settings db operations * Add AlertNotificationService as a proxy for alert notification db operations * Remove some securejsondata.GetEncryptedJsonData usages * Remove more securejsondata.GetEncryptedJsonData usages * Fix lint errors * Minor fixes * Remove encryption global functions usages from ngalert * Fix lint errors * Minor fixes * Minor fixes * Remove securejsondata.DecryptedValue usage * Refactor the refactor * Remove securejsondata.DecryptedValue usage * Move securejsondata to migrations package * Move securejsondata to migrations package * Minor fix * Fix integration test * Fix integration tests * Undo undesired changes * Fix tests * Add context.Context into encryption methods * Fix tests * Fix tests * Fix tests * Trigger CI * Fix test * Add names to params of encryption service interface * Remove bus from CacheServiceImpl * Add logging * Add keys to logger Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com> * Add missing key to logger Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com> * Undo changes in markdown files * Fix formatting * Add context to secrets service * Rename decryptSecureJsonData to decryptSecureJsonDataFn * Name args in GetDecryptedValueFn * Add template back to NewAlertmanagerNotifier * Copy GetDecryptedValueFn to ngalert * Add logging to pluginsettings * Fix pluginsettings test Co-authored-by: Tania B <yalyna.ts@gmail.com> Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
2021-10-07 09:33:50 -05:00
"context"
2016-12-06 14:48:13 -06:00
"fmt"
"strconv"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
2016-12-06 14:48:13 -06:00
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/notifications"
Encryption: Refactor securejsondata.SecureJsonData to stop relying on global functions (#38865) * Encryption: Add support to encrypt/decrypt sjd * Add datasources.Service as a proxy to datasources db operations * Encrypt ds.SecureJsonData before calling SQLStore * Move ds cache code into ds service * Fix tlsmanager tests * Fix pluginproxy tests * Remove some securejsondata.GetEncryptedJsonData usages * Add pluginsettings.Service as a proxy for plugin settings db operations * Add AlertNotificationService as a proxy for alert notification db operations * Remove some securejsondata.GetEncryptedJsonData usages * Remove more securejsondata.GetEncryptedJsonData usages * Fix lint errors * Minor fixes * Remove encryption global functions usages from ngalert * Fix lint errors * Minor fixes * Minor fixes * Remove securejsondata.DecryptedValue usage * Refactor the refactor * Remove securejsondata.DecryptedValue usage * Move securejsondata to migrations package * Move securejsondata to migrations package * Minor fix * Fix integration test * Fix integration tests * Undo undesired changes * Fix tests * Add context.Context into encryption methods * Fix tests * Fix tests * Fix tests * Trigger CI * Fix test * Add names to params of encryption service interface * Remove bus from CacheServiceImpl * Add logging * Add keys to logger Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com> * Add missing key to logger Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com> * Undo changes in markdown files * Fix formatting * Add context to secrets service * Rename decryptSecureJsonData to decryptSecureJsonDataFn * Name args in GetDecryptedValueFn * Add template back to NewAlertmanagerNotifier * Copy GetDecryptedValueFn to ngalert * Add logging to pluginsettings * Fix pluginsettings test Co-authored-by: Tania B <yalyna.ts@gmail.com> Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
2021-10-07 09:33:50 -05:00
"github.com/grafana/grafana/pkg/setting"
2016-12-06 14:48:13 -06:00
)
Alerting: Allow sending notification tags to Opsgenie as extra properties (#30332) * Alerting: Opsgenie send tags as extra properties Allow users to select where to send notification tags when alerting via OpsGenie. Supports sending tags as key/value details, concatenated strings in tags or both. Users will be able to see their tags as key/values under extra properties in an alert on the Opsgenie UI. These key/values can then be used in the platform for routing, templating etc. * Configurable delivery to either tags, extra properties or both * Default to current behaviour (tags only) * Support both so users can transition from tags to details Add docs and clean up references * Alerting: Add additional arg for Opsgenie tests The NewEvalContext function now requires a 'PluginRequestValidator' argument. As our test does not use the validator we can specify 'nil' to satisfy the function and allow our test to pass as expected. * Alerting: Opsgenie doc fixes Accept suggested changes for Opsgenie docs Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Alerting: Opsgenie provisioning settings docs Add the new setting to the provisioning docs * Alerting: Opsgenie doc typo correction Move the comma (,) out of the preformatting tags for the setting value * Alerting: Opsgenie refactor send switches Refactor the send switches to be methods on the OpsgenieNotiefier itself. This also cleans up the method names so that the code reads a bit more logically as: if we should send details: send details if we should send tags: send tags This avoids the calling code needing to care about passing the state and allows an engineer working in the `createAlert` function to focus on the results of applying the logic instead. * Alerting: Opsgenie docs rename note Rename the note heading to match the number to more clearly link them. * Alerting: Opsgenie use standard reference to note Refer to the note below as per recommendation and standards. Fixes #30331 Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
2021-03-24 11:07:26 -05:00
const (
sendTags = "tags"
sendDetails = "details"
sendBoth = "both"
)
2016-12-06 14:48:13 -06:00
func init() {
alerting.RegisterNotifier(&alerting.NotifierPlugin{
Type: "opsgenie",
Name: "OpsGenie",
Description: "Sends notifications to OpsGenie",
Heading: "OpsGenie settings",
Factory: NewOpsGenieNotifier,
Options: []alerting.NotifierOption{
{
Label: "API Key",
Element: alerting.ElementTypeInput,
InputType: alerting.InputTypeText,
Placeholder: "OpsGenie API Key",
PropertyName: "apiKey",
Required: true,
Secure: true,
},
{
Label: "Alert API Url",
Element: alerting.ElementTypeInput,
InputType: alerting.InputTypeText,
Placeholder: "https://api.opsgenie.com/v2/alerts",
PropertyName: "apiUrl",
Required: true,
},
{
Label: "Auto close incidents",
Element: alerting.ElementTypeCheckbox,
Description: "Automatically close alerts in OpsGenie once the alert goes back to ok.",
PropertyName: "autoClose",
}, {
Label: "Override priority",
Element: alerting.ElementTypeCheckbox,
Description: "Allow the alert priority to be set using the og_priority tag",
PropertyName: "overridePriority",
},
Alerting: Allow sending notification tags to Opsgenie as extra properties (#30332) * Alerting: Opsgenie send tags as extra properties Allow users to select where to send notification tags when alerting via OpsGenie. Supports sending tags as key/value details, concatenated strings in tags or both. Users will be able to see their tags as key/values under extra properties in an alert on the Opsgenie UI. These key/values can then be used in the platform for routing, templating etc. * Configurable delivery to either tags, extra properties or both * Default to current behaviour (tags only) * Support both so users can transition from tags to details Add docs and clean up references * Alerting: Add additional arg for Opsgenie tests The NewEvalContext function now requires a 'PluginRequestValidator' argument. As our test does not use the validator we can specify 'nil' to satisfy the function and allow our test to pass as expected. * Alerting: Opsgenie doc fixes Accept suggested changes for Opsgenie docs Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Alerting: Opsgenie provisioning settings docs Add the new setting to the provisioning docs * Alerting: Opsgenie doc typo correction Move the comma (,) out of the preformatting tags for the setting value * Alerting: Opsgenie refactor send switches Refactor the send switches to be methods on the OpsgenieNotiefier itself. This also cleans up the method names so that the code reads a bit more logically as: if we should send details: send details if we should send tags: send tags This avoids the calling code needing to care about passing the state and allows an engineer working in the `createAlert` function to focus on the results of applying the logic instead. * Alerting: Opsgenie docs rename note Rename the note heading to match the number to more clearly link them. * Alerting: Opsgenie use standard reference to note Refer to the note below as per recommendation and standards. Fixes #30331 Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
2021-03-24 11:07:26 -05:00
{
Label: "Send notification tags as",
Element: alerting.ElementTypeSelect,
SelectOptions: []alerting.SelectOption{
{
Value: sendTags,
Label: "Tags",
},
{
Value: sendDetails,
Label: "Extra Properties",
},
{
Value: sendBoth,
Label: "Tags & Extra Properties",
},
},
Description: "Send the notification tags to Opsgenie as either Extra Properties, Tags or both",
PropertyName: "sendTagsAs",
},
},
})
2016-12-06 14:48:13 -06:00
}
Alerting: Allow sending notification tags to Opsgenie as extra properties (#30332) * Alerting: Opsgenie send tags as extra properties Allow users to select where to send notification tags when alerting via OpsGenie. Supports sending tags as key/value details, concatenated strings in tags or both. Users will be able to see their tags as key/values under extra properties in an alert on the Opsgenie UI. These key/values can then be used in the platform for routing, templating etc. * Configurable delivery to either tags, extra properties or both * Default to current behaviour (tags only) * Support both so users can transition from tags to details Add docs and clean up references * Alerting: Add additional arg for Opsgenie tests The NewEvalContext function now requires a 'PluginRequestValidator' argument. As our test does not use the validator we can specify 'nil' to satisfy the function and allow our test to pass as expected. * Alerting: Opsgenie doc fixes Accept suggested changes for Opsgenie docs Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Alerting: Opsgenie provisioning settings docs Add the new setting to the provisioning docs * Alerting: Opsgenie doc typo correction Move the comma (,) out of the preformatting tags for the setting value * Alerting: Opsgenie refactor send switches Refactor the send switches to be methods on the OpsgenieNotiefier itself. This also cleans up the method names so that the code reads a bit more logically as: if we should send details: send details if we should send tags: send tags This avoids the calling code needing to care about passing the state and allows an engineer working in the `createAlert` function to focus on the results of applying the logic instead. * Alerting: Opsgenie docs rename note Rename the note heading to match the number to more clearly link them. * Alerting: Opsgenie use standard reference to note Refer to the note below as per recommendation and standards. Fixes #30331 Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
2021-03-24 11:07:26 -05:00
const (
Remove redundancy in variable declarations (golint) This commit fixes the following golint warnings: pkg/api/avatar/avatar.go:229:12: should omit type *http.Client from declaration of var client; it will be inferred from the right-hand side pkg/login/brute_force_login_protection.go:13:26: should omit type time.Duration from declaration of var loginAttemptsWindow; it will be inferred from the right-hand side pkg/metrics/graphitebridge/graphite.go:58:26: should omit type []string from declaration of var metricCategoryPrefix; it will be inferred from the right-hand side pkg/metrics/graphitebridge/graphite.go:69:22: should omit type []string from declaration of var trimMetricPrefix; it will be inferred from the right-hand side pkg/models/alert.go:37:36: should omit type error from declaration of var ErrCannotChangeStateOnPausedAlert; it will be inferred from the right-hand side pkg/models/alert.go:38:36: should omit type error from declaration of var ErrRequiresNewState; it will be inferred from the right-hand side pkg/models/datasource.go:61:28: should omit type map[string]bool from declaration of var knownDatasourcePlugins; it will be inferred from the right-hand side pkg/plugins/update_checker.go:16:13: should omit type http.Client from declaration of var httpClient; it will be inferred from the right-hand side pkg/services/alerting/engine.go:103:24: should omit type time.Duration from declaration of var unfinishedWorkTimeout; it will be inferred from the right-hand side pkg/services/alerting/engine.go:105:19: should omit type time.Duration from declaration of var alertTimeout; it will be inferred from the right-hand side pkg/services/alerting/engine.go:106:19: should omit type int from declaration of var alertMaxAttempts; it will be inferred from the right-hand side pkg/services/alerting/notifier.go:143:23: should omit type map[string]*NotifierPlugin from declaration of var notifierFactories; it will be inferred from the right-hand side pkg/services/alerting/rule.go:136:24: should omit type map[string]ConditionFactory from declaration of var conditionFactories; it will be inferred from the right-hand side pkg/services/alerting/conditions/evaluator.go:12:15: should omit type []string from declaration of var defaultTypes; it will be inferred from the right-hand side pkg/services/alerting/conditions/evaluator.go:13:15: should omit type []string from declaration of var rangedTypes; it will be inferred from the right-hand side pkg/services/alerting/notifiers/opsgenie.go:44:19: should omit type string from declaration of var opsgenieAlertURL; it will be inferred from the right-hand side pkg/services/alerting/notifiers/pagerduty.go:43:23: should omit type string from declaration of var pagerdutyEventApiUrl; it will be inferred from the right-hand side pkg/services/alerting/notifiers/telegram.go:21:17: should omit type string from declaration of var telegramApiUrl; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/config_reader_test.go:11:24: should omit type string from declaration of var simpleDashboardConfig; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/config_reader_test.go:12:24: should omit type string from declaration of var oldVersion; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/config_reader_test.go:13:24: should omit type string from declaration of var brokenConfigs; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/file_reader.go:22:30: should omit type time.Duration from declaration of var checkDiskForChangesInterval; it will be inferred from the right-hand side pkg/services/provisioning/dashboards/file_reader.go:24:23: should omit type error from declaration of var ErrFolderNameMissing; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:15:34: should omit type string from declaration of var twoDatasourcesConfig; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:16:34: should omit type string from declaration of var twoDatasourcesConfigPurgeOthers; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:17:34: should omit type string from declaration of var doubleDatasourcesConfig; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:18:34: should omit type string from declaration of var allProperties; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:19:34: should omit type string from declaration of var versionZero; it will be inferred from the right-hand side pkg/services/provisioning/datasources/config_reader_test.go:20:34: should omit type string from declaration of var brokenYaml; it will be inferred from the right-hand side pkg/services/sqlstore/stats.go:16:25: should omit type time.Duration from declaration of var activeUserTimeLimit; it will be inferred from the right-hand side pkg/services/sqlstore/migrator/mysql_dialect.go:69:14: should omit type bool from declaration of var hasLen1; it will be inferred from the right-hand side pkg/services/sqlstore/migrator/mysql_dialect.go:70:14: should omit type bool from declaration of var hasLen2; it will be inferred from the right-hand side pkg/services/sqlstore/migrator/postgres_dialect.go:95:14: should omit type bool from declaration of var hasLen1; it will be inferred from the right-hand side pkg/services/sqlstore/migrator/postgres_dialect.go:96:14: should omit type bool from declaration of var hasLen2; it will be inferred from the right-hand side pkg/setting/setting.go:42:15: should omit type string from declaration of var Env; it will be inferred from the right-hand side pkg/setting/setting.go:161:18: should omit type bool from declaration of var LdapAllowSignup; it will be inferred from the right-hand side pkg/setting/setting.go:473:30: should omit type bool from declaration of var skipStaticRootValidation; it will be inferred from the right-hand side pkg/tsdb/interval.go:14:21: should omit type time.Duration from declaration of var defaultMinInterval; it will be inferred from the right-hand side pkg/tsdb/interval.go:15:21: should omit type time.Duration from declaration of var year; it will be inferred from the right-hand side pkg/tsdb/interval.go:16:21: should omit type time.Duration from declaration of var day; it will be inferred from the right-hand side pkg/tsdb/cloudwatch/credentials.go:26:24: should omit type map[string]cache from declaration of var awsCredentialCache; it will be inferred from the right-hand side pkg/tsdb/influxdb/query.go:15:27: should omit type *regexp.Regexp from declaration of var regexpOperatorPattern; it will be inferred from the right-hand side pkg/tsdb/influxdb/query.go:16:27: should omit type *regexp.Regexp from declaration of var regexpMeasurementPattern; it will be inferred from the right-hand side pkg/tsdb/mssql/mssql_test.go:25:14: should omit type string from declaration of var serverIP; it will be inferred from the right-hand side
2018-04-27 15:14:36 -05:00
opsgenieAlertURL = "https://api.opsgenie.com/v2/alerts"
2016-12-06 14:48:13 -06:00
)
// NewOpsGenieNotifier is the constructor for OpsGenie.
func NewOpsGenieNotifier(model *models.AlertNotification, fn alerting.GetDecryptedValueFn, ns notifications.Service) (alerting.Notifier, error) {
2016-12-06 14:48:13 -06:00
autoClose := model.Settings.Get("autoClose").MustBool(true)
overridePriority := model.Settings.Get("overridePriority").MustBool(true)
Encryption: Refactor securejsondata.SecureJsonData to stop relying on global functions (#38865) * Encryption: Add support to encrypt/decrypt sjd * Add datasources.Service as a proxy to datasources db operations * Encrypt ds.SecureJsonData before calling SQLStore * Move ds cache code into ds service * Fix tlsmanager tests * Fix pluginproxy tests * Remove some securejsondata.GetEncryptedJsonData usages * Add pluginsettings.Service as a proxy for plugin settings db operations * Add AlertNotificationService as a proxy for alert notification db operations * Remove some securejsondata.GetEncryptedJsonData usages * Remove more securejsondata.GetEncryptedJsonData usages * Fix lint errors * Minor fixes * Remove encryption global functions usages from ngalert * Fix lint errors * Minor fixes * Minor fixes * Remove securejsondata.DecryptedValue usage * Refactor the refactor * Remove securejsondata.DecryptedValue usage * Move securejsondata to migrations package * Move securejsondata to migrations package * Minor fix * Fix integration test * Fix integration tests * Undo undesired changes * Fix tests * Add context.Context into encryption methods * Fix tests * Fix tests * Fix tests * Trigger CI * Fix test * Add names to params of encryption service interface * Remove bus from CacheServiceImpl * Add logging * Add keys to logger Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com> * Add missing key to logger Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com> * Undo changes in markdown files * Fix formatting * Add context to secrets service * Rename decryptSecureJsonData to decryptSecureJsonDataFn * Name args in GetDecryptedValueFn * Add template back to NewAlertmanagerNotifier * Copy GetDecryptedValueFn to ngalert * Add logging to pluginsettings * Fix pluginsettings test Co-authored-by: Tania B <yalyna.ts@gmail.com> Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
2021-10-07 09:33:50 -05:00
apiKey := fn(context.Background(), model.SecureSettings, "apiKey", model.Settings.Get("apiKey").MustString(), setting.SecretKey)
apiURL := model.Settings.Get("apiUrl").MustString()
2016-12-06 14:48:13 -06:00
if apiKey == "" {
return nil, alerting.ValidationError{Reason: "Could not find api key property in settings"}
}
if apiURL == "" {
apiURL = opsgenieAlertURL
}
2016-12-06 14:48:13 -06:00
Alerting: Allow sending notification tags to Opsgenie as extra properties (#30332) * Alerting: Opsgenie send tags as extra properties Allow users to select where to send notification tags when alerting via OpsGenie. Supports sending tags as key/value details, concatenated strings in tags or both. Users will be able to see their tags as key/values under extra properties in an alert on the Opsgenie UI. These key/values can then be used in the platform for routing, templating etc. * Configurable delivery to either tags, extra properties or both * Default to current behaviour (tags only) * Support both so users can transition from tags to details Add docs and clean up references * Alerting: Add additional arg for Opsgenie tests The NewEvalContext function now requires a 'PluginRequestValidator' argument. As our test does not use the validator we can specify 'nil' to satisfy the function and allow our test to pass as expected. * Alerting: Opsgenie doc fixes Accept suggested changes for Opsgenie docs Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Alerting: Opsgenie provisioning settings docs Add the new setting to the provisioning docs * Alerting: Opsgenie doc typo correction Move the comma (,) out of the preformatting tags for the setting value * Alerting: Opsgenie refactor send switches Refactor the send switches to be methods on the OpsgenieNotiefier itself. This also cleans up the method names so that the code reads a bit more logically as: if we should send details: send details if we should send tags: send tags This avoids the calling code needing to care about passing the state and allows an engineer working in the `createAlert` function to focus on the results of applying the logic instead. * Alerting: Opsgenie docs rename note Rename the note heading to match the number to more clearly link them. * Alerting: Opsgenie use standard reference to note Refer to the note below as per recommendation and standards. Fixes #30331 Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
2021-03-24 11:07:26 -05:00
sendTagsAs := model.Settings.Get("sendTagsAs").MustString(sendTags)
if sendTagsAs != sendTags && sendTagsAs != sendDetails && sendTagsAs != sendBoth {
return nil, alerting.ValidationError{
Reason: fmt.Sprintf("Invalid value for sendTagsAs: %q", sendTagsAs),
}
}
2016-12-06 14:48:13 -06:00
return &OpsGenieNotifier{
NotifierBase: NewNotifierBase(model, ns),
APIKey: apiKey,
APIUrl: apiURL,
AutoClose: autoClose,
OverridePriority: overridePriority,
Alerting: Allow sending notification tags to Opsgenie as extra properties (#30332) * Alerting: Opsgenie send tags as extra properties Allow users to select where to send notification tags when alerting via OpsGenie. Supports sending tags as key/value details, concatenated strings in tags or both. Users will be able to see their tags as key/values under extra properties in an alert on the Opsgenie UI. These key/values can then be used in the platform for routing, templating etc. * Configurable delivery to either tags, extra properties or both * Default to current behaviour (tags only) * Support both so users can transition from tags to details Add docs and clean up references * Alerting: Add additional arg for Opsgenie tests The NewEvalContext function now requires a 'PluginRequestValidator' argument. As our test does not use the validator we can specify 'nil' to satisfy the function and allow our test to pass as expected. * Alerting: Opsgenie doc fixes Accept suggested changes for Opsgenie docs Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Alerting: Opsgenie provisioning settings docs Add the new setting to the provisioning docs * Alerting: Opsgenie doc typo correction Move the comma (,) out of the preformatting tags for the setting value * Alerting: Opsgenie refactor send switches Refactor the send switches to be methods on the OpsgenieNotiefier itself. This also cleans up the method names so that the code reads a bit more logically as: if we should send details: send details if we should send tags: send tags This avoids the calling code needing to care about passing the state and allows an engineer working in the `createAlert` function to focus on the results of applying the logic instead. * Alerting: Opsgenie docs rename note Rename the note heading to match the number to more clearly link them. * Alerting: Opsgenie use standard reference to note Refer to the note below as per recommendation and standards. Fixes #30331 Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
2021-03-24 11:07:26 -05:00
SendTagsAs: sendTagsAs,
log: log.New("alerting.notifier.opsgenie"),
2016-12-06 14:48:13 -06:00
}, nil
}
// OpsGenieNotifier is responsible for sending
// alert notifications to OpsGenie
2016-12-06 14:48:13 -06:00
type OpsGenieNotifier struct {
NotifierBase
APIKey string
APIUrl string
AutoClose bool
OverridePriority bool
Alerting: Allow sending notification tags to Opsgenie as extra properties (#30332) * Alerting: Opsgenie send tags as extra properties Allow users to select where to send notification tags when alerting via OpsGenie. Supports sending tags as key/value details, concatenated strings in tags or both. Users will be able to see their tags as key/values under extra properties in an alert on the Opsgenie UI. These key/values can then be used in the platform for routing, templating etc. * Configurable delivery to either tags, extra properties or both * Default to current behaviour (tags only) * Support both so users can transition from tags to details Add docs and clean up references * Alerting: Add additional arg for Opsgenie tests The NewEvalContext function now requires a 'PluginRequestValidator' argument. As our test does not use the validator we can specify 'nil' to satisfy the function and allow our test to pass as expected. * Alerting: Opsgenie doc fixes Accept suggested changes for Opsgenie docs Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Alerting: Opsgenie provisioning settings docs Add the new setting to the provisioning docs * Alerting: Opsgenie doc typo correction Move the comma (,) out of the preformatting tags for the setting value * Alerting: Opsgenie refactor send switches Refactor the send switches to be methods on the OpsgenieNotiefier itself. This also cleans up the method names so that the code reads a bit more logically as: if we should send details: send details if we should send tags: send tags This avoids the calling code needing to care about passing the state and allows an engineer working in the `createAlert` function to focus on the results of applying the logic instead. * Alerting: Opsgenie docs rename note Rename the note heading to match the number to more clearly link them. * Alerting: Opsgenie use standard reference to note Refer to the note below as per recommendation and standards. Fixes #30331 Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
2021-03-24 11:07:26 -05:00
SendTagsAs string
log log.Logger
2016-12-06 14:48:13 -06:00
}
// Notify sends an alert notification to OpsGenie.
func (on *OpsGenieNotifier) Notify(evalContext *alerting.EvalContext) error {
2016-12-06 14:48:13 -06:00
var err error
switch evalContext.Rule.State {
case models.AlertStateOK:
if on.AutoClose {
err = on.closeAlert(evalContext)
2016-12-06 14:48:13 -06:00
}
case models.AlertStateAlerting:
err = on.createAlert(evalContext)
default:
// Handle other cases?
2016-12-06 14:48:13 -06:00
}
return err
}
func (on *OpsGenieNotifier) createAlert(evalContext *alerting.EvalContext) error {
on.log.Info("Creating OpsGenie alert", "ruleId", evalContext.Rule.ID, "notification", on.Name)
2016-12-06 14:48:13 -06:00
ruleURL, err := evalContext.GetRuleURL()
2016-12-06 14:48:13 -06:00
if err != nil {
on.log.Error("Failed get rule link", "error", err)
2016-12-06 14:48:13 -06:00
return err
}
Fix goconst issues See, $ gometalinter --vendor --disable-all --enable=goconst --disable=gotype --deadline=6m ./... build.go:113:15:warning: 2 other occurrence(s) of "linux" found in: build.go:119:15 build.go:491:34 (goconst) build.go:119:15:warning: 2 other occurrence(s) of "linux" found in: build.go:113:15 build.go:491:34 (goconst) build.go:491:34:warning: 2 other occurrence(s) of "linux" found in: build.go:113:15 build.go:119:15 (goconst) build.go:381:21:warning: 2 other occurrence(s) of "windows" found in: build.go:423:13 build.go:487:13 (goconst) build.go:423:13:warning: 2 other occurrence(s) of "windows" found in: build.go:381:21 build.go:487:13 (goconst) build.go:487:13:warning: 2 other occurrence(s) of "windows" found in: build.go:381:21 build.go:423:13 (goconst) pkg/api/dashboard.go:67:22:warning: 5 other occurrence(s) of "Anonymous" found in: pkg/api/dashboard.go:67:35 pkg/api/dashboard.go:131:10 pkg/api/dashboard.go:406:13 pkg/api/folder.go:98:22 pkg/api/folder.go:98:35 (goconst) pkg/api/dashboard.go:67:35:warning: 5 other occurrence(s) of "Anonymous" found in: pkg/api/dashboard.go:67:22 pkg/api/dashboard.go:131:10 pkg/api/dashboard.go:406:13 pkg/api/folder.go:98:22 pkg/api/folder.go:98:35 (goconst) pkg/api/dashboard.go:131:10:warning: 5 other occurrence(s) of "Anonymous" found in: pkg/api/dashboard.go:67:22 pkg/api/dashboard.go:67:35 pkg/api/dashboard.go:406:13 pkg/api/folder.go:98:22 pkg/api/folder.go:98:35 (goconst) pkg/api/dashboard.go:406:13:warning: 5 other occurrence(s) of "Anonymous" found in: pkg/api/dashboard.go:67:22 pkg/api/dashboard.go:67:35 pkg/api/dashboard.go:131:10 pkg/api/folder.go:98:22 pkg/api/folder.go:98:35 (goconst) pkg/api/folder.go:98:22:warning: 5 other occurrence(s) of "Anonymous" found in: pkg/api/dashboard.go:67:22 pkg/api/dashboard.go:67:35 pkg/api/dashboard.go:131:10 pkg/api/dashboard.go:406:13 pkg/api/folder.go:98:35 (goconst) pkg/api/folder.go:98:35:warning: 5 other occurrence(s) of "Anonymous" found in: pkg/api/dashboard.go:67:22 pkg/api/dashboard.go:67:35 pkg/api/dashboard.go:131:10 pkg/api/dashboard.go:406:13 pkg/api/folder.go:98:22 (goconst) pkg/api/index.go:63:47:warning: 2 other occurrence(s) of "light" found in: pkg/api/index.go:91:22 pkg/api/index.go:93:16 (goconst) pkg/api/index.go:91:22:warning: 2 other occurrence(s) of "light" found in: pkg/api/index.go:63:47 pkg/api/index.go:93:16 (goconst) pkg/api/index.go:93:16:warning: 2 other occurrence(s) of "light" found in: pkg/api/index.go:63:47 pkg/api/index.go:91:22 (goconst) pkg/components/null/float.go:71:25:warning: 2 other occurrence(s) of "null" found in: pkg/components/null/float.go:103:10 pkg/components/null/float.go:112:10 (goconst) pkg/components/null/float.go:103:10:warning: 2 other occurrence(s) of "null" found in: pkg/components/null/float.go:71:25 pkg/components/null/float.go:112:10 (goconst) pkg/components/null/float.go:112:10:warning: 2 other occurrence(s) of "null" found in: pkg/components/null/float.go:71:25 pkg/components/null/float.go:103:10 (goconst) pkg/services/alerting/notifiers/pagerduty.go:79:16:warning: 2 other occurrence(s) of "Triggered metrics:\n\n" found in: pkg/services/alerting/notifiers/kafka.go:64:16 pkg/services/alerting/notifiers/opsgenie.go:98:16 (goconst) pkg/services/alerting/notifiers/kafka.go:64:16:warning: 2 other occurrence(s) of "Triggered metrics:\n\n" found in: pkg/services/alerting/notifiers/pagerduty.go:79:16 pkg/services/alerting/notifiers/opsgenie.go:98:16 (goconst) pkg/services/alerting/notifiers/opsgenie.go:98:16:warning: 2 other occurrence(s) of "Triggered metrics:\n\n" found in: pkg/services/alerting/notifiers/pagerduty.go:79:16 pkg/services/alerting/notifiers/kafka.go:64:16 (goconst) pkg/social/social.go:85:11:warning: 2 other occurrence(s) of "grafana_com" found in: pkg/social/social.go:162:14 pkg/social/social.go:197:11 (goconst) pkg/social/social.go:162:14:warning: 2 other occurrence(s) of "grafana_com" found in: pkg/social/social.go:85:11 pkg/social/social.go:197:11 (goconst) pkg/social/social.go:197:11:warning: 2 other occurrence(s) of "grafana_com" found in: pkg/social/social.go:85:11 pkg/social/social.go:162:14 (goconst) pkg/tsdb/elasticsearch/time_series_query.go:92:17:warning: 3 other occurrence(s) of "count" found in: pkg/tsdb/elasticsearch/response_parser.go:152:8 pkg/tsdb/elasticsearch/response_parser.go:167:31 pkg/tsdb/elasticsearch/response_parser.go:315:9 (goconst) pkg/tsdb/elasticsearch/response_parser.go:152:8:warning: 3 other occurrence(s) of "count" found in: pkg/tsdb/elasticsearch/time_series_query.go:92:17 pkg/tsdb/elasticsearch/response_parser.go:167:31 pkg/tsdb/elasticsearch/response_parser.go:315:9 (goconst) pkg/tsdb/elasticsearch/response_parser.go:167:31:warning: 3 other occurrence(s) of "count" found in: pkg/tsdb/elasticsearch/time_series_query.go:92:17 pkg/tsdb/elasticsearch/response_parser.go:152:8 pkg/tsdb/elasticsearch/response_parser.go:315:9 (goconst) pkg/tsdb/elasticsearch/response_parser.go:315:9:warning: 3 other occurrence(s) of "count" found in: pkg/tsdb/elasticsearch/time_series_query.go:92:17 pkg/tsdb/elasticsearch/response_parser.go:152:8 pkg/tsdb/elasticsearch/response_parser.go:167:31 (goconst) pkg/tsdb/elasticsearch/time_series_query.go:78:9:warning: 2 other occurrence(s) of "date_histogram" found in: pkg/tsdb/elasticsearch/response_parser.go:84:22 pkg/tsdb/elasticsearch/response_parser.go:369:24 (goconst) pkg/tsdb/elasticsearch/response_parser.go:84:22:warning: 2 other occurrence(s) of "date_histogram" found in: pkg/tsdb/elasticsearch/time_series_query.go:78:9 pkg/tsdb/elasticsearch/response_parser.go:369:24 (goconst) pkg/tsdb/elasticsearch/response_parser.go:369:24:warning: 2 other occurrence(s) of "date_histogram" found in: pkg/tsdb/elasticsearch/time_series_query.go:78:9 pkg/tsdb/elasticsearch/response_parser.go:84:22 (goconst)
2018-09-22 03:50:00 -05:00
customData := triggMetrString
for _, evt := range evalContext.EvalMatches {
customData += fmt.Sprintf("%s: %v\n", evt.Metric, evt.Value)
}
2016-12-06 14:48:13 -06:00
bodyJSON := simplejson.New()
bodyJSON.Set("message", evalContext.Rule.Name)
bodyJSON.Set("source", "Grafana")
bodyJSON.Set("alias", "alertId-"+strconv.FormatInt(evalContext.Rule.ID, 10))
bodyJSON.Set("description", fmt.Sprintf("%s - %s\n%s\n%s", evalContext.Rule.Name, ruleURL, evalContext.Rule.Message, customData))
2016-12-06 14:48:13 -06:00
details := simplejson.New()
details.Set("url", ruleURL)
if on.NeedsImage() && evalContext.ImagePublicURL != "" {
details.Set("image", evalContext.ImagePublicURL)
2016-12-06 14:48:13 -06:00
}
tags := make([]string, 0)
for _, tag := range evalContext.Rule.AlertRuleTags {
Alerting: Allow sending notification tags to Opsgenie as extra properties (#30332) * Alerting: Opsgenie send tags as extra properties Allow users to select where to send notification tags when alerting via OpsGenie. Supports sending tags as key/value details, concatenated strings in tags or both. Users will be able to see their tags as key/values under extra properties in an alert on the Opsgenie UI. These key/values can then be used in the platform for routing, templating etc. * Configurable delivery to either tags, extra properties or both * Default to current behaviour (tags only) * Support both so users can transition from tags to details Add docs and clean up references * Alerting: Add additional arg for Opsgenie tests The NewEvalContext function now requires a 'PluginRequestValidator' argument. As our test does not use the validator we can specify 'nil' to satisfy the function and allow our test to pass as expected. * Alerting: Opsgenie doc fixes Accept suggested changes for Opsgenie docs Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Alerting: Opsgenie provisioning settings docs Add the new setting to the provisioning docs * Alerting: Opsgenie doc typo correction Move the comma (,) out of the preformatting tags for the setting value * Alerting: Opsgenie refactor send switches Refactor the send switches to be methods on the OpsgenieNotiefier itself. This also cleans up the method names so that the code reads a bit more logically as: if we should send details: send details if we should send tags: send tags This avoids the calling code needing to care about passing the state and allows an engineer working in the `createAlert` function to focus on the results of applying the logic instead. * Alerting: Opsgenie docs rename note Rename the note heading to match the number to more clearly link them. * Alerting: Opsgenie use standard reference to note Refer to the note below as per recommendation and standards. Fixes #30331 Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
2021-03-24 11:07:26 -05:00
if on.sendDetails() {
details.Set(tag.Key, tag.Value)
}
if on.sendTags() {
if len(tag.Value) > 0 {
tags = append(tags, fmt.Sprintf("%s:%s", tag.Key, tag.Value))
} else {
tags = append(tags, tag.Key)
}
}
if tag.Key == "og_priority" {
if on.OverridePriority {
validPriorities := map[string]bool{"P1": true, "P2": true, "P3": true, "P4": true, "P5": true}
if validPriorities[tag.Value] {
bodyJSON.Set("priority", tag.Value)
}
}
}
}
bodyJSON.Set("tags", tags)
Alerting: Allow sending notification tags to Opsgenie as extra properties (#30332) * Alerting: Opsgenie send tags as extra properties Allow users to select where to send notification tags when alerting via OpsGenie. Supports sending tags as key/value details, concatenated strings in tags or both. Users will be able to see their tags as key/values under extra properties in an alert on the Opsgenie UI. These key/values can then be used in the platform for routing, templating etc. * Configurable delivery to either tags, extra properties or both * Default to current behaviour (tags only) * Support both so users can transition from tags to details Add docs and clean up references * Alerting: Add additional arg for Opsgenie tests The NewEvalContext function now requires a 'PluginRequestValidator' argument. As our test does not use the validator we can specify 'nil' to satisfy the function and allow our test to pass as expected. * Alerting: Opsgenie doc fixes Accept suggested changes for Opsgenie docs Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Alerting: Opsgenie provisioning settings docs Add the new setting to the provisioning docs * Alerting: Opsgenie doc typo correction Move the comma (,) out of the preformatting tags for the setting value * Alerting: Opsgenie refactor send switches Refactor the send switches to be methods on the OpsgenieNotiefier itself. This also cleans up the method names so that the code reads a bit more logically as: if we should send details: send details if we should send tags: send tags This avoids the calling code needing to care about passing the state and allows an engineer working in the `createAlert` function to focus on the results of applying the logic instead. * Alerting: Opsgenie docs rename note Rename the note heading to match the number to more clearly link them. * Alerting: Opsgenie use standard reference to note Refer to the note below as per recommendation and standards. Fixes #30331 Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
2021-03-24 11:07:26 -05:00
bodyJSON.Set("details", details)
2016-12-06 14:48:13 -06:00
body, _ := bodyJSON.MarshalJSON()
cmd := &models.SendWebhookSync{
Url: on.APIUrl,
2016-12-06 14:48:13 -06:00
Body: string(body),
HttpMethod: "POST",
2017-10-05 00:42:45 -05:00
HttpHeader: map[string]string{
"Content-Type": "application/json",
"Authorization": fmt.Sprintf("GenieKey %s", on.APIKey),
2017-10-05 00:42:45 -05:00
},
2016-12-06 14:48:13 -06:00
}
if err := on.NotificationService.SendWebhookSync(evalContext.Ctx, cmd); err != nil {
on.log.Error("Failed to send notification to OpsGenie", "error", err, "body", string(body))
2016-12-06 14:48:13 -06:00
}
return nil
}
func (on *OpsGenieNotifier) closeAlert(evalContext *alerting.EvalContext) error {
on.log.Info("Closing OpsGenie alert", "ruleId", evalContext.Rule.ID, "notification", on.Name)
2016-12-06 14:48:13 -06:00
bodyJSON := simplejson.New()
bodyJSON.Set("source", "Grafana")
2016-12-06 14:48:13 -06:00
body, _ := bodyJSON.MarshalJSON()
cmd := &models.SendWebhookSync{
Url: fmt.Sprintf("%s/alertId-%d/close?identifierType=alias", on.APIUrl, evalContext.Rule.ID),
2016-12-06 14:48:13 -06:00
Body: string(body),
HttpMethod: "POST",
2017-10-05 00:42:45 -05:00
HttpHeader: map[string]string{
"Content-Type": "application/json",
"Authorization": fmt.Sprintf("GenieKey %s", on.APIKey),
2017-10-05 00:42:45 -05:00
},
2016-12-06 14:48:13 -06:00
}
if err := on.NotificationService.SendWebhookSync(evalContext.Ctx, cmd); err != nil {
on.log.Error("Failed to send notification to OpsGenie", "error", err, "body", string(body))
return err
2016-12-06 14:48:13 -06:00
}
return nil
}
Alerting: Allow sending notification tags to Opsgenie as extra properties (#30332) * Alerting: Opsgenie send tags as extra properties Allow users to select where to send notification tags when alerting via OpsGenie. Supports sending tags as key/value details, concatenated strings in tags or both. Users will be able to see their tags as key/values under extra properties in an alert on the Opsgenie UI. These key/values can then be used in the platform for routing, templating etc. * Configurable delivery to either tags, extra properties or both * Default to current behaviour (tags only) * Support both so users can transition from tags to details Add docs and clean up references * Alerting: Add additional arg for Opsgenie tests The NewEvalContext function now requires a 'PluginRequestValidator' argument. As our test does not use the validator we can specify 'nil' to satisfy the function and allow our test to pass as expected. * Alerting: Opsgenie doc fixes Accept suggested changes for Opsgenie docs Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Alerting: Opsgenie provisioning settings docs Add the new setting to the provisioning docs * Alerting: Opsgenie doc typo correction Move the comma (,) out of the preformatting tags for the setting value * Alerting: Opsgenie refactor send switches Refactor the send switches to be methods on the OpsgenieNotiefier itself. This also cleans up the method names so that the code reads a bit more logically as: if we should send details: send details if we should send tags: send tags This avoids the calling code needing to care about passing the state and allows an engineer working in the `createAlert` function to focus on the results of applying the logic instead. * Alerting: Opsgenie docs rename note Rename the note heading to match the number to more clearly link them. * Alerting: Opsgenie use standard reference to note Refer to the note below as per recommendation and standards. Fixes #30331 Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
2021-03-24 11:07:26 -05:00
func (on *OpsGenieNotifier) sendDetails() bool {
return on.SendTagsAs == sendDetails || on.SendTagsAs == sendBoth
}
func (on *OpsGenieNotifier) sendTags() bool {
return on.SendTagsAs == sendTags || on.SendTagsAs == sendBoth
}