-
Notifications
You must be signed in to change notification settings - Fork 674
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Resource] Deprecate Snapshot For Instance Snapshot #5675
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,332 @@ | ||
// Copyright IBM Corp. 2024 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_UserTags: { | ||
Description: "The user tags attached to this resource.", | ||
Elem: &schema.Schema{Type: schema.TypeString}, | ||
Optional: true, | ||
Set: schema.HashString, | ||
Type: schema.TypeSet, | ||
}, | ||
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_CRN: { | ||
Computed: true, | ||
Description: "The CRN of this resource.", | ||
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") | ||
} | ||
|
||
if v, ok := d.GetOk(Arg_UserTags); ok { | ||
snapshotBody.UserTags = flex.FlattenSet(v.(*schema.Set)) | ||
} | ||
|
||
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) | ||
} | ||
|
||
if _, ok := d.GetOk(Arg_UserTags); ok { | ||
if snapshotResponse.Crn != "" { | ||
oldList, newList := d.GetChange(Arg_UserTags) | ||
err := flex.UpdateGlobalTagsUsingCRN(oldList, newList, meta, string(snapshotResponse.Crn), "", UserTagType) | ||
if err != nil { | ||
log.Printf("Error on update of pi snapshot (%s) pi_user_tags during creation: %s", *snapshotResponse.SnapshotID, err) | ||
} | ||
} | ||
} | ||
|
||
return resourceIBMPIInstanceSnapshotRead(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()) | ||
if snapshotdata.Crn != "" { | ||
d.Set(Attr_CRN, snapshotdata.Crn) | ||
tags, err := flex.GetGlobalTagsUsingCRN(meta, string(snapshotdata.Crn), "", UserTagType) | ||
if err != nil { | ||
log.Printf("Error on get of pi snapshot (%s) pi_user_tags: %s", *snapshotdata.SnapshotID, err) | ||
} | ||
d.Set(Arg_UserTags, tags) | ||
} | ||
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.TimeoutUpdate)) | ||
if err != nil { | ||
return diag.FromErr(err) | ||
} | ||
} | ||
|
||
if d.HasChange(Arg_UserTags) { | ||
if crn, ok := d.GetOk(Attr_CRN); ok { | ||
oldList, newList := d.GetChange(Arg_UserTags) | ||
err := flex.UpdateGlobalTagsUsingCRN(oldList, newList, meta, crn.(string), "", UserTagType) | ||
if err != nil { | ||
log.Printf("Error on update of pi snapshot (%s) pi_user_tags: %s", snapshotID, err) | ||
} | ||
} | ||
} | ||
|
||
return resourceIBMPIInstanceSnapshotRead(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}, | ||
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 | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Did you mean to add a TODO comment?
Check if the error code is 404.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not following the issue in this line. Do you want me to check the error code of the get and only set the id to empty if the we get a 404 vs another unrelated reason the get failed? This step of getting the snapshot seems strange already because I'm not seeing other resources get the item they want to delete before calling delete. Before this PR, the last edit to this was here: https://github.com/IBM-Cloud/terraform-provider-ibm/pull/3429/files#diff-317acb20df0113077a2bc534ea43860b874afacdb0685550b7a64907721bec76 where it was assumed previously if we couldn't get it we should error out because it should still exist at that point to terraform before we delete it.
I don't think I mentioned this earlier. The main goal of this PR was to create a new resource called ibm_pi_instance_snapshot to replace the existing ibm_pi_snapshot because it called the instance snapshot api and not the snapshot api. I didn't touch any of the code or documentation in the snapshot ibm_pi_snapshot resource unless it was to add something new we needed (like user tags). I'm more than happy to make any tweaks to how this works, but I did not write this originally so I don't know why it was written this way. 🙂
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If I recall it correctly the delete api did not have a 404 return code hence we were relying on get api before deleting. If delete can return 404 we can remove the get call.
I'm not sure how that comment ended up there but this needs cleaning. That is why mentioned here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah I see, I'll double check it.
It looks like we have a 404 now, so I'll remove the check.