diff --git a/docs/index.md b/docs/index.md index 75b6e33d..5dfe0a4b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -14,19 +14,7 @@ resource. * Global Application Alert Configuration - `instana_global_application_alert_config` * Event Settings * Custom Event Specification - `instana_custom_event_specification` - * Entity Verification Rule - `instana_custom_event_spec_entity_verification_rule` - * System Rule - `instana_custom_event_spec_system_rule` - * Threshold Rule - `instana_custom_event_spec_threshold_rule` * Alerting Channels - `instana_alerting_channel` - * Email - `instana_alerting_channel_email` - * Google Chat - `instana_alerting_channel_google_chat` - * Office 365 - `instana_alerting_channel_office_365` - * OpsGenie - `instana_alerting_channel_ops_genie` - * Pager Duty - `instana_alerting_channel_pager_duty` - * Slack - `instana_alerting_channel_slack` - * Splunk - `instana_alerting_channel_splunk` - * VictorOps - `instana_alerting_channel_victor_ops` - * Webhook - `instana_alerting_channel_webhook` * Alerting Config - `instana_alerting_config` * Settings * API Tokens - `instana_api_token` diff --git a/docs/resources/custom_event_spec_entity_verification_rule.md b/docs/resources/custom_event_spec_entity_verification_rule.md deleted file mode 100644 index d4ba89b8..00000000 --- a/docs/resources/custom_event_spec_entity_verification_rule.md +++ /dev/null @@ -1,52 +0,0 @@ -# Custom Event Specification with Entity Verification Rule Resource - -**Deprecated** use `instana_custom_event_specification` - -Configuration of a custom event specification based on an entity verification rule. This rule type is used -to check for hosts which do not have matching entities running on them. - -API Documentation: - -## Example Usage - -```hcl -resource "instana_custom_event_spec_entity_verification_rule" "example" { - name = "name" - description = "description" - query = "query" - enabled = true - triggering = true - expiration_time = 60000 - - rule_severity = "warning" - rule_matching_entity_type = "process" - rule_matching_operator = "is" #allowed values: is, contains, startsWith, starts_with, endsWith, ends_with - rule_matching_entity_label = "entity-label" - rule_offline_duration = 60000 -} -``` - -## Argument Reference - -* `name` - Required - The name of the custom event specification -* `description` - Required - The description text of the custom event specification -* `query` - Optional - The dynamic filter query for which the rule should be applied to -* `enabled` - Optional - Boolean flag if the rule should be enabled - default = true -* `triggering` - Optional - Boolean flag if the rule should trigger an incident - default = false -* `expiration_time` - Optional - The grace period in milliseconds until the issue is closed -* `rule_severity` - Required - The severity of the rule - allowed values: `warning`, `critical` -* `rule_matching_entity_type` - Required - The entity type used to check for matching entities on the selected hosts. -Supported entity types (plugins) can be retrieved from the Instana REST API using the path -`/api/infrastructure-monitoring/catalog/plugins`. -* `rule_matching_operator` - Required - The comparison operator used to check for matching entities on the selected hosts. -Allowed values: `is`, `contains`, `startsWith`, `starts_with`, `endsWith`, `ends_with` -* `rule_matching_entity_label` - Required - The label/string to check for matching entities on the selected hosts -* `rule_offline_duration` - Required - The duration in milliseconds to wait until the entity is considered as offline - -## Import - -Custom event specifications with entity verification rule can be imported using the `id`, e.g.: - -``` -$ terraform import instana_custom_event_spec_entity_verification_rule.my_event_spec 60845e4e5e6b9cf8fc2868da -``` diff --git a/docs/resources/custom_event_spec_system_rule.md b/docs/resources/custom_event_spec_system_rule.md deleted file mode 100644 index 072a6bf1..00000000 --- a/docs/resources/custom_event_spec_system_rule.md +++ /dev/null @@ -1,42 +0,0 @@ -# Custom Event Specification with System Rule Resource - -**Deprecated** use `instana_custom_event_specification` - -Configuration of a custom event specification based on a system rule. - -API Documentation: - -## Example Usage - -```hcl -resource "instana_custom_event_spec_system_rule" "example" { - name = "name" - description = "description" - query = "query" - enabled = true - triggering = true - expiration_time = 60000 - - rule_severity = "warning" - rule_system_rule_id = "system-rule-id" -} -``` - -## Argument Reference - -* `name` - Required - The name of the custom event specification -* `description` - Required - The description text of the custom event specification -* `query` - Optional - The dynamic filter query for which the rule should be applied to -* `enabled` - Optional - Boolean flag if the rule should be enabled - default = true -* `triggering` - Optional - Boolean flag if the rule should trigger an incident - default = false -* `expiration_time` - Optional - The grace period in milliseconds until the issue is closed -* `rule_severity` - Required - The severity of the rule - allowed values: `warning`, `critical` -* `rule_system_rule_id` - Required - The id of the instana system rule of the given even - -## Import - -Custom event specifications with system rule can be imported using the `id`, e.g.: - -``` -$ terraform import instana_custom_event_spec_system_rule.my_event_spec 60845e4e5e6b9cf8fc2868da -``` diff --git a/docs/resources/custom_event_spec_threshold_rule.md b/docs/resources/custom_event_spec_threshold_rule.md deleted file mode 100644 index aaf9e424..00000000 --- a/docs/resources/custom_event_spec_threshold_rule.md +++ /dev/null @@ -1,123 +0,0 @@ -# Custom Event Specification with Threshold Rule Resource - -**Deprecated** use `instana_custom_event_specification` - -Configuration of a custom event specification based on a threshold rule. A threshold rule is verifies if a certain -condition applies to a given metric. Therefore you can either use `rule_rollup` or `rule_window` or both to define -the data points which should be evaluated. Instana API always returns max. 600 data points for validation. - -- `rule_window` = the time frame in seconds where the aggregation is applied to -- `rule_rollup` = the resolution of the data points which are considered for this event (See also ) - -Both are optional in the Instana API. Usually configurations define a **window** for calculating the event. - -API Documentation: - -## Example Usage - -### Built in metric - -```hcl -resource "instana_custom_event_spec_threshold_rule" "nomad_pending_allocations" { - name = "Nomad pending allocations" - description = "Pending allocations in nomad. Ensure the EC2 auto-scaling group is configured correct and sufficient instances are running" - query = "entity.tag:\"stage=prod\"" - enabled = true - triggering = true - expiration_time = 60000 - entity_type = "nomadScheduler" - - rule_severity = "critical" - rule_metric_name = "nomad.client.allocations.pending" - rule_window = 60000 - rule_aggregation = "avg" - rule_condition_operator = ">" - rule_condition_value = 0 -} -``` - -### Built in dynamic metric - -```hcl -resource "instana_custom_event_spec_threshold_rule" "mysql_number_of_writes" { - name = "mysql-number-of-writes-exceeded" - description = "Insert count exceeds supported write operations" - query = "entity.tag:\"stage=prod\"" - enabled = true - triggering = true - expiration_time = 60000 - entity_type = "mySqlDatabase" - - rule_severity = "warning" - rule_window = 60000 - rule_aggregation = "avg" - rule_condition_operator = ">" - rule_condition_value = 1000000 - - rule_metric_pattern_prefix = "databases" - rule_metric_pattern_postfix = "insert_count" - rule_metric_pattern_placeholder = "myschema" - rule_metric_pattern_operator = "is" -} -``` - -### Custom metric - -```hcl -resource "instana_custom_event_spec_threshold_rule" "custom_health_metrics_unhealthy" { - name = "MyApp is unhealthy" - description = "The custom health indicator of the application switched to unhealthy" - query = "entity.tag:\"stage=prod\" AND entity.service.name:myapp" - enabled = true - triggering = true - expiration_time = 60000 - entity_type = "jvmRuntimePlatform" - - rule_severity = "warning" - rule_metric_name = "metrics.gauges.myapp.healthIndicator" - rule_window = 10000 - rule_aggregation = "avg" - rule_condition_operator = "=" - rule_condition_value = 1 -} -``` - -## Argument Reference - -* `name` - Required - The name of the custom event specification -* `description` - Required - The description text of the custom event specification -* `query` - Optional - The dynamic filter query for which the rule should be applied to -* `enabled` - Optional - Boolean flag if the rule should be enabled - default = true -* `triggering` - Optional - Boolean flag if the rule should trigger an incident - default = false -* `expiration_time` - Optional - The grace period in milliseconds until the issue is closed -* `entity_type` - Required - The entity type/plugin for which the verification rule will be defined -Supported entity types (plugins) can be retrieved from the Instana REST API using the path -`/api/infrastructure-monitoring/catalog/plugins`. -* `rule_severity` - Required - The severity of the rule - allowed values: `warning`, `critical` - -* `rule_metric_name` - Required (Built-In and Custom Metrics only) The name of the built in or custom metric name (supported -built in metrics can be retrieved from the REST API using the endpoint `/api/infrastructure-monitoring/catalog/metrics/{plugin}`) - -* `rule_metric_pattern_prefix` - Required (Dynamic Built-In Metrics only) The prefix of the built in dynamic metric -* `rule_metric_pattern_postfix` - Optional (Dynamic Built-In Metrics only) The postfix of the built in dynamic metric -* `rule_metric_pattern_placeholder` - Required (Dynamic Built-In Metrics only) The placeholder string of the dynamic metric -* `rule_metric_pattern_operator` - Required (Dynamic Built-In Metrics only) The operation used to check for matching -placeholder string. Allowed values: `is`, `contains`, `any`, `startsWith`, `endsWith` - -* `rule_window` - Optional - The time window in milliseconds within the rule condition is applied to -* `rule_rollup` - Optional - The resolution of the monitored metrics -* `rule_aggregation` - Optional (depending on metric type) - the aggregation used to calculate the metric value for the given -time window and/or rollup. Supported value: `sum`, `avg`, `min`, `max` -* `rule_condition_operator` - Required - The condition operator used to check against the calculated metric value for the given -time window and/or rollup. Supported values: `=` (`==` also supported as an alternative representation for equals), `!=`, `<=`, -`<`, `>`, `=>` -* `rule_condition_value` - Required - The numeric condition value used to check against the calculated metric value for the given -time window and/or rollup. - -## Import - -Custom event specifications with threshold rule can be imported using the `id`, e.g.: - -``` -$ terraform import instana_custom_event_spec_threshold_rule.my_event_spec 60845e4e5e6b9cf8fc2868da -``` diff --git a/instana/provider.go b/instana/provider.go index d9e6b1fc..641ffe2c 100644 --- a/instana/provider.go +++ b/instana/provider.go @@ -62,9 +62,6 @@ func providerResources() map[string]*schema.Resource { bindResourceHandle(resources, NewApplicationAlertConfigResourceHandle()) bindResourceHandle(resources, NewGlobalApplicationAlertConfigResourceHandle()) bindResourceHandle(resources, NewCustomEventSpecificationResourceHandle()) - bindResourceHandle(resources, NewCustomEventSpecificationWithSystemRuleResourceHandle()) - bindResourceHandle(resources, NewCustomEventSpecificationWithThresholdRuleResourceHandle()) - bindResourceHandle(resources, NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle()) bindResourceHandle(resources, NewAlertingChannelResourceHandle()) bindResourceHandle(resources, NewAlertingConfigResourceHandle()) bindResourceHandle(resources, NewSliConfigResourceHandle()) diff --git a/instana/provider_test.go b/instana/provider_test.go index 35cd6ad5..d5291c24 100644 --- a/instana/provider_test.go +++ b/instana/provider_test.go @@ -5,7 +5,6 @@ import ( . "github.com/gessnerfl/terraform-provider-instana/instana" "github.com/gessnerfl/terraform-provider-instana/testutils" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/stretchr/testify/assert" ) @@ -30,7 +29,7 @@ func TestProviderShouldContainValidSchemaDefinition(t *testing.T) { func TestProviderShouldContainValidResourceDefinitions(t *testing.T) { config := Provider() - assert.Equal(t, 16, len(config.ResourcesMap)) + assert.Equal(t, 13, len(config.ResourcesMap)) assert.NotNil(t, config.ResourcesMap[ResourceInstanaAPIToken]) assert.NotNil(t, config.ResourcesMap[ResourceInstanaApplicationConfig]) @@ -45,14 +44,6 @@ func TestProviderShouldContainValidResourceDefinitions(t *testing.T) { assert.NotNil(t, config.ResourcesMap[ResourceInstanaCustomEventSpecification]) assert.NotNil(t, config.ResourcesMap[ResourceInstanaAlertingChannel]) assert.NotNil(t, config.ResourcesMap[ResourceInstanaAlertingConfig]) - - validateResourcesMapForCustomEvents(config.ResourcesMap, t) -} - -func validateResourcesMapForCustomEvents(resourceMap map[string]*schema.Resource, t *testing.T) { - assert.NotNil(t, resourceMap[ResourceInstanaCustomEventSpecificationSystemRule]) - assert.NotNil(t, resourceMap[ResourceInstanaCustomEventSpecificationThresholdRule]) - assert.NotNil(t, resourceMap[ResourceInstanaCustomEventSpecificationEntityVerificationRule]) } func TestProviderShouldContainValidDataSourceDefinitions(t *testing.T) { diff --git a/instana/resource-custom-event-specficiation-entity-verification-rule.go b/instana/resource-custom-event-specficiation-entity-verification-rule.go deleted file mode 100644 index 24922205..00000000 --- a/instana/resource-custom-event-specficiation-entity-verification-rule.go +++ /dev/null @@ -1,197 +0,0 @@ -package instana - -import ( - "context" - "github.com/gessnerfl/terraform-provider-instana/tfutils" - - "github.com/gessnerfl/terraform-provider-instana/instana/restapi" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -) - -// ResourceInstanaCustomEventSpecificationEntityVerificationRule the name of the terraform-provider-instana resource to manage custom event specifications with entity verification rule -const ResourceInstanaCustomEventSpecificationEntityVerificationRule = "instana_custom_event_spec_entity_verification_rule" - -const ( - //EntityVerificationRuleFieldMatchingEntityType constant value for the schema field matching_entity_type - EntityVerificationRuleFieldMatchingEntityType = ruleFieldPrefix + "matching_entity_type" - //EntityVerificationRuleFieldMatchingOperator constant value for the schema field matching_operator - EntityVerificationRuleFieldMatchingOperator = ruleFieldPrefix + "matching_operator" - //EntityVerificationRuleFieldMatchingEntityLabel constant value for the schema field matching_entity_label - EntityVerificationRuleFieldMatchingEntityLabel = ruleFieldPrefix + "matching_entity_label" - //EntityVerificationRuleFieldOfflineDuration constant value for the schema field offline_duration - EntityVerificationRuleFieldOfflineDuration = ruleFieldPrefix + "offline_duration" -) - -// EntityVerificationRuleEntityType the fix entity_type of entity verification rules -const EntityVerificationRuleEntityType = "host" - -var entityVerificationRuleSchemaFields = map[string]*schema.Schema{ - CustomEventSpecificationFieldEntityType: { - Type: schema.TypeString, - Computed: true, - Description: "The computed entity type of a entity verification rule 'host'", - }, - EntityVerificationRuleFieldMatchingEntityType: { - Type: schema.TypeString, - Required: true, - Description: "The type of the matching entity", - }, - EntityVerificationRuleFieldMatchingOperator: { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(restapi.SupportedMatchingOperators.TerrafromSupportedValues(), false), - StateFunc: func(val interface{}) string { - operator, _ := restapi.SupportedMatchingOperators.FromTerraformValue(val.(string)) - return operator.InstanaAPIValue() - }, - Description: "The operator which should be applied for matching the label for the given entity (e.g. IS, CONTAINS, STARTS_WITH, ENDS_WITH, NONE)", - }, - EntityVerificationRuleFieldMatchingEntityLabel: { - Type: schema.TypeString, - Required: true, - Description: "The label of the matching entity", - }, - EntityVerificationRuleFieldOfflineDuration: { - Type: schema.TypeInt, - Required: true, - Description: "The duration after which the matching entity is considered to be offline", - }, -} - -// NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle creates a new ResourceHandle for the terraform resource of custom event specifications with entity verification rules -func NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle() ResourceHandle[*restapi.CustomEventSpecification] { - commons := &customEventSpecificationCommons{} - deprecationNote := "This feature will be removed in version 2.x and should be replaced with instana_custom_event_specification" - return &customEventSpecificationWithEntityVerificationRuleResource{ - metaData: ResourceMetaData{ - ResourceName: ResourceInstanaCustomEventSpecificationEntityVerificationRule, - Schema: MergeSchemaMap(defaultCustomEventSchemaFields, entityVerificationRuleSchemaFields), - SchemaVersion: 4, - DeprecationMessage: deprecationNote, - }, - commons: commons, - } -} - -type customEventSpecificationWithEntityVerificationRuleResource struct { - metaData ResourceMetaData - commons *customEventSpecificationCommons -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) MetaData() *ResourceMetaData { - return &r.metaData -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) StateUpgraders() []schema.StateUpgrader { - return []schema.StateUpgrader{ - { - Type: r.schemaV0().CoreConfigSchema().ImpliedType(), - Upgrade: r.commons.migrateCustomEventConfigFullNameInStateFromV0toV1, - Version: 0, - }, - { - Type: r.schemaV1().CoreConfigSchema().ImpliedType(), - Upgrade: r.commons.migrateCustomEventConfigFullStateFromV1toV2AndRemoveDownstreamConfiguration, - Version: 1, - }, - { - Type: r.schemaV2().CoreConfigSchema().ImpliedType(), - Upgrade: r.migrateCustomEventConfigWithEntityVerificationRuleToVersion3ByChangingMatchingOperatorToInstanaRepresentation, - Version: 2, - }, - { - Type: r.schemaV3().CoreConfigSchema().ImpliedType(), - Upgrade: r.commons.migrateCustomEventConfigFullStateFromV2toV3AndRemoveFullname, - Version: 3, - }, - } -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) GetRestResource(api restapi.InstanaAPI) restapi.RestResource[*restapi.CustomEventSpecification] { - return api.CustomEventSpecifications() -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) SetComputedFields(d *schema.ResourceData) error { - return d.Set(CustomEventSpecificationFieldEntityType, EntityVerificationRuleEntityType) -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) UpdateState(d *schema.ResourceData, customEventSpecification *restapi.CustomEventSpecification) error { - data := r.commons.getDataForBasicCustomEventSpecification(customEventSpecification) - - ruleSpec := customEventSpecification.Rules[0] - severity, err := ConvertSeverityFromInstanaAPIToTerraformRepresentation(ruleSpec.Severity) - if err != nil { - return err - } - matchingOperator, err := ruleSpec.MatchingOperatorType() - if err != nil { - return err - } - data[CustomEventSpecificationRuleSeverity] = severity - data[EntityVerificationRuleFieldMatchingEntityLabel] = ruleSpec.MatchingEntityLabel - data[EntityVerificationRuleFieldMatchingEntityType] = ruleSpec.MatchingEntityType - data[EntityVerificationRuleFieldMatchingOperator] = matchingOperator.InstanaAPIValue() - data[EntityVerificationRuleFieldOfflineDuration] = ruleSpec.OfflineDuration - - d.SetId(customEventSpecification.ID) - return tfutils.UpdateState(d, data) -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) MapStateToDataObject(d *schema.ResourceData) (*restapi.CustomEventSpecification, error) { - severity, err := ConvertSeverityFromTerraformToInstanaAPIRepresentation(d.Get(CustomEventSpecificationRuleSeverity).(string)) - if err != nil { - return &restapi.CustomEventSpecification{}, err - } - entityLabel := d.Get(EntityVerificationRuleFieldMatchingEntityLabel).(string) - entityType := d.Get(EntityVerificationRuleFieldMatchingEntityType).(string) - - matchingOperatorString := d.Get(EntityVerificationRuleFieldMatchingOperator).(string) - matchingOperator, err := restapi.SupportedMatchingOperators.FromTerraformValue(matchingOperatorString) - if err != nil { - return &restapi.CustomEventSpecification{}, err - } - offlineDuration := d.Get(EntityVerificationRuleFieldOfflineDuration).(int) - - rule := restapi.NewEntityVerificationRuleSpecification(entityLabel, entityType, matchingOperator.InstanaAPIValue(), offlineDuration, severity) - - customEventSpecification := r.commons.createCustomEventSpecificationFromResourceData(d) - customEventSpecification.Rules = []restapi.RuleSpecification{rule} - return customEventSpecification, nil -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) schemaV0() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV0, entityVerificationRuleSchemaFields), - } -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) schemaV1() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV1, entityVerificationRuleSchemaFields), - } -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) schemaV2() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV1, entityVerificationRuleSchemaFields), - } -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) migrateCustomEventConfigWithEntityVerificationRuleToVersion3ByChangingMatchingOperatorToInstanaRepresentation(_ context.Context, rawState map[string]interface{}, _ interface{}) (map[string]interface{}, error) { - v, ok := rawState[EntityVerificationRuleFieldMatchingOperator] - if ok { - operator, err := restapi.SupportedMatchingOperators.FromTerraformValue(v.(string)) - if err != nil { - return rawState, err - } - rawState[EntityVerificationRuleFieldMatchingOperator] = operator.InstanaAPIValue() - } - return rawState, nil -} - -func (r *customEventSpecificationWithEntityVerificationRuleResource) schemaV3() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV2, entityVerificationRuleSchemaFields), - } -} diff --git a/instana/resource-custom-event-specficiation-entity-verification-rule_test.go b/instana/resource-custom-event-specficiation-entity-verification-rule_test.go deleted file mode 100644 index ed21bdc2..00000000 --- a/instana/resource-custom-event-specficiation-entity-verification-rule_test.go +++ /dev/null @@ -1,411 +0,0 @@ -package instana_test - -import ( - "context" - "fmt" - "strconv" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/stretchr/testify/require" - - . "github.com/gessnerfl/terraform-provider-instana/instana" - "github.com/gessnerfl/terraform-provider-instana/instana/restapi" - "github.com/gessnerfl/terraform-provider-instana/testutils" -) - -const resourceCustomEventSpecificationWithEntityVerificationRuleDefinitionTemplate = ` -resource "instana_custom_event_spec_entity_verification_rule" "example" { - name = "name %d" - query = "query" - enabled = true - triggering = true - description = "description" - expiration_time = 60000 - rule_severity = "warning" - rule_matching_entity_type = "matching-entity-type" - rule_matching_operator = "starts_with" - rule_matching_entity_label = "matching-entity-label" - rule_offline_duration = 60000 -} -` - -const ( - testCustomEventSpecificationWithEntityVerificationRuleDefinition = ResourceInstanaCustomEventSpecificationEntityVerificationRule + ".example" - - customEntityVerificationEventID = "custom-entity-verification-event-id" - customEntityVerificationEventName = resourceName - customEntityVerificationEventQuery = "query" - customEntityVerificationEventExpirationTime = 60000 - customEntityVerificationEventDescription = "description" - customEntityVerificationEventRuleMatchingEntityLabel = "matching-entity-label" - customEntityVerificationEventRuleMatchingEntityType = "matching-entity-type" - customEntityVerificationEventRuleOfflineDuration = 60000 -) - -var customEntityVerificationEventRuleMatchingOperator = restapi.MatchingOperatorStartsWith -var customEntityVerificationEventRuleSeverity = restapi.SeverityWarning.GetTerraformRepresentation() - -func TestCRUDOfCreateResourceCustomEventSpecificationWithEntityVerificationRuleResourceWithMockServer(t *testing.T) { - responseTemplate := ` - { - "id" : "%s", - "name" : "name %d", - "query" : "query", - "entityType" : "host", - "enabled" : true, - "triggering" : true, - "description" : "description", - "expirationTime" : 60000, - "rules" : [ { "ruleType" : "entity_verification", "severity" : 5, "matchingEntityLabel" : "matching-entity-label", "matchingEntityType" : "matching-entity-type", "matchingOperator" : "startsWith", "offlineDuration" : 60000 } ] - } - ` - httpServer := createMockHttpServerForResource(restapi.CustomEventSpecificationResourcePath, responseTemplate) - httpServer.Start() - defer httpServer.Close() - - resource.UnitTest(t, resource.TestCase{ - ProviderFactories: testProviderFactory, - Steps: []resource.TestStep{ - createCustomEventSpecificationWithEntityVerificationRuleResourceTestStep(httpServer.GetPort(), 0), - testStepImport(testCustomEventSpecificationWithEntityVerificationRuleDefinition), - createCustomEventSpecificationWithEntityVerificationRuleResourceTestStep(httpServer.GetPort(), 1), - testStepImport(testCustomEventSpecificationWithEntityVerificationRuleDefinition), - }, - }) -} - -func createCustomEventSpecificationWithEntityVerificationRuleResourceTestStep(httpPort int64, iteration int) resource.TestStep { - config := appendProviderConfig(fmt.Sprintf(resourceCustomEventSpecificationWithEntityVerificationRuleDefinitionTemplate, iteration), httpPort) - return resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet(testCustomEventSpecificationWithEntityVerificationRuleDefinition, "id"), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, CustomEventSpecificationFieldName, formatResourceName(iteration)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, CustomEventSpecificationFieldEntityType, EntityVerificationRuleEntityType), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, CustomEventSpecificationFieldQuery, customEntityVerificationEventQuery), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, CustomEventSpecificationFieldTriggering, trueAsString), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, CustomEventSpecificationFieldDescription, customEntityVerificationEventDescription), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, CustomEventSpecificationFieldExpirationTime, strconv.Itoa(customEntityVerificationEventExpirationTime)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, CustomEventSpecificationFieldEnabled, trueAsString), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, CustomEventSpecificationRuleSeverity, customEntityVerificationEventRuleSeverity), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, EntityVerificationRuleFieldMatchingEntityLabel, customEntityVerificationEventRuleMatchingEntityLabel), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, EntityVerificationRuleFieldMatchingEntityType, customEntityVerificationEventRuleMatchingEntityType), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, EntityVerificationRuleFieldMatchingOperator, customEntityVerificationEventRuleMatchingOperator.InstanaAPIValue()), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithEntityVerificationRuleDefinition, EntityVerificationRuleFieldOfflineDuration, strconv.Itoa(customEntityVerificationEventRuleOfflineDuration)), - ), - } -} - -func TestCustomEventSpecificationWithEntityVerificationRuleSchemaDefinitionIsValid(t *testing.T) { - schema := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().MetaData().Schema - - schemaAssert := testutils.NewTerraformSchemaAssert(schema, t) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(CustomEventSpecificationFieldName) - schemaAssert.AssertSchemaIsComputedAndOfTypeString(CustomEventSpecificationFieldEntityType) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(CustomEventSpecificationFieldQuery) - schemaAssert.AssertSchemaIsOfTypeBooleanWithDefault(CustomEventSpecificationFieldTriggering, false) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(CustomEventSpecificationFieldDescription) - schemaAssert.AssertSchemaIsOptionalAndOfTypeInt(CustomEventSpecificationFieldExpirationTime) - schemaAssert.AssertSchemaIsOfTypeBooleanWithDefault(CustomEventSpecificationFieldEnabled, true) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(CustomEventSpecificationRuleSeverity) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(EntityVerificationRuleFieldMatchingEntityLabel) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(EntityVerificationRuleFieldMatchingEntityType) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(EntityVerificationRuleFieldMatchingOperator) - schemaAssert.AssertSchemaIsRequiredAndOfTypeInt(EntityVerificationRuleFieldOfflineDuration) -} - -func TestCustomEventSpecificationWithEntityVerificationRuleResourceShouldHaveSchemaVersionFour(t *testing.T) { - require.Equal(t, 4, NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().MetaData().SchemaVersion) -} - -func TestCustomEventSpecificationWithEntityVerificationRuleShouldHaveFourStateUpgraderForVersionZeroToThree(t *testing.T) { - resourceHandler := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle() - - require.Equal(t, 4, len(resourceHandler.StateUpgraders())) - require.Equal(t, 0, resourceHandler.StateUpgraders()[0].Version) - require.Equal(t, 1, resourceHandler.StateUpgraders()[1].Version) - require.Equal(t, 2, resourceHandler.StateUpgraders()[2].Version) - require.Equal(t, 3, resourceHandler.StateUpgraders()[3].Version) -} - -func TestShouldMigrateCustomEventSpecificationWithEntityVerificationRuleStateAndAddFullNameWithSameValueAsNameWhenMigratingFromVersion0To1(t *testing.T) { - name := "Test Name" - rawData := make(map[string]interface{}) - rawData[CustomEventSpecificationFieldName] = name - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().StateUpgraders()[0].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Equal(t, name, result[CustomEventSpecificationFieldFullName]) -} - -func TestShouldMigrateEmptyCustomEventSpecificationWithEntityVerificationRuleStateFromVersion0To1(t *testing.T) { - rawData := make(map[string]interface{}) - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().StateUpgraders()[1].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result[CustomEventSpecificationFieldFullName]) -} - -func TestShouldMigrateCustomEventSpecificationWithEntityVerificationRuleStateToVersion2WhenDownstreamConfigurationIsProvided(t *testing.T) { - rawData := make(map[string]interface{}) - rawData["downstream_integration_ids"] = []interface{}{"id1", "id2"} - rawData["downstream_broadcast_to_all_alerting_configs"] = true - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().StateUpgraders()[1].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result["downstream_integration_ids"]) - require.Nil(t, result["downstream_broadcast_to_all_alerting_configs"]) -} - -func TestShouldMigrateCustomEventSpecificationWithEntityVerificationRuleStateToVersion2WhenNoDownstreamConfigurationIsProvided(t *testing.T) { - rawData := make(map[string]interface{}) - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().StateUpgraders()[0].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result["downstream_integration_ids"]) - require.Nil(t, result["downstream_broadcast_to_all_alerting_configs"]) -} - -func TestShouldMigrateCustomEventSpecificationWithEntityVerificationRuleStateToVersion3WhenMatchingOperatorIsDefinedAndValid(t *testing.T) { - for _, mo := range restapi.SupportedMatchingOperators { - for _, v := range mo.TerraformSupportedValues() { - t.Run(fmt.Sprintf("TestShouldMigrateCustomEventSpecificationWithEntityVerificationRuleStateToVersion3WhenMatchingOperatorIsDefinedAndValid%s", v), createTestCaseForSuccessfulMigrationOfCustomEventSpecificationWithEntityVerificationRuleToVersion3(mo, v)) - } - } -} - -func createTestCaseForSuccessfulMigrationOfCustomEventSpecificationWithEntityVerificationRuleToVersion3(mo restapi.MatchingOperator, value string) func(*testing.T) { - return func(t *testing.T) { - rawData := make(map[string]interface{}) - rawData[EntityVerificationRuleFieldMatchingOperator] = value - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().StateUpgraders()[2].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Equal(t, mo.InstanaAPIValue(), result[EntityVerificationRuleFieldMatchingOperator]) - } -} - -func TestShouldDoNothingWhenMigratingCustomEventSpecificationWithEntityVerificationRuleToVersion3AndNoMatchingOperatorIsDefined(t *testing.T) { - rawData := make(map[string]interface{}) - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().StateUpgraders()[2].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result[EntityVerificationRuleFieldMatchingOperator]) -} - -func TestShouldReturnErrorWhenCustomEventSpecificationWithEntityVerificationRuleCannotBeMigratedToVersion3BecauseOfUnsupportedMatchingOperatorInState(t *testing.T) { - rawData := make(map[string]interface{}) - rawData[EntityVerificationRuleFieldMatchingOperator] = "invalid" - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().StateUpgraders()[2].Upgrade(ctx, rawData, meta) - - require.NotNil(t, err) - require.Contains(t, err.Error(), "not a supported matching operator") - require.Equal(t, rawData, result) -} - -func TestCustomEventSpecificationWithEntityVerificationRuleShouldMigrateFullnameToNameWhenExecutingForthStateUpgraderAndFullnameIsAvailable(t *testing.T) { - input := map[string]interface{}{ - "full_name": "test", - } - result, err := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().StateUpgraders()[3].Upgrade(nil, input, nil) - - require.NoError(t, err) - require.Len(t, result, 1) - require.NotContains(t, result, CustomEventSpecificationFieldFullName) - require.Contains(t, result, CustomEventSpecificationFieldName) - require.Equal(t, "test", result[CustomEventSpecificationFieldName]) -} - -func TestCustomEventSpecificationWithEntityVerificationRuleShouldDoNothingWhenExecutingForthStateUpgraderAndFullnameIsAvailable(t *testing.T) { - input := map[string]interface{}{ - "name": "test", - } - result, err := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().StateUpgraders()[3].Upgrade(nil, input, nil) - - require.NoError(t, err) - require.Equal(t, input, result) -} - -func TestShouldReturnCorrectResourceNameForCustomEventSpecificationWithEntityVerificationRuleResource(t *testing.T) { - name := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle().MetaData().ResourceName - - require.Equal(t, name, "instana_custom_event_spec_entity_verification_rule") -} - -func TestShouldUpdateCustomEventSpecificationWithEntityVerificationRuleTerraformStateFromApiObject(t *testing.T) { - description := customEntityVerificationEventDescription - expirationTime := customEntityVerificationEventExpirationTime - query := customEntityVerificationEventQuery - spec := &restapi.CustomEventSpecification{ - ID: customEntityVerificationEventID, - Name: customEntityVerificationEventName, - EntityType: EntityVerificationRuleEntityType, - Query: &query, - Description: &description, - ExpirationTime: &expirationTime, - Triggering: true, - Enabled: true, - Rules: []restapi.RuleSpecification{ - restapi.NewEntityVerificationRuleSpecification(customEntityVerificationEventRuleMatchingEntityLabel, - customEntityVerificationEventRuleMatchingEntityType, - customEntityVerificationEventRuleMatchingOperator.InstanaAPIValue(), - customEntityVerificationEventRuleOfflineDuration, - restapi.SeverityWarning.GetAPIRepresentation()), - }, - } - - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - sut := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle() - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(sut) - - err := sut.UpdateState(resourceData, spec) - - require.Nil(t, err) - require.Equal(t, customEntityVerificationEventID, resourceData.Id()) - require.Equal(t, customEntityVerificationEventName, resourceData.Get(CustomEventSpecificationFieldName)) - require.Equal(t, EntityVerificationRuleEntityType, resourceData.Get(CustomEventSpecificationFieldEntityType)) - require.Equal(t, customEntityVerificationEventQuery, resourceData.Get(CustomEventSpecificationFieldQuery)) - require.Equal(t, description, resourceData.Get(CustomEventSpecificationFieldDescription)) - require.True(t, resourceData.Get(CustomEventSpecificationFieldTriggering).(bool)) - require.True(t, resourceData.Get(CustomEventSpecificationFieldEnabled).(bool)) - - require.Equal(t, customEntityVerificationEventRuleMatchingEntityLabel, resourceData.Get(EntityVerificationRuleFieldMatchingEntityLabel)) - require.Equal(t, customEntityVerificationEventRuleMatchingEntityType, resourceData.Get(EntityVerificationRuleFieldMatchingEntityType)) - require.Equal(t, customEntityVerificationEventRuleMatchingOperator.InstanaAPIValue(), resourceData.Get(EntityVerificationRuleFieldMatchingOperator)) - require.Equal(t, customEntityVerificationEventRuleOfflineDuration, resourceData.Get(EntityVerificationRuleFieldOfflineDuration)) - require.Equal(t, restapi.SeverityWarning.GetTerraformRepresentation(), resourceData.Get(CustomEventSpecificationRuleSeverity)) -} - -func TestShouldFailToUpdateTerraformStateForCustomEventSpecificationWithEntityVerificationRuleWhenMatchingOperatorTypeIsNotSupported(t *testing.T) { - description := customEntityVerificationEventDescription - expirationTime := customEntityVerificationEventExpirationTime - query := customEntityVerificationEventQuery - spec := &restapi.CustomEventSpecification{ - ID: customEntityVerificationEventID, - Name: customEntityVerificationEventName, - EntityType: EntityVerificationRuleEntityType, - Query: &query, - Description: &description, - ExpirationTime: &expirationTime, - Triggering: true, - Enabled: true, - Rules: []restapi.RuleSpecification{ - restapi.NewEntityVerificationRuleSpecification(customEntityVerificationEventRuleMatchingEntityLabel, - customEntityVerificationEventRuleMatchingEntityType, - "invalid", - customEntityVerificationEventRuleOfflineDuration, - restapi.SeverityWarning.GetAPIRepresentation()), - }, - } - - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - sut := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle() - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(sut) - - err := sut.UpdateState(resourceData, spec) - - require.NotNil(t, err) - require.Contains(t, err.Error(), "invalid is not a supported matching operator") -} - -func TestShouldSuccessfullyConvertCustomEventSpecificationWithEntityVerificationRuleStateToDataModel(t *testing.T) { - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - resourceHandle := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle() - - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(resourceHandle) - - resourceData.SetId(customEntityVerificationEventID) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldName, customEntityVerificationEventName) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldEntityType, EntityVerificationRuleEntityType) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldQuery, customEntityVerificationEventQuery) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldTriggering, true) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldDescription, customEntityVerificationEventDescription) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldExpirationTime, customEntityVerificationEventExpirationTime) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldEnabled, true) - setValueOnResourceData(t, resourceData, CustomEventSpecificationRuleSeverity, customEntityVerificationEventRuleSeverity) - setValueOnResourceData(t, resourceData, EntityVerificationRuleFieldMatchingEntityLabel, customEntityVerificationEventRuleMatchingEntityLabel) - setValueOnResourceData(t, resourceData, EntityVerificationRuleFieldMatchingEntityType, customEntityVerificationEventRuleMatchingEntityType) - setValueOnResourceData(t, resourceData, EntityVerificationRuleFieldMatchingOperator, customEntityVerificationEventRuleMatchingOperator.InstanaAPIValue()) - setValueOnResourceData(t, resourceData, EntityVerificationRuleFieldOfflineDuration, customEntityVerificationEventRuleOfflineDuration) - - result, err := resourceHandle.MapStateToDataObject(resourceData) - - require.Nil(t, err) - require.IsType(t, &restapi.CustomEventSpecification{}, result) - require.Equal(t, customEntityVerificationEventID, result.GetIDForResourcePath()) - require.Equal(t, customEntityVerificationEventName, result.Name) - require.Equal(t, EntityVerificationRuleEntityType, result.EntityType) - require.Equal(t, customEntityVerificationEventQuery, *result.Query) - require.Equal(t, customEntityVerificationEventDescription, *result.Description) - require.Equal(t, customEntityVerificationEventExpirationTime, *result.ExpirationTime) - require.True(t, result.Triggering) - require.True(t, result.Enabled) - - require.Equal(t, 1, len(result.Rules)) - require.Equal(t, customEntityVerificationEventRuleMatchingEntityLabel, *result.Rules[0].MatchingEntityLabel) - require.Equal(t, customEntityVerificationEventRuleMatchingEntityType, *result.Rules[0].MatchingEntityType) - require.Equal(t, customEntityVerificationEventRuleMatchingOperator.InstanaAPIValue(), *result.Rules[0].MatchingOperator) - require.Equal(t, customEntityVerificationEventRuleOfflineDuration, *result.Rules[0].OfflineDuration) - require.Equal(t, restapi.SeverityWarning.GetAPIRepresentation(), result.Rules[0].Severity) -} - -func TestShouldFailToConvertCustomEventSpecificationWithEntityVerificationRuleStateToDataModelWhenSeverityIsNotValid(t *testing.T) { - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - resourceHandle := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle() - - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(resourceHandle) - setValueOnResourceData(t, resourceData, CustomEventSpecificationRuleSeverity, "INVALID") - - _, err := resourceHandle.MapStateToDataObject(resourceData) - - require.NotNil(t, err) -} - -func TestShouldFailToConvertCustomEventSpecificationWithEntityVerificationRuleStateToDataModelWhenMatchingOperatorIsMissing(t *testing.T) { - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - resourceHandle := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle() - - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(resourceHandle) - setValueOnResourceData(t, resourceData, CustomEventSpecificationRuleSeverity, customEntityVerificationEventRuleSeverity) - - _, err := resourceHandle.MapStateToDataObject(resourceData) - - require.NotNil(t, err) - require.Contains(t, err.Error(), "is not a supported matching operator") -} - -func TestShouldFailToConvertCustomEventSpecificationWithEntityVerificationRuleStateToDataModelWhenMatchingOperatorIsNotValid(t *testing.T) { - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - resourceHandle := NewCustomEventSpecificationWithEntityVerificationRuleResourceHandle() - - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(resourceHandle) - setValueOnResourceData(t, resourceData, CustomEventSpecificationRuleSeverity, customEntityVerificationEventRuleSeverity) - setValueOnResourceData(t, resourceData, EntityVerificationRuleFieldMatchingOperator, "invalid") - - _, err := resourceHandle.MapStateToDataObject(resourceData) - - require.NotNil(t, err) - require.Contains(t, err.Error(), "invalid is not a supported matching operator") -} diff --git a/instana/resource-custom-event-specficiation-system-rule.go b/instana/resource-custom-event-specficiation-system-rule.go deleted file mode 100644 index 47984617..00000000 --- a/instana/resource-custom-event-specficiation-system-rule.go +++ /dev/null @@ -1,129 +0,0 @@ -package instana - -import ( - "github.com/gessnerfl/terraform-provider-instana/instana/restapi" - "github.com/gessnerfl/terraform-provider-instana/tfutils" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -// ResourceInstanaCustomEventSpecificationSystemRule the name of the terraform-provider-instana resource to manage custom event specifications with system rule -const ResourceInstanaCustomEventSpecificationSystemRule = "instana_custom_event_spec_system_rule" - -const ( - //SystemRuleSpecificationSystemRuleID constant value for the schema field system_rule_id of a rule specification - SystemRuleSpecificationSystemRuleID = ruleFieldPrefix + "system_rule_id" -) - -// SystemRuleEntityType the fix entity_type of entity verification rules -const SystemRuleEntityType = "any" - -var systemRuleSchemaFields = map[string]*schema.Schema{ - CustomEventSpecificationFieldEntityType: { - Type: schema.TypeString, - Computed: true, - Description: "The computed entity type of a entity verification rule 'any'", - }, - SystemRuleSpecificationSystemRuleID: { - Type: schema.TypeString, - Required: true, - Description: "Configures the system rule id for the system rule of the custom event specification", - }, -} - -// NewCustomEventSpecificationWithSystemRuleResourceHandle creates a new ResourceHandle for the terraform resource of custom event specifications with system rules -func NewCustomEventSpecificationWithSystemRuleResourceHandle() ResourceHandle[*restapi.CustomEventSpecification] { - commons := &customEventSpecificationCommons{} - deprecationNote := "This feature will be removed in version 2.x and should be replaced with instana_custom_event_specification" - return &customEventSpecificationWithSystemRuleResource{ - metaData: ResourceMetaData{ - ResourceName: ResourceInstanaCustomEventSpecificationSystemRule, - Schema: MergeSchemaMap(defaultCustomEventSchemaFields, systemRuleSchemaFields), - SchemaVersion: 3, - DeprecationMessage: deprecationNote, - }, - commons: commons, - } -} - -type customEventSpecificationWithSystemRuleResource struct { - metaData ResourceMetaData - commons *customEventSpecificationCommons -} - -func (r *customEventSpecificationWithSystemRuleResource) MetaData() *ResourceMetaData { - return &r.metaData -} - -func (r *customEventSpecificationWithSystemRuleResource) StateUpgraders() []schema.StateUpgrader { - return []schema.StateUpgrader{ - { - Type: r.schemaV0().CoreConfigSchema().ImpliedType(), - Upgrade: r.commons.migrateCustomEventConfigFullNameInStateFromV0toV1, - Version: 0, - }, - { - Type: r.schemaV1().CoreConfigSchema().ImpliedType(), - Upgrade: r.commons.migrateCustomEventConfigFullStateFromV1toV2AndRemoveDownstreamConfiguration, - Version: 1, - }, - { - Type: r.schemaV2().CoreConfigSchema().ImpliedType(), - Upgrade: r.commons.migrateCustomEventConfigFullStateFromV2toV3AndRemoveFullname, - Version: 2, - }, - } -} - -func (r *customEventSpecificationWithSystemRuleResource) GetRestResource(api restapi.InstanaAPI) restapi.RestResource[*restapi.CustomEventSpecification] { - return api.CustomEventSpecifications() -} - -func (r *customEventSpecificationWithSystemRuleResource) SetComputedFields(d *schema.ResourceData) error { - return d.Set(CustomEventSpecificationFieldEntityType, SystemRuleEntityType) -} - -func (r *customEventSpecificationWithSystemRuleResource) UpdateState(d *schema.ResourceData, customEventSpecification *restapi.CustomEventSpecification) error { - data := r.commons.getDataForBasicCustomEventSpecification(customEventSpecification) - - ruleSpec := customEventSpecification.Rules[0] - severity, err := ConvertSeverityFromInstanaAPIToTerraformRepresentation(ruleSpec.Severity) - if err != nil { - return err - } - data[CustomEventSpecificationRuleSeverity] = severity - data[SystemRuleSpecificationSystemRuleID] = ruleSpec.SystemRuleID - - d.SetId(customEventSpecification.ID) - return tfutils.UpdateState(d, data) -} - -func (r *customEventSpecificationWithSystemRuleResource) MapStateToDataObject(d *schema.ResourceData) (*restapi.CustomEventSpecification, error) { - severity, err := ConvertSeverityFromTerraformToInstanaAPIRepresentation(d.Get(CustomEventSpecificationRuleSeverity).(string)) - if err != nil { - return &restapi.CustomEventSpecification{}, err - } - systemRuleID := d.Get(SystemRuleSpecificationSystemRuleID).(string) - rule := restapi.NewSystemRuleSpecification(systemRuleID, severity) - - customEventSpecification := r.commons.createCustomEventSpecificationFromResourceData(d) - customEventSpecification.Rules = []restapi.RuleSpecification{rule} - return customEventSpecification, nil -} - -func (r *customEventSpecificationWithSystemRuleResource) schemaV0() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV0, systemRuleSchemaFields), - } -} - -func (r *customEventSpecificationWithSystemRuleResource) schemaV1() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV1, systemRuleSchemaFields), - } -} - -func (r *customEventSpecificationWithSystemRuleResource) schemaV2() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV2, systemRuleSchemaFields), - } -} diff --git a/instana/resource-custom-event-specficiation-system-rule_test.go b/instana/resource-custom-event-specficiation-system-rule_test.go deleted file mode 100644 index 2b58f157..00000000 --- a/instana/resource-custom-event-specficiation-system-rule_test.go +++ /dev/null @@ -1,280 +0,0 @@ -package instana_test - -import ( - "context" - "fmt" - "strconv" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/stretchr/testify/require" - - . "github.com/gessnerfl/terraform-provider-instana/instana" - "github.com/gessnerfl/terraform-provider-instana/instana/restapi" - "github.com/gessnerfl/terraform-provider-instana/testutils" -) - -const resourceCustomEventSpecificationWithSystemRuleDefinitionTemplate = ` -resource "instana_custom_event_spec_system_rule" "example" { - name = "name %d" - query = "query" - enabled = true - triggering = true - description = "description" - expiration_time = 60000 - rule_severity = "warning" - rule_system_rule_id = "system-rule-id" -} -` - -const ( - testCustomEventSpecificationWithSystemRuleDefinition = "instana_custom_event_spec_system_rule.example" - - customSystemEventID = "custom-system-event-id" - customSystemEventName = resourceName - customSystemEventQuery = "query" - customSystemEventExpirationTime = 60000 - customSystemEventDescription = "description" - customSystemEventRuleSystemRuleId = "system-rule-id" -) - -var customSystemEventRuleSeverity = restapi.SeverityWarning.GetTerraformRepresentation() - -func TestCRUDOfCreateResourceCustomEventSpecificationWithSystemdRuleResourceWithMockServer(t *testing.T) { - responseTemplate := ` - { - "id" : "%s", - "name" : "name %d", - "entityType" : "any", - "query" : "query", - "enabled" : true, - "triggering" : true, - "description" : "description", - "expirationTime" : 60000, - "rules" : [ { "ruleType" : "system", "severity" : 5, "systemRuleId" : "system-rule-id" } ] - } - ` - httpServer := createMockHttpServerForResource(restapi.CustomEventSpecificationResourcePath, responseTemplate) - httpServer.Start() - defer httpServer.Close() - - resource.UnitTest(t, resource.TestCase{ - ProviderFactories: testProviderFactory, - Steps: []resource.TestStep{ - createCustomEventSpecificationWithSystemRuleResourceTestStep(httpServer.GetPort(), 0), - testStepImport(testCustomEventSpecificationWithSystemRuleDefinition), - createCustomEventSpecificationWithSystemRuleResourceTestStep(httpServer.GetPort(), 1), - testStepImport(testCustomEventSpecificationWithSystemRuleDefinition), - }, - }) -} - -func createCustomEventSpecificationWithSystemRuleResourceTestStep(httpPort int64, iteration int) resource.TestStep { - config := appendProviderConfig(fmt.Sprintf(resourceCustomEventSpecificationWithSystemRuleDefinitionTemplate, iteration), httpPort) - return resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet(testCustomEventSpecificationWithSystemRuleDefinition, "id"), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithSystemRuleDefinition, CustomEventSpecificationFieldName, formatResourceName(iteration)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithSystemRuleDefinition, CustomEventSpecificationFieldEntityType, SystemRuleEntityType), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithSystemRuleDefinition, CustomEventSpecificationFieldQuery, customSystemEventQuery), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithSystemRuleDefinition, CustomEventSpecificationFieldTriggering, trueAsString), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithSystemRuleDefinition, CustomEventSpecificationFieldDescription, customSystemEventDescription), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithSystemRuleDefinition, CustomEventSpecificationFieldExpirationTime, strconv.Itoa(customSystemEventExpirationTime)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithSystemRuleDefinition, CustomEventSpecificationFieldEnabled, trueAsString), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithSystemRuleDefinition, CustomEventSpecificationRuleSeverity, customSystemEventRuleSeverity), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithSystemRuleDefinition, SystemRuleSpecificationSystemRuleID, customSystemEventRuleSystemRuleId), - ), - } -} - -func TestCustomEventSpecificationWithSystemRuleSchemaDefinitionIsValid(t *testing.T) { - schema := NewCustomEventSpecificationWithSystemRuleResourceHandle().MetaData().Schema - - schemaAssert := testutils.NewTerraformSchemaAssert(schema, t) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(CustomEventSpecificationFieldName) - schemaAssert.AssertSchemaIsComputedAndOfTypeString(CustomEventSpecificationFieldEntityType) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(CustomEventSpecificationFieldQuery) - schemaAssert.AssertSchemaIsOfTypeBooleanWithDefault(CustomEventSpecificationFieldTriggering, false) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(CustomEventSpecificationFieldDescription) - schemaAssert.AssertSchemaIsOptionalAndOfTypeInt(CustomEventSpecificationFieldExpirationTime) - schemaAssert.AssertSchemaIsOfTypeBooleanWithDefault(CustomEventSpecificationFieldEnabled, true) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(CustomEventSpecificationRuleSeverity) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(SystemRuleSpecificationSystemRuleID) -} - -func TestCustomEventSpecificationWithSystemRuleResourceShouldHaveSchemaVersionThree(t *testing.T) { - require.Equal(t, 3, NewCustomEventSpecificationWithSystemRuleResourceHandle().MetaData().SchemaVersion) -} - -func TestCustomEventSpecificationWithSystemRuleShouldHaveThreeStateUpgraderForVersionZeroToTwo(t *testing.T) { - resourceHandler := NewCustomEventSpecificationWithSystemRuleResourceHandle() - - require.Equal(t, 3, len(resourceHandler.StateUpgraders())) - require.Equal(t, 0, resourceHandler.StateUpgraders()[0].Version) - require.Equal(t, 1, resourceHandler.StateUpgraders()[1].Version) - require.Equal(t, 2, resourceHandler.StateUpgraders()[2].Version) -} - -func TestShouldMigrateCustomEventSpecificationWithSystemRuleStateAndAddFullNameWithSameValueAsNameWhenMigratingFromVersion0To1(t *testing.T) { - name := "Test Name" - rawData := make(map[string]interface{}) - rawData[CustomEventSpecificationFieldName] = name - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithSystemRuleResourceHandle().StateUpgraders()[0].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Equal(t, name, result[CustomEventSpecificationFieldFullName]) -} - -func TestShouldMigrateEmptyCustomEventSpecificationWithSystemRuleStateFromVersion0To1(t *testing.T) { - rawData := make(map[string]interface{}) - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithSystemRuleResourceHandle().StateUpgraders()[0].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result[CustomEventSpecificationFieldFullName]) -} - -func TestShouldMigrateCustomEventSpecificationWithSystemRuleStateToVersion2WhenDownstreamConfigurationIsProvided(t *testing.T) { - rawData := make(map[string]interface{}) - rawData["downstream_integration_ids"] = []interface{}{"id1", "id2"} - rawData["downstream_broadcast_to_all_alerting_configs"] = true - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithSystemRuleResourceHandle().StateUpgraders()[1].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result["downstream_integration_ids"]) - require.Nil(t, result["downstream_broadcast_to_all_alerting_configs"]) -} - -func TestShouldMigrateCustomEventSpecificationWithSystemRuleStateToVersion2WhenNoDownstreamConfigurationIsProvided(t *testing.T) { - rawData := make(map[string]interface{}) - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithSystemRuleResourceHandle().StateUpgraders()[0].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result["downstream_integration_ids"]) - require.Nil(t, result["downstream_broadcast_to_all_alerting_configs"]) -} - -func TestCustomEventSpecificationWithSystemRuleShouldMigrateFullnameToNameWhenExecutingThirdStateUpgraderAndFullnameIsAvailable(t *testing.T) { - input := map[string]interface{}{ - "full_name": "test", - } - result, err := NewCustomEventSpecificationWithSystemRuleResourceHandle().StateUpgraders()[2].Upgrade(nil, input, nil) - - require.NoError(t, err) - require.Len(t, result, 1) - require.NotContains(t, result, CustomEventSpecificationFieldFullName) - require.Contains(t, result, CustomEventSpecificationFieldName) - require.Equal(t, "test", result[CustomEventSpecificationFieldName]) -} - -func TestCustomEventSpecificationWithSystemRuleShouldDoNothingWhenExecutingThirdStateUpgraderAndFullnameIsAvailable(t *testing.T) { - input := map[string]interface{}{ - "name": "test", - } - result, err := NewCustomEventSpecificationWithSystemRuleResourceHandle().StateUpgraders()[2].Upgrade(nil, input, nil) - - require.NoError(t, err) - require.Equal(t, input, result) -} - -func TestShouldReturnCorrectResourceNameForCustomEventSpecificationWithSystemRuleResource(t *testing.T) { - name := NewCustomEventSpecificationWithSystemRuleResourceHandle().MetaData().ResourceName - - require.Equal(t, name, "instana_custom_event_spec_system_rule") -} - -func TestShouldUpdateCustomEventSpecificationWithSystemRuleTerraformStateFromApiObject(t *testing.T) { - description := customSystemEventDescription - expirationTime := customSystemEventExpirationTime - query := customSystemEventQuery - spec := restapi.CustomEventSpecification{ - ID: customSystemEventID, - Name: customSystemEventName, - EntityType: SystemRuleEntityType, - Query: &query, - Description: &description, - ExpirationTime: &expirationTime, - Triggering: true, - Enabled: true, - Rules: []restapi.RuleSpecification{ - restapi.NewSystemRuleSpecification(customSystemEventRuleSystemRuleId, restapi.SeverityWarning.GetAPIRepresentation()), - }, - } - - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - sut := NewCustomEventSpecificationWithSystemRuleResourceHandle() - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(sut) - - err := sut.UpdateState(resourceData, &spec) - - require.Nil(t, err) - require.Equal(t, customSystemEventID, resourceData.Id()) - require.Equal(t, customSystemEventName, resourceData.Get(CustomEventSpecificationFieldName)) - require.Equal(t, SystemRuleEntityType, resourceData.Get(CustomEventSpecificationFieldEntityType)) - require.Equal(t, customSystemEventQuery, resourceData.Get(CustomEventSpecificationFieldQuery)) - require.Equal(t, description, resourceData.Get(CustomEventSpecificationFieldDescription)) - require.True(t, resourceData.Get(CustomEventSpecificationFieldTriggering).(bool)) - require.True(t, resourceData.Get(CustomEventSpecificationFieldEnabled).(bool)) - - require.Equal(t, customSystemEventRuleSystemRuleId, resourceData.Get(SystemRuleSpecificationSystemRuleID)) - require.Equal(t, restapi.SeverityWarning.GetTerraformRepresentation(), resourceData.Get(CustomEventSpecificationRuleSeverity)) -} - -func TestShouldSuccessfullyConvertCustomEventSpecificationWithSystemRuleStateToDataModel(t *testing.T) { - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - resourceHandle := NewCustomEventSpecificationWithSystemRuleResourceHandle() - - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(resourceHandle) - - resourceData.SetId(customSystemEventID) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldName, customSystemEventName) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldEntityType, SystemRuleEntityType) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldQuery, customSystemEventQuery) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldTriggering, true) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldDescription, customSystemEventDescription) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldExpirationTime, customSystemEventExpirationTime) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldEnabled, true) - setValueOnResourceData(t, resourceData, CustomEventSpecificationRuleSeverity, customSystemEventRuleSeverity) - setValueOnResourceData(t, resourceData, SystemRuleSpecificationSystemRuleID, customSystemEventRuleSystemRuleId) - - result, err := resourceHandle.MapStateToDataObject(resourceData) - - require.Nil(t, err) - require.IsType(t, &restapi.CustomEventSpecification{}, result) - require.Equal(t, customSystemEventID, result.GetIDForResourcePath()) - require.Equal(t, customSystemEventName, result.Name) - require.Equal(t, SystemRuleEntityType, result.EntityType) - require.Equal(t, customSystemEventQuery, *result.Query) - require.Equal(t, customSystemEventDescription, *result.Description) - require.Equal(t, customSystemEventExpirationTime, *result.ExpirationTime) - require.True(t, result.Triggering) - require.True(t, result.Enabled) - - require.Equal(t, 1, len(result.Rules)) - require.Equal(t, customSystemEventRuleSystemRuleId, *result.Rules[0].SystemRuleID) - require.Equal(t, restapi.SeverityWarning.GetAPIRepresentation(), result.Rules[0].Severity) -} - -func TestShouldFailToConvertCustomEventSpecificationWithSystemRuleStateToDataModelWhenSeverityIsNotValid(t *testing.T) { - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - resourceHandle := NewCustomEventSpecificationWithSystemRuleResourceHandle() - - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(resourceHandle) - setValueOnResourceData(t, resourceData, CustomEventSpecificationRuleSeverity, "INVALID") - - _, err := resourceHandle.MapStateToDataObject(resourceData) - - require.NotNil(t, err) -} diff --git a/instana/resource-custom-event-specficiation-threshold-rule.go b/instana/resource-custom-event-specficiation-threshold-rule.go deleted file mode 100644 index f817dd82..00000000 --- a/instana/resource-custom-event-specficiation-threshold-rule.go +++ /dev/null @@ -1,299 +0,0 @@ -package instana - -import ( - "context" - "github.com/gessnerfl/terraform-provider-instana/tfutils" - - "github.com/gessnerfl/terraform-provider-instana/instana/restapi" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -) - -// ResourceInstanaCustomEventSpecificationThresholdRule the name of the terraform-provider-instana resource to manage custom event specifications with threshold rule -const ResourceInstanaCustomEventSpecificationThresholdRule = "instana_custom_event_spec_threshold_rule" - -const ( - //ThresholdRuleFieldMetricName constant value for the schema field rule_metric_name - ThresholdRuleFieldMetricName = ruleFieldPrefix + "metric_name" - //ThresholdRuleFieldRollup constant value for the schema field rule_rollup - ThresholdRuleFieldRollup = ruleFieldPrefix + "rollup" - //ThresholdRuleFieldWindow constant value for the schema field rule_window - ThresholdRuleFieldWindow = ruleFieldPrefix + "window" - //ThresholdRuleFieldAggregation constant value for the schema field rule_aggregation - ThresholdRuleFieldAggregation = ruleFieldPrefix + "aggregation" - //ThresholdRuleFieldConditionOperator constant value for the schema field rule_condition_operator - ThresholdRuleFieldConditionOperator = ruleFieldPrefix + "condition_operator" - //ThresholdRuleFieldConditionValue constant value for the schema field rule_condition_value - ThresholdRuleFieldConditionValue = ruleFieldPrefix + "condition_value" - - thresholdRuleFieldMetricPattern = ruleFieldPrefix + "metric_pattern_" - //ThresholdRuleFieldMetricPatternPrefix constant value for the schema field rule_metric_pattern_prefix - ThresholdRuleFieldMetricPatternPrefix = thresholdRuleFieldMetricPattern + "prefix" - //ThresholdRuleFieldMetricPatternPostfix constant value for the schema field rule_metric_pattern_postfix - ThresholdRuleFieldMetricPatternPostfix = thresholdRuleFieldMetricPattern + "postfix" - //ThresholdRuleFieldMetricPatternPlaceholder constant value for the schema field rule_metric_pattern_placeholder - ThresholdRuleFieldMetricPatternPlaceholder = thresholdRuleFieldMetricPattern + "placeholder" - //ThresholdRuleFieldMetricPatternOperator constant value for the schema field rule_metric_pattern_operator - ThresholdRuleFieldMetricPatternOperator = thresholdRuleFieldMetricPattern + "operator" -) - -var metricNameOrPattern = []string{ - ThresholdRuleFieldMetricName, ThresholdRuleFieldMetricPatternPrefix, -} - -var windowOrRollup = []string{ - ThresholdRuleFieldWindow, ThresholdRuleFieldRollup, -} - -var thresholdRuleSchemaFields = map[string]*schema.Schema{ - CustomEventSpecificationFieldEntityType: { - Type: schema.TypeString, - Required: true, - Description: "Configures the entity type of the custom event specification", - }, - ThresholdRuleFieldMetricName: { - Type: schema.TypeString, - Required: false, - Optional: true, - Description: "The metric name of the rule", - ExactlyOneOf: metricNameOrPattern, - }, - ThresholdRuleFieldRollup: { - Type: schema.TypeInt, - Required: false, - Optional: true, - Description: "The rollup of the metric", - ExactlyOneOf: windowOrRollup, - }, - ThresholdRuleFieldWindow: { - Type: schema.TypeInt, - Required: false, - Optional: true, - Description: "The time window where the condition has to be fulfilled", - ExactlyOneOf: windowOrRollup, - }, - ThresholdRuleFieldAggregation: { - Type: schema.TypeString, - Required: false, - Optional: true, - ValidateFunc: validation.StringInSlice(restapi.SupportedAggregationTypes.ToStringSlice(), false), - Description: "The aggregation type (e.g. sum, avg)", - }, - ThresholdRuleFieldConditionOperator: { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(restapi.SupportedConditionOperators.TerrafromSupportedValues(), false), - StateFunc: func(val interface{}) string { - operator, _ := restapi.SupportedConditionOperators.FromTerraformValue(val.(string)) - return operator.InstanaAPIValue() - }, - Description: "The condition operator (e.g >, <)", - }, - ThresholdRuleFieldConditionValue: { - Type: schema.TypeFloat, - Required: true, - Description: "The expected condition value to fulfill the rule", - }, - ThresholdRuleFieldMetricPatternPrefix: { - Type: schema.TypeString, - Required: false, - Optional: true, - RequiredWith: []string{ThresholdRuleFieldMetricPatternOperator}, - Description: "The metric pattern prefix of a dynamic built-in metrics", - ExactlyOneOf: metricNameOrPattern, - }, - ThresholdRuleFieldMetricPatternPostfix: { - Type: schema.TypeString, - Required: false, - Optional: true, - Description: "The metric pattern postfix of a dynamic built-in metrics", - }, - ThresholdRuleFieldMetricPatternPlaceholder: { - Type: schema.TypeString, - Required: false, - Optional: true, - Description: "The metric pattern placeholer/condition value of a dynamic built-in metrics", - }, - ThresholdRuleFieldMetricPatternOperator: { - Type: schema.TypeString, - Required: false, - Optional: true, - RequiredWith: []string{ThresholdRuleFieldMetricPatternPrefix}, - ValidateFunc: validation.StringInSlice(restapi.SupportedMetricPatternOperatorTypes.ToStringSlice(), false), - Description: "The condition operator (e.g >, <)", - }, -} - -// NewCustomEventSpecificationWithThresholdRuleResourceHandle creates a new ResourceHandle for the terraform resource of custom event specifications with system rules -func NewCustomEventSpecificationWithThresholdRuleResourceHandle() ResourceHandle[*restapi.CustomEventSpecification] { - commons := &customEventSpecificationCommons{} - deprecationNote := "This feature will be removed in version 2.x and should be replaced with instana_custom_event_specification" - return &customEventSpecificationWithThresholdRuleResource{ - metaData: ResourceMetaData{ - ResourceName: ResourceInstanaCustomEventSpecificationThresholdRule, - Schema: MergeSchemaMap(defaultCustomEventSchemaFields, thresholdRuleSchemaFields), - SchemaVersion: 4, - DeprecationMessage: deprecationNote, - }, - commons: commons, - } -} - -type customEventSpecificationWithThresholdRuleResource struct { - metaData ResourceMetaData - commons *customEventSpecificationCommons -} - -func (r *customEventSpecificationWithThresholdRuleResource) MetaData() *ResourceMetaData { - return &r.metaData -} - -func (r *customEventSpecificationWithThresholdRuleResource) StateUpgraders() []schema.StateUpgrader { - return []schema.StateUpgrader{ - { - Type: r.schemaV0().CoreConfigSchema().ImpliedType(), - Upgrade: r.commons.migrateCustomEventConfigFullNameInStateFromV0toV1, - Version: 0, - }, - { - Type: r.schemaV1().CoreConfigSchema().ImpliedType(), - Upgrade: r.commons.migrateCustomEventConfigFullStateFromV1toV2AndRemoveDownstreamConfiguration, - Version: 1, - }, - { - Type: r.schemaV2().CoreConfigSchema().ImpliedType(), - Upgrade: r.migrateCustomEventConfigWithThreasholdRuleToVersion3ByChangingConditionOperatorToInstanaRepresentation, - Version: 2, - }, - { - Type: r.schemaV3().CoreConfigSchema().ImpliedType(), - Upgrade: r.commons.migrateCustomEventConfigFullStateFromV2toV3AndRemoveFullname, - Version: 3, - }, - } -} - -func (r *customEventSpecificationWithThresholdRuleResource) GetRestResource(api restapi.InstanaAPI) restapi.RestResource[*restapi.CustomEventSpecification] { - return api.CustomEventSpecifications() -} - -func (r *customEventSpecificationWithThresholdRuleResource) SetComputedFields(_ *schema.ResourceData) error { - return nil -} - -func (r *customEventSpecificationWithThresholdRuleResource) UpdateState(d *schema.ResourceData, customEventSpecification *restapi.CustomEventSpecification) error { - ruleSpec := customEventSpecification.Rules[0] - - severity, err := ConvertSeverityFromInstanaAPIToTerraformRepresentation(ruleSpec.Severity) - if err != nil { - return err - } - conditionOperator, err := ruleSpec.ConditionOperatorType() - if err != nil { - return err - } - - data := r.commons.getDataForBasicCustomEventSpecification(customEventSpecification) - data[CustomEventSpecificationRuleSeverity] = severity - data[ThresholdRuleFieldMetricName] = ruleSpec.MetricName - data[ThresholdRuleFieldRollup] = ruleSpec.Rollup - data[ThresholdRuleFieldWindow] = ruleSpec.Window - data[ThresholdRuleFieldAggregation] = ruleSpec.Aggregation - data[ThresholdRuleFieldConditionOperator] = conditionOperator.InstanaAPIValue() - data[ThresholdRuleFieldConditionValue] = ruleSpec.ConditionValue - - if ruleSpec.MetricPattern != nil { - data[ThresholdRuleFieldMetricPatternPrefix] = ruleSpec.MetricPattern.Prefix - data[ThresholdRuleFieldMetricPatternPostfix] = ruleSpec.MetricPattern.Postfix - data[ThresholdRuleFieldMetricPatternPlaceholder] = ruleSpec.MetricPattern.Placeholder - data[ThresholdRuleFieldMetricPatternOperator] = ruleSpec.MetricPattern.Operator - } - - d.SetId(customEventSpecification.ID) - return tfutils.UpdateState(d, data) -} - -func (r *customEventSpecificationWithThresholdRuleResource) MapStateToDataObject(d *schema.ResourceData) (*restapi.CustomEventSpecification, error) { - severity, err := ConvertSeverityFromTerraformToInstanaAPIRepresentation(d.Get(CustomEventSpecificationRuleSeverity).(string)) - if err != nil { - return &restapi.CustomEventSpecification{}, err - } - metricName := d.Get(ThresholdRuleFieldMetricName).(string) - conditionOperatorString := d.Get(ThresholdRuleFieldConditionOperator).(string) - conditionOperator, err := restapi.SupportedConditionOperators.FromTerraformValue(conditionOperatorString) - if err != nil { - return &restapi.CustomEventSpecification{}, err - } - conditionOperatorInstanaValue := conditionOperator.InstanaAPIValue() - - rule := restapi.RuleSpecification{ - DType: restapi.ThresholdRuleType, - Severity: severity, - MetricName: &metricName, - Rollup: GetIntPointerFromResourceData(d, ThresholdRuleFieldRollup), - Window: GetIntPointerFromResourceData(d, ThresholdRuleFieldWindow), - Aggregation: r.getAggregationTypePointerFromResourceData(d, ThresholdRuleFieldAggregation), - ConditionOperator: &conditionOperatorInstanaValue, - ConditionValue: GetFloat64PointerFromResourceData(d, ThresholdRuleFieldConditionValue), - } - - metricPatternPrefix, ok := d.GetOk(ThresholdRuleFieldMetricPatternPrefix) - if ok { - metricPattern := restapi.MetricPattern{ - Prefix: metricPatternPrefix.(string), - Postfix: GetStringPointerFromResourceData(d, ThresholdRuleFieldMetricPatternPostfix), - Placeholder: GetStringPointerFromResourceData(d, ThresholdRuleFieldMetricPatternPlaceholder), - Operator: restapi.MetricPatternOperatorType(d.Get(ThresholdRuleFieldMetricPatternOperator).(string)), - } - rule.MetricPattern = &metricPattern - } - - customEventSpecification := r.commons.createCustomEventSpecificationFromResourceData(d) - customEventSpecification.Rules = []restapi.RuleSpecification{rule} - return customEventSpecification, nil -} - -func (r *customEventSpecificationWithThresholdRuleResource) getAggregationTypePointerFromResourceData(d *schema.ResourceData, key string) *restapi.AggregationType { - val, ok := d.GetOk(key) - if ok { - value := restapi.AggregationType(val.(string)) - return &value - } - return nil -} - -func (r *customEventSpecificationWithThresholdRuleResource) schemaV0() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV0, thresholdRuleSchemaFields), - } -} - -func (r *customEventSpecificationWithThresholdRuleResource) schemaV1() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV1, thresholdRuleSchemaFields), - } -} - -func (r *customEventSpecificationWithThresholdRuleResource) schemaV2() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV1, thresholdRuleSchemaFields), - } -} - -func (r *customEventSpecificationWithThresholdRuleResource) migrateCustomEventConfigWithThreasholdRuleToVersion3ByChangingConditionOperatorToInstanaRepresentation(_ context.Context, rawState map[string]interface{}, _ interface{}) (map[string]interface{}, error) { - v, ok := rawState[ThresholdRuleFieldConditionOperator] - if ok { - operator, err := restapi.SupportedConditionOperators.FromTerraformValue(v.(string)) - if err != nil { - return rawState, err - } - rawState[ThresholdRuleFieldConditionOperator] = operator.InstanaAPIValue() - } - return rawState, nil -} - -func (r *customEventSpecificationWithThresholdRuleResource) schemaV3() *schema.Resource { - return &schema.Resource{ - Schema: MergeSchemaMap(defaultCustomEventSchemaFieldsV2, thresholdRuleSchemaFields), - } -} diff --git a/instana/resource-custom-event-specficiation-threshold-rule_test.go b/instana/resource-custom-event-specficiation-threshold-rule_test.go deleted file mode 100644 index 234fbc68..00000000 --- a/instana/resource-custom-event-specficiation-threshold-rule_test.go +++ /dev/null @@ -1,601 +0,0 @@ -package instana_test - -import ( - "context" - "fmt" - "strconv" - "strings" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/stretchr/testify/require" - - . "github.com/gessnerfl/terraform-provider-instana/instana" - "github.com/gessnerfl/terraform-provider-instana/instana/restapi" - "github.com/gessnerfl/terraform-provider-instana/testutils" -) - -const resourceCustomEventSpecificationWithThresholdRuleAndRollupDefinitionTemplate = ` -resource "instana_custom_event_spec_threshold_rule" "example" { - name = "name %d" - entity_type = "entity_type" - query = "query" - enabled = true - triggering = true - description = "description" - expiration_time = "60000" - rule_severity = "warning" - rule_metric_name = "metric_name" - rule_rollup = "40000" - rule_condition_operator = "=" - rule_condition_value = "1.2" -} -` - -const resourceCustomEventSpecificationWithThresholdRuleAndWindowDefinitionTemplate = ` -resource "instana_custom_event_spec_threshold_rule" "example" { - name = "name %d" - entity_type = "entity_type" - query = "query" - enabled = true - triggering = true - description = "description" - expiration_time = 60000 - rule_severity = "warning" - rule_metric_name = "metric_name" - rule_window = 60000 - rule_aggregation = "sum" - rule_condition_operator = "{{CONDITION_OPERATOR}}" - rule_condition_value = 1.2 -} -` - -const resourceCustomEventSpecificationWithThresholdRuleAndMetricPatternDefinitionTemplate = ` -resource "instana_custom_event_spec_threshold_rule" "example" { - name = "name %d" - entity_type = "entity_type" - query = "query" - enabled = true - triggering = true - description = "description" - expiration_time = 60000 - rule_severity = "warning" - rule_window = 60000 - rule_aggregation = "sum" - rule_condition_operator = "=" - rule_condition_value = 1.2 - rule_metric_pattern_prefix = "prefix" - rule_metric_pattern_postfix = "postfix" - rule_metric_pattern_placeholder = "placeholder" - rule_metric_pattern_operator = "startsWith" -} -` - -const ( - testCustomEventSpecificationWithThresholdRuleDefinition = "instana_custom_event_spec_threshold_rule.example" - - customEventSpecificationWithThresholdRuleID = "custom-system-event-id" - customEventSpecificationWithThresholdRuleEntityType = "entity_type" - customEventSpecificationWithThresholdRuleQuery = "query" - customEventSpecificationWithThresholdRuleExpirationTime = 60000 - customEventSpecificationWithThresholdRuleDescription = "description" - customEventSpecificationWithThresholdRuleMetricName = "metric_name" - customEventSpecificationWithThresholdRuleRollup = 40000 - customEventSpecificationWithThresholdRuleWindow = 60000 - customEventSpecificationWithThresholdRuleAggregation = restapi.AggregationSum - customEventSpecificationWithThresholdRuleConditionValue = float64(1.2) -) - -var CustomEventSpecificationWithThresholdRuleRuleSeverity = restapi.SeverityWarning.GetTerraformRepresentation() - -func TestCRUDOfCustomEventSpecificationWithThresholdRuleWithRollupResourceWithMockServer(t *testing.T) { - ruleAsJson := `{ "ruleType" : "threshold", "severity" : 5, "metricName" : "metric_name", "rollup" : 40000, "conditionOperator" : "=", "conditionValue" : 1.2 }` - testCRUDOfResourceCustomEventSpecificationThresholdRuleResourceWithMockServer( - t, - resourceCustomEventSpecificationWithThresholdRuleAndRollupDefinitionTemplate, - ruleAsJson, - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldMetricName, customEventSpecificationWithThresholdRuleMetricName), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldRollup, strconv.FormatInt(customEventSpecificationWithThresholdRuleRollup, 10)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldConditionOperator, restapi.ConditionOperatorEquals.InstanaAPIValue()), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldConditionValue, "1.2"), - ) -} - -func TestCRUDOfCustomEventSpecificationWithThresholdRuleWithWindowResourceWithMockServer(t *testing.T) { - ruleAsJson := `{ "ruleType" : "threshold", "severity" : 5, "metricName": "metric_name", "window" : 60000, "aggregation": "sum", "conditionOperator" : "=", "conditionValue" : 1.2 }` - testCRUDOfResourceCustomEventSpecificationThresholdRuleResourceWithMockServer( - t, - strings.ReplaceAll(resourceCustomEventSpecificationWithThresholdRuleAndWindowDefinitionTemplate, "{{CONDITION_OPERATOR}}", "="), - ruleAsJson, - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldMetricName, customEventSpecificationWithThresholdRuleMetricName), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldWindow, strconv.FormatInt(customEventSpecificationWithThresholdRuleWindow, 10)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldAggregation, string(customEventSpecificationWithThresholdRuleAggregation)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldConditionOperator, restapi.ConditionOperatorEquals.InstanaAPIValue()), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldConditionValue, "1.2"), - ) -} - -func TestCRUDOfCustomEventSpecificationWithThresholdRuleWithWindowAndAlternativeConditionOperatorRepresentationResourceWithMockServer(t *testing.T) { - ruleAsJson := `{ "ruleType" : "threshold", "severity" : 5, "metricName": "metric_name", "window" : 60000, "aggregation": "sum", "conditionOperator" : "=", "conditionValue" : 1.2 }` - testCRUDOfResourceCustomEventSpecificationThresholdRuleResourceWithMockServer( - t, - strings.ReplaceAll(resourceCustomEventSpecificationWithThresholdRuleAndWindowDefinitionTemplate, "{{CONDITION_OPERATOR}}", "=="), - ruleAsJson, - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldMetricName, customEventSpecificationWithThresholdRuleMetricName), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldWindow, strconv.FormatInt(customEventSpecificationWithThresholdRuleWindow, 10)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldAggregation, string(customEventSpecificationWithThresholdRuleAggregation)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldConditionOperator, restapi.ConditionOperatorEquals.InstanaAPIValue()), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldConditionValue, "1.2"), - ) -} - -func TestCRUDOfCustomEventSpecificationWithThresholdRuleWithMetricPatternResourceWithMockServer(t *testing.T) { - ruleAsJson := `{ "ruleType" : "threshold", "severity" : 5, "window" : 60000, "aggregation": "sum", "conditionOperator" : "=", "conditionValue" : 1.2, "metricPattern" : { "prefix" : "prefix", "postfix" : "postfix", "placeholder" : "placeholder", "operator" : "startsWith" } }` - testCRUDOfResourceCustomEventSpecificationThresholdRuleResourceWithMockServer( - t, - resourceCustomEventSpecificationWithThresholdRuleAndMetricPatternDefinitionTemplate, - ruleAsJson, - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldWindow, strconv.FormatInt(customEventSpecificationWithThresholdRuleWindow, 10)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldAggregation, string(customEventSpecificationWithThresholdRuleAggregation)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldConditionOperator, restapi.ConditionOperatorEquals.InstanaAPIValue()), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldConditionValue, "1.2"), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldMetricPatternPrefix, "prefix"), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldMetricPatternPostfix, "postfix"), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldMetricPatternPlaceholder, "placeholder"), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, ThresholdRuleFieldMetricPatternOperator, string(restapi.MetricPatternOperatorTypeStartsWith)), - ) -} - -const httpServerResponseTemplate = ` -{ - "id" : "%s", - "name" : "name %d", - "entityType" : "entity_type", - "query" : "query", - "enabled" : true, - "triggering" : true, - "description" : "description", - "expirationTime" : 60000, - "rules" : [ %s ] -} -` - -func testCRUDOfResourceCustomEventSpecificationThresholdRuleResourceWithMockServer(t *testing.T, terraformDefinition, ruleAsJson string, ruleTestCheckFunctions ...resource.TestCheckFunc) { - httpServer := createMockHttpServerForResource(restapi.CustomEventSpecificationResourcePath, httpServerResponseTemplate, ruleAsJson) - httpServer.Start() - defer httpServer.Close() - - resource.UnitTest(t, resource.TestCase{ - ProviderFactories: testProviderFactory, - Steps: []resource.TestStep{ - { - Config: appendProviderConfig(fmt.Sprintf(terraformDefinition, 0), httpServer.GetPort()), - Check: resource.ComposeTestCheckFunc(createTestCheckFunctions(ruleTestCheckFunctions, 0)...), - }, - testStepImport(testCustomEventSpecificationWithThresholdRuleDefinition), - { - Config: appendProviderConfig(fmt.Sprintf(terraformDefinition, 1), httpServer.GetPort()), - Check: resource.ComposeTestCheckFunc(createTestCheckFunctions(ruleTestCheckFunctions, 1)...), - }, - testStepImport(testCustomEventSpecificationWithThresholdRuleDefinition), - }, - }) -} - -func createTestCheckFunctions(ruleTestCheckFunctions []resource.TestCheckFunc, iteration int) []resource.TestCheckFunc { - defaultCheckFunctions := []resource.TestCheckFunc{ - resource.TestCheckResourceAttrSet(testCustomEventSpecificationWithThresholdRuleDefinition, "id"), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, CustomEventSpecificationFieldName, formatResourceName(iteration)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, CustomEventSpecificationFieldEntityType, customEventSpecificationWithThresholdRuleEntityType), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, CustomEventSpecificationFieldQuery, customEventSpecificationWithThresholdRuleQuery), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, CustomEventSpecificationFieldTriggering, trueAsString), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, CustomEventSpecificationFieldDescription, customEventSpecificationWithThresholdRuleDescription), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, CustomEventSpecificationFieldExpirationTime, strconv.Itoa(customEventSpecificationWithThresholdRuleExpirationTime)), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, CustomEventSpecificationFieldEnabled, trueAsString), - resource.TestCheckResourceAttr(testCustomEventSpecificationWithThresholdRuleDefinition, CustomEventSpecificationRuleSeverity, CustomEventSpecificationWithThresholdRuleRuleSeverity), - } - allFunctions := append(defaultCheckFunctions, ruleTestCheckFunctions...) - return allFunctions -} - -func TestCustomEventSpecificationWithThresholdRuleSchemaDefinitionIsValid(t *testing.T) { - resourceSchema := NewCustomEventSpecificationWithThresholdRuleResourceHandle().MetaData().Schema - - schemaAssert := testutils.NewTerraformSchemaAssert(resourceSchema, t) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(CustomEventSpecificationFieldName) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(CustomEventSpecificationFieldEntityType) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(CustomEventSpecificationFieldQuery) - schemaAssert.AssertSchemaIsOfTypeBooleanWithDefault(CustomEventSpecificationFieldTriggering, false) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(CustomEventSpecificationFieldDescription) - schemaAssert.AssertSchemaIsOptionalAndOfTypeInt(CustomEventSpecificationFieldExpirationTime) - schemaAssert.AssertSchemaIsOfTypeBooleanWithDefault(CustomEventSpecificationFieldEnabled, true) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(CustomEventSpecificationRuleSeverity) - - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(ThresholdRuleFieldMetricName) - schemaAssert.AssertSchemaIsOptionalAndOfTypeInt(ThresholdRuleFieldWindow) - schemaAssert.AssertSchemaIsOptionalAndOfTypeInt(ThresholdRuleFieldRollup) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(ThresholdRuleFieldAggregation) - schemaAssert.AssertSchemaIsRequiredAndOfTypeString(ThresholdRuleFieldConditionOperator) - schemaAssert.AssertSchemaIsRequiredAndOfTypeFloat(ThresholdRuleFieldConditionValue) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(ThresholdRuleFieldMetricPatternPrefix) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(ThresholdRuleFieldMetricPatternPostfix) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(ThresholdRuleFieldMetricPatternPlaceholder) - schemaAssert.AssertSchemaIsOptionalAndOfTypeString(ThresholdRuleFieldMetricPatternOperator) -} - -func TestCustomEventSpecificationWithThresholdRuleResourceShouldHaveSchemaVersionFour(t *testing.T) { - require.Equal(t, 4, NewCustomEventSpecificationWithThresholdRuleResourceHandle().MetaData().SchemaVersion) -} - -func TestCustomEventSpecificationWithThresholdRuleShouldHaveFourStateUpgraderForVersionZeroAndOneAndTwoAndThree(t *testing.T) { - resourceHandler := NewCustomEventSpecificationWithThresholdRuleResourceHandle() - - require.Equal(t, 4, len(resourceHandler.StateUpgraders())) - require.Equal(t, 0, resourceHandler.StateUpgraders()[0].Version) - require.Equal(t, 1, resourceHandler.StateUpgraders()[1].Version) - require.Equal(t, 2, resourceHandler.StateUpgraders()[2].Version) - require.Equal(t, 3, resourceHandler.StateUpgraders()[3].Version) -} - -func TestShouldMigrateCustomEventSpecificationWithThresholdRuleStateAndAddFullNameWithSameValueAsNameWhenMigratingFromVersion0To1(t *testing.T) { - name := "Test Name" - rawData := make(map[string]interface{}) - rawData[CustomEventSpecificationFieldName] = name - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithThresholdRuleResourceHandle().StateUpgraders()[0].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Equal(t, name, result[CustomEventSpecificationFieldFullName]) -} - -func TestShouldMigrateEmptyCustomEventSpecificationWithThresholdRuleStateFromVersion0To1(t *testing.T) { - rawData := make(map[string]interface{}) - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithThresholdRuleResourceHandle().StateUpgraders()[0].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result[CustomEventSpecificationFieldFullName]) -} - -func TestShouldMigrateCustomEventSpecificationWithThresholdRuleStateToVersion2WhenDownstreamConfigurationIsProvided(t *testing.T) { - rawData := make(map[string]interface{}) - rawData["downstream_integration_ids"] = []interface{}{"id1", "id2"} - rawData["downstream_broadcast_to_all_alerting_configs"] = true - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithThresholdRuleResourceHandle().StateUpgraders()[1].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result["downstream_integration_ids"]) - require.Nil(t, result["downstream_broadcast_to_all_alerting_configs"]) -} - -func TestShouldMigrateCustomEventSpecificationWithThresholdRuleStateToVersion2WhenNoDownstreamConfigurationIsProvided(t *testing.T) { - rawData := make(map[string]interface{}) - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithThresholdRuleResourceHandle().StateUpgraders()[0].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result["downstream_integration_ids"]) - require.Nil(t, result["downstream_broadcast_to_all_alerting_configs"]) -} - -func TestShouldMigrateCustomEventSpecificationWithThresholdRuleStateToVersion3WhenConditionOperatorIsDefinedAndValid(t *testing.T) { - for _, op := range restapi.SupportedConditionOperators { - for _, v := range op.TerraformSupportedValues() { - t.Run(fmt.Sprintf("TestShouldMigrateCustomEventSpecificationWithThresholdRuleStateToVersion3WhenConditionOperatorIsDefinedAndValid%s", v), createTestCaseForSuccessfulMigrationOfCustomEventSpecificationWithThresholdRuleToVersion3(op, v)) - } - } -} - -func createTestCaseForSuccessfulMigrationOfCustomEventSpecificationWithThresholdRuleToVersion3(mo restapi.ConditionOperator, value string) func(*testing.T) { - return func(t *testing.T) { - rawData := make(map[string]interface{}) - rawData[ThresholdRuleFieldConditionOperator] = value - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithThresholdRuleResourceHandle().StateUpgraders()[2].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Equal(t, mo.InstanaAPIValue(), result[ThresholdRuleFieldConditionOperator]) - } -} - -func TestShouldDoNothingWhenMigratingCustomEventSpecificationWithThresholdRuleToVersion3AndNoConditionOperatorIsDefined(t *testing.T) { - rawData := make(map[string]interface{}) - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithThresholdRuleResourceHandle().StateUpgraders()[2].Upgrade(ctx, rawData, meta) - - require.Nil(t, err) - require.Nil(t, result[ThresholdRuleFieldConditionOperator]) -} - -func TestShouldReturnErrorWhenCustomEventSpecificationWithThresholdRuleCannotBeMigratedToVersion3BecuaseOfUnsupportedConditionOperatorInState(t *testing.T) { - rawData := make(map[string]interface{}) - rawData[ThresholdRuleFieldConditionOperator] = "invalid" - meta := "dummy" - ctx := context.Background() - - result, err := NewCustomEventSpecificationWithThresholdRuleResourceHandle().StateUpgraders()[2].Upgrade(ctx, rawData, meta) - - require.NotNil(t, err) - require.Contains(t, err.Error(), "not a supported condition operator") - require.Equal(t, rawData, result) -} - -func TestCustomEventSpecificationWithThresholdRuleShouldMigrateFullnameToNameWhenExecutingForthStateUpgraderAndFullnameIsAvailable(t *testing.T) { - input := map[string]interface{}{ - "full_name": "test", - } - result, err := NewCustomEventSpecificationWithThresholdRuleResourceHandle().StateUpgraders()[3].Upgrade(nil, input, nil) - - require.NoError(t, err) - require.Len(t, result, 1) - require.NotContains(t, result, CustomEventSpecificationFieldFullName) - require.Contains(t, result, CustomEventSpecificationFieldName) - require.Equal(t, "test", result[CustomEventSpecificationFieldName]) -} - -func TestCustomEventSpecificationWithThresholdRuleShouldDoNothingWhenExecutingForthStateUpgraderAndFullnameIsAvailable(t *testing.T) { - input := map[string]interface{}{ - "name": "test", - } - result, err := NewCustomEventSpecificationWithThresholdRuleResourceHandle().StateUpgraders()[3].Upgrade(nil, input, nil) - - require.NoError(t, err) - require.Equal(t, input, result) -} - -func TestShouldReturnCorrectResourceNameForCustomEventSpecificationWithThresholdRuleResource(t *testing.T) { - name := NewCustomEventSpecificationWithThresholdRuleResourceHandle().MetaData().ResourceName - - require.Equal(t, name, "instana_custom_event_spec_threshold_rule") -} - -func TestShouldUpdateCustomEventSpecificationWithThresholdRuleTerraformStateFromApiObject(t *testing.T) { - testMappingOfCustomEventSpecificationWithThresholdRuleTerraformDataModelToState(t, func(spec *restapi.CustomEventSpecification) { /* Default testcase without additional fields =< no additional mappings */ - }, func(resourceData *schema.ResourceData) { /* Default testcase without additional fields => no additional requires */ - }) -} - -func TestShouldUpdateCustomEventSpecificationWithThresholdRuleAndMetricPatternTerraformStateFromApiObject(t *testing.T) { - prefix := "prefix" - postfix := "postfix" - placeholder := "placeholder" - operator := restapi.MetricPatternOperatorTypeStartsWith - - additionalMappings := func(spec *restapi.CustomEventSpecification) { - metricPattern := restapi.MetricPattern{ - Prefix: prefix, - Postfix: &postfix, - Placeholder: &placeholder, - Operator: operator, - } - spec.Rules[0].MetricPattern = &metricPattern - } - - additionalAsserts := func(resourceData *schema.ResourceData) { - require.Equal(t, prefix, resourceData.Get(ThresholdRuleFieldMetricPatternPrefix)) - require.Equal(t, postfix, resourceData.Get(ThresholdRuleFieldMetricPatternPostfix)) - require.Equal(t, placeholder, resourceData.Get(ThresholdRuleFieldMetricPatternPlaceholder)) - require.Equal(t, string(operator), resourceData.Get(ThresholdRuleFieldMetricPatternOperator)) - } - - testMappingOfCustomEventSpecificationWithThresholdRuleTerraformDataModelToState(t, additionalMappings, additionalAsserts) -} - -func testMappingOfCustomEventSpecificationWithThresholdRuleTerraformDataModelToState(t *testing.T, additionalMappings func(spec *restapi.CustomEventSpecification), additionalAsserts func(resourceData *schema.ResourceData)) { - description := customEventSpecificationWithThresholdRuleDescription - expirationTime := customEventSpecificationWithThresholdRuleExpirationTime - query := customEventSpecificationWithThresholdRuleQuery - - window := customEventSpecificationWithThresholdRuleWindow - rollup := customEventSpecificationWithThresholdRuleRollup - aggregation := customEventSpecificationWithThresholdRuleAggregation - conditionValue := customEventSpecificationWithThresholdRuleConditionValue - metricName := customEventSpecificationWithThresholdRuleMetricName - conditionOperator := restapi.ConditionOperatorEquals.InstanaAPIValue() - - spec := &restapi.CustomEventSpecification{ - ID: customEventSpecificationWithThresholdRuleID, - Name: resourceName, - EntityType: customEventSpecificationWithThresholdRuleEntityType, - Query: &query, - Description: &description, - ExpirationTime: &expirationTime, - Triggering: true, - Enabled: true, - Rules: []restapi.RuleSpecification{ - { - DType: restapi.ThresholdRuleType, - Severity: restapi.SeverityWarning.GetAPIRepresentation(), - MetricName: &metricName, - Window: &window, - Rollup: &rollup, - Aggregation: &aggregation, - ConditionOperator: &conditionOperator, - ConditionValue: &conditionValue, - }, - }, - } - additionalMappings(spec) - - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - sut := NewCustomEventSpecificationWithThresholdRuleResourceHandle() - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(sut) - - err := sut.UpdateState(resourceData, spec) - - require.Nil(t, err) - require.Equal(t, customEventSpecificationWithThresholdRuleID, resourceData.Id()) - require.Equal(t, resourceName, resourceData.Get(CustomEventSpecificationFieldName)) - require.Equal(t, customEventSpecificationWithThresholdRuleEntityType, resourceData.Get(CustomEventSpecificationFieldEntityType)) - require.Equal(t, customEventSpecificationWithThresholdRuleQuery, resourceData.Get(CustomEventSpecificationFieldQuery)) - require.Equal(t, description, resourceData.Get(CustomEventSpecificationFieldDescription)) - require.True(t, resourceData.Get(CustomEventSpecificationFieldTriggering).(bool)) - require.True(t, resourceData.Get(CustomEventSpecificationFieldEnabled).(bool)) - - require.Equal(t, metricName, resourceData.Get(ThresholdRuleFieldMetricName)) - require.Equal(t, window, resourceData.Get(ThresholdRuleFieldWindow)) - require.Equal(t, rollup, resourceData.Get(ThresholdRuleFieldRollup)) - require.Equal(t, string(aggregation), resourceData.Get(ThresholdRuleFieldAggregation)) - require.Equal(t, conditionOperator, resourceData.Get(ThresholdRuleFieldConditionOperator)) - require.Equal(t, conditionValue, resourceData.Get(ThresholdRuleFieldConditionValue)) - require.Equal(t, restapi.SeverityWarning.GetTerraformRepresentation(), resourceData.Get(CustomEventSpecificationRuleSeverity)) - additionalAsserts(resourceData) -} - -func TestShouldFailToUpdateTerraformStateForCustomEventSpecificationWithThresholdRuleWhenSeverityIsNotSupported(t *testing.T) { - spec := &restapi.CustomEventSpecification{ - Rules: []restapi.RuleSpecification{ - { - DType: restapi.ThresholdRuleType, - Severity: 123, - }, - }, - } - - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - sut := NewCustomEventSpecificationWithThresholdRuleResourceHandle() - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(sut) - - err := sut.UpdateState(resourceData, spec) - - require.NotNil(t, err) - require.Contains(t, err.Error(), "is not a valid severity") -} - -func TestShouldFailToUpdateTerraformStateForCustomEventSpecificationWithThresholdRuleWhenConditionOperatorTypeIsNotSupported(t *testing.T) { - conditionOperator := "invalid" - - spec := &restapi.CustomEventSpecification{ - Rules: []restapi.RuleSpecification{ - { - DType: restapi.ThresholdRuleType, - Severity: restapi.SeverityWarning.GetAPIRepresentation(), - ConditionOperator: &conditionOperator, - }, - }, - } - - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - sut := NewCustomEventSpecificationWithThresholdRuleResourceHandle() - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(sut) - - err := sut.UpdateState(resourceData, spec) - - require.NotNil(t, err) - require.Contains(t, err.Error(), "invalid is not a supported condition operator") -} - -func TestShouldSuccessfullyConvertCustomEventSpecificationWithThresholdRuleStateToDataModel(t *testing.T) { - testMappingOfCustomEventSpecificationWithThresholdRuleTerraformStateToDataModel(t, func(resourceData *schema.ResourceData) { /* Default testcase without additional fields =< no additional mappings */ - }, func(spec restapi.CustomEventSpecification) { /* Default testcase without additional fields => no additional requires */ - }) -} - -func TestShouldSuccessfullyConvertCustomEventSpecificationWithThresholdRuleAndMetricPatternStateToDataModel(t *testing.T) { - prefix := "prefix" - postfix := "postfix" - placeholder := "placeholder" - operator := restapi.MetricPatternOperatorTypeStartsWith - - additionalMappings := func(resourceData *schema.ResourceData) { - setValueOnResourceData(t, resourceData, ThresholdRuleFieldMetricPatternPrefix, prefix) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldMetricPatternPostfix, postfix) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldMetricPatternPlaceholder, placeholder) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldMetricPatternOperator, operator) - } - - additionalAsserts := func(spec restapi.CustomEventSpecification) { - require.NotNil(t, spec.Rules[0].MetricPattern) - require.Equal(t, prefix, spec.Rules[0].MetricPattern.Prefix) - require.Equal(t, postfix, spec.Rules[0].MetricPattern.Postfix) - require.Equal(t, placeholder, spec.Rules[0].MetricPattern.Placeholder) - require.Equal(t, operator, spec.Rules[0].MetricPattern.Operator) - } - - testMappingOfCustomEventSpecificationWithThresholdRuleTerraformStateToDataModel(t, additionalMappings, additionalAsserts) -} - -func testMappingOfCustomEventSpecificationWithThresholdRuleTerraformStateToDataModel(t *testing.T, _ func(resourceData *schema.ResourceData), _ func(spec restapi.CustomEventSpecification)) { - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - resourceHandle := NewCustomEventSpecificationWithThresholdRuleResourceHandle() - - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(resourceHandle) - - resourceData.SetId(customEventSpecificationWithThresholdRuleID) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldName, resourceName) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldEntityType, customEventSpecificationWithThresholdRuleEntityType) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldQuery, customEventSpecificationWithThresholdRuleQuery) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldTriggering, true) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldDescription, customEventSpecificationWithThresholdRuleDescription) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldExpirationTime, customEventSpecificationWithThresholdRuleExpirationTime) - setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldEnabled, true) - setValueOnResourceData(t, resourceData, CustomEventSpecificationRuleSeverity, restapi.SeverityWarning.GetTerraformRepresentation()) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldMetricName, customEventSpecificationWithThresholdRuleMetricName) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldWindow, customEventSpecificationWithThresholdRuleWindow) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldRollup, customEventSpecificationWithThresholdRuleRollup) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldAggregation, customEventSpecificationWithThresholdRuleAggregation) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldConditionOperator, restapi.ConditionOperatorEquals.InstanaAPIValue()) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldConditionValue, customEventSpecificationWithThresholdRuleConditionValue) - - result, err := resourceHandle.MapStateToDataObject(resourceData) - - require.Nil(t, err) - require.IsType(t, &restapi.CustomEventSpecification{}, result) - require.Equal(t, customEventSpecificationWithThresholdRuleID, result.GetIDForResourcePath()) - require.Equal(t, resourceName, result.Name) - require.Equal(t, customEventSpecificationWithThresholdRuleEntityType, result.EntityType) - require.Equal(t, customEventSpecificationWithThresholdRuleQuery, *result.Query) - require.Equal(t, customEventSpecificationWithThresholdRuleDescription, *result.Description) - require.Equal(t, customEventSpecificationWithThresholdRuleExpirationTime, *result.ExpirationTime) - require.True(t, result.Triggering) - require.True(t, result.Enabled) - - require.Equal(t, 1, len(result.Rules)) - require.Equal(t, customEventSpecificationWithThresholdRuleMetricName, *result.Rules[0].MetricName) - require.Equal(t, customEventSpecificationWithThresholdRuleWindow, *result.Rules[0].Window) - require.Equal(t, customEventSpecificationWithThresholdRuleRollup, *result.Rules[0].Rollup) - require.Equal(t, customEventSpecificationWithThresholdRuleAggregation, *result.Rules[0].Aggregation) - require.Equal(t, restapi.ConditionOperatorEquals.InstanaAPIValue(), *result.Rules[0].ConditionOperator) - require.Equal(t, customEventSpecificationWithThresholdRuleConditionValue, *result.Rules[0].ConditionValue) - require.Equal(t, restapi.SeverityWarning.GetAPIRepresentation(), result.Rules[0].Severity) -} - -func TestShouldFailToConvertCustomEventSpecificationWithThresholdRuleStateToDataModelWhenSeverityIsNotValid(t *testing.T) { - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - resourceHandle := NewCustomEventSpecificationWithThresholdRuleResourceHandle() - - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(resourceHandle) - setValueOnResourceData(t, resourceData, CustomEventSpecificationRuleSeverity, "INVALID") - - _, err := resourceHandle.MapStateToDataObject(resourceData) - - require.Error(t, err) -} - -func TestShouldFailToConvertCustomEventSpecificationWithThresholdRuleStateToDataModelWhenConditionOperationIsNotSupported(t *testing.T) { - testHelper := NewTestHelper[*restapi.CustomEventSpecification](t) - resourceHandle := NewCustomEventSpecificationWithThresholdRuleResourceHandle() - - resourceData := testHelper.CreateEmptyResourceDataForResourceHandle(resourceHandle) - setValueOnResourceData(t, resourceData, CustomEventSpecificationRuleSeverity, restapi.SeverityWarning.GetTerraformRepresentation()) - setValueOnResourceData(t, resourceData, ThresholdRuleFieldConditionOperator, "invalid") - - _, err := resourceHandle.MapStateToDataObject(resourceData) - - require.Error(t, err) - require.Contains(t, err.Error(), "is not a supported condition operator of the Instana Terraform provider") -} diff --git a/instana/resource-custom-event-specficiation.go b/instana/resource-custom-event-specficiation.go index a3d7d52c..8ed19035 100644 --- a/instana/resource-custom-event-specficiation.go +++ b/instana/resource-custom-event-specficiation.go @@ -13,6 +13,14 @@ import ( const ResourceInstanaCustomEventSpecification = "instana_custom_event_specification" const ( + CustomEventSpecificationFieldName = "name" + CustomEventSpecificationFieldEntityType = "entity_type" + CustomEventSpecificationFieldQuery = "query" + CustomEventSpecificationFieldTriggering = "triggering" + CustomEventSpecificationFieldDescription = "description" + CustomEventSpecificationFieldExpirationTime = "expiration_time" + CustomEventSpecificationFieldEnabled = "enabled" + CustomEventSpecificationFieldRules = "rules" CustomEventSpecificationFieldEntityVerificationRule = "entity_verification" CustomEventSpecificationFieldSystemRule = "system" @@ -51,24 +59,59 @@ var ( } ) +var customEventSpecificationSchemaRuleSeverity = &schema.Schema{ + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice(restapi.SupportedSeverities.TerraformRepresentations(), false), + Description: "Configures the severity of the rule of the custom event specification", +} + // NewCustomEventSpecificationResourceHandle creates a new ResourceHandle for the terraform resource of custom event specifications func NewCustomEventSpecificationResourceHandle() ResourceHandle[*restapi.CustomEventSpecification] { - commons := &customEventSpecificationCommons{} return &customEventSpecificationResource{ metaData: ResourceMetaData{ ResourceName: ResourceInstanaCustomEventSpecification, Schema: map[string]*schema.Schema{ - CustomEventSpecificationFieldName: customEventSpecificationSchemaName, + CustomEventSpecificationFieldName: { + Type: schema.TypeString, + Required: true, + Description: "Configures the name of the custom event specification", + }, CustomEventSpecificationFieldEntityType: { Type: schema.TypeString, Required: true, Description: "Configures the entity type of the custom event specification. This value must be set to 'host' for entity verification rules and 'any' in case of system rules.", }, - CustomEventSpecificationFieldQuery: customEventSpecificationSchemaQuery, - CustomEventSpecificationFieldTriggering: customEventSpecificationSchemaTriggering, - CustomEventSpecificationFieldDescription: customEventSpecificationSchemaDescription, - CustomEventSpecificationFieldExpirationTime: customEventSpecificationSchemaExpirationTime, - CustomEventSpecificationFieldEnabled: customEventSpecificationSchemaEnabled, + CustomEventSpecificationFieldQuery: { + Type: schema.TypeString, + Required: false, + Optional: true, + Description: "Configures the dynamic focus query for the custom event specification", + }, + CustomEventSpecificationFieldTriggering: { + Type: schema.TypeBool, + Default: false, + Optional: true, + Description: "Configures the custom event specification should trigger an incident", + }, + CustomEventSpecificationFieldDescription: { + Type: schema.TypeString, + Required: false, + Optional: true, + Description: "Configures the description text of the custom event specification", + }, + CustomEventSpecificationFieldExpirationTime: { + Type: schema.TypeInt, + Required: false, + Optional: true, + Description: "Configures the expiration time (grace period) to wait before the issue is closed", + }, + CustomEventSpecificationFieldEnabled: { + Type: schema.TypeBool, + Default: true, + Optional: true, + Description: "Configures if the custom event specification is enabled or not", + }, CustomEventSpecificationFieldRules: { Type: schema.TypeList, MinItems: 1, @@ -177,7 +220,7 @@ func NewCustomEventSpecificationResourceHandle() ResourceHandle[*restapi.CustomE CustomEventSpecificationThresholdRuleFieldMetricPatternOperator: { Type: schema.TypeString, Required: true, - ValidateFunc: validation.StringInSlice(restapi.SupportedMetricPatternOperatorTypes.ToStringSlice(), false), + ValidateFunc: validation.StringInSlice([]string{"is", "contains", "startsWith", "endsWith"}, false), Description: "The metric pattern operator (e.g is, contains, startsWith, endsWith)", }, }, @@ -200,7 +243,7 @@ func NewCustomEventSpecificationResourceHandle() ResourceHandle[*restapi.CustomE CustomEventSpecificationThresholdRuleFieldAggregation: { Type: schema.TypeString, Required: true, - ValidateFunc: validation.StringInSlice(restapi.SupportedAggregationTypes.ToStringSlice(), false), + ValidateFunc: validation.StringInSlice([]string{"sum", "avg", "min", "max"}, false), Description: "The aggregation type (e.g. sum, avg)", }, CustomEventSpecificationThresholdRuleFieldConditionOperator: { @@ -231,13 +274,11 @@ func NewCustomEventSpecificationResourceHandle() ResourceHandle[*restapi.CustomE }, SchemaVersion: 0, }, - commons: commons, } } type customEventSpecificationResource struct { metaData ResourceMetaData - commons *customEventSpecificationCommons } func (r *customEventSpecificationResource) MetaData() *ResourceMetaData { @@ -423,14 +464,14 @@ func (r *customEventSpecificationResource) mapThresholdRuleFromState(rule map[st Prefix: metricPatternData[CustomEventSpecificationThresholdRuleFieldMetricPatternPrefix].(string), Postfix: GetPointerFromMap[string](metricPatternData, CustomEventSpecificationThresholdRuleFieldMetricPatternPostfix), Placeholder: GetPointerFromMap[string](metricPatternData, CustomEventSpecificationThresholdRuleFieldMetricPatternPlaceholder), - Operator: restapi.MetricPatternOperatorType(metricPatternData[CustomEventSpecificationThresholdRuleFieldMetricPatternOperator].(string)), + Operator: metricPatternData[CustomEventSpecificationThresholdRuleFieldMetricPatternOperator].(string), } metricPattern = &metricPatternObj } - var aggregation *restapi.AggregationType + var aggregation *string if val, ok := rule[CustomEventSpecificationThresholdRuleFieldAggregation]; ok { - agg := restapi.AggregationType(val.(string)) + agg := val.(string) aggregation = &agg } diff --git a/instana/resource-custom-event-specficiation_test.go b/instana/resource-custom-event-specficiation_test.go index ba8aacb8..f3634e49 100644 --- a/instana/resource-custom-event-specficiation_test.go +++ b/instana/resource-custom-event-specficiation_test.go @@ -44,6 +44,21 @@ const ( customEventSpecificationConfigResourceName = "instana_custom_event_specification.example" customEventSpecificationRuleFieldPattern = "%s.0.%s.0.%s" customEventSpecificationRuleMetricPatternFieldPattern = "%s.0.%s.0.%s.0.%s" + + customEventSpecificationWithThresholdRuleSeverity = "warning" + customEventSpecificationWithThresholdRuleID = "custom-system-event-id" + customEventSpecificationWithThresholdRuleEntityType = "entity_type" + customEventSpecificationWithThresholdRuleQuery = "query" + customEventSpecificationWithThresholdRuleExpirationTime = 60000 + customEventSpecificationWithThresholdRuleDescription = "description" + customEventSpecificationWithThresholdRuleMetricName = "metric_name" + customEventSpecificationWithThresholdRuleRollup = 40000 + customEventSpecificationWithThresholdRuleWindow = 60000 + customEventSpecificationWithThresholdRuleAggregation = "sum" + customEventSpecificationWithThresholdRuleConditionValue = float64(1.2) + + entityVerificationRuleEntityType = "host" + systemRuleEntityType = "any" ) func customerEventSpecificationIntegrationTestWithEntityVerificationRule() *customerEventSpecificationIntegrationTest { @@ -93,11 +108,11 @@ resource "instana_custom_event_specification" "example" { customEventSpecificationConfigResourceName, httpServerResponseTemplate, []resource.TestCheckFunc{ - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationRuleFieldSeverity), CustomEventSpecificationWithThresholdRuleRuleSeverity), - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationEntityVerificationRuleFieldMatchingEntityLabel), customEntityVerificationEventRuleMatchingEntityLabel), - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationEntityVerificationRuleFieldMatchingEntityType), customEntityVerificationEventRuleMatchingEntityType), - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationEntityVerificationRuleFieldMatchingOperator), customEntityVerificationEventRuleMatchingOperator.InstanaAPIValue()), - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationEntityVerificationRuleFieldOfflineDuration), strconv.FormatInt(customEntityVerificationEventRuleOfflineDuration, 10)), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationRuleFieldSeverity), customEventSpecificationWithThresholdRuleSeverity), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationEntityVerificationRuleFieldMatchingEntityLabel), "matching-entity-label"), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationEntityVerificationRuleFieldMatchingEntityType), "matching-entity-type"), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationEntityVerificationRuleFieldMatchingOperator), "startsWith"), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldEntityVerificationRule, CustomEventSpecificationEntityVerificationRuleFieldOfflineDuration), "60000"), }, ) } @@ -143,7 +158,7 @@ resource "instana_custom_event_specification" "example" { customEventSpecificationConfigResourceName, httpServerResponseTemplate, []resource.TestCheckFunc{ - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldSystemRule, CustomEventSpecificationRuleFieldSeverity), CustomEventSpecificationWithThresholdRuleRuleSeverity), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldSystemRule, CustomEventSpecificationRuleFieldSeverity), customEventSpecificationWithThresholdRuleSeverity), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldSystemRule, CustomEventSpecificationSystemRuleFieldSystemRuleId), "system_rule_id"), }, ) @@ -200,12 +215,12 @@ resource "instana_custom_event_specification" "example" { customEventSpecificationConfigResourceName, httpServerResponseTemplate, []resource.TestCheckFunc{ - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationRuleFieldSeverity), CustomEventSpecificationWithThresholdRuleRuleSeverity), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationRuleFieldSeverity), customEventSpecificationWithThresholdRuleSeverity), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldMetricName), customEventSpecificationWithThresholdRuleMetricName), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldAggregation), string(customEventSpecificationWithThresholdRuleAggregation)), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldWindow), strconv.FormatInt(customEventSpecificationWithThresholdRuleWindow, 10)), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldRollup), strconv.FormatInt(customEventSpecificationWithThresholdRuleRollup, 10)), - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldConditionOperator), string(restapi.ConditionOperatorEquals.InstanaAPIValue())), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldConditionOperator), string("=")), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldConditionValue), "1.2"), }, ) @@ -272,7 +287,7 @@ resource "instana_custom_event_specification" "example" { customEventSpecificationConfigResourceName, httpServerResponseTemplate, []resource.TestCheckFunc{ - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationRuleFieldSeverity), CustomEventSpecificationWithThresholdRuleRuleSeverity), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationRuleFieldSeverity), customEventSpecificationWithThresholdRuleSeverity), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleMetricPatternFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldMetricPattern, CustomEventSpecificationThresholdRuleFieldMetricPatternPrefix), "prefix"), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleMetricPatternFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldMetricPattern, CustomEventSpecificationThresholdRuleFieldMetricPatternPostfix), "postfix"), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleMetricPatternFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldMetricPattern, CustomEventSpecificationThresholdRuleFieldMetricPatternPlaceholder), "placeholder"), @@ -280,7 +295,7 @@ resource "instana_custom_event_specification" "example" { resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldAggregation), string(customEventSpecificationWithThresholdRuleAggregation)), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldWindow), strconv.FormatInt(customEventSpecificationWithThresholdRuleWindow, 10)), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldRollup), strconv.FormatInt(customEventSpecificationWithThresholdRuleRollup, 10)), - resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldConditionOperator), string(restapi.ConditionOperatorEquals.InstanaAPIValue())), + resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldConditionOperator), string("=")), resource.TestCheckResourceAttr(customEventSpecificationConfigResourceName, fmt.Sprintf(customEventSpecificationRuleFieldPattern, CustomEventSpecificationFieldRules, CustomEventSpecificationFieldThresholdRule, CustomEventSpecificationThresholdRuleFieldConditionValue), "1.2"), }, ) @@ -440,7 +455,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapEntityVerificationRuleToSt spec := &restapi.CustomEventSpecification{ ID: customEventSpecificationWithThresholdRuleID, Name: resourceName, - EntityType: EntityVerificationRuleEntityType, + EntityType: entityVerificationRuleEntityType, Query: &query, Description: &description, ExpirationTime: &expirationTime, @@ -467,7 +482,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapEntityVerificationRuleToSt require.Nil(t, err) require.Equal(t, customEventSpecificationWithThresholdRuleID, resourceData.Id()) require.Equal(t, resourceName, resourceData.Get(CustomEventSpecificationFieldName)) - require.Equal(t, EntityVerificationRuleEntityType, resourceData.Get(CustomEventSpecificationFieldEntityType)) + require.Equal(t, entityVerificationRuleEntityType, resourceData.Get(CustomEventSpecificationFieldEntityType)) require.Equal(t, customEventSpecificationWithThresholdRuleQuery, resourceData.Get(CustomEventSpecificationFieldQuery)) require.Equal(t, description, resourceData.Get(CustomEventSpecificationFieldDescription)) require.True(t, resourceData.Get(CustomEventSpecificationFieldTriggering).(bool)) @@ -505,7 +520,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapSystemRuleToState(t *testi spec := &restapi.CustomEventSpecification{ ID: customEventSpecificationWithThresholdRuleID, Name: resourceName, - EntityType: SystemRuleEntityType, + EntityType: systemRuleEntityType, Query: &query, Description: &description, ExpirationTime: &expirationTime, @@ -529,7 +544,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapSystemRuleToState(t *testi require.Nil(t, err) require.Equal(t, customEventSpecificationWithThresholdRuleID, resourceData.Id()) require.Equal(t, resourceName, resourceData.Get(CustomEventSpecificationFieldName)) - require.Equal(t, SystemRuleEntityType, resourceData.Get(CustomEventSpecificationFieldEntityType)) + require.Equal(t, systemRuleEntityType, resourceData.Get(CustomEventSpecificationFieldEntityType)) require.Equal(t, customEventSpecificationWithThresholdRuleQuery, resourceData.Get(CustomEventSpecificationFieldQuery)) require.Equal(t, description, resourceData.Get(CustomEventSpecificationFieldDescription)) require.True(t, resourceData.Get(CustomEventSpecificationFieldTriggering).(bool)) @@ -565,7 +580,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapThresholdRuleAndMetricName aggregation := customEventSpecificationWithThresholdRuleAggregation conditionValue := customEventSpecificationWithThresholdRuleConditionValue metricName := customEventSpecificationWithThresholdRuleMetricName - conditionOperator := restapi.ConditionOperatorEquals.InstanaAPIValue() + conditionOperator := "=" spec := &restapi.CustomEventSpecification{ ID: customEventSpecificationWithThresholdRuleID, @@ -640,11 +655,11 @@ func (r *customerEventSpecificationUnitTest) shouldMapThresholdRuleAndMetricPatt rollup := customEventSpecificationWithThresholdRuleRollup aggregation := customEventSpecificationWithThresholdRuleAggregation conditionValue := customEventSpecificationWithThresholdRuleConditionValue - conditionOperator := restapi.ConditionOperatorEquals.InstanaAPIValue() + conditionOperator := "=" prefix := "prefix" postfix := "postfix" placeholder := "placeholder" - operator := restapi.MetricPatternOperatorTypeStartsWith + operator := "startsWith" spec := &restapi.CustomEventSpecification{ ID: customEventSpecificationWithThresholdRuleID, @@ -937,7 +952,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapStateOfThresholdRuleWithMe CustomEventSpecificationThresholdRuleFieldRollup: customEventSpecificationWithThresholdRuleRollup, CustomEventSpecificationThresholdRuleFieldWindow: customEventSpecificationWithThresholdRuleWindow, CustomEventSpecificationThresholdRuleFieldAggregation: customEventSpecificationWithThresholdRuleAggregation, - CustomEventSpecificationThresholdRuleFieldConditionOperator: restapi.ConditionOperatorEquals.InstanaAPIValue(), + CustomEventSpecificationThresholdRuleFieldConditionOperator: "=", CustomEventSpecificationThresholdRuleFieldConditionValue: customEventSpecificationWithThresholdRuleConditionValue, }, }, @@ -963,7 +978,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapStateOfThresholdRuleWithMe require.Equal(t, customEventSpecificationWithThresholdRuleWindow, *customEventSpec.Rules[0].Window) require.Equal(t, customEventSpecificationWithThresholdRuleRollup, *customEventSpec.Rules[0].Rollup) require.Equal(t, customEventSpecificationWithThresholdRuleAggregation, *customEventSpec.Rules[0].Aggregation) - require.Equal(t, restapi.ConditionOperatorEquals.InstanaAPIValue(), *customEventSpec.Rules[0].ConditionOperator) + require.Equal(t, "=", *customEventSpec.Rules[0].ConditionOperator) require.Equal(t, customEventSpecificationWithThresholdRuleConditionValue, *customEventSpec.Rules[0].ConditionValue) require.Equal(t, restapi.SeverityWarning.GetAPIRepresentation(), customEventSpec.Rules[0].Severity) } @@ -976,7 +991,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapStateOfThresholdRuleWithMe prefix := "prefix" postfix := "postfix" placeholder := "placeholder" - operator := restapi.MetricPatternOperatorTypeStartsWith + operator := "startsWith" resourceData.SetId(customEventSpecificationWithThresholdRuleID) setValueOnResourceData(t, resourceData, CustomEventSpecificationFieldName, resourceName) @@ -1004,7 +1019,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapStateOfThresholdRuleWithMe CustomEventSpecificationThresholdRuleFieldRollup: customEventSpecificationWithThresholdRuleRollup, CustomEventSpecificationThresholdRuleFieldWindow: customEventSpecificationWithThresholdRuleWindow, CustomEventSpecificationThresholdRuleFieldAggregation: customEventSpecificationWithThresholdRuleAggregation, - CustomEventSpecificationThresholdRuleFieldConditionOperator: restapi.ConditionOperatorEquals.InstanaAPIValue(), + CustomEventSpecificationThresholdRuleFieldConditionOperator: "=", CustomEventSpecificationThresholdRuleFieldConditionValue: customEventSpecificationWithThresholdRuleConditionValue, }, }, @@ -1034,7 +1049,7 @@ func (r *customerEventSpecificationUnitTest) shouldMapStateOfThresholdRuleWithMe require.Equal(t, customEventSpecificationWithThresholdRuleWindow, *customEventSpec.Rules[0].Window) require.Equal(t, customEventSpecificationWithThresholdRuleRollup, *customEventSpec.Rules[0].Rollup) require.Equal(t, customEventSpecificationWithThresholdRuleAggregation, *customEventSpec.Rules[0].Aggregation) - require.Equal(t, restapi.ConditionOperatorEquals.InstanaAPIValue(), *customEventSpec.Rules[0].ConditionOperator) + require.Equal(t, "=", *customEventSpec.Rules[0].ConditionOperator) require.Equal(t, customEventSpecificationWithThresholdRuleConditionValue, *customEventSpec.Rules[0].ConditionValue) require.Equal(t, restapi.SeverityWarning.GetAPIRepresentation(), customEventSpec.Rules[0].Severity) } diff --git a/instana/resource-custom-event-specification-common.go b/instana/resource-custom-event-specification-common.go deleted file mode 100644 index 8ade5255..00000000 --- a/instana/resource-custom-event-specification-common.go +++ /dev/null @@ -1,195 +0,0 @@ -package instana - -import ( - "context" - - "github.com/gessnerfl/terraform-provider-instana/instana/restapi" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -) - -const ( - //CustomEventSpecificationFieldName constant value for the schema field name - CustomEventSpecificationFieldName = "name" - //CustomEventSpecificationFieldFullName constant value for the schema field full_name. The field is computed and contains the name which is sent to instana. The computation depends on the configured default_name_prefix and default_name_suffix at provider level - CustomEventSpecificationFieldFullName = "full_name" - //CustomEventSpecificationFieldEntityType constant value for the schema field entity type - CustomEventSpecificationFieldEntityType = "entity_type" - //CustomEventSpecificationFieldQuery constant value for the schema field query - CustomEventSpecificationFieldQuery = "query" - //CustomEventSpecificationFieldTriggering constant value for the schema field triggering - CustomEventSpecificationFieldTriggering = "triggering" - //CustomEventSpecificationFieldDescription constant value for the schema field description - CustomEventSpecificationFieldDescription = "description" - //CustomEventSpecificationFieldExpirationTime constant value for the schema field expiration_time - CustomEventSpecificationFieldExpirationTime = "expiration_time" - //CustomEventSpecificationFieldEnabled constant value for the schema field enabled - CustomEventSpecificationFieldEnabled = "enabled" - - ruleFieldPrefix = "rule_" - - //CustomEventSpecificationRuleSeverity constant value for the schema field severity of a rule specification - CustomEventSpecificationRuleSeverity = ruleFieldPrefix + "severity" - - downstreamFieldPrefix = "downstream_" - customEventSpecificationDownstreamIntegrationIds = downstreamFieldPrefix + "integration_ids" - customEventSpecificationDownstreamBroadcastToAllAlertingConfigs = downstreamFieldPrefix + "broadcast_to_all_alerting_configs" -) - -var customEventSpecificationSchemaName = &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "Configures the name of the custom event specification", -} - -var customEventSpecificationSchemaFullName = &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The computed full name of the custom event specification. The field contains the name which is sent to instana. The computation depends on the configured default_name_prefix and default_name_suffix at provider level", -} -var customEventSpecificationSchemaQuery = &schema.Schema{ - Type: schema.TypeString, - Required: false, - Optional: true, - Description: "Configures the dynamic focus query for the custom event specification", -} -var customEventSpecificationSchemaTriggering = &schema.Schema{ - Type: schema.TypeBool, - Default: false, - Optional: true, - Description: "Configures the custom event specification should trigger an incident", -} -var customEventSpecificationSchemaDescription = &schema.Schema{ - Type: schema.TypeString, - Required: false, - Optional: true, - Description: "Configures the description text of the custom event specification", -} -var customEventSpecificationSchemaExpirationTime = &schema.Schema{ - Type: schema.TypeInt, - Required: false, - Optional: true, - Description: "Configures the expiration time (grace period) to wait before the issue is closed", -} -var customEventSpecificationSchemaEnabled = &schema.Schema{ - Type: schema.TypeBool, - Default: true, - Optional: true, - Description: "Configures if the custom event specification is enabled or not", -} -var customEventSpecificationSchemaDownstreamIntegrationIds = &schema.Schema{ - Type: schema.TypeList, - Required: false, - Optional: true, - MinItems: 0, - MaxItems: 16, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - Description: "Configures the list of integration ids which should be used for downstream reporting", -} -var customEventSpecificationSchemaDownstreamBroadcastToAllAlertingConfigs = &schema.Schema{ - Type: schema.TypeBool, - Default: true, - Optional: true, - Description: "Configures the downstream reporting should be sent to all integrations", -} -var customEventSpecificationSchemaRuleSeverity = &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(restapi.SupportedSeverities.TerraformRepresentations(), false), - Description: "Configures the severity of the rule of the custom event specification", -} - -var defaultCustomEventSchemaFieldsV0 = map[string]*schema.Schema{ - CustomEventSpecificationFieldName: customEventSpecificationSchemaName, - CustomEventSpecificationFieldQuery: customEventSpecificationSchemaQuery, - CustomEventSpecificationFieldTriggering: customEventSpecificationSchemaTriggering, - CustomEventSpecificationFieldDescription: customEventSpecificationSchemaDescription, - CustomEventSpecificationFieldExpirationTime: customEventSpecificationSchemaExpirationTime, - CustomEventSpecificationFieldEnabled: customEventSpecificationSchemaEnabled, - customEventSpecificationDownstreamIntegrationIds: customEventSpecificationSchemaDownstreamIntegrationIds, - customEventSpecificationDownstreamBroadcastToAllAlertingConfigs: customEventSpecificationSchemaDownstreamBroadcastToAllAlertingConfigs, - CustomEventSpecificationRuleSeverity: customEventSpecificationSchemaRuleSeverity, -} - -var defaultCustomEventSchemaFieldsV1 = map[string]*schema.Schema{ - CustomEventSpecificationFieldName: customEventSpecificationSchemaName, - CustomEventSpecificationFieldFullName: customEventSpecificationSchemaFullName, - CustomEventSpecificationFieldQuery: customEventSpecificationSchemaQuery, - CustomEventSpecificationFieldTriggering: customEventSpecificationSchemaTriggering, - CustomEventSpecificationFieldDescription: customEventSpecificationSchemaDescription, - CustomEventSpecificationFieldExpirationTime: customEventSpecificationSchemaExpirationTime, - CustomEventSpecificationFieldEnabled: customEventSpecificationSchemaEnabled, - customEventSpecificationDownstreamIntegrationIds: customEventSpecificationSchemaDownstreamIntegrationIds, - customEventSpecificationDownstreamBroadcastToAllAlertingConfigs: customEventSpecificationSchemaDownstreamBroadcastToAllAlertingConfigs, - CustomEventSpecificationRuleSeverity: customEventSpecificationSchemaRuleSeverity, -} - -var defaultCustomEventSchemaFieldsV2 = map[string]*schema.Schema{ - CustomEventSpecificationFieldName: customEventSpecificationSchemaName, - CustomEventSpecificationFieldFullName: customEventSpecificationSchemaFullName, - CustomEventSpecificationFieldQuery: customEventSpecificationSchemaQuery, - CustomEventSpecificationFieldTriggering: customEventSpecificationSchemaTriggering, - CustomEventSpecificationFieldDescription: customEventSpecificationSchemaDescription, - CustomEventSpecificationFieldExpirationTime: customEventSpecificationSchemaExpirationTime, - CustomEventSpecificationFieldEnabled: customEventSpecificationSchemaEnabled, - CustomEventSpecificationRuleSeverity: customEventSpecificationSchemaRuleSeverity, -} - -var defaultCustomEventSchemaFields = map[string]*schema.Schema{ - CustomEventSpecificationFieldName: customEventSpecificationSchemaName, - CustomEventSpecificationFieldQuery: customEventSpecificationSchemaQuery, - CustomEventSpecificationFieldTriggering: customEventSpecificationSchemaTriggering, - CustomEventSpecificationFieldDescription: customEventSpecificationSchemaDescription, - CustomEventSpecificationFieldExpirationTime: customEventSpecificationSchemaExpirationTime, - CustomEventSpecificationFieldEnabled: customEventSpecificationSchemaEnabled, - CustomEventSpecificationRuleSeverity: customEventSpecificationSchemaRuleSeverity, -} - -type customEventSpecificationCommons struct{} - -func (c *customEventSpecificationCommons) createCustomEventSpecificationFromResourceData(d *schema.ResourceData) *restapi.CustomEventSpecification { - apiModel := restapi.CustomEventSpecification{ - ID: d.Id(), - Name: d.Get(CustomEventSpecificationFieldName).(string), - EntityType: d.Get(CustomEventSpecificationFieldEntityType).(string), - Query: GetStringPointerFromResourceData(d, CustomEventSpecificationFieldQuery), - Triggering: d.Get(CustomEventSpecificationFieldTriggering).(bool), - Description: GetStringPointerFromResourceData(d, CustomEventSpecificationFieldDescription), - ExpirationTime: GetIntPointerFromResourceData(d, CustomEventSpecificationFieldExpirationTime), - Enabled: d.Get(CustomEventSpecificationFieldEnabled).(bool), - } - return &apiModel -} - -func (c *customEventSpecificationCommons) getDataForBasicCustomEventSpecification(spec *restapi.CustomEventSpecification) map[string]interface{} { - return map[string]interface{}{ - CustomEventSpecificationFieldName: spec.Name, - CustomEventSpecificationFieldQuery: spec.Query, - CustomEventSpecificationFieldEntityType: spec.EntityType, - CustomEventSpecificationFieldTriggering: spec.Triggering, - CustomEventSpecificationFieldDescription: spec.Description, - CustomEventSpecificationFieldExpirationTime: spec.ExpirationTime, - CustomEventSpecificationFieldEnabled: spec.Enabled, - } -} - -func (c *customEventSpecificationCommons) migrateCustomEventConfigFullNameInStateFromV0toV1(_ context.Context, rawState map[string]interface{}, _ interface{}) (map[string]interface{}, error) { - rawState[CustomEventSpecificationFieldFullName] = rawState[CustomEventSpecificationFieldName] - return rawState, nil -} - -func (c *customEventSpecificationCommons) migrateCustomEventConfigFullStateFromV1toV2AndRemoveDownstreamConfiguration(_ context.Context, rawState map[string]interface{}, _ interface{}) (map[string]interface{}, error) { - delete(rawState, customEventSpecificationDownstreamIntegrationIds) - delete(rawState, customEventSpecificationDownstreamBroadcastToAllAlertingConfigs) - return rawState, nil -} - -func (c *customEventSpecificationCommons) migrateCustomEventConfigFullStateFromV2toV3AndRemoveFullname(_ context.Context, state map[string]interface{}, _ interface{}) (map[string]interface{}, error) { - if _, ok := state[CustomEventSpecificationFieldFullName]; ok { - state[CustomEventSpecificationFieldName] = state[CustomEventSpecificationFieldFullName] - delete(state, CustomEventSpecificationFieldFullName) - } - return state, nil -} diff --git a/instana/restapi/custom-event-specficiations-api.go b/instana/restapi/custom-event-specficiations-api.go index 88995da2..40a20d61 100644 --- a/instana/restapi/custom-event-specficiations-api.go +++ b/instana/restapi/custom-event-specficiations-api.go @@ -16,94 +16,12 @@ const ( EntityVerificationRuleType = "entity_verification" ) -// AggregationType custom type representing an aggregation of a custom event specification rule -type AggregationType string - -// AggregationTypes custom type representing a slice of AggregationType -type AggregationTypes []AggregationType - -// ToStringSlice Returns the string representations fo the aggregations -func (types AggregationTypes) ToStringSlice() []string { - result := make([]string, len(types)) - for i, v := range types { - result[i] = string(v) - } - return result -} - -const ( - //AggregationSum const for a sum aggregation - AggregationSum = AggregationType("sum") - //AggregationAvg const for a avg aggregation - AggregationAvg = AggregationType("avg") - //AggregationMin const for a min aggregation - AggregationMin = AggregationType("min") - //AggregationMax const for a max aggregation - AggregationMax = AggregationType("max") -) - -// SupportedAggregationTypes slice of supported aggregation types -var SupportedAggregationTypes = AggregationTypes{AggregationSum, AggregationAvg, AggregationMin, AggregationMax} - -// MetricPatternOperatorType the operator type of the metric pattern of a dynamic built-in metric -type MetricPatternOperatorType string - -// MetricPatternOperatorTypes type definition of a slice of MetricPatternOperatorType -type MetricPatternOperatorTypes []MetricPatternOperatorType - -// ToStringSlice Returns the string representations of the metric pattern operator types -func (types MetricPatternOperatorTypes) ToStringSlice() []string { - result := make([]string, len(types)) - for i, v := range types { - result[i] = string(v) - } - return result -} - -// Constant values of all supported MetricPatternOperatorTypes -const ( - //MetricPatternOperatorTypeIs constant value for the metric pattern operator type 'is' - MetricPatternOperatorTypeIs = MetricPatternOperatorType("is") - //MetricPatternOperatorTypeContains constant value for the metric pattern operator type 'contains' - MetricPatternOperatorTypeContains = MetricPatternOperatorType("contains") - //MetricPatternOperatorTypeAny constant value for the metric pattern operator type 'any' - MetricPatternOperatorTypeAny = MetricPatternOperatorType("any") - //MetricPatternOperatorTypeStartsWith constant value for the metric pattern operator type 'startsWith' - MetricPatternOperatorTypeStartsWith = MetricPatternOperatorType("startsWith") - //MetricPatternOperatorTypeEndsWith constant value for the metric pattern operator type 'endsWith' - MetricPatternOperatorTypeEndsWith = MetricPatternOperatorType("endsWith") -) - -// SupportedMetricPatternOperatorTypes slice of all supported MetricPatternOperatorTypes of the Instana Web Rest API -var SupportedMetricPatternOperatorTypes = MetricPatternOperatorTypes{MetricPatternOperatorTypeIs, MetricPatternOperatorTypeContains, MetricPatternOperatorTypeAny, MetricPatternOperatorTypeStartsWith, MetricPatternOperatorTypeEndsWith} - -// NewSystemRuleSpecification creates a new instance of System Rule -func NewSystemRuleSpecification(systemRuleID string, severity int) RuleSpecification { - return RuleSpecification{ - DType: SystemRuleType, - SystemRuleID: &systemRuleID, - Severity: severity, - } -} - -// NewEntityVerificationRuleSpecification creates a new instance of Entity Verification Rule -func NewEntityVerificationRuleSpecification(matchingEntityLabel string, matchingEntityType string, matchingOperator string, offlineDuration int, severity int) RuleSpecification { - return RuleSpecification{ - DType: EntityVerificationRuleType, - MatchingEntityLabel: &matchingEntityLabel, - MatchingEntityType: &matchingEntityType, - MatchingOperator: &matchingOperator, - OfflineDuration: &offlineDuration, - Severity: severity, - } -} - // MetricPattern representation of a metric pattern for dynamic built-in metrics for CustomEventSpecification type MetricPattern struct { - Prefix string `json:"prefix"` - Postfix *string `json:"postfix"` - Placeholder *string `json:"placeholder"` - Operator MetricPatternOperatorType `json:"operator"` + Prefix string `json:"prefix"` + Postfix *string `json:"postfix"` + Placeholder *string `json:"placeholder"` + Operator string `json:"operator"` } // RuleSpecification representation of a rule specification for a CustomEventSpecification @@ -116,13 +34,13 @@ type RuleSpecification struct { SystemRuleID *string `json:"systemRuleId"` //Threshold Rule fields - MetricName *string `json:"metricName"` - Rollup *int `json:"rollup"` - Window *int `json:"window"` - Aggregation *AggregationType `json:"aggregation"` - ConditionOperator *string `json:"conditionOperator"` - ConditionValue *float64 `json:"conditionValue"` - MetricPattern *MetricPattern `json:"metricPattern"` + MetricName *string `json:"metricName"` + Rollup *int `json:"rollup"` + Window *int `json:"window"` + Aggregation *string `json:"aggregation"` + ConditionOperator *string `json:"conditionOperator"` + ConditionValue *float64 `json:"conditionValue"` + MetricPattern *MetricPattern `json:"metricPattern"` //Entity Verification Rule MatchingEntityType *string `json:"matchingEntityType"` @@ -131,30 +49,6 @@ type RuleSpecification struct { OfflineDuration *int `json:"offlineDuration"` } -// ConditionOperatorType returns the ConditionOperator for the given Instana Web REST API representation when available. In case of invalid values an error will be returned -func (r *RuleSpecification) ConditionOperatorType() (ConditionOperator, error) { - if r.ConditionOperator != nil { - operator, err := SupportedConditionOperators.FromInstanaAPIValue(*r.ConditionOperator) - if err != nil { - return nil, err - } - return operator, nil - } - return nil, nil -} - -// MatchingOperatorType returns the MatchingOperatorType for the given Instana Web REST API representation when available. In case of invalid values an error will be returned -func (r *RuleSpecification) MatchingOperatorType() (MatchingOperator, error) { - if r.MatchingOperator != nil { - operator, err := SupportedMatchingOperators.FromInstanaAPIValue(*r.MatchingOperator) - if err != nil { - return nil, err - } - return operator, nil - } - return nil, nil -} - // CustomEventSpecification is the representation of a custom event specification in Instana type CustomEventSpecification struct { ID string `json:"id"` @@ -168,7 +62,7 @@ type CustomEventSpecification struct { Rules []RuleSpecification `json:"rules"` } -// GetIDForResourcePath implemention of the interface InstanaDataObject +// GetIDForResourcePath implementation of the interface InstanaDataObject func (spec *CustomEventSpecification) GetIDForResourcePath() string { return spec.ID } diff --git a/instana/restapi/custom-event-specficiations-api_test.go b/instana/restapi/custom-event-specficiations-api_test.go deleted file mode 100644 index 4acc852d..00000000 --- a/instana/restapi/custom-event-specficiations-api_test.go +++ /dev/null @@ -1,152 +0,0 @@ -package restapi_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - . "github.com/gessnerfl/terraform-provider-instana/instana/restapi" -) - -const ( - customEventMetricName = "threshold-rule-metric-name" - customEventRollup = 40000 - customEventConditionValue = 1.2 - - customEventMatchingEntityLabel = "custom-event-matching-entity-label" - customEventMatchingEntityType = "custom-event-matching-entity-type" - customEventOfflineDuration = 60000 -) - -func TestShouldReturnConditionOperatorTypeOfThresholdRuleWhenValidInstanaWebRestAPIConditionOperatorTypoIsProvided(t *testing.T) { - metricName := customEventMetricName - conditionOperator := ConditionOperatorEquals.InstanaAPIValue() - rollup := customEventRollup - conditionValue := customEventConditionValue - rule := RuleSpecification{ - DType: ThresholdRuleType, - Severity: SeverityWarning.GetAPIRepresentation(), - MetricName: &metricName, - Rollup: &rollup, - ConditionOperator: &conditionOperator, - ConditionValue: &conditionValue, - } - - val, err := rule.ConditionOperatorType() - - assert.Nil(t, err) - assert.NotNil(t, val) - assert.Equal(t, ConditionOperatorEquals, val) -} - -func TestShouldReturnErrorWheConditionOperatorTypeOfThresholdnRuleIsNotAValidInstanaWebRestAPIValue(t *testing.T) { - metricName := customEventMetricName - conditionOperator := "invalid" - rollup := customEventRollup - conditionValue := customEventConditionValue - rule := RuleSpecification{ - DType: ThresholdRuleType, - Severity: SeverityWarning.GetAPIRepresentation(), - MetricName: &metricName, - Rollup: &rollup, - ConditionOperator: &conditionOperator, - ConditionValue: &conditionValue, - } - - val, err := rule.ConditionOperatorType() - - assert.NotNil(t, err) - assert.Nil(t, val) -} - -func TestShouldReturnNilWhenRuleSpecificationDoesNotSupportConditionOperatorTypesAndConditionOperatorTypeIsRequested(t *testing.T) { - entityLabel := customEventMatchingEntityLabel - entityType := customEventMatchingEntityType - operator := MatchingOperatorIs.InstanaAPIValue() - offlineDuration := customEventOfflineDuration - rule := RuleSpecification{ - DType: EntityVerificationRuleType, - Severity: SeverityWarning.GetAPIRepresentation(), - MatchingEntityLabel: &entityLabel, - MatchingEntityType: &entityType, - MatchingOperator: &operator, - OfflineDuration: &offlineDuration, - } - - val, err := rule.ConditionOperatorType() - - assert.Nil(t, err) - assert.Nil(t, val) -} - -func TestShouldReturnMatchingOperatorTypeForEntityVerificationRuleWhenValidInstanaWebRestAPIMatchingOperatorTypoIsProvided(t *testing.T) { - entityLabel := customEventMatchingEntityLabel - entityType := customEventMatchingEntityType - operator := MatchingOperatorIs.InstanaAPIValue() - offlineDuration := customEventOfflineDuration - rule := RuleSpecification{ - DType: EntityVerificationRuleType, - Severity: SeverityWarning.GetAPIRepresentation(), - MatchingEntityLabel: &entityLabel, - MatchingEntityType: &entityType, - MatchingOperator: &operator, - OfflineDuration: &offlineDuration, - } - - val, err := rule.MatchingOperatorType() - - assert.Nil(t, err) - assert.NotNil(t, val) - assert.Equal(t, MatchingOperatorIs, val) -} - -func TestShouldReturnErrorWhenMatchingOperatorTypeForEntityVerificationRuleIsNotAValidInstanaWebRestAPIValue(t *testing.T) { - entityLabel := customEventMatchingEntityLabel - entityType := customEventMatchingEntityType - operator := "invalid" - offlineDuration := customEventOfflineDuration - rule := RuleSpecification{ - DType: EntityVerificationRuleType, - Severity: SeverityWarning.GetAPIRepresentation(), - MatchingEntityLabel: &entityLabel, - MatchingEntityType: &entityType, - MatchingOperator: &operator, - OfflineDuration: &offlineDuration, - } - - val, err := rule.MatchingOperatorType() - - assert.NotNil(t, err) - assert.Nil(t, val) -} - -func TestShouldReturnNilWhenRuleSpecificationDoesNotSupportMatchingOperatorTypesAndMatchingOperatorTypeIsRequested(t *testing.T) { - metricName := customEventMetricName - conditionOperator := ConditionOperatorEquals.InstanaAPIValue() - rollup := customEventRollup - conditionValue := customEventConditionValue - rule := RuleSpecification{ - DType: ThresholdRuleType, - Severity: SeverityWarning.GetAPIRepresentation(), - MetricName: &metricName, - Rollup: &rollup, - ConditionOperator: &conditionOperator, - ConditionValue: &conditionValue, - } - - val, err := rule.MatchingOperatorType() - - assert.Nil(t, err) - assert.Nil(t, val) -} - -func TestShouldConvertSupportedAggregationTypesToSliceOfString(t *testing.T) { - expectedResult := []string{string(AggregationSum), string(AggregationAvg), string(AggregationMin), string(AggregationMax)} - result := SupportedAggregationTypes.ToStringSlice() - - assert.Equal(t, expectedResult, result) -} - -func TestShouldConvertMetricPatternOperatorTypesToStringSlice(t *testing.T) { - assert.Equal(t, []string{"is", "contains", "any", "startsWith", "endsWith"}, SupportedMetricPatternOperatorTypes.ToStringSlice()) -} diff --git a/instana/restapi/custom-event-specification-threshold-rule-condition-operator.go b/instana/restapi/custom-event-specification-threshold-rule-condition-operator.go deleted file mode 100644 index 32686609..00000000 --- a/instana/restapi/custom-event-specification-threshold-rule-condition-operator.go +++ /dev/null @@ -1,90 +0,0 @@ -package restapi - -import "fmt" - -// ConditionOperator representation of a ConditionOperator of a threshold rule of a custom event specification of the Instana Web REST API -type ConditionOperator interface { - InstanaAPIValue() string - TerraformSupportedValues() []string -} - -func newBasicConditionOperator(instanaAPIValue string, additionalSupportedTerraformValues ...string) ConditionOperator { - return &baseConditionOperator{instanaAPIValue: instanaAPIValue, terraformSupportedValues: append(additionalSupportedTerraformValues, instanaAPIValue)} -} - -// ConditionOperatorType custom type representing a condition operator of a custom event specification rule -type baseConditionOperator struct { - instanaAPIValue string - terraformSupportedValues []string -} - -// InstanaAPIValue implementation of ConditionOperator interace -func (b *baseConditionOperator) InstanaAPIValue() string { - return b.instanaAPIValue -} - -// TerraformSupportedValues implementation of ConditionOperator interace -func (b *baseConditionOperator) TerraformSupportedValues() []string { - return b.terraformSupportedValues -} - -// ConditionOperators custom type representing a slice of ConditionOperatorType -type ConditionOperators []ConditionOperator - -// TerrafromSupportedValues Returns the terraform string representations fo the condition operators -func (types ConditionOperators) TerrafromSupportedValues() []string { - result := make([]string, 0) - for _, v := range types { - result = append(result, v.TerraformSupportedValues()...) - } - return result -} - -// InstanaAPISupportedValues Returns the terraform string representations fo the condition operators -func (types ConditionOperators) InstanaAPISupportedValues() []string { - result := make([]string, len(types)) - for i, v := range types { - result[i] = v.InstanaAPIValue() - } - return result -} - -// FromInstanaAPIValue returns the ConditionOperator for the given instana apistring value or an error if the operator type does not exist -func (types ConditionOperators) FromInstanaAPIValue(instanaAPIvalue string) (ConditionOperator, error) { - for _, t := range types { - if t.InstanaAPIValue() == instanaAPIvalue { - return t, nil - } - } - return ConditionOperatorEquals, fmt.Errorf("%s is not a supported condition operator of the Instana Web REST API", instanaAPIvalue) -} - -// FromTerraformValue returns the ConditionOperator for the given terraform string value or an error if the operator type does not exist -func (types ConditionOperators) FromTerraformValue(terraformRepresentation string) (ConditionOperator, error) { - for _, t := range types { - for _, v := range t.TerraformSupportedValues() { - if v == terraformRepresentation { - return t, nil - } - } - } - return ConditionOperatorEquals, fmt.Errorf("%s is not a supported condition operator of the Instana Terraform provider", terraformRepresentation) -} - -var ( - //ConditionOperatorEquals const for a equals (==) condition operator - ConditionOperatorEquals = newBasicConditionOperator("=", "==") - //ConditionOperatorNotEqual const for a not equal (!=) condition operator - ConditionOperatorNotEqual = newBasicConditionOperator("!=") - //ConditionOperatorLessThan const for a less than (<) condition operator - ConditionOperatorLessThan = newBasicConditionOperator("<") - //ConditionOperatorLessThanOrEqual const for a less than or equal (<=) condition operator - ConditionOperatorLessThanOrEqual = newBasicConditionOperator("<=") - //ConditionOperatorGreaterThan const for a greater than (>) condition operator - ConditionOperatorGreaterThan = newBasicConditionOperator(">") - //ConditionOperatorGreaterThanOrEqual const for a greater than or equal (<=) condition operator - ConditionOperatorGreaterThanOrEqual = newBasicConditionOperator(">=") -) - -// SupportedConditionOperators slice of supported condition operator types -var SupportedConditionOperators = ConditionOperators{ConditionOperatorEquals, ConditionOperatorNotEqual, ConditionOperatorLessThan, ConditionOperatorLessThanOrEqual, ConditionOperatorGreaterThan, ConditionOperatorGreaterThanOrEqual} diff --git a/instana/restapi/custom-event-specification-threshold-rule-condition-operator_test.go b/instana/restapi/custom-event-specification-threshold-rule-condition-operator_test.go deleted file mode 100644 index 2ae06a8e..00000000 --- a/instana/restapi/custom-event-specification-threshold-rule-condition-operator_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package restapi_test - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" - - . "github.com/gessnerfl/terraform-provider-instana/instana/restapi" -) - -func TestShouldPovideInstanaSupportedValuesOfConditionOperatorTypes(t *testing.T) { - expectedResult := []string{ConditionOperatorEquals.InstanaAPIValue(), ConditionOperatorNotEqual.InstanaAPIValue(), ConditionOperatorLessThan.InstanaAPIValue(), ConditionOperatorLessThanOrEqual.InstanaAPIValue(), ConditionOperatorGreaterThan.InstanaAPIValue(), ConditionOperatorGreaterThanOrEqual.InstanaAPIValue()} - result := SupportedConditionOperators.InstanaAPISupportedValues() - - assert.Equal(t, expectedResult, result) -} - -func TestShouldPovideTerraformSupportedValuesOfConditionOperatorTypes(t *testing.T) { - expectedResult := []string{} - for _, op := range SupportedConditionOperators { - expectedResult = append(expectedResult, op.TerraformSupportedValues()...) - } - result := SupportedConditionOperators.TerrafromSupportedValues() - - assert.Equal(t, expectedResult, result) -} - -func TestShouldReturnTheConditionOperatorTypeForAllSupportedInstanaWebRestAPIValues(t *testing.T) { - for _, op := range SupportedConditionOperators { - t.Run(fmt.Sprintf("TestShouldReturnTheConditionOperatorTypeForAllSupportedInstanaWebRestAPIValues%s", op), createTestCaseForTestShouldReturnTheConditionOperatorTypeForAllSupportedInstanaWebRestAPIValues(op)) - } -} - -func createTestCaseForTestShouldReturnTheConditionOperatorTypeForAllSupportedInstanaWebRestAPIValues(op ConditionOperator) func(*testing.T) { - return func(t *testing.T) { - val, err := SupportedConditionOperators.FromInstanaAPIValue(op.InstanaAPIValue()) - - assert.Nil(t, err) - assert.Equal(t, op, val) - } -} - -func TestShouldReturnErrorWhenTheConditionOperatorTypeIsNotASupportedInstanaWebRestAPIValue(t *testing.T) { - val, err := SupportedConditionOperators.FromInstanaAPIValue("invalid") - - assert.NotNil(t, err) - assert.Equal(t, ConditionOperatorEquals, val) -} - -func TestShouldReturnTheConditionOperatorTypeForAllSupportedTerraformProviderValues(t *testing.T) { - for _, op := range SupportedConditionOperators { - for _, v := range op.TerraformSupportedValues() { - t.Run(fmt.Sprintf("TestShouldReturnTheConditionOperatorTypeForAllSupportedTerraformProviderValues%s", v), createTestCaseForTestShouldReturnTheConditionOperatorTypeForAllSupportedTerraformProviderValues(op, v)) - } - } -} - -func createTestCaseForTestShouldReturnTheConditionOperatorTypeForAllSupportedTerraformProviderValues(op ConditionOperator, value string) func(*testing.T) { - return func(t *testing.T) { - val, err := SupportedConditionOperators.FromTerraformValue(value) - - assert.Nil(t, err) - assert.Equal(t, op, val) - } -} - -func TestShouldReturnErrorWhenTheConditionOperatorTypeIsNotASupportedInstanaTerraformProviderValue(t *testing.T) { - val, err := SupportedConditionOperators.FromTerraformValue("invalid") - - assert.NotNil(t, err) - assert.Equal(t, ConditionOperatorEquals, val) -} diff --git a/instana/restapi/custom-event-specification-threshold-rule-matching-operator.go b/instana/restapi/custom-event-specification-threshold-rule-matching-operator.go deleted file mode 100644 index 7b00c14b..00000000 --- a/instana/restapi/custom-event-specification-threshold-rule-matching-operator.go +++ /dev/null @@ -1,86 +0,0 @@ -package restapi - -import "fmt" - -// MatchingOperator representation of a MatchingOperator of a threshold rule of a custom event specification of the Instana Web REST API -type MatchingOperator interface { - InstanaAPIValue() string - TerraformSupportedValues() []string -} - -func newBasicMatchingOperator(instanaAPIValue string, additionalSupportedTerraformValues ...string) MatchingOperator { - return &baseMatchingOperator{instanaAPIValue: instanaAPIValue, terraformSupportedValues: append(additionalSupportedTerraformValues, instanaAPIValue)} -} - -// MatchingOperatorType custom type representing a matching operator of a custom event specification rule -type baseMatchingOperator struct { - instanaAPIValue string - terraformSupportedValues []string -} - -// InstanaAPIValue implementation of MatchingOperator interace -func (b *baseMatchingOperator) InstanaAPIValue() string { - return b.instanaAPIValue -} - -// TerraformSupportedValues implementation of MatchingOperator interace -func (b *baseMatchingOperator) TerraformSupportedValues() []string { - return b.terraformSupportedValues -} - -// MatchingOperators custom type representing a slice of MatchingOperatorType -type MatchingOperators []MatchingOperator - -// TerrafromSupportedValues Returns the terraform string representations fo the matching operators -func (types MatchingOperators) TerrafromSupportedValues() []string { - result := make([]string, 0) - for _, v := range types { - result = append(result, v.TerraformSupportedValues()...) - } - return result -} - -// InstanaAPISupportedValues Returns the terraform string representations fo the matching operators -func (types MatchingOperators) InstanaAPISupportedValues() []string { - result := make([]string, len(types)) - for i, v := range types { - result[i] = v.InstanaAPIValue() - } - return result -} - -// FromInstanaAPIValue returns the MatchingOperator for the given instana apistring value or an error if the operator type does not exist -func (types MatchingOperators) FromInstanaAPIValue(instanaAPIvalue string) (MatchingOperator, error) { - for _, t := range types { - if t.InstanaAPIValue() == instanaAPIvalue { - return t, nil - } - } - return MatchingOperatorIs, fmt.Errorf("%s is not a supported matching operator of the Instana Web REST API", instanaAPIvalue) -} - -// FromTerraformValue returns the MatchingOperator for the given terraform string value or an error if the operator type does not exist -func (types MatchingOperators) FromTerraformValue(terraformRepresentation string) (MatchingOperator, error) { - for _, t := range types { - for _, v := range t.TerraformSupportedValues() { - if v == terraformRepresentation { - return t, nil - } - } - } - return MatchingOperatorIs, fmt.Errorf("%s is not a supported matching operator of the Instana Terraform provider", terraformRepresentation) -} - -var ( - //MatchingOperatorIs const for IS condition operator - MatchingOperatorIs = newBasicMatchingOperator("is") - //MatchingOperatorContains const for CONTAINS condition operator - MatchingOperatorContains = newBasicMatchingOperator("contains") - //MatchingOperatorStartsWith const for STARTS_WITH condition operator - MatchingOperatorStartsWith = newBasicMatchingOperator("startsWith", "starts_with") - //MatchingOperatorEndsWith const for ENDS_WITH condition operator - MatchingOperatorEndsWith = newBasicMatchingOperator("endsWith", "ends_with") -) - -// SupportedMatchingOperators slice of supported matching operatorTypes types -var SupportedMatchingOperators = MatchingOperators{MatchingOperatorIs, MatchingOperatorContains, MatchingOperatorStartsWith, MatchingOperatorEndsWith} diff --git a/instana/restapi/custom-event-specification-threshold-rule-matching-operator_test.go b/instana/restapi/custom-event-specification-threshold-rule-matching-operator_test.go deleted file mode 100644 index b55196b0..00000000 --- a/instana/restapi/custom-event-specification-threshold-rule-matching-operator_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package restapi_test - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" - - . "github.com/gessnerfl/terraform-provider-instana/instana/restapi" -) - -func TestShouldPovideInstanaSupportedValuesOfMatchingOperatorTypes(t *testing.T) { - expectedResult := []string{MatchingOperatorIs.InstanaAPIValue(), MatchingOperatorContains.InstanaAPIValue(), MatchingOperatorStartsWith.InstanaAPIValue(), MatchingOperatorEndsWith.InstanaAPIValue()} - result := SupportedMatchingOperators.InstanaAPISupportedValues() - - assert.Equal(t, expectedResult, result) -} - -func TestShouldPovideTerraformSupportedValuesOfMatchingOperatorTypes(t *testing.T) { - expectedResult := []string{} - for _, mo := range SupportedMatchingOperators { - expectedResult = append(expectedResult, mo.TerraformSupportedValues()...) - } - result := SupportedMatchingOperators.TerrafromSupportedValues() - - assert.Equal(t, expectedResult, result) -} - -func TestShouldReturnTheMatchingOperatorTypeForAllSupportedInstanaWebRestAPIValues(t *testing.T) { - for _, mo := range SupportedMatchingOperators { - t.Run(fmt.Sprintf("TestShouldReturnTheMatchingOperatorTypeForAllSupportedInstanaWebRestAPIValues%s", mo), createTestCaseForTestShouldReturnTheMatchingOperatorTypeForAllSupportedInstanaWebRestAPIValues(mo)) - } -} - -func createTestCaseForTestShouldReturnTheMatchingOperatorTypeForAllSupportedInstanaWebRestAPIValues(mo MatchingOperator) func(*testing.T) { - return func(t *testing.T) { - val, err := SupportedMatchingOperators.FromInstanaAPIValue(mo.InstanaAPIValue()) - - assert.Nil(t, err) - assert.Equal(t, mo, val) - } -} - -func TestShouldReturnErrorWhenTheMatchingOperatorTypeIsNotASupportedInstanaWebRestAPIValue(t *testing.T) { - val, err := SupportedMatchingOperators.FromInstanaAPIValue("invalid") - - assert.NotNil(t, err) - assert.Equal(t, MatchingOperatorIs, val) -} - -func TestShouldReturnTheMatchingOperatorTypeForAllSupportedTerraformProviderValues(t *testing.T) { - for _, mo := range SupportedMatchingOperators { - for _, v := range mo.TerraformSupportedValues() { - t.Run(fmt.Sprintf("TestShouldReturnTheMatchingOperatorTypeForAllSupportedTerraformProviderValues%s", v), createTestCaseForTestShouldReturnTheMatchingOperatorTypeForAllSupportedTerraformProviderValues(mo, v)) - } - } -} - -func createTestCaseForTestShouldReturnTheMatchingOperatorTypeForAllSupportedTerraformProviderValues(mo MatchingOperator, value string) func(*testing.T) { - return func(t *testing.T) { - val, err := SupportedMatchingOperators.FromTerraformValue(value) - - assert.Nil(t, err) - assert.Equal(t, mo, val) - } -} - -func TestShouldReturnErrorWhenTheMatchingOperatorTypeIsNotASupportedInstanaTerraformProviderValue(t *testing.T) { - val, err := SupportedMatchingOperators.FromTerraformValue("invalid") - - assert.NotNil(t, err) - assert.Equal(t, MatchingOperatorIs, val) -}