Skip to content

Commit

Permalink
[Resource] Deprecate Snapshot For Instance Snapshot
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelkad committed Sep 19, 2024
1 parent 2aa2176 commit 50230ca
Show file tree
Hide file tree
Showing 9 changed files with 489 additions and 71 deletions.
4 changes: 0 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,6 @@ github.com/IBM/container-registry-go-sdk v1.1.0 h1:sYyknIod8R4RJZQqAheiduP6wbSTp
github.com/IBM/container-registry-go-sdk v1.1.0/go.mod h1:4TwsCnQtVfZ4Vkapy/KPvQBKFc3VOyUZYkwRU4FTPrs=
github.com/IBM/continuous-delivery-go-sdk v1.6.0 h1:eAL/jIWHrDFlWDF+Qd9Y5UN99Pr5Mjd/H/bvTbXUbz4=
github.com/IBM/continuous-delivery-go-sdk v1.6.0/go.mod h1:nZdKUnubXNLo+zo28R4Rd+TGDqiJ/xoE8WO/A3kLw1E=
github.com/IBM/event-notifications-go-admin-sdk v0.8.0 h1:xk2CYTayQtKi6LSgGGFRxFJfWUxyM5SY8Rs64ducAhw=
github.com/IBM/event-notifications-go-admin-sdk v0.8.0/go.mod h1:OByvqfrNVxs7G6ggv8pwQCEVw10/TBJCLh7NM3z707w=
github.com/IBM/event-notifications-go-admin-sdk v0.9.0 h1:eaCd+GkxhNyot+8rA9WkAQdlVYrRD20LYiXjEytFO6M=
github.com/IBM/event-notifications-go-admin-sdk v0.9.0/go.mod h1:OByvqfrNVxs7G6ggv8pwQCEVw10/TBJCLh7NM3z707w=
github.com/IBM/eventstreams-go-sdk v1.4.0 h1:yS/Ns29sBOe8W2tynQmz9HTKqQZ0ckse4Py5Oy/F2rM=
Expand Down Expand Up @@ -187,8 +185,6 @@ github.com/IBM/scc-go-sdk/v5 v5.4.1 h1:RXIuxOo9/hxkWyHCI69ae+KIJgSbXcAkJwTEl+fO3
github.com/IBM/scc-go-sdk/v5 v5.4.1/go.mod h1:2xQTDgNXG5QMEfQxBDKB067z+5ha6OgcaKCTcdGDAo8=
github.com/IBM/schematics-go-sdk v0.2.3 h1:lgTt0Sbudii3cuSk1YSQgrtiZAXDbBABAoVj3eQuBrU=
github.com/IBM/schematics-go-sdk v0.2.3/go.mod h1:Tw2OSAPdpC69AxcwoyqcYYaGTTW6YpERF9uNEU+BFRQ=
github.com/IBM/secrets-manager-go-sdk/v2 v2.0.5 h1:VMc/Zd6RzB8j60CqZekkwYT2wQsCfrkGV2n01Gviuaw=
github.com/IBM/secrets-manager-go-sdk/v2 v2.0.5/go.mod h1:5kUgJ1dG9cdiAcPDqVz46m362bPnoqZQSth24NiowSg=
github.com/IBM/secrets-manager-go-sdk/v2 v2.0.6 h1:bF6bAdI4wDZSje6+Yx1mJxvirboxO+uMuKhzgfRCNxE=
github.com/IBM/secrets-manager-go-sdk/v2 v2.0.6/go.mod h1:XWYnbcc5vN1RnKwk/fCzfD8aZd7At/Y1/b6c+oDyliU=
github.com/IBM/vmware-go-sdk v0.1.2 h1:5lKWFyInWz9e2hwGsoFTEoLa1jYkD30SReN0fQ10w9M=
Expand Down
1 change: 1 addition & 0 deletions ibm/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1296,6 +1296,7 @@ func Provider() *schema.Provider {
"ibm_pi_image": power.ResourceIBMPIImage(),
"ibm_pi_instance_action": power.ResourceIBMPIInstanceAction(),
"ibm_pi_instance": power.ResourceIBMPIInstance(),
"ibm_pi_intance_snapshot": power.ResourceIBMPIInstanceSnapshot(),
"ibm_pi_ipsec_policy": power.ResourceIBMPIIPSecPolicy(),
"ibm_pi_key": power.ResourceIBMPIKey(),
"ibm_pi_network_port_attach": power.ResourceIBMPINetworkPortAttach(),
Expand Down
1 change: 1 addition & 0 deletions ibm/service/power/ibm_pi_constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ const (
Arg_SharedProcessorPoolReservedCores = "pi_shared_processor_pool_reserved_cores"
Arg_SnapshotID = "pi_snapshot_id"
Arg_SnapShotName = "pi_snap_shot_name"
Arg_SnapshotName = "pi_snapshot_name"
Arg_SPPPlacementGroupID = "pi_spp_placement_group_id"
Arg_SPPPlacementGroupName = "pi_spp_placement_group_name"
Arg_SPPPlacementGroupPolicy = "pi_spp_placement_group_policy"
Expand Down
288 changes: 288 additions & 0 deletions ibm/service/power/resource_ibm_pi_instance_snapshot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,288 @@
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0

package power

import (
"context"
"fmt"
"log"
"time"

"github.com/IBM-Cloud/power-go-client/clients/instance"
"github.com/IBM-Cloud/power-go-client/power/models"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)

func ResourceIBMPIInstanceSnapshot() *schema.Resource {
return &schema.Resource{
CreateContext: resourceIBMPIInstanceSnapshotCreate,
ReadContext: resourceIBMPIInstanceSnapshotRead,
UpdateContext: resourceIBMPIInstanceSnapshotUpdate,
DeleteContext: resourceIBMPIInstanceSnapshotDelete,
Importer: &schema.ResourceImporter{},

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},

Schema: map[string]*schema.Schema{
// Arguments
Arg_CloudInstanceID: {
Description: "The GUID of the service instance associated with an account.",
Required: true,
Type: schema.TypeString,
ValidateFunc: validation.NoZeroValues,
},
Arg_Description: {
Description: "Description of the PVM instance snapshot.",
Optional: true,
Type: schema.TypeString,
},
Arg_InstanceName: {
Description: "The name of the instance you want to take a snapshot of.",
Required: true,
Type: schema.TypeString,
ValidateFunc: validation.NoZeroValues,
},
Arg_SnapshotName: {
Description: "The unique name of the snapshot.",
Required: true,
Type: schema.TypeString,
ValidateFunc: validation.NoZeroValues,
},
Arg_VolumeIDs: {
Description: "A list of volume IDs of the instance that will be part of the snapshot. If none are provided, then all the volumes of the instance will be part of the snapshot.",
DiffSuppressFunc: flex.ApplyOnce,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Set: schema.HashString,
Type: schema.TypeSet,
},

// Attributes
Attr_CreationDate: {
Computed: true,
Description: "Creation date of the snapshot.",
Type: schema.TypeString,
},
Attr_LastUpdateDate: {
Computed: true,
Description: "The last updated date of the snapshot.",
Type: schema.TypeString,
},
Attr_SnapshotID: {
Computed: true,
Description: "ID of the PVM instance snapshot.",
Type: schema.TypeString,
},
Attr_Status: {
Computed: true,
Description: "Status of the PVM instance snapshot.",
Type: schema.TypeString,
},
Attr_VolumeSnapshots: {
Computed: true,
Description: "A map of volume snapshots included in the PVM instance snapshot.",
Type: schema.TypeMap,
},
},
}
}

func resourceIBMPIInstanceSnapshotCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
sess, err := meta.(conns.ClientSession).IBMPISession()
if err != nil {
return diag.FromErr(err)
}

cloudInstanceID := d.Get(Arg_CloudInstanceID).(string)
instanceid := d.Get(Arg_InstanceName).(string)
name := d.Get(Arg_SnapshotName).(string)
volumeIDs := flex.ExpandStringList((d.Get(Arg_VolumeIDs).(*schema.Set)).List())

var description string
if v, ok := d.GetOk(Arg_Description); ok {
description = v.(string)
}

client := instance.NewIBMPIInstanceClient(ctx, sess, cloudInstanceID)

snapshotBody := &models.SnapshotCreate{Name: &name, Description: description}

if len(volumeIDs) > 0 {
snapshotBody.VolumeIDs = volumeIDs
} else {
log.Printf("no volumeids provided. Will snapshot the entire instance")
}

snapshotResponse, err := client.CreatePvmSnapShot(instanceid, snapshotBody)
if err != nil {
log.Printf("[DEBUG] err %s", err)
return diag.FromErr(err)
}

d.SetId(fmt.Sprintf("%s/%s", cloudInstanceID, *snapshotResponse.SnapshotID))

piSnapClient := instance.NewIBMPISnapshotClient(ctx, sess, cloudInstanceID)
_, err = isWaitForPIInstanceSnapshotAvailable(ctx, piSnapClient, *snapshotResponse.SnapshotID, d.Timeout(schema.TimeoutCreate))
if err != nil {
return diag.FromErr(err)
}

return resourceIBMPISnapshotRead(ctx, d, meta)
}

func resourceIBMPIInstanceSnapshotRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
sess, err := meta.(conns.ClientSession).IBMPISession()
if err != nil {
return diag.FromErr(err)
}

cloudInstanceID, snapshotID, err := splitID(d.Id())
if err != nil {
return diag.FromErr(err)
}

snapshot := instance.NewIBMPISnapshotClient(ctx, sess, cloudInstanceID)
snapshotdata, err := snapshot.Get(snapshotID)
if err != nil {
return diag.FromErr(err)
}

d.Set(Arg_SnapshotName, snapshotdata.Name)
d.Set(Attr_CreationDate, snapshotdata.CreationDate.String())
d.Set(Attr_LastUpdateDate, snapshotdata.LastUpdateDate.String())
d.Set(Attr_SnapshotID, *snapshotdata.SnapshotID)
d.Set(Attr_Status, snapshotdata.Status)
d.Set(Attr_VolumeSnapshots, snapshotdata.VolumeSnapshots)

return nil
}

func resourceIBMPIInstanceSnapshotUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
sess, err := meta.(conns.ClientSession).IBMPISession()
if err != nil {
return diag.FromErr(err)
}

cloudInstanceID, snapshotID, err := splitID(d.Id())
if err != nil {
return diag.FromErr(err)
}

client := instance.NewIBMPISnapshotClient(ctx, sess, cloudInstanceID)

