package sqlserverflexbeta import ( "context" _ "embed" "fmt" "net/http" "strings" "time" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types/basetypes" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/stackitcloud/stackit-sdk-go/core/config" "github.com/stackitcloud/stackit-sdk-go/core/oapierror" "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/conversion" wait "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/wait/sqlserverflexbeta" "github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex/v3beta1api" "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/core" "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/utils" sqlserverflexbetaResGen "tf-provider.git.onstackit.cloud/stackit-dev-tools/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexbeta/instance/resources_gen" ) var ( _ resource.Resource = &instanceResource{} _ resource.ResourceWithConfigure = &instanceResource{} _ resource.ResourceWithImportState = &instanceResource{} _ resource.ResourceWithModifyPlan = &instanceResource{} ) func NewInstanceResource() resource.Resource { return &instanceResource{} } type instanceResource struct { client *v3beta1api.APIClient providerData core.ProviderData } // LocalInstanceModel describes the resource data model. type LocalInstanceModel struct { sqlserverflexbetaResGen.InstanceModel Flavor types.Object `tfsdk:"flavor"` } // LocalFlavorModel Struct corresponding to Model.Flavor type LocalFlavorModel struct { Id types.String `tfsdk:"id"` Description types.String `tfsdk:"description"` CPU types.Int64 `tfsdk:"cpu"` RAM types.Int64 `tfsdk:"ram"` } func (r *instanceResource) Metadata( _ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse, ) { resp.TypeName = req.ProviderTypeName + "_sqlserverflexbeta_instance" } //go:embed planModifiers.yaml var modifiersFileByte []byte func (r *instanceResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { s := sqlserverflexbetaResGen.InstanceResourceSchema(ctx) s.Attributes["flavor"] = schema.SingleNestedAttribute{ Optional: true, DeprecationMessage: "Please use flavor_id instead.", Attributes: map[string]schema.Attribute{ "id": schema.StringAttribute{ Computed: true, PlanModifiers: []planmodifier.String{ UseStateForUnknownIfFlavorUnchanged(req), }, }, "description": schema.StringAttribute{ Computed: true, PlanModifiers: []planmodifier.String{ UseStateForUnknownIfFlavorUnchanged(req), }, }, "cpu": schema.Int64Attribute{ DeprecationMessage: "Please use flavor_id instead.", Optional: true, }, "ram": schema.Int64Attribute{ DeprecationMessage: "Please use flavor_id instead.", Optional: true, }, }, } s.Attributes["flavor_id"] = schema.StringAttribute{ Optional: true, Description: "The id of the instance flavor.", MarkdownDescription: "The id of the instance flavor.", } fields, err := utils.ReadModifiersConfig(modifiersFileByte) if err != nil { resp.Diagnostics.AddError("error during read modifiers config file", err.Error()) return } err = utils.AddPlanModifiersToResourceSchema(fields, &s) if err != nil { resp.Diagnostics.AddError("error adding plan modifiers", err.Error()) return } resp.Schema = s } // Configure adds the provider configured client to the resource. func (r *instanceResource) Configure( ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse, ) { var ok bool r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) if !ok { return } apiClientConfigOptions := []config.ConfigurationOption{ config.WithCustomAuth(r.providerData.RoundTripper), utils.UserAgentConfigOption(r.providerData.Version), } if r.providerData.SQLServerFlexCustomEndpoint != "" { apiClientConfigOptions = append( apiClientConfigOptions, config.WithEndpoint(r.providerData.SQLServerFlexCustomEndpoint), ) } else { apiClientConfigOptions = append(apiClientConfigOptions, config.WithRegion(r.providerData.GetRegion())) } apiClient, err := v3beta1api.NewAPIClient(apiClientConfigOptions...) if err != nil { resp.Diagnostics.AddError( "Error configuring API client", fmt.Sprintf( "Configuring client: %v. This is an error related to the provider configuration, not to the resource configuration", err, ), ) return } r.client = apiClient tflog.Info(ctx, "sqlserverflexbeta.Instance client configured") } // ModifyPlan implements resource.ResourceWithModifyPlan. // Use the modifier to set the effective region in the current plan. func (r *instanceResource) ModifyPlan( ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse, ) { // nolint:gocritic // function signature required by Terraform // skip initial empty configuration to avoid follow-up errors if req.Config.Raw.IsNull() { return } var configModel LocalInstanceModel resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...) if resp.Diagnostics.HasError() { return } if req.Plan.Raw.IsNull() { return } var planModel LocalInstanceModel resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...) if resp.Diagnostics.HasError() { return } utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp) if resp.Diagnostics.HasError() { return } resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...) if resp.Diagnostics.HasError() { return } } func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { var data LocalInstanceModel crateErr := "[SQL Server Flex BETA - Create] error" // Read Terraform plan data into the model resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } ctx = core.InitProviderContext(ctx) projectID := data.ProjectId.ValueString() region := data.Region.ValueString() ctx = tflog.SetField(ctx, "project_id", projectID) ctx = tflog.SetField(ctx, "region", region) // determine flavor ID var flModel = &LocalFlavorModel{} if !(data.Flavor.IsNull() || data.Flavor.IsUnknown()) { diags := data.Flavor.As(ctx, flModel, basetypes.ObjectAsOptions{}) resp.Diagnostics.Append(diags...) if resp.Diagnostics.HasError() { return } flavors, err := getAllFlavors(ctx, r.client.DefaultAPI, projectID, region) if err != nil { core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading flavors", fmt.Sprintf("getAllFlavors: %v", err)) return } tflog.Debug(ctx, fmt.Sprintf("loaded flavors: %d", len(flavors))) var foundFlavors []v3beta1api.ListFlavors for _, flavor := range flavors { if flModel.CPU.ValueInt64() != int64(flavor.Cpu) { // tflog.Debug(ctx, fmt.Sprintf("flavor - cpu did not match (%d - %d)", flModel.CPU.ValueInt64(), flavor.Cpu)) continue } if flModel.RAM.ValueInt64() != int64(flavor.Memory) { // tflog.Debug(ctx, fmt.Sprintf("flavor - ram did not match (%d - %d)", flModel.RAM.ValueInt64(), flavor.Memory)) continue } tmpNodeType := "Single" if data.Replicas.ValueInt64() > 1 { tmpNodeType = "Replica" } if strings.ToLower(tmpNodeType) != strings.ToLower(flavor.NodeType) { //tflog.Debug( // ctx, // fmt.Sprintf( // "flavor - nodeType did not match ('%s' - '%s')", // strings.ToLower(tmpNodeType), // strings.ToLower(flavor.NodeType), // ), //) continue } tflog.Debug(ctx, fmt.Sprintf("found flavor %s, checking storage classes", flavor.Id)) for _, sc := range flavor.StorageClasses { if data.Storage.Class.ValueString() != sc.Class { continue } tflog.Debug(ctx, fmt.Sprintf("found storage class '%s' for flavor '%s', checking storage classes", sc.Class, flavor.Id)) foundFlavors = append(foundFlavors, flavor) } } if len(foundFlavors) == 0 { resp.Diagnostics.AddError("get flavor", "could not find requested flavor") return } if len(foundFlavors) > 1 { resp.Diagnostics.AddError("get flavor", "found too many matching flavors") return } f := foundFlavors[0] flModel.Description = types.StringValue(f.Description) flModel.Id = utils.BuildInternalTerraformId(data.ProjectId.ValueString(), region, f.Id) data.FlavorId = types.StringValue(f.Id) //flModel. .MaxGb = types.Int32Value(f.MaxGB) //flModel.MinGb = types.Int32Value(f.MinGB) } // Generate API request body from model payload, err := toCreatePayload(ctx, &data) if err != nil { core.LogAndAddError( ctx, &resp.Diagnostics, crateErr, fmt.Sprintf("Creating API payload: %v", err), ) return } // Create new Instance createResp, err := r.client.DefaultAPI.CreateInstanceRequest( ctx, projectID, region, ).CreateInstanceRequestPayload(*payload).Execute() if err != nil { core.LogAndAddError(ctx, &resp.Diagnostics, crateErr, fmt.Sprintf("Calling API: %v", err)) return } ctx = core.LogResponse(ctx) instanceID := createResp.Id data.InstanceId = types.StringValue(instanceID) data.Id = utils.BuildInternalTerraformId(projectID, region, instanceID) // Set data returned by API in id resp.Diagnostics.Append( resp.State.SetAttribute( ctx, path.Root("id"), utils.BuildInternalTerraformId(projectID, region, instanceID), )..., ) resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), instanceID)...) waitResp, err := wait.CreateInstanceWaitHandler( ctx, r.client.DefaultAPI, projectID, instanceID, region, ).SetSleepBeforeWait( 10 * time.Second, ).SetTimeout( 90 * time.Minute, ).WaitWithContext(ctx) if err != nil { core.LogAndAddError( ctx, &resp.Diagnostics, crateErr, fmt.Sprintf("Instance creation waiting: %v", err), ) return } if waitResp.Id == "" { core.LogAndAddError( ctx, &resp.Diagnostics, crateErr, "Instance creation waiting: returned id is nil", ) return } // Map response body to schema err = mapResponseToModel(ctx, waitResp, &data, resp.Diagnostics) if err != nil { core.LogAndAddError( ctx, &resp.Diagnostics, crateErr, fmt.Sprintf("processing API payload: %v", err), ) return } // Save data into Terraform state resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) tflog.Info(ctx, "sqlserverflexbeta.Instance created") } func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { var data LocalInstanceModel // Read Terraform prior state data into the model resp.Diagnostics.Append(req.State.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } ctx = core.InitProviderContext(ctx) projectID := data.ProjectId.ValueString() region := data.Region.ValueString() ctx = tflog.SetField(ctx, "project_id", projectID) ctx = tflog.SetField(ctx, "region", region) instanceID := data.InstanceId.ValueString() ctx = tflog.SetField(ctx, "instance_id", instanceID) instanceResp, err := r.client.DefaultAPI.GetInstanceRequest(ctx, projectID, region, instanceID).Execute() if err != nil { oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped if ok && oapiErr.StatusCode == http.StatusNotFound { resp.State.RemoveResource(ctx) return } core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", err.Error()) return } ctx = core.LogResponse(ctx) // Map response body to schema err = mapResponseToModel(ctx, instanceResp, &data, resp.Diagnostics) if err != nil { core.LogAndAddError( ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err), ) return } // Save updated data into Terraform state resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) if resp.Diagnostics.HasError() { return } tflog.Info(ctx, "sqlserverflexbeta.Instance read") } func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { var data LocalInstanceModel updateInstanceError := "Error updating instance" resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } ctx = core.InitProviderContext(ctx) projectID := data.ProjectId.ValueString() region := data.Region.ValueString() ctx = tflog.SetField(ctx, "project_id", projectID) ctx = tflog.SetField(ctx, "region", region) instanceID := data.InstanceId.ValueString() ctx = tflog.SetField(ctx, "instance_id", instanceID) // Generate API request body from model payload, err := toUpdatePayload(ctx, &data, resp) if err != nil { core.LogAndAddError( ctx, &resp.Diagnostics, updateInstanceError, fmt.Sprintf("Creating API payload: %v", err), ) return } // Update existing instance err = r.client.DefaultAPI.UpdateInstanceRequest( ctx, projectID, region, instanceID, ).UpdateInstanceRequestPayload(*payload).Execute() if err != nil { core.LogAndAddError(ctx, &resp.Diagnostics, updateInstanceError, err.Error()) return } ctx = core.LogResponse(ctx) waitResp, err := wait. UpdateInstanceWaitHandler(ctx, r.client.DefaultAPI, projectID, instanceID, region). SetSleepBeforeWait(10 * time.Second). SetTimeout(90 * time.Minute). WaitWithContext(ctx) if err != nil { core.LogAndAddError( ctx, &resp.Diagnostics, updateInstanceError, fmt.Sprintf("Instance update waiting: %v", err), ) return } // Map response body to schema err = mapResponseToModel(ctx, waitResp, &data, resp.Diagnostics) if err != nil { core.LogAndAddError( ctx, &resp.Diagnostics, updateInstanceError, fmt.Sprintf("Processing API payload: %v", err), ) return } // Save updated data into Terraform state resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) if resp.Diagnostics.HasError() { return } tflog.Info(ctx, "sqlserverflexbeta.Instance updated") } func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { var data LocalInstanceModel // Read Terraform prior state data into the model resp.Diagnostics.Append(req.State.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } ctx = core.InitProviderContext(ctx) projectID := data.ProjectId.ValueString() region := data.Region.ValueString() ctx = tflog.SetField(ctx, "project_id", projectID) ctx = tflog.SetField(ctx, "region", region) instanceID := data.InstanceId.ValueString() ctx = tflog.SetField(ctx, "instance_id", instanceID) // Delete existing instance err := r.client.DefaultAPI.DeleteInstanceRequest(ctx, projectID, region, instanceID).Execute() if err != nil { core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err)) return } ctx = core.LogResponse(ctx) delResp, err := wait.DeleteInstanceWaitHandler(ctx, r.client.DefaultAPI, projectID, instanceID, region). SetSleepBeforeWait(10 * time.Second). SetTimeout(90 * time.Minute). WaitWithContext(ctx) if err != nil { core.LogAndAddError( ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err), ) return } if delResp != nil { core.LogAndAddError( ctx, &resp.Diagnostics, "Error deleting instance", "wait handler returned non nil result", ) return } resp.State.RemoveResource(ctx) tflog.Info(ctx, "sqlserverflexbeta.Instance deleted") } // ImportState imports a resource into the Terraform state on success. // The expected format of the resource import identifier is: project_id,zone_id,record_set_id func (r *instanceResource) ImportState( ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse, ) { ctx = core.InitProviderContext(ctx) idParts := strings.Split(req.ID, core.Separator) if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { core.LogAndAddError( ctx, &resp.Diagnostics, "Error importing instance", fmt.Sprintf( "Expected import identifier with format [project_id],[region],[instance_id] Got: %q", req.ID, ), ) return } resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), utils.BuildInternalTerraformId(idParts...).ValueString())...) resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...) resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...) resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...) tflog.Info(ctx, "Sqlserverflexbeta instance state imported") }