diff --git a/CHANGELOG.md b/CHANGELOG.md index 692fd914..0b709653 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -336,38 +336,43 @@ DEVELOPERS: * using grpc endpoint instead of the REST endpoint. * moved to `plugin-framework`. -Release 1.8.0 +## Release 1.8.0 Breaking Changes: #### resource/coralogix_dashboard * schemas where changed to support the new dashboard widgets and more convenient schema. -Release 1.8.6 +## Release 1.8.6 New Features: #### resource/coralogix_alert * Adding support for `flow.group_by`. -Release 1.8.10 +## Release 1.8.10 New Features: #### resource/coralogix_dashboard * Adding limitation for `layout.sections` length (will support few sections in the future). * is_visible is true by default (for all is_visible fields). * Removing `gauge.query.logs/spans.aggregation` from schema. -Release 1.8.11 +## Release 1.8.11 New Features: #### resource/coralogix_dashboard * Adding support for `markdown` and `horizonal_bar_chart` widgets. * Adding support for `color_scheme` and `sort_by` for `bar_chart`. -Release 1.9.0 +## Release 1.9.0 Breaking Changes: #### resource/coralogix_webhook * All webhook types changed from `TypeList` to `SingleNestedAttribute` e.g. - `slack { }` => `slack = { }`. * Linkage between webhook and alert was changed from webhook's `id` to webhook's `external_id`. e.g.- `integration_id = coralogix_webhook.slack_webhook.id` => `integration_id = coralogix_webhook.slack_webhook.external_id` -Release 1.10.0 +## Release 1.10.0 Breaking Changes: #### resource/coralogix_recording_rules_groups_set * `group` was changed to `groups` and from `TypeSet` to `SetNestedAttribute`. e.g. - `group { }` => `groups = [{ }]`. * `group.rule` was changed to `groups.rules` and from `TypeList` to `ListNestedAttribute`. e.g. - `rule { }` => `rules = [{ }]`. -* this version contains a [State Upgrader](https://developer.hashicorp.com/terraform/plugin/framework/migrating/resources/state-upgrade#framework). It will upgrade the state to the new schema. Please make sure to back up your state before upgrading. \ No newline at end of file +* this version contains a [State Upgrader](https://developer.hashicorp.com/terraform/plugin/framework/migrating/resources/state-upgrade#framework). It will upgrade the state to the new schema. Please make sure to back up your state before upgrading. + +## Release 1.10.4 +Breaking Changes: +#### resource/coralogix_tco_policy_overrides +* the resource was deprecated and removed. \ No newline at end of file diff --git a/coralogix/clientset/enrichments-client.go b/coralogix/clientset/enrichments-client.go index 925d8295..b1e6ca88 100644 --- a/coralogix/clientset/enrichments-client.go +++ b/coralogix/clientset/enrichments-client.go @@ -4,15 +4,13 @@ import ( "context" enrichment "terraform-provider-coralogix/coralogix/clientset/grpc/enrichment/v1" - - "google.golang.org/protobuf/types/known/wrapperspb" ) type EnrichmentsClient struct { callPropertiesCreator *CallPropertiesCreator } -func (e EnrichmentsClient) CreateEnrichments(ctx context.Context, req []*enrichment.EnrichmentRequestModel) ([]*enrichment.Enrichment, error) { +func (e EnrichmentsClient) CreateEnrichments(ctx context.Context, req *enrichment.AddEnrichmentsRequest) ([]*enrichment.Enrichment, error) { callProperties, err := e.callPropertiesCreator.GetCallProperties(ctx) if err != nil { return nil, err @@ -22,14 +20,13 @@ func (e EnrichmentsClient) CreateEnrichments(ctx context.Context, req []*enrichm defer conn.Close() client := enrichment.NewEnrichmentServiceClient(conn) - addReq := &enrichment.AddEnrichmentsRequest{RequestEnrichments: req} - resp, err := client.AddEnrichments(callProperties.Ctx, addReq, callProperties.CallOptions...) + resp, err := client.AddEnrichments(callProperties.Ctx, req, callProperties.CallOptions...) if err != nil { return nil, err } enrichments := resp.GetEnrichments() - from := len(enrichments) - len(req) + from := len(enrichments) - len(req.GetRequestEnrichments()) to := len(enrichments) return enrichments[from:to], nil } @@ -84,44 +81,7 @@ func (e EnrichmentsClient) GetCustomEnrichments(ctx context.Context, customEnric return result, nil } -func (e EnrichmentsClient) UpdateEnrichments(ctx context.Context, ids []uint32, req []*enrichment.EnrichmentRequestModel) ([]*enrichment.Enrichment, error) { - err := e.DeleteEnrichments(ctx, ids) - if err != nil { - return nil, err - } - return e.CreateEnrichments(ctx, req) -} - -func (e EnrichmentsClient) DeleteEnrichments(ctx context.Context, ids []uint32) error { - callProperties, err := e.callPropertiesCreator.GetCallProperties(ctx) - if err != nil { - return err - } - - conn := callProperties.Connection - defer conn.Close() - - client := enrichment.NewEnrichmentServiceClient(conn) - - enrichmentIds := make([]*wrapperspb.UInt32Value, 0, len(ids)) - for _, id := range ids { - enrichmentIds = append(enrichmentIds, wrapperspb.UInt32(id)) - } - - req := &enrichment.RemoveEnrichmentsRequest{ - EnrichmentIds: enrichmentIds, - } - - _, err = client.RemoveEnrichments(callProperties.Ctx, req, callProperties.CallOptions...) - return err -} - -func (e EnrichmentsClient) DeleteEnrichmentsByType(ctx context.Context, enrichmentType string) error { - enrichmentsToDelete, err := e.GetEnrichmentsByType(ctx, enrichmentType) - if err != nil { - return err - } - +func (e EnrichmentsClient) DeleteEnrichments(ctx context.Context, req *enrichment.RemoveEnrichmentsRequest) error { callProperties, err := e.callPropertiesCreator.GetCallProperties(ctx) if err != nil { return err @@ -132,15 +92,6 @@ func (e EnrichmentsClient) DeleteEnrichmentsByType(ctx context.Context, enrichme client := enrichment.NewEnrichmentServiceClient(conn) - enrichmentIds := make([]*wrapperspb.UInt32Value, 0, len(enrichmentsToDelete)) - for _, enrichment := range enrichmentsToDelete { - enrichmentIds = append(enrichmentIds, wrapperspb.UInt32(enrichment.GetId())) - } - - req := &enrichment.RemoveEnrichmentsRequest{ - EnrichmentIds: enrichmentIds, - } - _, err = client.RemoveEnrichments(callProperties.Ctx, req, callProperties.CallOptions...) return err } diff --git a/coralogix/clientset/recording-rules-groups-sets-client.go b/coralogix/clientset/recording-rules-groups-sets-client.go index d1e7c82a..4a19cd96 100644 --- a/coralogix/clientset/recording-rules-groups-sets-client.go +++ b/coralogix/clientset/recording-rules-groups-sets-client.go @@ -3,8 +3,9 @@ package clientset import ( "context" - "google.golang.org/protobuf/types/known/emptypb" rrg "terraform-provider-coralogix/coralogix/clientset/grpc/recording-rules-groups-sets/v1" + + "google.golang.org/protobuf/types/known/emptypb" ) type RecordingRulesGroupsSetsClient struct { diff --git a/coralogix/data_source_coralogix_action.go b/coralogix/data_source_coralogix_action.go index 59eec58c..485ea090 100644 --- a/coralogix/data_source_coralogix_action.go +++ b/coralogix/data_source_coralogix_action.go @@ -5,13 +5,16 @@ import ( "fmt" "log" + "google.golang.org/protobuf/encoding/protojson" + + "terraform-provider-coralogix/coralogix/clientset" + actions "terraform-provider-coralogix/coralogix/clientset/grpc/actions/v2" + "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "terraform-provider-coralogix/coralogix/clientset" - actions "terraform-provider-coralogix/coralogix/clientset/grpc/actions/v2" "google.golang.org/protobuf/types/known/wrapperspb" ) @@ -47,10 +50,10 @@ func (d *ActionDataSource) Configure(_ context.Context, req datasource.Configure d.client = clientSet.Actions() } -func (d *ActionDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { +func (d *ActionDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { var r ActionResource var resourceResp resource.SchemaResponse - r.Schema(nil, resource.SchemaRequest{}, &resourceResp) + r.Schema(ctx, resource.SchemaRequest{}, &resourceResp) resp.Schema = frameworkDatasourceSchemaFromFrameworkResourceSchema(resourceResp.Schema) } @@ -65,7 +68,8 @@ func (d *ActionDataSource) Read(ctx context.Context, req datasource.ReadRequest, //Get refreshed Action value from Coralogix id := data.ID.ValueString() log.Printf("[INFO] Reading Action: %s", id) - getActionResp, err := d.client.GetAction(ctx, &actions.GetActionRequest{Id: wrapperspb.String(id)}) + getActionReq := &actions.GetActionRequest{Id: wrapperspb.String(id)} + getActionResp, err := d.client.GetAction(ctx, getActionReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -77,12 +81,12 @@ func (d *ActionDataSource) Read(ctx context.Context, req datasource.ReadRequest, } else { resp.Diagnostics.AddError( "Error reading Action", - handleRpcErrorNewFramework(err, "Action"), + formatRpcErrors(err, getActionURL, protojson.Format(getActionReq)), ) } return } - log.Printf("[INFO] Received Action: %#v", getActionResp) + log.Printf("[INFO] Received Action: %s", protojson.Format(getActionResp)) data = flattenAction(getActionResp.GetAction()) diff --git a/coralogix/data_source_coralogix_alert.go b/coralogix/data_source_coralogix_alert.go index 8451d5c2..78b304f6 100644 --- a/coralogix/data_source_coralogix_alert.go +++ b/coralogix/data_source_coralogix_alert.go @@ -4,6 +4,8 @@ import ( "context" "log" + "google.golang.org/protobuf/encoding/protojson" + "terraform-provider-coralogix/coralogix/clientset" alertsv1 "terraform-provider-coralogix/coralogix/clientset/grpc/alerts/v2" @@ -35,11 +37,12 @@ func dataSourceCoralogixAlertRead(ctx context.Context, d *schema.ResourceData, m log.Printf("[INFO] Reading alert %s", id) alertResp, err := meta.(*clientset.ClientSet).Alerts().GetAlert(ctx, getAlertRequest) if err != nil { + reqStr := protojson.Format(getAlertRequest) log.Printf("[ERROR] Received error: %#v", err) - return handleRpcErrorWithID(err, "alert", id.GetValue()) + return diag.Errorf(formatRpcErrors(err, getAlertURL, reqStr)) } alert := alertResp.GetAlert() - log.Printf("[INFO] Received alert: %#v", alert) + log.Printf("[INFO] Received alert: %s", protojson.Format(alert)) d.SetId(alert.GetId().GetValue()) diff --git a/coralogix/data_source_coralogix_dashboard.go b/coralogix/data_source_coralogix_dashboard.go index f9527c92..7dc74761 100644 --- a/coralogix/data_source_coralogix_dashboard.go +++ b/coralogix/data_source_coralogix_dashboard.go @@ -5,14 +5,17 @@ import ( "fmt" "log" + "terraform-provider-coralogix/coralogix/clientset" + dashboards "terraform-provider-coralogix/coralogix/clientset/grpc/coralogix-dashboards/v1" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - dashboards "terraform-provider-coralogix/coralogix/clientset/grpc/coralogix-dashboards/v1" ) var _ datasource.DataSourceWithConfigure = &DashboardDataSource{} @@ -46,10 +49,10 @@ func (d *DashboardDataSource) Configure(_ context.Context, req datasource.Config d.client = clientSet.Dashboards() } -func (d *DashboardDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { +func (d *DashboardDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { var r DashboardResource var resourceResp resource.SchemaResponse - r.Schema(nil, resource.SchemaRequest{}, &resourceResp) + r.Schema(ctx, resource.SchemaRequest{}, &resourceResp) resp.Schema = frameworkDatasourceSchemaFromFrameworkResourceSchema(resourceResp.Schema) } @@ -64,7 +67,8 @@ func (d *DashboardDataSource) Read(ctx context.Context, req datasource.ReadReque //Get refreshed Dashboard value from Coralogix id := data.ID.ValueString() log.Printf("[INFO] Reading Dashboard: %s", id) - getDashboardResp, err := d.client.GetDashboard(ctx, &dashboards.GetDashboardRequest{DashboardId: wrapperspb.String(id)}) + getDashboardReq := &dashboards.GetDashboardRequest{DashboardId: wrapperspb.String(id)} + getDashboardResp, err := d.client.GetDashboard(ctx, getDashboardReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -76,7 +80,7 @@ func (d *DashboardDataSource) Read(ctx context.Context, req datasource.ReadReque } else { resp.Diagnostics.AddError( "Error reading Dashboard", - handleRpcErrorNewFramework(err, "Dashboard"), + formatRpcErrors(err, getDashboardURL, protojson.Format(getDashboardReq)), ) } return diff --git a/coralogix/data_source_coralogix_data_set.go b/coralogix/data_source_coralogix_data_set.go index 5f03af10..d56b324c 100644 --- a/coralogix/data_source_coralogix_data_set.go +++ b/coralogix/data_source_coralogix_data_set.go @@ -7,6 +7,8 @@ import ( "terraform-provider-coralogix/coralogix/clientset" enrichmentv1 "terraform-provider-coralogix/coralogix/clientset/grpc/enrichment/v1" + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "google.golang.org/protobuf/types/known/wrapperspb" @@ -33,9 +35,10 @@ func dataSourceCoralogixDataSetRead(ctx context.Context, d *schema.ResourceData, enrichmentResp, err := meta.(*clientset.ClientSet).DataSet().GetDataSet(ctx, req) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcErrorWithID(err, "custom-enrichment-data", id) + reqStr := protojson.Format(req) + return diag.Errorf(formatRpcErrors(err, getDataSetURL, reqStr)) } - log.Printf("[INFO] Received custom-enrichment-data: %#v", enrichmentResp) + log.Printf("[INFO] Received custom-enrichment-data: %s", protojson.Format(enrichmentResp)) d.SetId(uint32ToStr(enrichmentResp.GetCustomEnrichment().GetId())) diff --git a/coralogix/data_source_coralogix_enrichment.go b/coralogix/data_source_coralogix_enrichment.go index dce78822..c703c2c0 100644 --- a/coralogix/data_source_coralogix_enrichment.go +++ b/coralogix/data_source_coralogix_enrichment.go @@ -7,6 +7,8 @@ import ( "terraform-provider-coralogix/coralogix/clientset" enrichmentv1 "terraform-provider-coralogix/coralogix/clientset/grpc/enrichment/v1" + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -39,8 +41,9 @@ func dataSourceCoralogixEnrichmentRead(ctx context.Context, d *schema.ResourceDa enrichmentResp, err = meta.(*clientset.ClientSet).Enrichments().GetCustomEnrichments(ctx, strToUint32(id)) } if err != nil { + reqStr := protojson.Format(&enrichmentv1.GetEnrichmentsRequest{}) log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "enrichment") + return diag.Errorf(formatRpcErrors(err, getEnrichmentsURL, reqStr)) } log.Printf("[INFO] Received enrichment: %#v", enrichmentResp) d.SetId(id) diff --git a/coralogix/data_source_coralogix_events2meric.go b/coralogix/data_source_coralogix_events2meric.go index 68cb9e2d..bc01ddb6 100644 --- a/coralogix/data_source_coralogix_events2meric.go +++ b/coralogix/data_source_coralogix_events2meric.go @@ -5,14 +5,17 @@ import ( "fmt" "log" + "terraform-provider-coralogix/coralogix/clientset" + e2m "terraform-provider-coralogix/coralogix/clientset/grpc/events2metrics/v2" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - e2m "terraform-provider-coralogix/coralogix/clientset/grpc/events2metrics/v2" ) var _ datasource.DataSourceWithConfigure = &Events2MetricDataSource{} @@ -46,10 +49,10 @@ func (d *Events2MetricDataSource) Configure(_ context.Context, req datasource.Co d.client = clientSet.Events2Metrics() } -func (d *Events2MetricDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { +func (d *Events2MetricDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { var r Events2MetricResource var resourceResp resource.SchemaResponse - r.Schema(nil, resource.SchemaRequest{}, &resourceResp) + r.Schema(ctx, resource.SchemaRequest{}, &resourceResp) resp.Schema = frameworkDatasourceSchemaFromFrameworkResourceSchema(resourceResp.Schema) } @@ -64,7 +67,8 @@ func (d *Events2MetricDataSource) Read(ctx context.Context, req datasource.ReadR //Get refreshed Events2Metric value from Coralogix id := data.ID.ValueString() log.Printf("[INFO] Reading Events2metric: %s", id) - getE2MResp, err := d.client.GetEvents2Metric(ctx, &e2m.GetE2MRequest{Id: wrapperspb.String(id)}) + getE2MReq := &e2m.GetE2MRequest{Id: wrapperspb.String(id)} + getE2MResp, err := d.client.GetEvents2Metric(ctx, getE2MReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -76,12 +80,12 @@ func (d *Events2MetricDataSource) Read(ctx context.Context, req datasource.ReadR } else { resp.Diagnostics.AddError( "Error reading Events2Metric", - handleRpcErrorNewFramework(err, "Events2metric"), + formatRpcErrors(err, getEvents2MetricURL, protojson.Format(getE2MReq)), ) } return } - log.Printf("[INFO] Received Events2metric: %#v", getE2MResp) + log.Printf("[INFO] Received Events2metric: %s", protojson.Format(getE2MResp)) data = flattenE2M(ctx, getE2MResp.GetE2M()) diff --git a/coralogix/data_source_coralogix_recording_rules_group.go b/coralogix/data_source_coralogix_recording_rules_group.go index 632d46bd..5b84bd00 100644 --- a/coralogix/data_source_coralogix_recording_rules_group.go +++ b/coralogix/data_source_coralogix_recording_rules_group.go @@ -5,13 +5,16 @@ import ( "fmt" "log" + "terraform-provider-coralogix/coralogix/clientset" + rrgs "terraform-provider-coralogix/coralogix/clientset/grpc/recording-rules-groups-sets/v1" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "terraform-provider-coralogix/coralogix/clientset" - rrgs "terraform-provider-coralogix/coralogix/clientset/grpc/recording-rules-groups-sets/v1" ) var _ datasource.DataSourceWithConfigure = &RecordingRuleGroupSetDataSource{} @@ -45,10 +48,10 @@ func (d *RecordingRuleGroupSetDataSource) Configure(_ context.Context, req datas d.client = clientSet.RecordingRuleGroupsSets() } -func (d *RecordingRuleGroupSetDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { +func (d *RecordingRuleGroupSetDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { var r RecordingRuleGroupSetResource var resourceResp resource.SchemaResponse - r.Schema(nil, resource.SchemaRequest{}, &resourceResp) + r.Schema(ctx, resource.SchemaRequest{}, &resourceResp) resp.Schema = frameworkDatasourceSchemaFromFrameworkResourceSchema(resourceResp.Schema) } @@ -63,7 +66,8 @@ func (d *RecordingRuleGroupSetDataSource) Read(ctx context.Context, req datasour //Get refreshed recording-rule-group-set value from Coralogix id := data.ID.ValueString() log.Printf("[INFO] Reading recording-rule-group-set: %s", id) - getResp, err := d.client.GetRecordingRuleGroupsSet(ctx, &rrgs.FetchRuleGroupSet{Id: id}) + getReq := &rrgs.FetchRuleGroupSet{Id: id} + getResp, err := d.client.GetRecordingRuleGroupsSet(ctx, getReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -75,12 +79,12 @@ func (d *RecordingRuleGroupSetDataSource) Read(ctx context.Context, req datasour } else { resp.Diagnostics.AddError( "Error reading recording-rule-group-set", - handleRpcErrorNewFramework(err, "recording-rule-group-set"), + formatRpcErrors(err, getRuleGroupURL, protojson.Format(getReq)), ) } return } - log.Printf("[INFO] Received recording-rule-group-set: %#v", getResp) + log.Printf("[INFO] Received recording-rule-group-set: %s", protojson.Format(getResp)) data, diags := flattenRecordingRuleGroupSet(ctx, &RecordingRuleGroupSetResourceModel{}, getResp) if diags.HasError() { diff --git a/coralogix/data_source_coralogix_rules_group.go b/coralogix/data_source_coralogix_rules_group.go index 054350ac..caff1285 100644 --- a/coralogix/data_source_coralogix_rules_group.go +++ b/coralogix/data_source_coralogix_rules_group.go @@ -7,6 +7,8 @@ import ( "terraform-provider-coralogix/coralogix/clientset" v1 "terraform-provider-coralogix/coralogix/clientset/grpc/rules-groups/v1" + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -34,8 +36,9 @@ func dataSourceCoralogixRulesGroupRead(ctx context.Context, d *schema.ResourceDa log.Printf("[INFO] Reading rule-group %s", id) ruleGroupResp, err := meta.(*clientset.ClientSet).RuleGroups().GetRuleGroup(ctx, getRuleGroupRequest) if err != nil { + reqStr := protojson.Format(getRuleGroupRequest) log.Printf("[ERROR] Received error: %#v", err) - return handleRpcErrorWithID(err, "rule-group", id) + return diag.Errorf(formatRpcErrors(err, getParsingRuleURL, reqStr)) } ruleGroup := ruleGroupResp.GetRuleGroup() log.Printf("[INFO] Received rule-group: %#v", ruleGroup) diff --git a/coralogix/data_source_coralogix_sli.go b/coralogix/data_source_coralogix_sli.go index 49fab1fb..c6c5941f 100644 --- a/coralogix/data_source_coralogix_sli.go +++ b/coralogix/data_source_coralogix_sli.go @@ -5,6 +5,11 @@ import ( "fmt" "log" + "terraform-provider-coralogix/coralogix/clientset" + sli "terraform-provider-coralogix/coralogix/clientset/grpc/sli" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework/datasource" datasourceschema "github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/resource" @@ -12,8 +17,6 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - sli "terraform-provider-coralogix/coralogix/clientset/grpc/sli" ) var _ datasource.DataSourceWithConfigure = &SLIDataSource{} @@ -47,10 +50,10 @@ func (d *SLIDataSource) Configure(_ context.Context, req datasource.ConfigureReq d.client = clientSet.SLIs() } -func (d *SLIDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { +func (d *SLIDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { var r SLIResource var resourceResp resource.SchemaResponse - r.Schema(nil, resource.SchemaRequest{}, &resourceResp) + r.Schema(ctx, resource.SchemaRequest{}, &resourceResp) schema := frameworkDatasourceSchemaFromFrameworkResourceSchema(resourceResp.Schema) schema.Attributes["service_name"] = datasourceschema.StringAttribute{ @@ -71,7 +74,8 @@ func (d *SLIDataSource) Read(ctx context.Context, req datasource.ReadRequest, re id := data.ID.ValueString() serviceName := data.ServiceName.ValueString() log.Printf("[INFO] Reading sli: %s", id) - getSLIsresp, err := d.client.GetSLIs(ctx, &sli.GetSlisRequest{ServiceName: wrapperspb.String(serviceName)}) + getSLIsReq := &sli.GetSlisRequest{ServiceName: wrapperspb.String(serviceName)} + getSLIsResp, err := d.client.GetSLIs(ctx, getSLIsReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -82,15 +86,15 @@ func (d *SLIDataSource) Read(ctx context.Context, req datasource.ReadRequest, re ) } else { resp.Diagnostics.AddError( - "Error reading tco-policy", - handleRpcErrorNewFramework(err, "SLI"), + "Error reading SLI", + formatRpcErrors(err, getSliURL, protojson.Format(getSLIsReq)), ) } return } var SLI *sli.Sli - for _, sli := range getSLIsresp.GetSlis() { + for _, sli := range getSLIsResp.GetSlis() { if sli.SliId.GetValue() == id { SLI = sli break @@ -105,7 +109,7 @@ func (d *SLIDataSource) Read(ctx context.Context, req datasource.ReadRequest, re return } - log.Printf("[INFO] Received SLI: %#v", SLI) + log.Printf("[INFO] Received SLI: %s", protojson.Format(SLI)) data, diags := flattenSLI(ctx, SLI) if diags.HasError() { diff --git a/coralogix/data_source_coralogix_tco_policy_logs.go b/coralogix/data_source_coralogix_tco_policy_logs.go index 1f916d17..2de01eae 100644 --- a/coralogix/data_source_coralogix_tco_policy_logs.go +++ b/coralogix/data_source_coralogix_tco_policy_logs.go @@ -5,13 +5,16 @@ import ( "fmt" "log" + "terraform-provider-coralogix/coralogix/clientset" + tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "terraform-provider-coralogix/coralogix/clientset" - tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" "google.golang.org/protobuf/types/known/wrapperspb" ) @@ -47,10 +50,10 @@ func (d *TCOPolicyDataSource) Configure(_ context.Context, req datasource.Config d.client = clientSet.TCOPolicies() } -func (d *TCOPolicyDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { +func (d *TCOPolicyDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { var r TCOPolicyResource var resourceResp resource.SchemaResponse - r.Schema(nil, resource.SchemaRequest{}, &resourceResp) + r.Schema(ctx, resource.SchemaRequest{}, &resourceResp) resp.Schema = frameworkDatasourceSchemaFromFrameworkResourceSchema(resourceResp.Schema) } @@ -65,7 +68,8 @@ func (d *TCOPolicyDataSource) Read(ctx context.Context, req datasource.ReadReque //Get refreshed tco-policy value from Coralogix id := data.ID.ValueString() log.Printf("[INFO] Reading tco-policy: %s", id) - getPolicyResp, err := d.client.GetTCOPolicy(ctx, &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)}) + getPolicyReq := &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)} + getPolicyResp, err := d.client.GetTCOPolicy(ctx, getPolicyReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -77,12 +81,12 @@ func (d *TCOPolicyDataSource) Read(ctx context.Context, req datasource.ReadReque } else { resp.Diagnostics.AddError( "Error reading tco-policy", - handleRpcErrorNewFramework(err, "tco-policy"), + formatRpcErrors(err, getTCOPolicyURL, protojson.Format(getPolicyReq)), ) } return } - log.Printf("[INFO] Received tco-policy: %#v", getPolicyResp) + log.Printf("[INFO] Received tco-policy: %s", protojson.Format(getPolicyResp)) data, diags := flattenTCOPolicy(ctx, getPolicyResp.GetPolicy()) if diags.HasError() { diff --git a/coralogix/data_source_coralogix_tco_policy_override.go b/coralogix/data_source_coralogix_tco_policy_override.go deleted file mode 100644 index ad93cf74..00000000 --- a/coralogix/data_source_coralogix_tco_policy_override.go +++ /dev/null @@ -1,41 +0,0 @@ -package coralogix - -import ( - "context" - "log" - - "terraform-provider-coralogix/coralogix/clientset" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func dataSourceCoralogixTCOPolicyOverride() *schema.Resource { - tcoPolicyOverrideSchema := datasourceSchemaFromResourceSchema(TCOPolicyOverrideSchema()) - tcoPolicyOverrideSchema["id"] = &schema.Schema{ - Type: schema.TypeString, - Required: true, - } - - return &schema.Resource{ - ReadContext: dataSourceCoralogixTCOPolicyOverrideRead, - - Schema: tcoPolicyOverrideSchema, - } -} - -func dataSourceCoralogixTCOPolicyOverrideRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - id := d.Get("id").(string) - - log.Printf("[INFO] Reading tco-policy-override %s", id) - tcoPolicyOverride, err := meta.(*clientset.ClientSet).TCOPoliciesOverrides().GetTCOPolicyOverride(ctx, id) - if err != nil { - log.Printf("[ERROR] Received error: %#v", err) - return handleRpcErrorWithID(err, "tco-policy-override", id) - } - log.Printf("[INFO] Received tco-policy-override: %#v", tcoPolicyOverride) - - d.SetId(id) - - return setTCOPolicyOverride(d, tcoPolicyOverride) -} diff --git a/coralogix/data_source_coralogix_tco_policy_override_test.go b/coralogix/data_source_coralogix_tco_policy_override_test.go deleted file mode 100644 index 51f1580d..00000000 --- a/coralogix/data_source_coralogix_tco_policy_override_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package coralogix - -var tcoPolicyOverrideDataSourceName = "data." + tcoPolicyOverrideResourceName - -//func TestAccCoralogixDataSourceTCOPolicyOverride_basic(t *testing.T) { -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// ProviderFactories: testAccProviderFactories, -// Steps: []resource.TestStep{ -// { -// Config: testAccCoralogixResourceTCOPolicyOverride() + -// testAccCoralogixResourceTCOPolicyOverride_read(), -// Check: resource.ComposeAggregateTestCheckFunc( -// resource.TestCheckResourceAttrSet(tcoPolicyOverrideDataSourceName, "id"), -// ), -// }, -// }, -// }) -//} - -func testAccCoralogixResourceTCOPolicyOverride_read() string { - return `data "coralogix_tco_policy_override" "test" { - id = coralogix_tco_policy_override.test.id -} -` -} diff --git a/coralogix/data_source_coralogix_tco_policy_traces.go b/coralogix/data_source_coralogix_tco_policy_traces.go index 03ae1a86..96893010 100644 --- a/coralogix/data_source_coralogix_tco_policy_traces.go +++ b/coralogix/data_source_coralogix_tco_policy_traces.go @@ -5,13 +5,16 @@ import ( "fmt" "log" + "terraform-provider-coralogix/coralogix/clientset" + tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "terraform-provider-coralogix/coralogix/clientset" - tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" "google.golang.org/protobuf/types/known/wrapperspb" ) @@ -47,10 +50,10 @@ func (d *TCOPolicyTracesDataSource) Configure(_ context.Context, req datasource. d.client = clientSet.TCOPolicies() } -func (d *TCOPolicyTracesDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { +func (d *TCOPolicyTracesDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { var r TCOPolicyTracesResource var resourceResp resource.SchemaResponse - r.Schema(nil, resource.SchemaRequest{}, &resourceResp) + r.Schema(ctx, resource.SchemaRequest{}, &resourceResp) resp.Schema = frameworkDatasourceSchemaFromFrameworkResourceSchema(resourceResp.Schema) } @@ -65,7 +68,8 @@ func (d *TCOPolicyTracesDataSource) Read(ctx context.Context, req datasource.Rea //Get refreshed tco-policy value from Coralogix id := data.ID.ValueString() log.Printf("[INFO] Reading tco-policy: %s", id) - getPolicyResp, err := d.client.GetTCOPolicy(ctx, &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)}) + getPolicyReq := &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)} + getPolicyResp, err := d.client.GetTCOPolicy(ctx, getPolicyReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -77,12 +81,12 @@ func (d *TCOPolicyTracesDataSource) Read(ctx context.Context, req datasource.Rea } else { resp.Diagnostics.AddError( "Error reading tco-policy", - handleRpcErrorNewFramework(err, "tco-policy"), + formatRpcErrors(err, getTCOPolicyURL, protojson.Format(getPolicyReq)), ) } return } - log.Printf("[INFO] Received tco-policy: %#v", getPolicyResp) + log.Printf("[INFO] Received tco-policy: %s", protojson.Format(getPolicyResp)) data, diags := flattenTCOPolicyTraces(ctx, getPolicyResp.GetPolicy()) if diags.HasError() { diff --git a/coralogix/data_source_coralogix_webhook.go b/coralogix/data_source_coralogix_webhook.go index 91dc8d85..3511e31c 100644 --- a/coralogix/data_source_coralogix_webhook.go +++ b/coralogix/data_source_coralogix_webhook.go @@ -5,13 +5,16 @@ import ( "fmt" "log" + "terraform-provider-coralogix/coralogix/clientset" + webhooks "terraform-provider-coralogix/coralogix/clientset/grpc/webhooks" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "terraform-provider-coralogix/coralogix/clientset" - webhooks "terraform-provider-coralogix/coralogix/clientset/grpc/webhooks" "google.golang.org/protobuf/types/known/wrapperspb" ) @@ -47,10 +50,10 @@ func (d *WebhookDataSource) Configure(_ context.Context, req datasource.Configur d.client = clientSet.Webhooks() } -func (d *WebhookDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { +func (d *WebhookDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { var r WebhookResource var resourceResp resource.SchemaResponse - r.Schema(nil, resource.SchemaRequest{}, &resourceResp) + r.Schema(ctx, resource.SchemaRequest{}, &resourceResp) resp.Schema = frameworkDatasourceSchemaFromFrameworkResourceSchema(resourceResp.Schema) } @@ -65,7 +68,9 @@ func (d *WebhookDataSource) Read(ctx context.Context, req datasource.ReadRequest //Get refreshed Webhook value from Coralogix id := data.ID.ValueString() log.Printf("[INFO] Reading Webhook: %s", id) - getWebhookResp, err := d.client.GetWebhook(ctx, &webhooks.GetOutgoingWebhookRequest{Id: wrapperspb.String(id)}) + + getWebhookReq := &webhooks.GetOutgoingWebhookRequest{Id: wrapperspb.String(id)} + getWebhookResp, err := d.client.GetWebhook(ctx, getWebhookReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -75,14 +80,15 @@ func (d *WebhookDataSource) Read(ctx context.Context, req datasource.ReadRequest fmt.Sprintf("%s will be recreated when you apply", id), ) } else { + reqStr := protojson.Format(getWebhookReq) resp.Diagnostics.AddError( "Error reading Webhook", - handleRpcErrorNewFramework(err, "Webhook"), + formatRpcErrors(err, "Webhook", reqStr), ) } return } - log.Printf("[INFO] Received Webhook: %#v", getWebhookResp) + log.Printf("[INFO] Received Webhook: %s", protojson.Format(getWebhookResp)) data, diags := flattenWebhook(ctx, getWebhookResp.GetWebhook()) if diags.HasError() { diff --git a/coralogix/provider.go b/coralogix/provider.go index f6fd4b08..b8495730 100644 --- a/coralogix/provider.go +++ b/coralogix/provider.go @@ -5,6 +5,8 @@ import ( "fmt" "os" + "terraform-provider-coralogix/coralogix/clientset" + "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/provider" @@ -12,7 +14,6 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" oldSchema "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "terraform-provider-coralogix/coralogix/clientset" "github.com/hashicorp/terraform-plugin-framework/provider/schema" ) @@ -61,12 +62,11 @@ func OldProvider() *oldSchema.Provider { }, DataSourcesMap: map[string]*oldSchema.Resource{ - "coralogix_rules_group": dataSourceCoralogixRulesGroup(), - "coralogix_alert": dataSourceCoralogixAlert(), - "coralogix_enrichment": dataSourceCoralogixEnrichment(), - "coralogix_data_set": dataSourceCoralogixDataSet(), - "coralogix_hosted_dashboard": dataSourceCoralogixHostedDashboard(), - "coralogix_tco_policy_override": dataSourceCoralogixTCOPolicyOverride(), + "coralogix_rules_group": dataSourceCoralogixRulesGroup(), + "coralogix_alert": dataSourceCoralogixAlert(), + "coralogix_enrichment": dataSourceCoralogixEnrichment(), + "coralogix_data_set": dataSourceCoralogixDataSet(), + "coralogix_hosted_dashboard": dataSourceCoralogixHostedDashboard(), }, ResourcesMap: map[string]*oldSchema.Resource{ diff --git a/coralogix/resource_coralogix_action.go b/coralogix/resource_coralogix_action.go index 975d7f0c..b4c99690 100644 --- a/coralogix/resource_coralogix_action.go +++ b/coralogix/resource_coralogix_action.go @@ -5,7 +5,11 @@ import ( "fmt" "log" - "github.com/golang/protobuf/jsonpb" + "terraform-provider-coralogix/coralogix/clientset" + actions "terraform-provider-coralogix/coralogix/clientset/grpc/actions/v2" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/diag" @@ -20,8 +24,6 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - actions "terraform-provider-coralogix/coralogix/clientset/grpc/actions/v2" ) var ( @@ -33,6 +35,10 @@ var ( } actionProtoSourceTypeToSchemaSourceType = ReverseMap(actionSchemaSourceTypeToProtoSourceType) actionValidSourceTypes = GetKeys(actionSchemaSourceTypeToProtoSourceType) + createActionURL = "com.coralogixapis.actions.v2.ActionsService/CreateAction" + updateActionURL = "com.coralogixapis.actions.v2.ActionsService/ReplaceAction" + getActionURL = "com.coralogixapis.actions.v2.ActionsService/GetAction" + deleteActionURL = "com.coralogixapis.actions.v2.ActionsService/DeleteAction" ) func NewActionResource() resource.Resource { @@ -141,7 +147,6 @@ func (r *ActionResource) ImportState(ctx context.Context, req resource.ImportSta } func (r *ActionResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - jsm := &jsonpb.Marshaler{} var plan ActionResourceModel diags := req.Plan.Get(ctx, &plan) resp.Diagnostics.Append(diags...) @@ -154,20 +159,16 @@ func (r *ActionResource) Create(ctx context.Context, req resource.CreateRequest, resp.Diagnostics.Append(diags...) return } - actionStr, _ := jsm.MarshalToString(createActionRequest) + actionStr := protojson.Format(createActionRequest) log.Printf("[INFO] Creating new action: %s", actionStr) createResp, err := r.client.CreateAction(ctx, createActionRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - resp.Diagnostics.AddError( - "Error creating Action", - "Could not create Action, unexpected error: "+err.Error(), - ) + formatRpcErrors(err, createActionURL, actionStr) return } action := createResp.GetAction() - actionStr, _ = jsm.MarshalToString(action) - log.Printf("[INFO] Submitted new action: %#v", action) + log.Printf("[INFO] Submitted new action: %s", protojson.Format(action)) plan = flattenAction(action) @@ -201,7 +202,8 @@ func (r *ActionResource) Read(ctx context.Context, req resource.ReadRequest, res //Get refreshed Action value from Coralogix id := state.ID.ValueString() log.Printf("[INFO] Reading Action: %s", id) - getActionResp, err := r.client.GetAction(ctx, &actions.GetActionRequest{Id: wrapperspb.String(id)}) + getActionReq := &actions.GetActionRequest{Id: wrapperspb.String(id)} + getActionResp, err := r.client.GetAction(ctx, getActionReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -213,13 +215,13 @@ func (r *ActionResource) Read(ctx context.Context, req resource.ReadRequest, res } else { resp.Diagnostics.AddError( "Error reading Action", - handleRpcErrorNewFramework(err, "Action"), + formatRpcErrors(err, getActionURL, protojson.Format(getActionReq)), ) } return } action := getActionResp.GetAction() - log.Printf("[INFO] Received Action: %#v", action) + log.Printf("[INFO] Received Action: %s", protojson.Format(action)) state = flattenAction(action) // @@ -241,21 +243,22 @@ func (r ActionResource) Update(ctx context.Context, req resource.UpdateRequest, resp.Diagnostics.Append(diags...) return } - log.Printf("[INFO] Updating Action: %#v", actionUpdateReq) + log.Printf("[INFO] Updating Action: %s", protojson.Format(actionUpdateReq)) actionUpdateResp, err := r.client.UpdateAction(ctx, actionUpdateReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error updating Action", - "Could not update Action, unexpected error: "+err.Error(), + formatRpcErrors(err, updateActionURL, protojson.Format(actionUpdateReq)), ) return } - log.Printf("[INFO] Submitted updated Action: %#v", actionUpdateResp) + log.Printf("[INFO] Submitted updated Action: %s", protojson.Format(actionUpdateResp)) // Get refreshed Action value from Coralogix id := plan.ID.ValueString() - getActionResp, err := r.client.GetAction(ctx, &actions.GetActionRequest{Id: wrapperspb.String(id)}) + getActionReq := &actions.GetActionRequest{Id: wrapperspb.String(id)} + getActionResp, err := r.client.GetAction(ctx, getActionReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -267,12 +270,12 @@ func (r ActionResource) Update(ctx context.Context, req resource.UpdateRequest, } else { resp.Diagnostics.AddError( "Error reading Action", - handleRpcErrorNewFramework(err, "Action"), + formatRpcErrors(err, getActionURL, protojson.Format(getActionReq)), ) } return } - log.Printf("[INFO] Received Action: %#v", getActionResp) + log.Printf("[INFO] Received Action: %s", protojson.Format(getActionResp)) plan = flattenAction(getActionResp.GetAction()) @@ -290,15 +293,16 @@ func (r ActionResource) Delete(ctx context.Context, req resource.DeleteRequest, } id := state.ID.ValueString() - log.Printf("[INFO] Deleting Action %s\n", id) - if _, err := r.client.DeleteAction(ctx, &actions.DeleteActionRequest{Id: wrapperspb.String(id)}); err != nil { + log.Printf("[INFO] Deleting Action %s", id) + deleteReq := &actions.DeleteActionRequest{Id: wrapperspb.String(id)} + if _, err := r.client.DeleteAction(ctx, deleteReq); err != nil { resp.Diagnostics.AddError( - fmt.Sprintf("Error Deleting Action %s", state.ID.ValueString()), - handleRpcErrorNewFramework(err, "Action"), + fmt.Sprintf("Error Deleting Action %s", id), + formatRpcErrors(err, deleteActionURL, protojson.Format(deleteReq)), ) return } - log.Printf("[INFO] Action %s deleted\n", id) + log.Printf("[INFO] Action %s deleted", id) } type ActionResourceModel struct { diff --git a/coralogix/resource_coralogix_action_test.go b/coralogix/resource_coralogix_action_test.go index d4ac76d8..585ab8a9 100644 --- a/coralogix/resource_coralogix_action_test.go +++ b/coralogix/resource_coralogix_action_test.go @@ -5,10 +5,11 @@ import ( "fmt" "testing" - terraform2 "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "terraform-provider-coralogix/coralogix/clientset" actions "terraform-provider-coralogix/coralogix/clientset/grpc/actions/v2" + terraform2 "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/coralogix/resource_coralogix_alert.go b/coralogix/resource_coralogix_alert.go index 87fb31eb..2fc434f1 100644 --- a/coralogix/resource_coralogix_alert.go +++ b/coralogix/resource_coralogix_alert.go @@ -9,12 +9,14 @@ import ( "strings" "time" - "github.com/golang/protobuf/jsonpb" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "terraform-provider-coralogix/coralogix/clientset" alerts "terraform-provider-coralogix/coralogix/clientset/grpc/alerts/v2" + "google.golang.org/protobuf/encoding/protojson" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + . "github.com/ahmetalpbalkan/go-linq" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -166,6 +168,10 @@ var ( alerts.EvaluationWindow_EVALUATION_WINDOW_DYNAMIC: "Dynamic", } validEvaluationWindow = []string{"Rolling", "Dynamic"} + getAlertURL = "com.coralogix.alerts.v2.AlertService/CreateAlert" + createAlertURL = "com.coralogix.alerts.v2.AlertService/GetAlertByUniqueId" + updateAlertURL = "com.coralogix.alerts.v2.AlertService/UpdateAlertByUniqueId" + deleteAlertURL = "com.coralogix.alerts.v2.AlertService/DeleteAlertByUniqueId" ) type alertParams struct { @@ -1440,18 +1446,17 @@ func resourceCoralogixAlertCreate(ctx context.Context, d *schema.ResourceData, m return diags } - createAlertStr, _ := jsm.MarshalToString(createAlertRequest) + createAlertStr := protojson.Format(createAlertRequest) log.Printf("[INFO] Creating new alert: %s", createAlertStr) AlertResp, err := meta.(*clientset.ClientSet).Alerts().CreateAlert(ctx, createAlertRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "alert") + return diag.Errorf(formatRpcErrors(err, createAlertStr, createAlertStr)) } alert := AlertResp.GetAlert() - alertStr, _ := jsm.MarshalToString(alert) - log.Printf("[INFO] Submitted new alert: %s", alertStr) + log.Printf("[INFO] Submitted new alert: %s", protojson.Format(alert)) d.SetId(alert.GetUniqueIdentifier().GetValue()) return resourceCoralogixAlertRead(ctx, d, meta) @@ -1475,11 +1480,10 @@ func resourceCoralogixAlertRead(ctx context.Context, d *schema.ResourceData, met Detail: fmt.Sprintf("%s will be recreated when you apply", id), }} } - return handleRpcErrorWithID(err, "alert", id.GetValue()) + return diag.Errorf(formatRpcErrors(err, getAlertURL, protojson.Format(getAlertRequest))) } alert := alertResp.GetAlert() - jsm := jsonpb.Marshaler{} - alertStr, _ := jsm.MarshalToString(alert) + alertStr := protojson.Format(alert) log.Printf("[INFO] Received alert: %s", alertStr) return setAlert(d, alert) @@ -1491,18 +1495,17 @@ func resourceCoralogixAlertUpdate(ctx context.Context, d *schema.ResourceData, m return diags } - id := d.Id() updateAlertRequest := &alerts.UpdateAlertByUniqueIdRequest{ Alert: req, } - updateAlertStr, _ := jsm.MarshalToString(updateAlertRequest) + updateAlertStr := protojson.Format(updateAlertRequest) log.Printf("[INFO] Updating alert %s", updateAlertStr) alertResp, err := meta.(*clientset.ClientSet).Alerts().UpdateAlert(ctx, updateAlertRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcErrorWithID(err, "alert", id) + return diag.Errorf(formatRpcErrors(err, updateAlertURL, updateAlertStr)) } - updateAlertStr, _ = jsm.MarshalToString(alertResp) + updateAlertStr = protojson.Format(alertResp) log.Printf("[INFO] Submitted updated alert: %s", updateAlertStr) d.SetId(alertResp.GetAlert().GetUniqueIdentifier().GetValue()) @@ -1515,13 +1518,13 @@ func resourceCoralogixAlertDelete(ctx context.Context, d *schema.ResourceData, m Id: id, } - log.Printf("[INFO] Deleting alert %s\n", id) + log.Printf("[INFO] Deleting alert %s", id) _, err := meta.(*clientset.ClientSet).Alerts().DeleteAlert(ctx, deleteAlertRequest) if err != nil { log.Printf("[ERROR] Received error: %#v\n", err) - return handleRpcErrorWithID(err, "alert", id.GetValue()) + return diag.Errorf(formatRpcErrors(err, getAlertURL, protojson.Format(deleteAlertRequest))) } - log.Printf("[INFO] alert %s deleted\n", id) + log.Printf("[INFO] alert %s deleted", id) d.SetId("") return nil diff --git a/coralogix/resource_coralogix_dashboard.go b/coralogix/resource_coralogix_dashboard.go index c0415d7b..57758ae3 100644 --- a/coralogix/resource_coralogix_dashboard.go +++ b/coralogix/resource_coralogix_dashboard.go @@ -17,7 +17,6 @@ import ( "terraform-provider-coralogix/coralogix/clientset" dashboards "terraform-provider-coralogix/coralogix/clientset/grpc/coralogix-dashboards/v1" - "github.com/golang/protobuf/jsonpb" "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/objectvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" @@ -188,6 +187,10 @@ var ( dashboardValidSpanFieldTypes = []string{"metadata", "tag", "process_tag"} dashboardValidSpanAggregationTypes = []string{"metric", "dimension"} dashboardValidColorSchemes = []string{"classic", "severity", "cold", "negative", "green", "red", "blue"} + createDashboardURL = "com.coralogixapis.dashboards.v1.services.DashboardsService/CreateDashboard" + getDashboardURL = "com.coralogixapis.dashboards.v1.services.DashboardsService/GetDashboard" + updateDashboardURL = "com.coralogixapis.dashboards.v1.services.DashboardsService/ReplaceDashboard" + deleteDashboardURL = "com.coralogixapis.dashboards.v1.services.DashboardsService/DeleteDashboard" ) var ( @@ -2340,7 +2343,6 @@ func spansFilterSchema() schema.ListNestedAttribute { func (r DashboardResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // Retrieve values from plan - jsm := &jsonpb.Marshaler{} var plan DashboardResourceModel diags := req.Plan.Get(ctx, &plan) resp.Diagnostics.Append(diags...) @@ -2354,17 +2356,17 @@ func (r DashboardResource) Create(ctx context.Context, req resource.CreateReques return } - dashboardStr, _ := jsm.MarshalToString(dashboard) - log.Printf("[INFO] Creating new Dashboard: %#v", dashboardStr) createDashboardReq := &dashboards.CreateDashboardRequest{ Dashboard: dashboard, } + dashboardStr := protojson.Format(createDashboardReq) + log.Printf("[INFO] Creating new Dashboard: %s", dashboardStr) _, err := r.client.CreateDashboard(ctx, createDashboardReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error creating Dashboard", - "Could not create Dashboard, unexpected error: "+err.Error(), + formatRpcErrors(err, createDashboardURL, dashboardStr), ) return } @@ -2375,14 +2377,15 @@ func (r DashboardResource) Create(ctx context.Context, req resource.CreateReques getDashboardResp, err := r.client.GetDashboard(ctx, getDashboardReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) + reqStr := protojson.Format(getDashboardReq) resp.Diagnostics.AddError( "Error getting Dashboard", - "Could not create Dashboard, unexpected error: "+err.Error(), + formatRpcErrors(err, getDashboardURL, reqStr), ) return } - createDashboardRespStr, _ := jsm.MarshalToString(getDashboardResp.GetDashboard()) - log.Printf("[INFO] Submitted new Dashboard: %#v", createDashboardRespStr) + createDashboardRespStr := protojson.Format(getDashboardResp.GetDashboard()) + log.Printf("[INFO] Submitted new Dashboard: %s", createDashboardRespStr) flattenedDashboard, diags := flattenDashboard(ctx, plan, getDashboardResp.GetDashboard()) if diags.HasError() { @@ -4145,6 +4148,9 @@ func expandLineChartSpansQuery(ctx context.Context, spans *LineChartQuerySpansMo } groupBy, diags := expandSpansFields(ctx, spans.GroupBy) + if diags.HasError() { + return nil, diags + } aggregations, diags := expandSpansAggregations(ctx, spans.Aggregations) if diags.HasError() { @@ -6432,6 +6438,9 @@ func flattenDataTableSpansQueryGrouping(ctx context.Context, grouping *dashboard } groupBy, diags := flattenSpansFields(ctx, grouping.GetGroupBy()) + if diags.HasError() { + return nil, diags + } return &DataTableSpansQueryGroupingModel{ Aggregations: aggregations, GroupBy: groupBy, @@ -7336,7 +7345,8 @@ func (r *DashboardResource) Read(ctx context.Context, req resource.ReadRequest, //Get refreshed Dashboard value from Coralogix id := state.ID.ValueString() log.Printf("[INFO] Reading Dashboard: %s", id) - getDashboardResp, err := r.client.GetDashboard(ctx, &dashboards.GetDashboardRequest{DashboardId: wrapperspb.String(id)}) + getDashboardReq := &dashboards.GetDashboardRequest{DashboardId: wrapperspb.String(id)} + getDashboardResp, err := r.client.GetDashboard(ctx, getDashboardReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -7348,12 +7358,12 @@ func (r *DashboardResource) Read(ctx context.Context, req resource.ReadRequest, } else { resp.Diagnostics.AddError( "Error reading Dashboard", - handleRpcErrorNewFramework(err, "Dashboard"), + formatRpcErrors(err, getDashboardURL, protojson.Format(getDashboardReq)), ) } return } - log.Printf("[INFO] Received Dashboard: %#v", getDashboardResp) + log.Printf("[INFO] Received Dashboard: %s", protojson.Format(getDashboardResp)) flattenedDashboard, diags := flattenDashboard(ctx, state, getDashboardResp.GetDashboard()) if diags != nil { @@ -7380,13 +7390,16 @@ func (r *DashboardResource) Update(ctx context.Context, req resource.UpdateReque resp.Diagnostics.Append(diags...) return } - log.Printf("[INFO] Updating Dashboard: %#v", *dashboard) - _, err := r.client.UpdateDashboard(ctx, &dashboards.ReplaceDashboardRequest{Dashboard: dashboard}) + + updateReq := &dashboards.ReplaceDashboardRequest{Dashboard: dashboard} + reqStr := protojson.Format(updateReq) + log.Printf("[INFO] Updating Dashboard: %#v", reqStr) + _, err := r.client.UpdateDashboard(ctx, updateReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error updating Dashboard", - "Could not update Dashboard, unexpected error: "+err.Error(), + formatRpcErrors(err, updateDashboardURL, reqStr), ) return } @@ -7399,12 +7412,12 @@ func (r *DashboardResource) Update(ctx context.Context, req resource.UpdateReque log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error getting Dashboard", - "Could not create Dashboard, unexpected error: "+err.Error(), + formatRpcErrors(err, getDashboardURL, protojson.Format(getDashboardReq)), ) return } - updateDashboardRespStr, _ := jsm.MarshalToString(getDashboardResp.GetDashboard()) + updateDashboardRespStr := protojson.Format(getDashboardResp.GetDashboard()) log.Printf("[INFO] Submitted updated Dashboard: %#v", updateDashboardRespStr) flattenedDashboard, diags := flattenDashboard(ctx, plan, getDashboardResp.GetDashboard()) @@ -7429,10 +7442,11 @@ func (r *DashboardResource) Delete(ctx context.Context, req resource.DeleteReque id := state.ID.ValueString() log.Printf("[INFO] Deleting Dashboard %s", id) - if _, err := r.client.DeleteDashboard(ctx, &dashboards.DeleteDashboardRequest{DashboardId: wrapperspb.String(id)}); err != nil { + deleteReq := &dashboards.DeleteDashboardRequest{DashboardId: wrapperspb.String(id)} + if _, err := r.client.DeleteDashboard(ctx, deleteReq); err != nil { resp.Diagnostics.AddError( - fmt.Sprintf("Error Deleting Dashboard %s", state.ID.ValueString()), - handleRpcErrorNewFramework(err, "Dashboard"), + fmt.Sprintf("Error Deleting Dashboard %s", id), + formatRpcErrors(err, deleteDashboardURL, protojson.Format(deleteReq)), ) return } diff --git a/coralogix/resource_coralogix_data_set.go b/coralogix/resource_coralogix_data_set.go index 6f827fa6..68d12ee8 100644 --- a/coralogix/resource_coralogix_data_set.go +++ b/coralogix/resource_coralogix_data_set.go @@ -10,18 +10,27 @@ import ( "strings" "time" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "terraform-provider-coralogix/coralogix/clientset" enrichment "terraform-provider-coralogix/coralogix/clientset/grpc/enrichment/v1" + "google.golang.org/protobuf/encoding/protojson" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "google.golang.org/protobuf/types/known/wrapperspb" ) -var fileContentLimit = int(1e6) +var ( + fileContentLimit = int(1e6) + createDataSetURL = "com.coralogix.enrichment.v1.CustomEnrichmentService/CreateCustomEnrichment" + getDataSetURL = "com.coralogix.enrichment.v1.CustomEnrichmentService/GetCustomEnrichment" + updateDataSetURL = "com.coralogix.enrichment.v1.CustomEnrichmentService/UpdateCustomEnrichment" + deleteDataSetURL = "com.coralogix.enrichment.v1.CustomEnrichmentService/DeleteCustomEnrichment" +) func resourceCoralogixDataSet() *schema.Resource { return &schema.Resource{ @@ -111,15 +120,15 @@ func fileContentNoLongerThan(i interface{}, k string) ([]string, []error) { func resourceCoralogixDataSetCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { req, fileModificationTime, err := expandDataSetRequest(d) if err != nil { - log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "enrichment-data") + log.Printf("[ERROR] Received error while expanding enrichment-data: %#v", err) + return diag.FromErr(err) } - log.Printf("[INFO] Creating new enrichment-data: %#v", req) + log.Printf("[INFO] Creating new enrichment-data: %s", protojson.Format(req)) resp, err := meta.(*clientset.ClientSet).DataSet().CreatDataSet(ctx, req) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "enrichment-data") + return diag.Errorf(formatRpcErrors(err, createDataSetURL, protojson.Format(req))) } if uploadedFile, ok := d.GetOk("uploaded_file"); ok { @@ -157,10 +166,10 @@ func resourceCoralogixDataSetRead(ctx context.Context, d *schema.ResourceData, m Detail: fmt.Sprintf("%s will be recreated when you apply", id), }} } - return handleRpcErrorWithID(err, "enrichment-data", id) + return diag.Errorf(formatRpcErrors(err, getDataSetURL, protojson.Format(req))) } - log.Printf("[INFO] Received enrichment-data: %#v", DataSetResp) + log.Printf("[INFO] Received enrichment-data: %s", protojson.Format(DataSetResp)) return setDataSet(d, DataSetResp.GetCustomEnrichment()) } @@ -174,11 +183,11 @@ func resourceCoralogixDataSetUpdate(ctx context.Context, d *schema.ResourceData, _, err = meta.(*clientset.ClientSet).DataSet().UpdateDataSet(ctx, req) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "enrichment-data") + return diag.Errorf(formatRpcErrors(err, getDataSetURL, protojson.Format(req))) } if uploadedFile, ok := d.GetOk("uploaded_file"); ok { - if err := setModificationTimeUploaded(d, uploadedFile, fileModificationTime); err != nil { + if err = setModificationTimeUploaded(d, uploadedFile, fileModificationTime); err != nil { return diag.FromErr(err) } } @@ -190,14 +199,14 @@ func resourceCoralogixDataSetDelete(ctx context.Context, d *schema.ResourceData, id := d.Id() req := &enrichment.DeleteCustomEnrichmentRequest{CustomEnrichmentId: wrapperspb.UInt32(strToUint32(id))} - log.Printf("[INFO] Deleting enrichment-data %s\n", id) + log.Printf("[INFO] Deleting enrichment-data %s", id) _, err := meta.(*clientset.ClientSet).DataSet().DeleteDataSet(ctx, req) if err != nil { - log.Printf("[ERROR] Received error: %#v\n", err) - return handleRpcErrorWithID(err, "enrichment-data", id) + log.Printf("[ERROR] Received error: %#v", err) + return diag.Errorf(formatRpcErrors(err, deleteDataSetURL, protojson.Format(req))) } - log.Printf("[INFO] enrichment-data %s deleted\n", id) + log.Printf("[INFO] enrichment-data %s deleted", id) d.SetId("") return nil diff --git a/coralogix/resource_coralogix_enrichment.go b/coralogix/resource_coralogix_enrichment.go index c2057193..051e2ab0 100644 --- a/coralogix/resource_coralogix_enrichment.go +++ b/coralogix/resource_coralogix_enrichment.go @@ -6,17 +6,25 @@ import ( "log" "time" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "terraform-provider-coralogix/coralogix/clientset" enrichment "terraform-provider-coralogix/coralogix/clientset/grpc/enrichment/v1" + "google.golang.org/protobuf/encoding/protojson" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "google.golang.org/protobuf/types/known/wrapperspb" ) -var validEnrichmentTypes = []string{"geo_ip", "suspicious_ip", "aws", "custom"} +var ( + validEnrichmentTypes = []string{"geo_ip", "suspicious_ip", "aws", "custom"} + createEnrichmentsURL = "com.coralogix.enrichment.v1.EnrichmentService/AddEnrichments" + getEnrichmentsURL = "com.coralogix.enrichment.v1.EnrichmentService/GetEnrichments" + deleteEnrichmentsURL = "com.coralogix.enrichment.v1.EnrichmentService/RemoveEnrichments" +) func resourceCoralogixEnrichment() *schema.Resource { return &schema.Resource{ @@ -88,7 +96,7 @@ func EnrichmentSchema() map[string]*schema.Schema { Optional: true, Elem: awsFields(), Set: hashAwsFields(), - Description: fmt.Sprintf("Set of fields to enrich with aws information."), + Description: "Set of fields to enrich with aws information.", }, }, }, @@ -110,7 +118,7 @@ func EnrichmentSchema() map[string]*schema.Schema { Optional: true, Elem: fields(), Set: hashFields(), - Description: fmt.Sprintf("Set of fields to enrich with the custom information."), + Description: "Set of fields to enrich with the custom information.", }, }, }, @@ -168,20 +176,21 @@ func resourceCoralogixEnrichmentCreate(ctx context.Context, d *schema.ResourceDa if err != nil { return diag.FromErr(err) } - log.Printf("[INFO] Creating new enrichment: %#v", enrichmentReq) - enrichmentResp, err := meta.(*clientset.ClientSet).Enrichments().CreateEnrichments(ctx, enrichmentReq) + createReq := &enrichment.AddEnrichmentsRequest{RequestEnrichments: enrichmentReq} + log.Printf("[INFO] Creating new enrichment: %s", protojson.Format(createReq)) + enrichmentResp, err := meta.(*clientset.ClientSet).Enrichments().CreateEnrichments(ctx, createReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "enrichment") + return diag.Errorf(formatRpcErrors(err, createEnrichmentsURL, protojson.Format(createReq))) } - log.Printf("[INFO] Submitted new enrichment: %#v", enrichmentResp) + log.Printf("[INFO] Submitted new enrichment: %s", protojson.Format(&enrichment.AddEnrichmentsResponse{Enrichments: enrichmentResp})) d.SetId(enrichmentTypeOrCustomId) return resourceCoralogixEnrichmentRead(ctx, d, meta) } func resourceCoralogixEnrichmentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { enrichmentType, customId := extractEnrichmentTypeAndCustomId(d) - log.Print("[INFO] Reading enrichment") + log.Printf("[INFO] Reading enrichment %s", customId) var enrichmentResp []*enrichment.Enrichment var err error if customId == "" { @@ -200,9 +209,10 @@ func resourceCoralogixEnrichmentRead(ctx context.Context, d *schema.ResourceData Detail: fmt.Sprintf("%s will be recreated when you apply", customId), }} } - return handleRpcError(err, "enrichment") + return diag.Errorf(formatRpcErrors(err, getEnrichmentsURL, protojson.Format(&enrichment.GetEnrichmentsRequest{}))) + } - log.Printf("[INFO] Received enrichment: %#v", enrichmentResp) + log.Printf("[INFO] Received enrichment: %s", enrichmentResp) return setEnrichment(d, enrichmentType, enrichmentResp) } @@ -245,30 +255,49 @@ func resourceCoralogixEnrichmentUpdate(ctx context.Context, d *schema.ResourceDa return diag.FromErr(err) } log.Print("[INFO] Updating enrichment") - enrichmentResp, err := meta.(*clientset.ClientSet).Enrichments().UpdateEnrichments(ctx, ids, enrichmentReq) + deleteReq := &enrichment.RemoveEnrichmentsRequest{EnrichmentIds: uint32SliceToWrappedUint32Slice(ids)} + if err = meta.(*clientset.ClientSet).Enrichments().DeleteEnrichments(ctx, deleteReq); err != nil { + log.Printf("[ERROR] Received error: %#v", err) + return diag.Errorf(formatRpcErrors(err, deleteEnrichmentsURL, protojson.Format(deleteReq))) + } + createReq := &enrichment.AddEnrichmentsRequest{RequestEnrichments: enrichmentReq} + enrichmentResp, err := meta.(*clientset.ClientSet).Enrichments().CreateEnrichments(ctx, createReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "enrichment") + return diag.Errorf(formatRpcErrors(err, createEnrichmentsURL, protojson.Format(createReq))) } - log.Printf("[INFO] Received enrichment: %#v", enrichmentResp) + log.Printf("[INFO] Received enrichment: %s", protojson.Format(&enrichment.AddEnrichmentsResponse{Enrichments: enrichmentResp})) return resourceCoralogixEnrichmentRead(ctx, d, meta) } func resourceCoralogixEnrichmentDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { id := d.Id() - var err error - log.Printf("[INFO] Deleting enrichment %s\n", id) + log.Printf("[INFO] Deleting enrichment %s", id) if id == "geo_ip" || id == "suspicious_ip" || id == "aws" { - err = meta.(*clientset.ClientSet).Enrichments().DeleteEnrichmentsByType(ctx, id) + enrichments, err := meta.(*clientset.ClientSet).Enrichments().GetEnrichmentsByType(ctx, id) + if err != nil { + log.Printf("[ERROR] Received error: %#v", err) + return diag.Errorf(formatRpcErrors(err, getEnrichmentsURL, protojson.Format(&enrichment.GetEnrichmentsRequest{}))) + } + enrichmentIds := make([]*wrapperspb.UInt32Value, 0, len(enrichments)) + for _, enrichment := range enrichments { + enrichmentIds = append(enrichmentIds, wrapperspb.UInt32(enrichment.GetId())) + } + deleteReq := &enrichment.RemoveEnrichmentsRequest{EnrichmentIds: enrichmentIds} + if err = meta.(*clientset.ClientSet).Enrichments().DeleteEnrichments(ctx, deleteReq); err != nil { + log.Printf("[ERROR] Received error: %#v\n", err) + return diag.Errorf(formatRpcErrors(err, deleteEnrichmentsURL, protojson.Format(deleteReq))) + } } else { ids := extractIdsFromEnrichment(d) - err = meta.(*clientset.ClientSet).Enrichments().DeleteEnrichments(ctx, ids) - } - if err != nil { - log.Printf("[ERROR] Received error: %#v\n", err) - return handleRpcError(err, "enrichment") + deleteReq := &enrichment.RemoveEnrichmentsRequest{EnrichmentIds: uint32SliceToWrappedUint32Slice(ids)} + if err := meta.(*clientset.ClientSet).Enrichments().DeleteEnrichments(ctx, deleteReq); err != nil { + log.Printf("[ERROR] Received error: %#v\n", err) + return diag.Errorf(formatRpcErrors(err, deleteEnrichmentsURL, protojson.Format(deleteReq))) + } } - log.Printf("[INFO] enrichment %s deleted\n", id) + + log.Printf("[INFO] enrichment %s deleted", id) d.SetId("") return nil diff --git a/coralogix/resource_coralogix_events2metric.go b/coralogix/resource_coralogix_events2metric.go index 254b9e4e..83b0ee41 100644 --- a/coralogix/resource_coralogix_events2metric.go +++ b/coralogix/resource_coralogix_events2metric.go @@ -6,7 +6,12 @@ import ( "log" "regexp" - "github.com/golang/protobuf/jsonpb" + "terraform-provider-coralogix/coralogix/clientset" + e2m "terraform-provider-coralogix/coralogix/clientset/grpc/events2metrics/v2" + l2m "terraform-provider-coralogix/coralogix/clientset/grpc/logs2metrics/v2" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" "github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/resourcevalidator" @@ -27,9 +32,6 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - e2m "terraform-provider-coralogix/coralogix/clientset/grpc/events2metrics/v2" - l2m "terraform-provider-coralogix/coralogix/clientset/grpc/logs2metrics/v2" ) var ( @@ -51,7 +53,11 @@ var ( e2m.E2MAggSamples_SAMPLE_TYPE_MIN: "Min", e2m.E2MAggSamples_SAMPLE_TYPE_MAX: "Max", } - validSampleTypes = []string{"Min", "Max"} + validSampleTypes = []string{"Min", "Max"} + createEvents2MetricURL = "com.coralogixapis.events2metrics.v2.Events2MetricService/CreateE2M" + getEvents2MetricURL = "com.coralogixapis.events2metrics.v2.Events2MetricService/GetE2M" + updateEvents2MetricURL = "com.coralogixapis.events2metrics.v2.Events2MetricService/ReplaceE2M" + deleteEvents2MetricURL = "com.coralogixapis.events2metrics.v2.Events2MetricService/DeleteE2M" ) var ( @@ -819,28 +825,28 @@ func (r *Events2MetricResource) ConfigValidators(_ context.Context) []resource.C func (r *Events2MetricResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // Retrieve values from plan - jsm := &jsonpb.Marshaler{} var plan Events2MetricResourceModel diags := req.Plan.Get(ctx, &plan) - resp.Diagnostics.Append(diags...) - if resp.Diagnostics.HasError() { + if diags.HasError() { + resp.Diagnostics.Append(diags...) return } - e2mCreateReq := extractCreateE2M(ctx, plan) - e2mStr, _ := jsm.MarshalToString(e2mCreateReq) - log.Printf("[INFO] Creating new Events2metric: %#v", e2mStr) + e2mCreateReq, diags := extractCreateE2M(ctx, plan) + if diags.HasError() { + resp.Diagnostics.Append(diags...) + return + } + log.Printf("[INFO] Creating new Events2metric: %s", protojson.Format(e2mCreateReq)) e2mCreateResp, err := r.client.CreateEvents2Metric(ctx, e2mCreateReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error creating Events2Metric", - "Could not create Events2Metric, unexpected error: "+err.Error(), + formatRpcErrors(err, createEvents2MetricURL, protojson.Format(e2mCreateReq)), ) - return } - e2mStr, _ = jsm.MarshalToString(e2mCreateResp) - log.Printf("[INFO] Submitted new Events2metric: %#v", e2mStr) + log.Printf("[INFO] Submitted new Events2metric: %s", protojson.Format(e2mCreateResp)) plan = flattenE2M(ctx, e2mCreateResp.GetE2M()) @@ -872,12 +878,12 @@ func (r *Events2MetricResource) Read(ctx context.Context, req resource.ReadReque } else { resp.Diagnostics.AddError( "Error reading Events2Metric", - handleRpcErrorNewFramework(err, "Events2metric"), + formatRpcErrors(err, getEvents2MetricURL, protojson.Format(getE2MResp)), ) } return } - log.Printf("[INFO] Received Events2metric: %#v", getE2MResp) + log.Printf("[INFO] Received Events2metric: %s", protojson.Format(getE2MResp)) state = flattenE2M(ctx, getE2MResp.GetE2M()) // @@ -899,13 +905,13 @@ func (r *Events2MetricResource) Update(ctx context.Context, req resource.UpdateR resp.Diagnostics.Append(diags...) return } - log.Printf("[INFO] Updating Events2metric: %#v", *e2mUpdateReq) + log.Printf("[INFO] Updating Events2metric: %s", protojson.Format(e2mUpdateReq)) e2mUpdateResp, err := r.client.UpdateEvents2Metric(ctx, e2mUpdateReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error updating Events2Metric", - "Could not update Events2Metric, unexpected error: "+err.Error(), + formatRpcErrors(err, updateEvents2MetricURL, protojson.Format(e2mUpdateReq)), ) return } @@ -925,12 +931,12 @@ func (r *Events2MetricResource) Update(ctx context.Context, req resource.UpdateR } else { resp.Diagnostics.AddError( "Error reading Events2Metric", - handleRpcErrorNewFramework(err, "Events2metric"), + formatRpcErrors(err, getEvents2MetricURL, protojson.Format(e2mUpdateReq)), ) } return } - log.Printf("[INFO] Received Events2metric: %#v", getE2MResp) + log.Printf("[INFO] Received Events2metric: %s", protojson.Format(getE2MResp)) plan = flattenE2M(ctx, e2mUpdateResp.GetE2M()) @@ -948,11 +954,12 @@ func (r *Events2MetricResource) Delete(ctx context.Context, req resource.DeleteR } id := state.ID.ValueString() + deleteReq := &e2m.DeleteE2MRequest{Id: wrapperspb.String(id)} log.Printf("[INFO] Deleting Events2metric %s\n", id) - if _, err := r.client.DeleteEvents2Metric(ctx, &e2m.DeleteE2MRequest{Id: wrapperspb.String(id)}); err != nil { + if _, err := r.client.DeleteEvents2Metric(ctx, deleteReq); err != nil { resp.Diagnostics.AddError( - fmt.Sprintf("Error Deleting Events2Metric %s", state.ID.ValueString()), - handleRpcErrorNewFramework(err, "Events2Metric"), + "Error Deleting Events2Metric", + formatRpcErrors(err, deleteEvents2MetricURL, protojson.Format(deleteReq)), ) return } @@ -983,12 +990,15 @@ func flattenDescription(e2mDescription *wrapperspb.StringValue) types.String { return types.StringValue(e2mDescription.GetValue()) } -func extractCreateE2M(ctx context.Context, plan Events2MetricResourceModel) *e2m.CreateE2MRequest { +func extractCreateE2M(ctx context.Context, plan Events2MetricResourceModel) (*e2m.CreateE2MRequest, diag.Diagnostics) { name := typeStringToWrapperspbString(plan.Name) description := typeStringToWrapperspbString(plan.Description) permutations := expandPermutations(plan.Permutations) permutationsLimit := wrapperspb.Int32(permutations.GetLimit()) - metricLabels := expandE2MLabels(ctx, plan.MetricLabels) + metricLabels, diags := expandE2MLabels(ctx, plan.MetricLabels) + if diags.HasError() { + return nil, diags + } metricFields := expandE2MFields(ctx, plan.MetricFields) e2mParams := &e2m.E2MCreateParams{ @@ -999,7 +1009,6 @@ func extractCreateE2M(ctx context.Context, plan Events2MetricResourceModel) *e2m MetricFields: metricFields, } - var diags diag.Diagnostics if spansQuery := plan.SpansQuery; spansQuery != nil { e2mParams.Type = e2m.E2MType_E2M_TYPE_SPANS2METRICS e2mParams.Query, diags = expandSpansQuery(ctx, spansQuery) @@ -1009,12 +1018,12 @@ func extractCreateE2M(ctx context.Context, plan Events2MetricResourceModel) *e2m } if diags.HasError() { - return nil + return nil, diags } return &e2m.CreateE2MRequest{ E2M: e2mParams, - } + }, nil } func expandPermutations(permutations *PermutationsModel) *e2m.E2MPermutations { @@ -1032,7 +1041,10 @@ func extractUpdateE2M(ctx context.Context, plan Events2MetricResourceModel) (*e2 name := wrapperspb.String(plan.Name.ValueString()) description := wrapperspb.String(plan.Description.ValueString()) permutations := expandPermutations(plan.Permutations) - metricLabels := expandE2MLabels(ctx, plan.MetricLabels) + metricLabels, diags := expandE2MLabels(ctx, plan.MetricLabels) + if diags.HasError() { + return nil, diags + } metricFields := expandE2MFields(ctx, plan.MetricFields) e2mParams := &e2m.E2M{ @@ -1044,7 +1056,6 @@ func extractUpdateE2M(ctx context.Context, plan Events2MetricResourceModel) (*e2 MetricFields: metricFields, } - var diags diag.Diagnostics if spansQuery := plan.SpansQuery; spansQuery != nil { e2mParams.Type = e2m.E2MType_E2M_TYPE_SPANS2METRICS e2mParams.Query, diags = expandUpdateSpansQuery(ctx, spansQuery) @@ -1062,18 +1073,26 @@ func extractUpdateE2M(ctx context.Context, plan Events2MetricResourceModel) (*e2 }, nil } -func expandE2MLabels(ctx context.Context, labels types.Map) []*e2m.MetricLabel { +func expandE2MLabels(ctx context.Context, labels types.Map) ([]*e2m.MetricLabel, diag.Diagnostics) { labelsMap := labels.Elements() result := make([]*e2m.MetricLabel, 0, len(labelsMap)) + var diags diag.Diagnostics for targetField, value := range labelsMap { v, _ := value.ToTerraformValue(ctx) var sourceField string - v.As(&sourceField) + if err := v.As(&sourceField); err != nil { + diags.AddError("error expanding metric labels", + err.Error()) + continue + } label := expandE2MLabel(targetField, sourceField) result = append(result, label) } + if diags.HasError() { + return nil, diags + } - return result + return result, nil } func expandE2MLabel(targetLabel, sourceField string) *e2m.MetricLabel { @@ -1163,19 +1182,19 @@ func expandBuckets(buckets []types.Float64) []float32 { func expandSpansQuery(ctx context.Context, spansQuery *SpansQueryModel) (*e2m.E2MCreateParams_SpansQuery, diag.Diagnostics) { lucene := typeStringToWrapperspbString(spansQuery.Lucene) applications, diags := typeStringSliceToWrappedStringSlice(ctx, spansQuery.Applications.Elements()) - if diags != nil { + if diags.HasError() { return nil, diags } subsystems, diags := typeStringSliceToWrappedStringSlice(ctx, spansQuery.Subsystems.Elements()) - if diags != nil { + if diags.HasError() { return nil, diags } actions, diags := typeStringSliceToWrappedStringSlice(ctx, spansQuery.Actions.Elements()) - if diags != nil { + if diags.HasError() { return nil, diags } services, diags := typeStringSliceToWrappedStringSlice(ctx, spansQuery.Services.Elements()) - if diags != nil { + if diags.HasError() { return nil, diags } @@ -1200,7 +1219,10 @@ func expandLogsQuery(ctx context.Context, logsQuery *LogsQueryModel) (*e2m.E2MCr if diags.HasError() { return nil, diags } - severities := expandLogsQuerySeverities(ctx, logsQuery.Severities.Elements()) + severities, diags := expandLogsQuerySeverities(ctx, logsQuery.Severities.Elements()) + if diags.HasError() { + return nil, diags + } return &e2m.E2MCreateParams_LogsQuery{ LogsQuery: &l2m.LogsQuery{ @@ -1245,14 +1267,17 @@ func expandUpdateSpansQuery(ctx context.Context, spansQuery *SpansQueryModel) (* func expandUpdateLogsQuery(ctx context.Context, logsQuery *LogsQueryModel) (*e2m.E2M_LogsQuery, diag.Diagnostics) { searchQuery := wrapperspb.String(logsQuery.Lucene.ValueString()) applications, diags := typeStringSliceToWrappedStringSlice(ctx, logsQuery.Applications.Elements()) - if diags != nil { + if diags.HasError() { return nil, diags } subsystems, diags := typeStringSliceToWrappedStringSlice(ctx, logsQuery.Subsystems.Elements()) - if diags != nil { + if diags.HasError() { + return nil, diags + } + severities, diags := expandLogsQuerySeverities(ctx, logsQuery.Severities.Elements()) + if diags.HasError() { return nil, diags } - severities := expandLogsQuerySeverities(ctx, logsQuery.Severities.Elements()) return &e2m.E2M_LogsQuery{ LogsQuery: &l2m.LogsQuery{ @@ -1264,17 +1289,31 @@ func expandUpdateLogsQuery(ctx context.Context, logsQuery *LogsQueryModel) (*e2m }, nil } -func expandLogsQuerySeverities(ctx context.Context, severities []attr.Value) []l2m.Severity { +func expandLogsQuerySeverities(ctx context.Context, severities []attr.Value) ([]l2m.Severity, diag.Diagnostics) { result := make([]l2m.Severity, 0, len(severities)) + var diags diag.Diagnostics for _, s := range severities { - v, _ := s.ToTerraformValue(ctx) + v, err := s.ToTerraformValue(ctx) + if err != nil { + diags.AddError("error expanding logs query severities", + err.Error()) + continue + } var str string - v.As(&str) + if err = v.As(&str); err != nil { + diags.AddError("error expanding logs query severities", + err.Error()) + continue + } severity := l2m.Severity(l2m.Severity_value[str]) result = append(result, severity) } - return result + if diags.HasError() { + return nil, diags + } + + return result, nil } func flattenE2MPermutations(permutations *e2m.E2MPermutations) *PermutationsModel { diff --git a/coralogix/resource_coralogix_events2metric_test.go b/coralogix/resource_coralogix_events2metric_test.go index 02340d17..d3c968bd 100644 --- a/coralogix/resource_coralogix_events2metric_test.go +++ b/coralogix/resource_coralogix_events2metric_test.go @@ -6,11 +6,12 @@ import ( "strconv" "testing" + "terraform-provider-coralogix/coralogix/clientset" + e2m "terraform-provider-coralogix/coralogix/clientset/grpc/events2metrics/v2" + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" - "terraform-provider-coralogix/coralogix/clientset" - e2m "terraform-provider-coralogix/coralogix/clientset/grpc/events2metrics/v2" "google.golang.org/protobuf/types/known/wrapperspb" ) diff --git a/coralogix/resource_coralogix_recording_rules_groups_set.go b/coralogix/resource_coralogix_recording_rules_groups_set.go index c8a943c8..afc88a7e 100644 --- a/coralogix/resource_coralogix_recording_rules_groups_set.go +++ b/coralogix/resource_coralogix_recording_rules_groups_set.go @@ -5,6 +5,11 @@ import ( "fmt" "log" + "terraform-provider-coralogix/coralogix/clientset" + rrgs "terraform-provider-coralogix/coralogix/clientset/grpc/recording-rules-groups-sets/v1" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" @@ -23,14 +28,16 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "gopkg.in/yaml.v3" - "terraform-provider-coralogix/coralogix/clientset" - rrgs "terraform-provider-coralogix/coralogix/clientset/grpc/recording-rules-groups-sets/v1" ) var ( - _ resource.ResourceWithConfigure = &RecordingRuleGroupSetResource{} - _ resource.ResourceWithImportState = &RecordingRuleGroupSetResource{} - _ resource.ResourceWithUpgradeState = &RecordingRuleGroupSetResource{} + _ resource.ResourceWithConfigure = &RecordingRuleGroupSetResource{} + _ resource.ResourceWithImportState = &RecordingRuleGroupSetResource{} + _ resource.ResourceWithUpgradeState = &RecordingRuleGroupSetResource{} + createRuleGroupURL = "rule_manager.groups.RuleGroupSets/Create" + getRuleGroupURL = "rule_manager.groups.RuleGroupSets/Fetch" + updateRuleGroupURL = "rule_manager.groups.RuleGroupSets/Update" + deleteRuleGroupURL = "rule_manager.groups.RuleGroupSets/Delete" ) func NewRecordingRuleGroupSetResource() resource.Resource { @@ -355,23 +362,22 @@ func (r *RecordingRuleGroupSetResource) Create(ctx context.Context, req resource resp.Diagnostics.Append(diags...) return } - rrgStr, _ := jsm.MarshalToString(createRequest) - log.Printf("[INFO] Creating new recogring-rule-group-set: %s", rrgStr) + log.Printf("[INFO] Creating new recogring-rule-group-set: %s", protojson.Format(createRequest)) createResp, err := r.client.CreateRecordingRuleGroupsSet(ctx, createRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error creating recording-rule-group-set", - "Could not create recording-rule-group-set, unexpected error: "+err.Error(), + formatRpcErrors(err, createRuleGroupURL, protojson.Format(createRequest)), ) return } id := createResp.GetId() - log.Printf("[INFO] Submitted new recording-rule-group-set id: %#v", id) + log.Printf("[INFO] Submitted new recording-rule-group-set id: %s", id) plan.ID = types.StringValue(id) - log.Printf("[INFO] Reading recording-rule-group-set id: %#v", id) + log.Printf("[INFO] Reading recording-rule-group-set id: %s", id) getResp, err := r.client.GetRecordingRuleGroupsSet(ctx, &rrgs.FetchRuleGroupSet{Id: id}) if err != nil { log.Printf("[ERROR] Received error: %#v", err) @@ -383,14 +389,13 @@ func (r *RecordingRuleGroupSetResource) Create(ctx context.Context, req resource } else { resp.Diagnostics.AddError( "Error reading recording-rule-group-set", - handleRpcErrorNewFramework(err, "recording-rule-group-set"), + formatRpcErrors(err, getRuleGroupURL, protojson.Format(createRequest)), ) } return } - rrgStr, _ = jsm.MarshalToString(getResp) - log.Printf("[INFO] Received recogring-rule-group-set: %s", rrgStr) + log.Printf("[INFO] Received recogring-rule-group-set: %s", protojson.Format(getResp)) plan, diags = flattenRecordingRuleGroupSet(ctx, plan, getResp) if diags.HasError() { @@ -536,7 +541,8 @@ func (r *RecordingRuleGroupSetResource) Read(ctx context.Context, req resource.R id := state.ID.ValueString() log.Printf("[INFO] Reading recording-rule-group-set id: %s", id) - getResp, err := r.client.GetRecordingRuleGroupsSet(ctx, &rrgs.FetchRuleGroupSet{Id: id}) + getReq := &rrgs.FetchRuleGroupSet{Id: id} + getResp, err := r.client.GetRecordingRuleGroupsSet(ctx, getReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -547,7 +553,7 @@ func (r *RecordingRuleGroupSetResource) Read(ctx context.Context, req resource.R } else { resp.Diagnostics.AddError( "Error reading recording-rule-group-set", - handleRpcErrorNewFramework(err, "recording-rule-group-set"), + formatRpcErrors(err, getRuleGroupURL, protojson.Format(getReq)), ) } return @@ -576,21 +582,21 @@ func (r *RecordingRuleGroupSetResource) Update(ctx context.Context, req resource resp.Diagnostics.Append(diags...) return } - rrgStr, _ := jsm.MarshalToString(updateRequest) - log.Printf("[INFO] Updating recording-rule-group-set: %s", rrgStr) + log.Printf("[INFO] Updating recording-rule-group-set: %s", protojson.Format(updateRequest)) _, err := r.client.UpdateRecordingRuleGroupsSet(ctx, updateRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error updating recording-rule-group-set", - handleRpcErrorNewFramework(err, "recording-rule-group-set"), + formatRpcErrors(err, updateRuleGroupURL, protojson.Format(updateRequest)), ) return } - log.Printf("[INFO] Reading recording-rule-group-set id: %#v", plan.ID.ValueString()) - getResp, err := r.client.GetRecordingRuleGroupsSet(ctx, &rrgs.FetchRuleGroupSet{Id: plan.ID.ValueString()}) + log.Printf("[INFO] Reading recording-rule-group-set id: %s", plan.ID.ValueString()) + getReq := &rrgs.FetchRuleGroupSet{Id: plan.ID.ValueString()} + getResp, err := r.client.GetRecordingRuleGroupsSet(ctx, getReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -601,7 +607,7 @@ func (r *RecordingRuleGroupSetResource) Update(ctx context.Context, req resource } else { resp.Diagnostics.AddError( "Error reading recording-rule-group-set", - handleRpcErrorNewFramework(err, "recording-rule-group-set"), + formatRpcErrors(err, getRuleGroupURL, protojson.Format(getReq)), ) } return @@ -626,7 +632,8 @@ func (r *RecordingRuleGroupSetResource) Delete(ctx context.Context, req resource } id := state.ID.ValueString() log.Printf("[INFO] Deleting recording-rule-group-set id: %s", id) - _, err := r.client.DeleteRecordingRuleGroupsSet(ctx, &rrgs.DeleteRuleGroupSet{Id: id}) + deleteReq := &rrgs.DeleteRuleGroupSet{Id: id} + _, err := r.client.DeleteRecordingRuleGroupsSet(ctx, deleteReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -637,7 +644,7 @@ func (r *RecordingRuleGroupSetResource) Delete(ctx context.Context, req resource } else { resp.Diagnostics.AddError( "Error deleting recording-rule-group-set", - handleRpcErrorNewFramework(err, "recording-rule-group-set"), + formatRpcErrors(err, deleteRuleGroupURL, protojson.Format(deleteReq)), ) } return diff --git a/coralogix/resource_coralogix_rules_group.go b/coralogix/resource_coralogix_rules_group.go index 66e6a2d2..5c4b8e77 100644 --- a/coralogix/resource_coralogix_rules_group.go +++ b/coralogix/resource_coralogix_rules_group.go @@ -6,11 +6,14 @@ import ( "log" "time" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "terraform-provider-coralogix/coralogix/clientset" rulesv1 "terraform-provider-coralogix/coralogix/clientset/grpc/rules-groups/v1" + "google.golang.org/protobuf/encoding/protojson" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -48,6 +51,10 @@ var ( } rulesProtoFormatStandardToSchemaFormatStandard = reverseMapStrings(rulesSchemaFormatStandardToProtoFormatStandard) rulesValidFormatStandards = getKeysStrings(rulesSchemaFormatStandardToProtoFormatStandard) + createParsingRuleURL = "com.coralogix.rules.v1.RuleGroupsService/CreateRuleGroup" + getParsingRuleURL = "com.coralogix.rules.v1.RuleGroupsService/GetRuleGroup" + updateParsingRuleURL = "com.coralogix.rules.v1.RuleGroupsService/UpdateRuleGroup" + deleteParsingRuleURL = "com.coralogix.rules.v1.RuleGroupsService/DeleteRuleGroup" ) func resourceCoralogixRulesGroup() *schema.Resource { @@ -456,14 +463,14 @@ func resourceCoralogixRulesGroupCreate(ctx context.Context, d *schema.ResourceDa return diag.FromErr(err) } - log.Printf("[INFO] Creating new rule-group: %#v", createRuleGroupRequest) + log.Printf("[INFO] Creating new rule-group: %s", protojson.Format(createRuleGroupRequest)) ruleGroupResp, err := meta.(*clientset.ClientSet).RuleGroups().CreateRuleGroup(ctx, createRuleGroupRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "rule-group") + return diag.Errorf(formatRpcErrors(err, createParsingRuleURL, protojson.Format(createRuleGroupRequest))) } ruleGroup := ruleGroupResp.GetRuleGroup() - log.Printf("[INFO] Submitted new rule-group: %#v", ruleGroup) + log.Printf("[INFO] Submitted new rule-group: %s", protojson.Format(ruleGroup)) d.SetId(ruleGroup.GetId().GetValue()) return resourceCoralogixRulesGroupRead(ctx, d, meta) @@ -487,10 +494,10 @@ func resourceCoralogixRulesGroupRead(ctx context.Context, d *schema.ResourceData Detail: fmt.Sprintf("%s will be recreated when you apply", id), }} } - return handleRpcErrorWithID(err, "rule-group", id) + return diag.Errorf(formatRpcErrors(err, getParsingRuleURL, protojson.Format(getRuleGroupRequest))) } ruleGroup := ruleGroupResp.GetRuleGroup() - log.Printf("[INFO] Received rule-group: %#v", ruleGroup) + log.Printf("[INFO] Received rule-group: %s", protojson.Format(ruleGroup)) return setRuleGroup(d, ruleGroup) } @@ -507,13 +514,13 @@ func resourceCoralogixRulesGroupUpdate(ctx context.Context, d *schema.ResourceDa RuleGroup: req, } - log.Printf("[INFO] Updating rule-group %s to %s", id, updateRuleGroupRequest) + log.Printf("[INFO] Updating rule-group %s to %s", id, protojson.Format(updateRuleGroupRequest)) ruleGroupResp, err := meta.(*clientset.ClientSet).RuleGroups().UpdateRuleGroup(ctx, updateRuleGroupRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcErrorWithID(err, "rule-group", id) + return diag.Errorf(formatRpcErrors(err, updateParsingRuleURL, protojson.Format(updateRuleGroupRequest))) } - log.Printf("[INFO] Submitted updated rule-group: %#v", ruleGroupResp) + log.Printf("[INFO] Submitted updated rule-group: %s", protojson.Format(ruleGroupResp)) return resourceCoralogixRulesGroupRead(ctx, d, meta) } @@ -528,7 +535,7 @@ func resourceCoralogixRulesGroupDelete(ctx context.Context, d *schema.ResourceDa _, err := meta.(*clientset.ClientSet).RuleGroups().DeleteRuleGroup(ctx, deleteRuleGroupRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return handleRpcErrorWithID(err, "rule-group", id) + return diag.Errorf(formatRpcErrors(err, deleteParsingRuleURL, protojson.Format(deleteRuleGroupRequest))) } log.Printf("[INFO] rule-group %s deleted", id) diff --git a/coralogix/resource_coralogix_sli.go b/coralogix/resource_coralogix_sli.go index 237c7915..82bf0a1a 100644 --- a/coralogix/resource_coralogix_sli.go +++ b/coralogix/resource_coralogix_sli.go @@ -5,6 +5,11 @@ import ( "fmt" "log" + "terraform-provider-coralogix/coralogix/clientset" + sli "terraform-provider-coralogix/coralogix/clientset/grpc/sli" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/attr" @@ -22,8 +27,6 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - sli "terraform-provider-coralogix/coralogix/clientset/grpc/sli" ) var ( @@ -62,7 +65,6 @@ var ( sli.SloStatusType_SLO_STATUS_TYPE_BREACHED: "breached", } sliSchemaToProtoSloStatusType = ReverseMap(sliProtoToSchemaSloStatusType) - sliValidSloStatusTypes = GetKeys(sliSchemaToProtoSloStatusType) sliProtoToSchemaTimeUnitType = map[sli.TimeUnitType]string{ sli.TimeUnitType_TIME_UNIT_TYPE_UNSPECIFIED: "unspecified", sli.TimeUnitType_TIME_UNIT_TYPE_MICROSECOND: "microsecond", @@ -81,6 +83,10 @@ var ( } sliSchemaToProtoCompareType = ReverseMap(sliProtoToSchemaCompareType) sliValidCompareTypes = GetKeys(sliSchemaToProtoCompareType) + createSliURL = "com.coralogix.catalog.v1.SliService/CreateSli" + getSliURL = "com.coralogix.catalog.v1.SliService/GetSli" + updateSliURL = "com.coralogix.catalog.v1.SliService/UpdateSli" + deleteSliURL = "com.coralogix.catalog.v1.SliService/DeleteSli" ) func NewSLIResource() resource.Resource { @@ -191,6 +197,9 @@ func (r *SLIResource) Schema(ctx context.Context, req resource.SchemaRequest, re }, "compare_type": schema.StringAttribute{ Required: true, + Validators: []validator.String{ + stringvalidator.OneOf(sliValidCompareTypes...), + }, }, "field_values": schema.ListAttribute{ Required: true, @@ -281,20 +290,18 @@ func (r *SLIResource) Create(ctx context.Context, req resource.CreateRequest, re resp.Diagnostics = diags return } - sliStr, _ := jsm.MarshalToString(createSLIRequest) - log.Printf("[INFO] Creating new SLI: %s", sliStr) + log.Printf("[INFO] Creating new SLI: %s", protojson.Format(createSLIRequest)) createResp, err := r.client.CreateSLI(ctx, createSLIRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error creating SLI", - "Could not create SLI, unexpected error: "+err.Error(), + formatRpcErrors(err, createSliURL, protojson.Format(createSLIRequest)), ) return } sli := createResp.GetSli() - sliStr, _ = jsm.MarshalToString(sli) - log.Printf("[INFO] Submitted new SLI: %#v", sliStr) + log.Printf("[INFO] Submitted new SLI: %s", protojson.Format(sli)) plan.ID = types.StringValue(sli.GetSliId().GetValue()) plan, diags = flattenSLI(ctx, sli) if diags.HasError() { @@ -466,7 +473,8 @@ func (r *SLIResource) Read(ctx context.Context, req resource.ReadRequest, resp * id := state.ID.ValueString() serviceName := state.ServiceName.ValueString() log.Printf("[INFO] Reading SLIs of service: %s", serviceName) - getSLIsResp, err := r.client.GetSLIs(ctx, &sli.GetSlisRequest{ServiceName: wrapperspb.String(serviceName)}) + getSliReq := &sli.GetSlisRequest{ServiceName: wrapperspb.String(serviceName)} + getSLIsResp, err := r.client.GetSLIs(ctx, getSliReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -478,7 +486,7 @@ func (r *SLIResource) Read(ctx context.Context, req resource.ReadRequest, resp * } else { resp.Diagnostics.AddError( "Error reading SLI", - handleRpcErrorNewFramework(err, "SLI"), + formatRpcErrors(err, getSliURL, protojson.Format(getSliReq)), ) } return @@ -500,7 +508,8 @@ func (r *SLIResource) Read(ctx context.Context, req resource.ReadRequest, resp * return } - log.Printf("[INFO] Received SLI: %#v", *SLI) + sliStr := protojson.Format(SLI) + log.Printf("[INFO] Received SLI: %s", sliStr) state, diags = flattenSLI(ctx, SLI) if diags.HasError() { @@ -526,22 +535,25 @@ func (r *SLIResource) Update(ctx context.Context, req resource.UpdateRequest, re resp.Diagnostics = diags return } - log.Printf("[INFO] Updating SLI: %#v", SLI) - sliUpdateResp, err := r.client.UpdateSLI(ctx, &sli.UpdateSliRequest{Sli: SLI}) + + updateSliReq := &sli.UpdateSliRequest{Sli: SLI} + log.Printf("[INFO] Updating SLI: %s", protojson.Format(updateSliReq)) + updateSliResp, err := r.client.UpdateSLI(ctx, updateSliReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error updating SLI", - "Could not update SLI, unexpected error: "+err.Error(), + formatRpcErrors(err, updateSliURL, protojson.Format(updateSliReq)), ) return } - log.Printf("[INFO] Submitted updated SLI: %#v", sliUpdateResp) + log.Printf("[INFO] Submitted updated SLI: %s", updateSliResp) // Get refreshed SLI value from Coralogix id := plan.ID.ValueString() serviceName := plan.ServiceName.ValueString() - getSLIsResp, err := r.client.GetSLIs(ctx, &sli.GetSlisRequest{ServiceName: wrapperspb.String(serviceName)}) + getSliReq := &sli.GetSlisRequest{ServiceName: wrapperspb.String(serviceName)} + getSLIsResp, err := r.client.GetSLIs(ctx, getSliReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -552,7 +564,7 @@ func (r *SLIResource) Update(ctx context.Context, req resource.UpdateRequest, re } else { resp.Diagnostics.AddError( "Error reading SLI", - handleRpcErrorNewFramework(err, "SLI"), + formatRpcErrors(err, getSliURL, protojson.Format(getSliReq)), ) } return @@ -573,7 +585,7 @@ func (r *SLIResource) Update(ctx context.Context, req resource.UpdateRequest, re return } - log.Printf("[INFO] Received SLI: %#v", *SLI) + log.Printf("[INFO] Received SLI: %s", protojson.Format(SLI)) plan, diags = flattenSLI(ctx, SLI) if diags.HasError() { @@ -596,10 +608,12 @@ func (r *SLIResource) Delete(ctx context.Context, req resource.DeleteRequest, re id := state.ID.ValueString() log.Printf("[INFO] Deleting SLI %s\n", id) - if _, err := r.client.DeleteSLI(ctx, &sli.DeleteSliRequest{SliId: wrapperspb.String(id)}); err != nil { + deleteReq := &sli.DeleteSliRequest{SliId: wrapperspb.String(id)} + if _, err := r.client.DeleteSLI(ctx, deleteReq); err != nil { + reqStr := protojson.Format(deleteReq) resp.Diagnostics.AddError( fmt.Sprintf("Error Deleting SLI %s", state.ID.ValueString()), - handleRpcErrorNewFramework(err, "SLI"), + formatRpcErrors(err, deleteSliURL, reqStr), ) return } diff --git a/coralogix/resource_coralogix_sli_test.go b/coralogix/resource_coralogix_sli_test.go index 66f0e313..9a3a722b 100644 --- a/coralogix/resource_coralogix_sli_test.go +++ b/coralogix/resource_coralogix_sli_test.go @@ -5,11 +5,12 @@ import ( "fmt" "testing" + "terraform-provider-coralogix/coralogix/clientset" + sli "terraform-provider-coralogix/coralogix/clientset/grpc/sli" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - sli "terraform-provider-coralogix/coralogix/clientset/grpc/sli" ) var sliResourceName = "coralogix_sli.test" @@ -56,12 +57,11 @@ func testAccSLICheckDestroy(s *terraform.State) error { } func testAccCoralogixResourceSLI() string { - return fmt.Sprintf( - `resource "coralogix_sli" "test" { + return `resource "coralogix_sli" "test" { name = "coralogix_sli_example" slo_percentage = 80 service_name = "service_name" threshold_value = 3 } - `) + ` } diff --git a/coralogix/resource_coralogix_tco_policy_logs.go b/coralogix/resource_coralogix_tco_policy_logs.go index cfe3d574..eddcda59 100644 --- a/coralogix/resource_coralogix_tco_policy_logs.go +++ b/coralogix/resource_coralogix_tco_policy_logs.go @@ -7,7 +7,11 @@ import ( "strings" "time" - "github.com/golang/protobuf/jsonpb" + "terraform-provider-coralogix/coralogix/clientset" + tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" @@ -26,8 +30,6 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" ) var ( @@ -60,7 +62,11 @@ var ( } tcoPolicySeverityProtoToSchema = ReverseMap(tcoPolicySeveritySchemaToProto) validPolicySeverities = GetKeys(tcoPolicySeveritySchemaToProto) - jsm = &jsonpb.Marshaler{} + createTCOPolicyURL = "com.coralogix.quota.v1.PoliciesService/CreatePolicy" + getTCOPolicyURL = "com.coralogix.quota.v1.PoliciesService/GetPolicy" + updateTCOPolicyURL = "com.coralogix.quota.v1.PoliciesService/UpdatePolicy" + deleteTCOPolicyURL = "com.coralogix.quota.v1.PoliciesService/DeletePolicy" + updateTCOPoliciesOrderURL = "com.coralogix.quota.v1.PoliciesService/ReorderPolicies" ) func NewTCOPolicyResource() resource.Resource { @@ -328,15 +334,11 @@ func upgradeTCOPolicyRuleV0ToV1(ctx context.Context, tCOPolicyRule types.List) t } if rule := tCORuleModelObjectV0.Rule.ValueString(); rule != "" { - elements := []attr.Value{types.StringValue(rule)} - tCORuleModelObjectV1.Names = types.SetValueMust(types.StringType, elements) + rules := []attr.Value{types.StringValue(rule)} + tCORuleModelObjectV1.Names = types.SetValueMust(types.StringType, rules) } else { rules := tCORuleModelObjectV0.Rules.Elements() - elements := make([]attr.Value, 0, len(rules)) - for _, rule := range rules { - elements = append(elements, rule) - } - tCORuleModelObjectV1.Names = types.SetValueMust(types.StringType, elements) + tCORuleModelObjectV1.Names = types.SetValueMust(types.StringType, rules) } obj, _ := types.ObjectValueFrom(ctx, tcoPolicyRuleAttributes(), tCORuleModelObjectV1) @@ -469,27 +471,44 @@ func (r *TCOPolicyResource) Create(ctx context.Context, req resource.CreateReque resp.Diagnostics.Append(diags...) return } - policyStr, _ := jsm.MarshalToString(createPolicyRequest) - log.Printf("[INFO] Creating new tco-policy: %s", policyStr) + + log.Printf("[INFO] Creating new tco-policy: %s", protojson.Format(createPolicyRequest)) createResp, err := r.client.CreateTCOPolicy(ctx, createPolicyRequest) for err != nil { log.Printf("[ERROR] Received error: %#v", err) if retryableStatusCode(status.Code(err)) { - log.Printf("[INFO] Retrying to create tco-policy: %s", policyStr) + log.Printf("[INFO] Retrying to create tco-policy: %s", protojson.Format(createPolicyRequest)) createResp, err = r.client.CreateTCOPolicy(ctx, createPolicyRequest) continue } resp.Diagnostics.AddError( "Error creating tco-policy", - "Could not create tco-policy, unexpected error: "+err.Error(), + formatRpcErrors(err, createTCOPolicyURL, protojson.Format(createPolicyRequest)), ) return } policy := createResp.GetPolicy() - policyStr, _ = jsm.MarshalToString(policy) - log.Printf("[INFO] Submitted new tco-policy: %#v", policy) + log.Printf("[INFO] Submitted new tco-policy: %s", protojson.Format(policy)) plan.ID = types.StringValue(createResp.GetPolicy().GetId().GetValue()) - updatePoliciesOrder(ctx, r.client, plan.ID.ValueString(), int(plan.Order.ValueInt64()), tcopolicies.SourceType_SOURCE_TYPE_LOGS) + + // Update order + id := plan.ID.ValueString() + order := int(plan.Order.ValueInt64()) + log.Print("[INFO] Reordering tco-policies") + err, updateReq := updatePoliciesOrder(ctx, r.client, id, order, tcopolicies.SourceType_SOURCE_TYPE_LOGS) + for err != nil { + log.Printf("[ERROR] Received error: %#v", err) + if retryableStatusCode(status.Code(err)) { + log.Print("[INFO] Retrying to reorder tco-policies") + err, updateReq = updatePoliciesOrder(ctx, r.client, id, order, tcopolicies.SourceType_SOURCE_TYPE_LOGS) + continue + } + resp.Diagnostics.AddError( + "Error Reordering tco-policy", + formatRpcErrors(err, updateTCOPoliciesOrderURL, updateReq), + ) + return + } policy.Order = wrapperspb.Int32(int32(plan.Order.ValueInt64())) plan, diags = flattenTCOPolicy(ctx, policy) @@ -516,12 +535,13 @@ func (r *TCOPolicyResource) Read(ctx context.Context, req resource.ReadRequest, //Get refreshed tco-policy value from Coralogix id := state.ID.ValueString() log.Printf("[INFO] Reading tco-policy: %s", id) - getPolicyResp, err := r.client.GetTCOPolicy(ctx, &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)}) + getPolicyReq := &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)} + getPolicyResp, err := r.client.GetTCOPolicy(ctx, getPolicyReq) for err != nil { log.Printf("[ERROR] Received error: %#v", err) if retryableStatusCode(status.Code(err)) { log.Printf("[INFO] Retrying to read tco-policy: %s", id) - getPolicyResp, err = r.client.GetTCOPolicy(ctx, &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)}) + getPolicyResp, err = r.client.GetTCOPolicy(ctx, getPolicyReq) continue } if status.Code(err) == codes.NotFound { @@ -533,13 +553,13 @@ func (r *TCOPolicyResource) Read(ctx context.Context, req resource.ReadRequest, } else { resp.Diagnostics.AddError( "Error reading tco-policy", - handleRpcErrorNewFramework(err, "tco-policy"), + formatRpcErrors(err, getTCOPolicyURL, protojson.Format(getPolicyReq)), ) } return } policy := getPolicyResp.GetPolicy() - log.Printf("[INFO] Received tco-policy: %#v", policy) + log.Printf("[INFO] Received tco-policy: %s", protojson.Format(policy)) state, diags = flattenTCOPolicy(ctx, policy) if diags.HasError() { @@ -569,28 +589,42 @@ func (r *TCOPolicyResource) Update(ctx context.Context, req resource.UpdateReque return } - log.Printf("[INFO] Updating tco-policy: %#v", policyUpdateReq) + log.Printf("[INFO] Updating tco-policy: %s", protojson.Format(policyUpdateReq)) policyUpdateResp, err := r.client.UpdateTCOPolicy(ctx, policyUpdateReq) for err != nil { log.Printf("[ERROR] Received error: %#v", err) if retryableStatusCode(status.Code(err)) { - log.Printf("[INFO] Retrying to update tco-policy: %#v", policyUpdateReq) + log.Printf("[INFO] Retrying to update tco-policy: %s", protojson.Format(policyUpdateReq)) policyUpdateResp, err = r.client.UpdateTCOPolicy(ctx, policyUpdateReq) continue } resp.Diagnostics.AddError( "Error updating tco-policy", - "Could not update tco-policy, unexpected error: "+err.Error(), + formatRpcErrors(err, updateTCOPolicyURL, protojson.Format(policyUpdateReq)), ) return } - log.Printf("[INFO] Submitted updated tco-policy: %#v", policyUpdateResp) - - updatePoliciesOrder(ctx, r.client, plan.ID.ValueString(), int(plan.Order.ValueInt64()), tcopolicies.SourceType_SOURCE_TYPE_LOGS) + log.Printf("[INFO] Submitted updated tco-policy: %s", protojson.Format(policyUpdateResp)) + err, reqStr := updatePoliciesOrder(ctx, r.client, plan.ID.ValueString(), int(plan.Order.ValueInt64()), tcopolicies.SourceType_SOURCE_TYPE_LOGS) + for err != nil { + log.Printf("[ERROR] Received error: %#v", err) + if retryableStatusCode(status.Code(err)) { + log.Printf("[INFO] Retrying to reorder tco-policies") + err, reqStr = updatePoliciesOrder(ctx, r.client, plan.ID.ValueString(), int(plan.Order.ValueInt64()), tcopolicies.SourceType_SOURCE_TYPE_LOGS) + continue + } + resp.Diagnostics.AddError( + "Error Reordering tco-policy", + formatRpcErrors(err, updateTCOPolicyURL, reqStr), + ) + return + } // Get refreshed tco-policy value from Coralogix id := plan.ID.ValueString() - getPolicyResp, err := r.client.GetTCOPolicy(ctx, &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)}) + getPolicyReq := &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)} + log.Printf("[INFO] Reading tco-policy %s", id) + getPolicyResp, err := r.client.GetTCOPolicy(ctx, getPolicyReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -602,12 +636,12 @@ func (r *TCOPolicyResource) Update(ctx context.Context, req resource.UpdateReque } else { resp.Diagnostics.AddError( "Error reading tco-policy", - handleRpcErrorNewFramework(err, "tco-policy"), + formatRpcErrors(err, getTCOPolicyURL, protojson.Format(getPolicyReq)), ) } return } - log.Printf("[INFO] Received tco-policy: %#v", getPolicyResp) + log.Printf("[INFO] Received tco-policy: %s", protojson.Format(getPolicyResp)) plan, diags = flattenTCOPolicy(ctx, getPolicyResp.GetPolicy()) if diags.HasError() { @@ -631,7 +665,7 @@ func (r TCOPolicyResource) Delete(ctx context.Context, req resource.DeleteReques } id := state.ID.ValueString() - log.Printf("[INFO] Deleting tco-policy %s\n", id) + log.Printf("[INFO] Deleting tco-policy %s", id) deleteReq := &tcopolicies.DeletePolicyRequest{Id: wrapperspb.String(id)} _, err := r.client.DeleteTCOPolicy(ctx, deleteReq) for err != nil { @@ -641,9 +675,10 @@ func (r TCOPolicyResource) Delete(ctx context.Context, req resource.DeleteReques _, err = r.client.DeleteTCOPolicy(ctx, deleteReq) continue } + reqStr := protojson.Format(deleteReq) resp.Diagnostics.AddError( - fmt.Sprintf("Error Deleting tco-policy %s", state.ID.ValueString()), - handleRpcErrorNewFramework(err, "tco-policy"), + fmt.Sprintf("Error Deleting tco-policy %s", id), + formatRpcErrors(err, deleteTCOPolicyURL, reqStr), ) return } @@ -790,7 +825,10 @@ func expandTCOPolicyRule(ctx context.Context, rule types.Object) (*tcopolicies.R } ruleType := tcoPoliciesRuleTypeSchemaToProto[tcoRuleModel.RuleType.ValueString()] - names := typeStringSliceToStringSlice(ctx, tcoRuleModel.Names.Elements()) + names, diags := typeStringSliceToStringSlice(ctx, tcoRuleModel.Names.Elements()) + if diags.HasError() { + return nil, diags + } nameStr := wrapperspb.String(strings.Join(names, ",")) return &tcopolicies.Rule{ @@ -799,21 +837,21 @@ func expandTCOPolicyRule(ctx context.Context, rule types.Object) (*tcopolicies.R }, nil } -func updatePoliciesOrder(ctx context.Context, client *clientset.TCOPoliciesClient, policyID string, policyOrder int, sourceType tcopolicies.SourceType) error { +func updatePoliciesOrder(ctx context.Context, client *clientset.TCOPoliciesClient, policyID string, policyOrder int, sourceType tcopolicies.SourceType) (error, string) { getPoliciesReq := &tcopolicies.GetCompanyPoliciesRequest{ EnabledOnly: wrapperspb.Bool(false), SourceType: &sourceType, } - getPoliciesReqStr, _ := jsm.MarshalToString(getPoliciesReq) + getPoliciesReqStr := protojson.Format(getPoliciesReq) log.Printf("[INFO] Get tco-policies request: %s", getPoliciesReqStr) getPoliciesResp, err := client.GetTCOPolicies(ctx, getPoliciesReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return err + return err, getPoliciesReqStr } - getPoliciesRespStr, _ := jsm.MarshalToString(getPoliciesResp) + getPoliciesRespStr := protojson.Format(getPoliciesResp) log.Printf("[INFO] Get tco-policies response: %#v", getPoliciesRespStr) policies := getPoliciesResp.GetPolicies() @@ -822,7 +860,7 @@ func updatePoliciesOrder(ctx context.Context, client *clientset.TCOPoliciesClien desiredPolicyIndex := getPolicyDesireIndex(policyOrder, policies) if currentPolicyIndex == desiredPolicyIndex { - return nil + return nil, "" } policiesIDsByOrder[currentPolicyIndex].Order, policiesIDsByOrder[desiredPolicyIndex].Order = policiesIDsByOrder[desiredPolicyIndex].Order, policiesIDsByOrder[currentPolicyIndex].Order @@ -830,18 +868,18 @@ func updatePoliciesOrder(ctx context.Context, client *clientset.TCOPoliciesClien Orders: policiesIDsByOrder, SourceType: sourceType, } - reorderReqStr, _ := jsm.MarshalToString(reorderReq) + reorderReqStr := protojson.Format(reorderReq) log.Printf("[INFO] Reorder tco-policies request: %s", reorderReqStr) reorderResp, err := client.ReorderTCOPolicies(ctx, reorderReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - return err + return err, reorderReqStr } - reorderRespStr, _ := jsm.MarshalToString(reorderResp) + reorderRespStr := protojson.Format(reorderResp) log.Printf("[INFO] Reorder tco-policies response: %s", reorderRespStr) - return nil + return nil, "" } func getPoliciesIDsByOrderAndCurrentPolicyIndex(policies []*tcopolicies.Policy, policyID string) ([]*tcopolicies.PolicyOrder, int) { @@ -889,7 +927,10 @@ func expandTCOPolicySeverities(ctx context.Context, severities []attr.Value) ([] continue } var str string - val.As(&str) + if err = val.As(&str); err != nil { + diags.AddError("Error expanding tco-policy severities", err.Error()) + continue + } s := tcoPolicySeveritySchemaToProto[str] result = append(result, s) } diff --git a/coralogix/resource_coralogix_tco_policy_logs_test.go b/coralogix/resource_coralogix_tco_policy_logs_test.go index 061cd44c..d5ffeeeb 100644 --- a/coralogix/resource_coralogix_tco_policy_logs_test.go +++ b/coralogix/resource_coralogix_tco_policy_logs_test.go @@ -5,11 +5,12 @@ import ( "fmt" "testing" + "terraform-provider-coralogix/coralogix/clientset" + tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" ) var tcoPolicyResourceName1 = "coralogix_tco_policy_logs.test_1" @@ -96,8 +97,7 @@ func testAccTCOPolicyCheckDestroy(s *terraform.State) error { } func testAccCoralogixResourceTCOPolicy() string { - return fmt.Sprintf( - `resource "coralogix_tco_policy_logs" test_1 { + return `resource "coralogix_tco_policy_logs" test_1 { name = "Example tco_policy from terraform 1" priority = "low" order = 1 @@ -142,5 +142,5 @@ func testAccCoralogixResourceTCOPolicy() string { names = ["mobile", "web"] } } - `) + ` } diff --git a/coralogix/resource_coralogix_tco_policy_override.go b/coralogix/resource_coralogix_tco_policy_override.go deleted file mode 100644 index 86f59fda..00000000 --- a/coralogix/resource_coralogix_tco_policy_override.go +++ /dev/null @@ -1,227 +0,0 @@ -package coralogix - -import ( - "context" - "encoding/json" - "fmt" - "log" - "time" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "terraform-provider-coralogix/coralogix/clientset" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -) - -var ( - tcoPolicySchemaSeverityToTcoPolicyRequestSeverity = map[string]int{ - "debug": 1, - "verbose": 2, - "info": 3, - "warning": 4, - "error": 5, - "critical": 6, - } - tcoPolicyResponseSeverityToTcoPolicySchemaSeverity = reverseMapIntToString(tcoPolicySchemaSeverityToTcoPolicyRequestSeverity) - validPolicyPriorities = []string{"high", "medium", "low", "block"} -) - -type tcoPolicyOverrideRequest struct { - Priority string `json:"priority"` - ApplicationName *string `json:"applicationName,omitempty"` - SubsystemName *string `json:"subsystemName,omitempty"` - Severity int `json:"severity,omitempty"` -} - -func resourceCoralogixTCOPolicyOverride() *schema.Resource { - return &schema.Resource{ - CreateContext: resourceCoralogixTCOPolicyOverrideCreate, - ReadContext: resourceCoralogixTCOPolicyOverrideRead, - UpdateContext: resourceCoralogixTCOPolicyOverrideUpdate, - DeleteContext: resourceCoralogixTCOPolicyOverrideDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(60 * time.Second), - Read: schema.DefaultTimeout(30 * time.Second), - Update: schema.DefaultTimeout(60 * time.Second), - Delete: schema.DefaultTimeout(30 * time.Second), - }, - - Schema: TCOPolicyOverrideSchema(), - - Description: "Coralogix TCO-Policy-Override. For more information - https://coralogix.com/docs/tco-optimizer-api/#policy-overrides .", - } -} - -func resourceCoralogixTCOPolicyOverrideCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - tcoPolicyReq, err := extractTCOPolicyOverrideRequest(d) - if err != nil { - return diag.FromErr(err) - } - - log.Printf("[INFO] Creating new tco-policy-override: %#v", tcoPolicyReq) - tcoPolicyOverrideResp, err := meta.(*clientset.ClientSet).TCOPoliciesOverrides().CreateTCOPolicyOverride(ctx, tcoPolicyReq) - if err != nil { - log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "tco-policy-override") - } - - log.Printf("[INFO] Submitted new tco-policy-override: %#v", tcoPolicyOverrideResp) - - var m map[string]interface{} - if err = json.Unmarshal([]byte(tcoPolicyOverrideResp), &m); err != nil { - return diag.FromErr(err) - } - - d.SetId(m["id"].(string)) - return resourceCoralogixTCOPolicyOverrideRead(ctx, d, meta) -} - -func resourceCoralogixTCOPolicyOverrideRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - id := d.Id() - log.Printf("[INFO] Reading tco-policy-override %s", id) - tcoPolicyResp, err := meta.(*clientset.ClientSet).TCOPoliciesOverrides().GetTCOPolicyOverride(ctx, id) - if err != nil { - log.Printf("[ERROR] Received error: %#v", err) - if status.Code(err) == codes.NotFound { - d.SetId("") - return diag.Diagnostics{diag.Diagnostic{ - Severity: diag.Warning, - Summary: fmt.Sprintf("TCOPoliciesOverride %q is in state, but no longer exists in Coralogix backend", id), - Detail: fmt.Sprintf("%s will be recreated when you apply", id), - }} - } - return diag.FromErr(err) - } - - log.Printf("[INFO] Received tco-policy-override: %#v", tcoPolicyResp) - - return setTCOPolicyOverride(d, tcoPolicyResp) -} - -func resourceCoralogixTCOPolicyOverrideUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - tcoPolicyOverrideReq, err := extractTCOPolicyOverrideRequest(d) - if err != nil { - return diag.FromErr(err) - } - - id := d.Id() - log.Printf("[INFO] Updating tco-policy-override %s to %s", id, tcoPolicyOverrideReq) - tcoPolicyOverrideResp, err := meta.(*clientset.ClientSet).TCOPoliciesOverrides().UpdateTCOPolicyOverride(ctx, id, tcoPolicyOverrideReq) - if err != nil { - log.Printf("[ERROR] Received error: %#v", err) - return handleRpcError(err, "tco-policy-override") - } - - log.Printf("[INFO] Submitted new tco-policy-override: %#v", tcoPolicyOverrideResp) - - var m map[string]interface{} - if err = json.Unmarshal([]byte(tcoPolicyOverrideResp), &m); err != nil { - return diag.FromErr(err) - } - - d.SetId(m["id"].(string)) - return resourceCoralogixTCOPolicyOverrideRead(ctx, d, meta) -} - -func resourceCoralogixTCOPolicyOverrideDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - id := d.Id() - - log.Printf("[INFO] Deleting tco-policy %s", id) - err := meta.(*clientset.ClientSet).TCOPoliciesOverrides().DeleteTCOPolicyOverride(ctx, id) - if err != nil { - log.Printf("[ERROR] Received error: %#v", err) - return handleRpcErrorWithID(err, "tco-policy-override", id) - } - log.Printf("[INFO] tco-policy-override %s deleted", id) - - d.SetId("") - return nil -} - -func extractTCOPolicyOverrideRequest(d *schema.ResourceData) (string, error) { - priority := d.Get("priority").(string) - var applicationName *string - if s := d.Get("application_name").(string); s != "" { - applicationName = new(string) - *applicationName = s - } - - var subsystemName *string - if s := d.Get("subsystem_name").(string); s != "" { - subsystemName = new(string) - *subsystemName = s - } - - severity := tcoPolicySchemaSeverityToTcoPolicyRequestSeverity[d.Get("severity").(string)] - reqStruct := tcoPolicyOverrideRequest{ - Priority: priority, - ApplicationName: applicationName, - SubsystemName: subsystemName, - Severity: severity, - } - - requestJson, err := json.Marshal(reqStruct) - if err != nil { - return "", err - } - - return string(requestJson), nil -} - -func setTCOPolicyOverride(d *schema.ResourceData, tcoPolicyOverrideResp string) diag.Diagnostics { - var m map[string]interface{} - if err := json.Unmarshal([]byte(tcoPolicyOverrideResp), &m); err != nil { - return diag.FromErr(err) - } - - var diags diag.Diagnostics - if err := d.Set("priority", m["priority"].(string)); err != nil { - diags = append(diags, diag.FromErr(err)...) - } - if err := d.Set("severity", tcoPolicyResponseSeverityToTcoPolicySchemaSeverity[int(m["severity"].(float64))]); err != nil { - diags = append(diags, diag.FromErr(err)...) - } - if err := d.Set("application_name", m["applicationName"].(string)); err != nil { - diags = append(diags, diag.FromErr(err)...) - } - if err := d.Set("subsystem_name", m["subsystemName"].(string)); err != nil { - diags = append(diags, diag.FromErr(err)...) - } - - return diags -} - -func TCOPolicyOverrideSchema() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "priority": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(validPolicyPriorities, false), - Description: fmt.Sprintf("The policy-override priority. Can be one of %q.", validPolicyPriorities), - }, - "severity": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(validPolicySeverities, false), - Description: fmt.Sprintf("The severity to apply the policy on. Can be one of %q.", validPolicySeverities), - }, - "application_name": { - Type: schema.TypeString, - Required: true, - Description: "The application to apply the policy on. Applies the policy on all the applications by default.", - }, - "subsystem_name": { - Type: schema.TypeString, - Required: true, - Description: "The subsystem to apply the policy on. Applies the policy on all the subsystems by default.", - }, - } -} diff --git a/coralogix/resource_coralogix_tco_policy_override_test.go b/coralogix/resource_coralogix_tco_policy_override_test.go deleted file mode 100644 index aef95050..00000000 --- a/coralogix/resource_coralogix_tco_policy_override_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package coralogix - -import ( - "context" - "encoding/json" - "fmt" - - "terraform-provider-coralogix/coralogix/clientset" - - "github.com/hashicorp/terraform-plugin-testing/terraform" -) - -var tcoPolicyOverrideResourceName = "coralogix_tco_policy_override.test" - -//func TestAccCoralogixResourceTCOPolicyOverrideCreate(t *testing.T) { -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// ProviderFactories: testAccProviderFactories, -// CheckDestroy: testAccTCOPolicyOverrideCheckDestroy, -// Steps: []resource.TestStep{ -// { -// Config: testAccCoralogixResourceTCOPolicyOverride(), -// Check: resource.ComposeTestCheckFunc( -// resource.TestCheckResourceAttr(tcoPolicyOverrideResourceName, "priority", "medium"), -// resource.TestCheckResourceAttr(tcoPolicyOverrideResourceName, "severity", "debug"), -// resource.TestCheckResourceAttr(tcoPolicyOverrideResourceName, "application_name", "prod"), -// resource.TestCheckResourceAttr(tcoPolicyOverrideResourceName, "subsystem_name", "mobile"), -// ), -// }, -// { -// ResourceName: tcoPolicyOverrideResourceName, -// ImportState: true, -// ImportStateVerify: true, -// }, -// { -// Config: testAccCoralogixUpdatedResourceTCOPolicyOverride(), -// Check: resource.ComposeTestCheckFunc( -// resource.TestCheckResourceAttr(tcoPolicyOverrideResourceName, "priority", "low"), -// resource.TestCheckTypeSetElemAttr(tcoPolicyOverrideResourceName, "severity", "warning"), -// resource.TestCheckResourceAttr(tcoPolicyOverrideResourceName, "application_name", "dev"), -// resource.TestCheckTypeSetElemAttr(tcoPolicyOverrideResourceName, "subsystem_name", "web"), -// ), -// }, -// }, -// }) -//} - -func testAccTCOPolicyOverrideCheckDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*clientset.ClientSet).TCOPoliciesOverrides() - ctx := context.TODO() - for _, rs := range s.RootModule().Resources { - if rs.Type != "coralogix_tco_policy_override" { - continue - } - - if resp, err := client.GetTCOPolicyOverride(ctx, rs.Primary.ID); err == nil { - var m map[string]interface{} - if err = json.Unmarshal([]byte(resp), &m); err == nil { - if id, ok := m["id"]; ok && id.(string) == rs.Primary.ID { - return fmt.Errorf("tco-policy-override still exists: %s", id) - } - } - } - } - - return nil -} - -func testAccCoralogixResourceTCOPolicyOverride() string { - return fmt.Sprintf( - `resource "coralogix_tco_policy_override" test { - priority = "medium" - severity = "debug" - application_name = "prod" - subsystem_name = "mobile" - } - `) -} - -func testAccCoralogixUpdatedResourceTCOPolicyOverride() string { - return fmt.Sprintf( - `resource "coralogix_tco_policy_override" test { - priority = "high" - severity = "error" - application_name = "staging" - subsystem_name = "web" - } - `) -} diff --git a/coralogix/resource_coralogix_tco_policy_traces.go b/coralogix/resource_coralogix_tco_policy_traces.go index 45c762c5..b9a2f8f8 100644 --- a/coralogix/resource_coralogix_tco_policy_traces.go +++ b/coralogix/resource_coralogix_tco_policy_traces.go @@ -7,6 +7,11 @@ import ( "regexp" "strings" + "terraform-provider-coralogix/coralogix/clientset" + tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" "github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" @@ -25,8 +30,6 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" ) var ( @@ -293,23 +296,37 @@ func (r *TCOPolicyTracesResource) Create(ctx context.Context, req resource.Creat resp.Diagnostics = diags return } - policyStr, _ := jsm.MarshalToString(createPolicyRequest) + policyStr := protojson.Format(createPolicyRequest) log.Printf("[INFO] Creating new tco-policy: %s", policyStr) createResp, err := r.client.CreateTCOPolicy(ctx, createPolicyRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error creating tco-policy", - "Could not create tco-policy, unexpected error: "+err.Error(), + formatRpcErrors(err, createTCOPolicyURL, policyStr), ) return } policy := createResp.GetPolicy() - policyStr, _ = jsm.MarshalToString(policy) - log.Printf("[INFO] Submitted new tco-policy: %#v", policy) + policyStr = protojson.Format(policy) + log.Printf("[INFO] Submitted new tco-policy: %s", policyStr) plan.ID = types.StringValue(createResp.GetPolicy().GetId().GetValue()) - updatePoliciesOrder(ctx, r.client, plan.ID.ValueString(), int(plan.Order.ValueInt64()), tcopolicies.SourceType_SOURCE_TYPE_SPANS) - + id := plan.ID.ValueString() + order := int(plan.Order.ValueInt64()) + err, reqStr := updatePoliciesOrder(ctx, r.client, id, order, tcopolicies.SourceType_SOURCE_TYPE_SPANS) + for err != nil { + log.Printf("[ERROR] Received error: %#v", err) + if retryableStatusCode(status.Code(err)) { + log.Print("[INFO] Retrying to reorder tco-policies") + err, reqStr = updatePoliciesOrder(ctx, r.client, id, order, tcopolicies.SourceType_SOURCE_TYPE_SPANS) + continue + } + resp.Diagnostics.AddError( + "Error Reordering tco-policy", + formatRpcErrors(err, updateTCOPoliciesOrderURL, reqStr), + ) + return + } policy.Order = wrapperspb.Int32(int32(plan.Order.ValueInt64())) plan, diags = flattenTCOPolicyTraces(ctx, policy) if diags.HasError() { @@ -332,7 +349,8 @@ func (r *TCOPolicyTracesResource) Read(ctx context.Context, req resource.ReadReq //Get refreshed tco-policy value from Coralogix id := state.ID.ValueString() log.Printf("[INFO] Reading tco-policy: %s", id) - getPolicyResp, err := r.client.GetTCOPolicy(ctx, &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)}) + getPolicyReq := &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)} + getPolicyResp, err := r.client.GetTCOPolicy(ctx, getPolicyReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -342,15 +360,16 @@ func (r *TCOPolicyTracesResource) Read(ctx context.Context, req resource.ReadReq fmt.Sprintf("%s will be recreated when you apply", id), ) } else { + reqStr := protojson.Format(getPolicyReq) resp.Diagnostics.AddError( "Error reading tco-policy", - handleRpcErrorNewFramework(err, "tco-policy"), + formatRpcErrors(err, getTCOPolicyURL, reqStr), ) } return } policy := getPolicyResp.GetPolicy() - log.Printf("[INFO] Received tco-policy: %#v", policy) + log.Printf("[INFO] Received tco-policy: %s", protojson.Format(policy)) state, diags = flattenTCOPolicyTraces(ctx, policy) if diags.HasError() { @@ -376,23 +395,37 @@ func (r TCOPolicyTracesResource) Update(ctx context.Context, req resource.Update resp.Diagnostics = diags return } - log.Printf("[INFO] Updating tco-policy: %#v", policyUpdateReq) + log.Printf("[INFO] Updating tco-policy: %s", protojson.Format(policyUpdateReq)) policyUpdateResp, err := r.client.UpdateTCOPolicy(ctx, policyUpdateReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error updating tco-policy", - "Could not update tco-policy, unexpected error: "+err.Error(), + formatRpcErrors(err, updateTCOPolicyURL, protojson.Format(policyUpdateReq)), ) return } - log.Printf("[INFO] Submitted updated tco-policy: %#v", policyUpdateResp) + log.Printf("[INFO] Submitted updated tco-policy: %s", protojson.Format(policyUpdateResp)) - updatePoliciesOrder(ctx, r.client, plan.ID.ValueString(), int(plan.Order.ValueInt64()), tcopolicies.SourceType_SOURCE_TYPE_SPANS) + id := plan.ID.ValueString() + order := int(plan.Order.ValueInt64()) + err, reqStr := updatePoliciesOrder(ctx, r.client, id, order, tcopolicies.SourceType_SOURCE_TYPE_SPANS) + for err != nil { + log.Printf("[ERROR] Received error: %#v", err) + if retryableStatusCode(status.Code(err)) { + log.Print("[INFO] Retrying to reorder tco-policies") + err, reqStr = updatePoliciesOrder(ctx, r.client, id, order, tcopolicies.SourceType_SOURCE_TYPE_SPANS) + continue + } + resp.Diagnostics.AddError( + "Error Reordering tco-policy", + formatRpcErrors(err, updateTCOPoliciesOrderURL, reqStr), + ) + } // Get refreshed tco-policy value from Coralogix - id := plan.ID.ValueString() - getPolicyResp, err := r.client.GetTCOPolicy(ctx, &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)}) + getPolicyReq := &tcopolicies.GetPolicyRequest{Id: wrapperspb.String(id)} + getPolicyResp, err := r.client.GetTCOPolicy(ctx, getPolicyReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) if status.Code(err) == codes.NotFound { @@ -404,12 +437,12 @@ func (r TCOPolicyTracesResource) Update(ctx context.Context, req resource.Update } else { resp.Diagnostics.AddError( "Error reading tco-policy", - handleRpcErrorNewFramework(err, "tco-policy"), + formatRpcErrors(err, getTCOPolicyURL, protojson.Format(getPolicyReq)), ) } return } - log.Printf("[INFO] Received tco-policy: %#v", getPolicyResp) + log.Printf("[INFO] Received tco-policy: %s", getPolicyResp) plan, diags = flattenTCOPolicyTraces(ctx, getPolicyResp.GetPolicy()) if diags.HasError() { @@ -430,15 +463,16 @@ func (r TCOPolicyTracesResource) Delete(ctx context.Context, req resource.Delete } id := state.ID.ValueString() - log.Printf("[INFO] Deleting tco-policy %s\n", id) - if _, err := r.client.DeleteTCOPolicy(ctx, &tcopolicies.DeletePolicyRequest{Id: wrapperspb.String(id)}); err != nil { + deleteReq := &tcopolicies.DeletePolicyRequest{Id: wrapperspb.String(id)} + log.Printf("[INFO] Deleting tco-policy %s", id) + if _, err := r.client.DeleteTCOPolicy(ctx, deleteReq); err != nil { resp.Diagnostics.AddError( - fmt.Sprintf("Error Deleting tco-policy %s", state.ID.ValueString()), - handleRpcErrorNewFramework(err, "tco-policy"), + fmt.Sprintf("Error Deleting tco-policy %s", id), + formatRpcErrors(err, deleteTCOPolicyURL, protojson.Format(deleteReq)), ) return } - log.Printf("[INFO] tco-policy %s deleted\n", id) + log.Printf("[INFO] tco-policy %s deleted", id) } func flattenTCOPolicyTraces(ctx context.Context, policy *tcopolicies.Policy) (*TCOPolicyTracesResourceModel, diag.Diagnostics) { diff --git a/coralogix/resource_coralogix_tco_policy_traces_test.go b/coralogix/resource_coralogix_tco_policy_traces_test.go index d3c6a9f4..429bc0d7 100644 --- a/coralogix/resource_coralogix_tco_policy_traces_test.go +++ b/coralogix/resource_coralogix_tco_policy_traces_test.go @@ -5,11 +5,12 @@ import ( "fmt" "testing" + "terraform-provider-coralogix/coralogix/clientset" + tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - tcopolicies "terraform-provider-coralogix/coralogix/clientset/grpc/tco-policies" ) var tcoPolicyTracesResourceName1 = "coralogix_tco_policy_traces.test_1" @@ -119,8 +120,7 @@ func testAccTCOPolicyTracesCheckDestroy(s *terraform.State) error { } func testAccCoralogixResourceTCOPolicyTraces() string { - return fmt.Sprintf( - `resource "coralogix_tco_policy_traces" "test_1" { + return `resource "coralogix_tco_policy_traces" "test_1" { name = "Example tco_policy from terraform 1" priority = "low" order = 1 @@ -199,5 +199,5 @@ func testAccCoralogixResourceTCOPolicyTraces() string { } } } - `) + ` } diff --git a/coralogix/resource_coralogix_webhook.go b/coralogix/resource_coralogix_webhook.go index 3e542aec..8a1e3e16 100644 --- a/coralogix/resource_coralogix_webhook.go +++ b/coralogix/resource_coralogix_webhook.go @@ -7,7 +7,11 @@ import ( "strconv" "strings" - "github.com/golang/protobuf/jsonpb" + "terraform-provider-coralogix/coralogix/clientset" + webhooks "terraform-provider-coralogix/coralogix/clientset/grpc/webhooks" + + "google.golang.org/protobuf/encoding/protojson" + "github.com/hashicorp/terraform-plugin-framework-validators/objectvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" @@ -24,8 +28,6 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - webhooks "terraform-provider-coralogix/coralogix/clientset/grpc/webhooks" ) var ( @@ -214,6 +216,10 @@ var ( } ] }` + createWebhookURL = "com.coralogix.outgoing_webhooks.v1.OutgoingWebhooksService/CreateOutgoingWebhook" + getWebhookURL = "com.coralogix.outgoing_webhooks.v1.OutgoingWebhooksService/GetOutgoingWebhook" + updateWebhookURL = "com.coralogix.outgoing_webhooks.v1.OutgoingWebhooksService/UpdateOutgoingWebhook" + deleteWebhookURL = "com.coralogix.outgoing_webhooks.v1.OutgoingWebhooksService/DeleteOutgoingWebhook" ) func NewWebhookResource() resource.Resource { @@ -604,7 +610,6 @@ func (r *WebhookResource) Schema(_ context.Context, _ resource.SchemaRequest, re } func (r *WebhookResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - jsm := &jsonpb.Marshaler{} var plan *WebhookResourceModel diags := req.Plan.Get(ctx, &plan) resp.Diagnostics.Append(diags...) @@ -617,14 +622,14 @@ func (r *WebhookResource) Create(ctx context.Context, req resource.CreateRequest resp.Diagnostics.Append(diags...) return } - webhookStr, _ := jsm.MarshalToString(createWebhookRequest) + webhookStr := protojson.Format(createWebhookRequest) log.Printf("[INFO] Creating new webhook: %s", webhookStr) createResp, err := r.client.CreateWebhook(ctx, createWebhookRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error creating Webhook", - "Could not create Webhook, unexpected error: "+err.Error(), + formatRpcErrors(err, createWebhookURL, webhookStr), ) return } @@ -639,23 +644,25 @@ func (r *WebhookResource) Create(ctx context.Context, req resource.CreateRequest log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error reading Webhook", - "Could not read Webhook, unexpected error: "+err.Error(), + formatRpcErrors(err, getWebhookURL, protojson.Format(readWebhookRequest)), ) return } - getWebhookStr, _ := jsm.MarshalToString(getWebhookResp) + getWebhookStr := protojson.Format(getWebhookResp) log.Printf("[INFO] Reading webhook - %s", getWebhookStr) plan, diags = flattenWebhook(ctx, getWebhookResp.GetWebhook()) - + if diags.HasError() { + resp.Diagnostics.Append(diags...) + return + } // Set state to fully populated data diags = resp.State.Set(ctx, plan) resp.Diagnostics.Append(diags...) } func (r *WebhookResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - jsm := &jsonpb.Marshaler{} var state *WebhookResourceModel diags := req.State.Get(ctx, &state) @@ -673,7 +680,7 @@ func (r *WebhookResource) Read(ctx context.Context, req resource.ReadRequest, re getWebhookResp, err := r.client.GetWebhook(ctx, readWebhookRequest) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - if status.Code(err) == codes.NotFound || status.Code(err) == codes.NotFound { + if status.Code(err) == codes.NotFound { state.ID = types.StringNull() resp.Diagnostics.AddWarning( fmt.Sprintf("Webhook %q is in state, but no longer exists in Coralogix backend", id), @@ -682,16 +689,19 @@ func (r *WebhookResource) Read(ctx context.Context, req resource.ReadRequest, re } else { resp.Diagnostics.AddError( "Error reading Webhook", - handleRpcErrorNewFramework(err, "Webhook"), + formatRpcErrors(err, getWebhookURL, protojson.Format(readWebhookRequest)), ) } return } - getWebhookStr, _ := jsm.MarshalToString(getWebhookResp) - log.Printf("[INFO] Reading webhook - %s", getWebhookStr) + log.Printf("[INFO] Reading webhook - %s", protojson.Format(getWebhookResp)) state, diags = flattenWebhook(ctx, getWebhookResp.GetWebhook()) + if diags.HasError() { + resp.Diagnostics.Append(diags...) + return + } // Set state to fully populated data diags = resp.State.Set(ctx, state) @@ -718,7 +728,7 @@ func (r WebhookResource) Update(ctx context.Context, req resource.UpdateRequest, log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error updating Webhook", - "Could not update Webhook, unexpected error: "+err.Error(), + formatRpcErrors(err, updateWebhookURL, protojson.Format(webhookUpdateReq)), ) return } @@ -726,10 +736,11 @@ func (r WebhookResource) Update(ctx context.Context, req resource.UpdateRequest, // Get refreshed Webhook value from Coralogix id := plan.ID.ValueString() - getWebhookResp, err := r.client.GetWebhook(ctx, &webhooks.GetOutgoingWebhookRequest{Id: wrapperspb.String(id)}) + getWebhookReq := &webhooks.GetOutgoingWebhookRequest{Id: wrapperspb.String(id)} + getWebhookResp, err := r.client.GetWebhook(ctx, getWebhookReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) - if status.Code(err) == codes.NotFound || status.Code(err) == codes.NotFound { + if status.Code(err) == codes.NotFound { plan.ID = types.StringNull() resp.Diagnostics.AddWarning( fmt.Sprintf("Webhook %q is in state, but no longer exists in Coralogix backend", id), @@ -738,15 +749,18 @@ func (r WebhookResource) Update(ctx context.Context, req resource.UpdateRequest, } else { resp.Diagnostics.AddError( "Error reading Webhook", - handleRpcErrorNewFramework(err, "Webhook"), + formatRpcErrors(err, getWebhookURL, protojson.Format(getWebhookReq)), ) } return } - log.Printf("[INFO] Received Webhook: %#v", getWebhookResp) + log.Printf("[INFO] Received Webhook: %s", protojson.Format(getWebhookResp)) plan, diags = flattenWebhook(ctx, getWebhookResp.GetWebhook()) - + if diags.HasError() { + resp.Diagnostics.Append(diags...) + return + } // Set state to fully populated data diags = resp.State.Set(ctx, plan) resp.Diagnostics.Append(diags...) @@ -762,12 +776,13 @@ func (r WebhookResource) Delete(ctx context.Context, req resource.DeleteRequest, id := state.ID.ValueString() log.Printf("[INFO] Deleting Webhook: %s", id) - _, err := r.client.DeleteWebhook(ctx, &webhooks.DeleteOutgoingWebhookRequest{Id: wrapperspb.String(id)}) + deleteReq := &webhooks.DeleteOutgoingWebhookRequest{Id: wrapperspb.String(id)} + _, err := r.client.DeleteWebhook(ctx, deleteReq) if err != nil { log.Printf("[ERROR] Received error: %#v", err) resp.Diagnostics.AddError( "Error deleting Webhook", - "Could not delete Webhook, unexpected error: "+err.Error(), + formatRpcErrors(err, deleteTCOPolicyURL, protojson.Format(deleteReq)), ) return } @@ -883,7 +898,10 @@ func expandDigests(ctx context.Context, digestsSet types.Set) ([]*webhooks.Slack continue } var str string - val.As(&str) + if err = val.As(&str); err != nil { + diags.AddError("Error expanding digest", err.Error()) + continue + } digestType := webhooksProtoToSchemaSlackConfigDigestType[str] expandedDigests = append(expandedDigests, expandDigest(digestType)) } diff --git a/coralogix/resource_coralogix_webhook_test.go b/coralogix/resource_coralogix_webhook_test.go index 123d2e30..48cd3487 100644 --- a/coralogix/resource_coralogix_webhook_test.go +++ b/coralogix/resource_coralogix_webhook_test.go @@ -5,12 +5,13 @@ import ( "fmt" "testing" + "terraform-provider-coralogix/coralogix/clientset" + webhooks "terraform-provider-coralogix/coralogix/clientset/grpc/webhooks" + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "google.golang.org/protobuf/types/known/wrapperspb" - "terraform-provider-coralogix/coralogix/clientset" - webhooks "terraform-provider-coralogix/coralogix/clientset/grpc/webhooks" ) type webhookTestFields struct { diff --git a/coralogix/resource_grafana_folder.go b/coralogix/resource_grafana_folder.go index 2f84b7a4..cfde666e 100644 --- a/coralogix/resource_grafana_folder.go +++ b/coralogix/resource_grafana_folder.go @@ -7,12 +7,13 @@ import ( "strconv" "strings" + "terraform-provider-coralogix/coralogix/clientset" + gapi "github.com/grafana/grafana-api-golang-client" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "terraform-provider-coralogix/coralogix/clientset" ) func resourceGrafanaFolder() *schema.Resource { @@ -157,7 +158,7 @@ func DeleteFolder(ctx context.Context, d *schema.ResourceData, meta interface{}) Detail: fmt.Sprintf("%s will be recreated when you apply", d.Id()), }} } - return handleRpcError(err, "grafana-folder") + return diag.Errorf(formatRpcErrors(err, fmt.Sprintf("/grafana/api/folders/%s", folder.UID), fmt.Sprintf("%#v", folder))) } d.SetId("") diff --git a/coralogix/utils.go b/coralogix/utils.go index 4a9f6f5c..7d174079 100644 --- a/coralogix/utils.go +++ b/coralogix/utils.go @@ -13,14 +13,12 @@ import ( "time" gouuid "github.com/google/uuid" - "github.com/hashicorp/go-cty/cty" "github.com/hashicorp/terraform-plugin-framework/attr" datasourceschema "github.com/hashicorp/terraform-plugin-framework/datasource/schema" diag2 "github.com/hashicorp/terraform-plugin-framework/diag" resourceschema "github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/schema/validator" "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-plugin-testing/helper/acctest" @@ -35,39 +33,19 @@ var ( msInSecond = int(time.Second.Milliseconds()) ) -func handleRpcError(err error, resource string) diag.Diagnostics { +func formatRpcErrors(err error, url, requestStr string) string { switch status.Code(err) { case codes.PermissionDenied, codes.Unauthenticated: - return diag.Errorf("permission denied for %s endpoint, check your api-key", resource) + return fmt.Sprintf("permission denied for url - %s\ncheck your api-key and permissions", url) case codes.Internal: - return diag.Errorf("internal error for %s in Coralogix backend - %s", resource, err) + return fmt.Sprintf("internal error in Coralogix backend - %s\nurl - %s request - %s", url, err, requestStr) case codes.InvalidArgument: - return diag.Errorf("invalid argument for %s - %s", resource, err) - default: - return diag.FromErr(err) - } -} - -func handleRpcErrorNewFramework(err error, resource string) string { - switch status.Code(err) { - case codes.PermissionDenied, codes.Unauthenticated: - return fmt.Sprintf("permission denied for %s endpoint, check your api-key", resource) - case codes.Internal: - return fmt.Sprintf("internal error for %s in Coralogix backend - %s", resource, err) - case codes.InvalidArgument: - return fmt.Sprintf("invalid argument for %s - %s", resource, err) + return fmt.Sprintf("invalid argument error - %s\nurl - %s request - %s", err, url, requestStr) default: return err.Error() } } -func handleRpcErrorWithID(err error, resource, id string) diag.Diagnostics { - if status.Code(err) == codes.NotFound { - return diag.Errorf("no %s with id %s found", resource, id) - } - return handleRpcError(err, resource) -} - // datasourceSchemaFromResourceSchema is a recursive func that // converts an existing Resource schema to a Datasource schema. // All schema elements are copied, but certain attributes are ignored or changed: @@ -238,37 +216,6 @@ func convertAttribute(resourceAttribute resourceschema.Attribute) datasourcesche } } -//func convertBlocks(blocks map[string]resourceschema.Block) map[string]datasourceschema.Block { -// result := make(map[string]datasourceschema.Block, len(blocks)) -// for k, v := range blocks { -// result[k] = convertBlock(v) -// } -// return result -//} - -//func convertBlock(resourceBlock resourceschema.Block) datasourceschema.Block { -// switch block := resourceBlock.(type) { -// case resourceschema.ListNestedBlock: -// return datasourceschema.ListNestedBlock{ -// NestedObject: -// Description: attr.Description, -// MarkdownDescription: attr.MarkdownDescription, -// } -// case resourceschema.SetNestedBlock: -// return datasourceschema.SetNestedBlock{ -// Description: attr.Description, -// MarkdownDescription: attr.MarkdownDescription, -// } -// case resourceschema.SingleNestedBlock: -// return datasourceschema.SingleNestedBlock{ -// Description: attr.Description, -// MarkdownDescription: attr.MarkdownDescription, -// } -// default: -// panic(fmt.Sprintf("unknown resource block type: %T", resourceAttribute)) -// } -//} - func interfaceSliceToStringSlice(s []interface{}) []string { result := make([]string, 0, len(s)) for _, v := range s { @@ -367,15 +314,26 @@ func typeBoolToWrapperspbBool(v types.Bool) *wrapperspb.BoolValue { return wrapperspb.Bool(v.ValueBool()) } -func typeStringSliceToStringSlice(ctx context.Context, s []attr.Value) []string { +func typeStringSliceToStringSlice(ctx context.Context, s []attr.Value) ([]string, diag2.Diagnostics) { result := make([]string, 0, len(s)) + var diags diag2.Diagnostics for _, v := range s { - val, _ := v.ToTerraformValue(ctx) + val, err := v.ToTerraformValue(ctx) + if err != nil { + diags.AddError("Failed to convert value to Terraform", err.Error()) + continue + } var str string - val.As(&str) + if err = val.As(&str); err != nil { + diags.AddError("Failed to convert value to Terraform", err.Error()) + continue + } result = append(result, str) } - return result + if diags.HasError() { + return nil, diags + } + return result, nil } func timeInDaySchema(description string) *schema.Schema { @@ -508,14 +466,6 @@ func getKeysInt32(m map[string]int32) []string { return result } -func getKeysInt(m map[string]int) []string { - result := make([]string, 0) - for k := range m { - result = append(result, k) - } - return result -} - func getKeysRelativeTimeFrame(m map[string]protoTimeFrameAndRelativeTimeFrame) []string { result := make([]string, 0) for k := range m { @@ -557,25 +507,6 @@ func uint32ToStr(n uint32) string { return strconv.FormatUint(uint64(n), 10) } -func urlValidationFunc() schema.SchemaValidateDiagFunc { - return func(v interface{}, _ cty.Path) diag.Diagnostics { - if _, err := url.ParseRequestURI(v.(string)); err != nil { - return diag.Errorf("%s in not valid url - %s", v.(string), err.Error()) - } - return nil - } -} - -func jsonValidationFuncWithDiagnostics() schema.SchemaValidateDiagFunc { - return func(v interface{}, _ cty.Path) diag.Diagnostics { - var m map[string]interface{} - if err := json.Unmarshal([]byte(v.(string)), &m); err != nil { - return diag.Errorf("%s in not valid json - %s", v.(string), err.Error()) - } - return nil - } -} - type urlValidationFuncFramework struct { } @@ -605,15 +536,6 @@ func (u urlValidationFuncFramework) ValidateString(ctx context.Context, req vali } } -//func urlValidationFuncFramework() schema.SchemaValidateDiagFunc { -// return func(v interface{}, _ cty.Path) diag.Diagnostics { -// if _, err := url.ParseRequestURI(v.(string)); err != nil { -// return diag.Errorf("%s in not valid url - %s", v.(string), err.Error()) -// } -// return nil -// } -//} - const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func RandStringBytes(n int) string { @@ -624,10 +546,6 @@ func RandStringBytes(n int) string { return string(b) } -func SuppressEquivalentJSONDiffs(k, old, new string, d *schema.ResourceData) bool { - return JSONStringsEqual(old, new) -} - func JSONStringsEqual(s1, s2 string) bool { b1 := bytes.NewBufferString("") if err := json.Compact(b1, []byte(s1)); err != nil { @@ -769,3 +687,11 @@ func retryableStatusCode(statusCode codes.Code) bool { return false } } + +func uint32SliceToWrappedUint32Slice(s []uint32) []*wrapperspb.UInt32Value { + result := make([]*wrapperspb.UInt32Value, 0, len(s)) + for _, n := range s { + result = append(result, wrapperspb.UInt32(n)) + } + return result +} diff --git a/docs/data-sources/tco_policy_override.md b/docs/data-sources/tco_policy_override.md deleted file mode 100644 index 8b9181c9..00000000 --- a/docs/data-sources/tco_policy_override.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "coralogix_tco_policy_override Data Source - terraform-provider-coralogix" -subcategory: "" -description: |- - ---- - -# coralogix_tco_policy_override (Data Source) - - - - - - -## Schema - -### Read-Only - -- `application_name` (String) The application to apply the policy on. Applies the policy on all the applications by default. -- `id` (String) The ID of this resource. -- `priority` (String) The policy-override priority. Can be one of ["high" "medium" "low" "block"]. -- `severity` (String) The severity to apply the policy on. Can be one of ["debug" "verbose" "info" "warning" "error" "critical"]. -- `subsystem_name` (String) The subsystem to apply the policy on. Applies the policy on all the subsystems by default. - - diff --git a/examples/tco_policy_override/main.tf b/examples/tco_policy_override/main.tf deleted file mode 100644 index c204a5c2..00000000 --- a/examples/tco_policy_override/main.tf +++ /dev/null @@ -1,27 +0,0 @@ -terraform { - required_providers { - coralogix = { - version = "~> 1.5" - source = "coralogix/coralogix" - } - } -} - -provider "coralogix" { - #api_key = "" - #env = "" -} - -resource "coralogix_tco_policy_override" "tco_policy" { - priority = "medium" - severity = "debug" - application_name = "prod" - subsystem_name = "mobile" -} - -resource "coralogix_tco_policy_override" "tco_policy_2" { - priority = "high" - severity = "error" - application_name = "staging" - subsystem_name = "web" -} \ No newline at end of file diff --git a/go.mod b/go.mod index cc88fe48..ce0a3f6c 100644 --- a/go.mod +++ b/go.mod @@ -4,10 +4,9 @@ go 1.20 require ( github.com/ahmetalpbalkan/go-linq v3.0.0+incompatible - github.com/golang/protobuf v1.5.3 + github.com/google/uuid v1.4.0 github.com/grafana/grafana-api-golang-client v0.23.0 github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 - github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 github.com/hashicorp/terraform-plugin-docs v0.15.0 github.com/hashicorp/terraform-plugin-framework v1.2.0 github.com/hashicorp/terraform-plugin-framework-validators v0.10.0 @@ -32,11 +31,12 @@ require ( github.com/bgentry/speakeasy v0.1.0 // indirect github.com/cloudflare/circl v1.3.3 // indirect github.com/fatih/color v1.13.0 // indirect + github.com/golang/protobuf v1.5.3 // indirect github.com/google/go-cmp v0.5.9 // indirect - github.com/google/uuid v1.4.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-checkpoint v0.5.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect github.com/hashicorp/go-hclog v1.5.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-plugin v1.4.10 // indirect diff --git a/go.sum b/go.sum index 4a82d696..3f991783 100644 --- a/go.sum +++ b/go.sum @@ -70,8 +70,6 @@ github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grafana/grafana-api-golang-client v0.23.0 h1:Uta0dSkxWYf1D83/E7MRLCG69387FiUc+k9U/35nMhY= diff --git a/main.go b/main.go index 81cbcae3..2f6cd7c8 100644 --- a/main.go +++ b/main.go @@ -4,12 +4,13 @@ import ( "context" "log" + "terraform-provider-coralogix/coralogix" + "github.com/hashicorp/terraform-plugin-framework/providerserver" "github.com/hashicorp/terraform-plugin-go/tfprotov6" "github.com/hashicorp/terraform-plugin-go/tfprotov6/tf6server" "github.com/hashicorp/terraform-plugin-mux/tf5to6server" "github.com/hashicorp/terraform-plugin-mux/tf6muxserver" - "terraform-provider-coralogix/coralogix" ) // Generate the Terraform provider documentation using `tfplugindocs`: @@ -38,4 +39,8 @@ func main() { muxServer.ProviderServer, serveOpts..., ) + + if err != nil { + log.Fatal(err) + } }