if d.HasChange(Arg_SnapshotName) || d.HasChange(Arg_Description) {
name := d.Get(Arg_SnapshotName).(string)
description := d.Get(Arg_Description).(string)
snapshotBody := &models.SnapshotUpdate{Name: name, Description: description}

_, err := client.Update(snapshotID, snapshotBody)
if err != nil {
return diag.FromErr(err)
}

_, err = isWaitForPIInstanceSnapshotAvailable(ctx, client, snapshotID, d.Timeout(schema.TimeoutCreate))
if err != nil {
return diag.FromErr(err)
}
}

return resourceIBMPISnapshotRead(ctx, d, meta)
}

func resourceIBMPIInstanceSnapshotDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
sess, err := meta.(conns.ClientSession).IBMPISession()
if err != nil {
return diag.FromErr(err)
}

cloudInstanceID, snapshotID, err := splitID(d.Id())
if err != nil {
return diag.FromErr(err)
}

client := instance.NewIBMPISnapshotClient(ctx, sess, cloudInstanceID)
snapshot, err := client.Get(snapshotID)
if err != nil {
// snapshot does not exist
d.SetId("")
return nil
}

log.Printf("The snapshot to be deleted is in the following state .. %s", snapshot.Status)

err = client.Delete(snapshotID)
if err != nil {
return diag.FromErr(err)
}

_, err = isWaitForPIInstanceSnapshotDeleted(ctx, client, snapshotID, d.Timeout(schema.TimeoutDelete))
if err != nil {
return diag.FromErr(err)
}

d.SetId("")
return nil
}

func isWaitForPIInstanceSnapshotAvailable(ctx context.Context, client *instance.IBMPISnapshotClient, id string, timeout time.Duration) (interface{}, error) {
stateConf := &retry.StateChangeConf{
Pending: []string{State_InProgress},
Target: []string{State_Available, State_ACTIVE},
Refresh: isPIInstanceSnapshotRefreshFunc(client, id),
Delay: 30 * time.Second,
MinTimeout: 2 * time.Minute,
Timeout: timeout,
}

return stateConf.WaitForStateContext(ctx)
}

func isPIInstanceSnapshotRefreshFunc(client *instance.IBMPISnapshotClient, id string) retry.StateRefreshFunc {
return func() (interface{}, string, error) {
snapshotInfo, err := client.Get(id)
if err != nil {
return nil, "", err
}

if snapshotInfo.Status == State_Available && snapshotInfo.PercentComplete == 100 {
log.Printf("The snapshot is now available")
return snapshotInfo, State_Available, nil

}
return snapshotInfo, State_InProgress, nil
}
}

func isWaitForPIInstanceSnapshotDeleted(ctx context.Context, client *instance.IBMPISnapshotClient, id string, timeout time.Duration) (interface{}, error) {
stateConf := &retry.StateChangeConf{
Pending: []string{State_Retry},
Target: []string{State_NotFound},
Refresh: isPIInstanceSnapshotDeleteRefreshFunc(client, id),
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
Timeout: timeout,
}

return stateConf.WaitForStateContext(ctx)
}

func isPIInstanceSnapshotDeleteRefreshFunc(client *instance.IBMPISnapshotClient, id string) retry.StateRefreshFunc {
return func() (interface{}, string, error) {
snapshot, err := client.Get(id)
if err != nil {
log.Printf("The snapshot is not found.")
return snapshot, State_NotFound, nil
}
return snapshot, State_NotFound, nil
}
}
Loading

0 comments on commit 50230ca

Please sign in to comment.