Skip to content

Commit

Permalink
# This is a combination of 5 commits.
Browse files Browse the repository at this point in the history
# This is the 1st commit message:

fix(CLOUDDEV-574): up version go client to v2.0.22

# This is the commit message #2:

feat(CLOUDDEV-568): added file for test data source snapshot

# This is the commit message #3:

feat(CLOUDDEV-568): added file for test data source snapshot

# This is the commit message #4:

feat(CLOUDDEV-575): merge resource from Clouddev-568

# This is the commit message #5:

feat(CLOUDDEV-575): added uniq name for volume
  • Loading branch information
damir.zinatullin authored and Sergey Davydov committed Mar 7, 2024
1 parent d12f2d7 commit 10d1acc
Show file tree
Hide file tree
Showing 5 changed files with 296 additions and 3 deletions.
193 changes: 193 additions & 0 deletions edgecenter/data_source_edgecenter_snapshot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package edgecenter

import (
"context"
"log"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"

edgecloudV2 "github.com/Edge-Center/edgecentercloud-go/v2"
)

func dataSourceSnapshot() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceSnapshotRead,
Description: "Represent snapshot",
Schema: map[string]*schema.Schema{
"project_id": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
Description: "The uuid of the project. Either 'project_id' or 'project_name' must be specified.",
ExactlyOneOf: []string{"project_id", "project_name"},
},
"project_name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: "The name of the project. Either 'project_id' or 'project_name' must be specified.",
ExactlyOneOf: []string{"project_id", "project_name"},
},
"region_id": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
Description: "The uuid of the region. Either 'region_id' or 'region_name' must be specified.",
ExactlyOneOf: []string{"region_id", "region_name"},
},
"region_name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: "The name of the region. Either 'region_id' or 'region_name' must be specified.",
ExactlyOneOf: []string{"region_id", "region_name"},
},
"name": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: "The name of the snapshot. Use only with uniq name.",
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: "The ID of the snapshot.",
},
"description": {
Type: schema.TypeString,
Computed: true,
Description: "The description of the snapshot.",
},
"creator_task_id": {
Type: schema.TypeString,
Computed: true,
Description: "The task that created this entity.",
},
"status": {
Type: schema.TypeString,
Computed: true,
Description: "The status of the snapshot.",
},
"size": {
Type: schema.TypeInt,
Computed: true,
Description: "The size of the snapshot, GiB.",
},
"volume_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: "The ID of the volume this snapshot was made from.",
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
Description: "The datetime when the volume was last updated.",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "The datetime when the volume was created.",
},
"metadata": {
Type: schema.TypeMap,
Computed: true,
Description: "The metadata",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
}
}

func dataSourceSnapshotRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
log.Println("[DEBUG] Start snapshot reading")
var diags diag.Diagnostics
config := m.(*Config)
clientV2 := config.CloudClient

regionID, projectID, err := GetRegionIDandProjectID(ctx, clientV2, d)
if err != nil {
return diag.FromErr(err)
}

clientV2.Region = regionID
clientV2.Project = projectID

snapshotID := d.Get("snapshot_id").(string)
volumeID := d.Get("volume_id").(string)

log.Printf("[DEBUG] Snapshot id = %s", snapshotID)

if snapshotID != "" {
snapshot, _, err := clientV2.Snapshots.Get(ctx, snapshotID)
if err != nil {
return diag.Errorf("cannot get snapshot with ID %s. Error: %s", snapshotID, err.Error())
}

setSnapshotData(d, snapshot)

log.Println("[DEBUG] Finish snapshot reading")
return diags
}

name := d.Get("name").(string)
snapshotsOpts := &edgecloudV2.SnapshotListOptions{VolumeID: volumeID}

if name == "" && volumeID != "" {
return diag.Errorf("Name must be specified when VolumeID is provided")
}
allSnapshots, _, err := clientV2.Snapshots.List(ctx, snapshotsOpts)
if err != nil {
return diag.Errorf("cannot get snapshots. Error: %s", err.Error())
}

var foundSnapshots []*edgecloudV2.Snapshot
for _, s := range allSnapshots {
snapshot := s
if name == snapshot.Name {
foundSnapshots = append(foundSnapshots, &snapshot)
}
}

if len(foundSnapshots) == 0 {
return diag.Errorf("snapshot with name %s does not exist", name)
} else if len(foundSnapshots) > 1 {
return diag.Errorf("multiple snapshots found with name %s. Use snapshot_id instead of name.", name)
}

if volumeID != "" && foundSnapshots[0].VolumeID != volumeID {
return diag.Errorf("snapshot with name %s does not match the specified volume_id", name)
}

setSnapshotData(d, foundSnapshots[0])

log.Println("[DEBUG] Finish snapshot reading")

return diags
}

func setSnapshotData(d *schema.ResourceData, snapshot *edgecloudV2.Snapshot) {
var diags diag.Diagnostics
d.SetId(snapshot.ID)
d.Set("name", snapshot.Name)
d.Set("updated_at", snapshot.UpdatedAt)
d.Set("created_at", snapshot.CreatedAt)
d.Set("status", snapshot.Status)
d.Set("creator_task_id", snapshot.CreatorTaskID)
d.Set("size", snapshot.Size)
d.Set("volume_id", snapshot.VolumeID)
d.Set("description", snapshot.Description)
d.Set("snapshot_id", snapshot.ID)

if err := d.Set("metadata", snapshot.Metadata); err != nil {
_ = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to set metadata",
Detail: err.Error(),
})
}
}
1 change: 1 addition & 0 deletions edgecenter/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ func Provider() *schema.Provider {
"edgecenter_storage_s3_bucket": dataSourceStorageS3Bucket(),
"edgecenter_reservedfixedip": dataSourceReservedFixedIP(),
"edgecenter_servergroup": dataSourceServerGroup(),
"edgecenter_snapshot": dataSourceSnapshot(),
"edgecenter_k8s": dataSourceK8s(),
"edgecenter_k8s_pool": dataSourceK8sPool(),
"edgecenter_k8s_client_config": dataSourceK8sClientConfig(),
Expand Down
99 changes: 99 additions & 0 deletions edgecenter/test/data_source_edgecenter_snapshot_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
//go:build cloud_data_source

package edgecenter_test

import (
"context"
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"

edgecloudV2 "github.com/Edge-Center/edgecentercloud-go/v2"
utilV2 "github.com/Edge-Center/edgecentercloud-go/v2/util"
)

func TestAccSnapshotDataSource(t *testing.T) {
cfg, err := createTestConfig()
if err != nil {
t.Fatal(err)
}

ctx := context.Background()

volumeOpts := edgecloudV2.VolumeCreateRequest{
Name: "test-snapshot-volume",
Size: volumeSizeTest,
Source: edgecloudV2.VolumeSourceNewVolume,
TypeName: edgecloudV2.VolumeTypeStandard,
}

volumeID, err := createTestVolumeV2(ctx, cfg.CloudClient, &volumeOpts)
if err != nil {
t.Fatal(err)
}

snapshotOpts := edgecloudV2.SnapshotCreateRequest{
Name: "snapshot-" + volumeTestName,
VolumeID: volumeID,
}

taskResultCreate, err := utilV2.ExecuteAndExtractTaskResult(ctx, cfg.CloudClient.Snapshots.Create, &snapshotOpts, cfg.CloudClient)
if err != nil {
t.Fatal(err)
}

snapshotID := taskResultCreate.Snapshots[0]

resourceName := "data.edgecenter_snapshot.acctest"
tpl := func(name string) string {
return fmt.Sprintf(`
data "edgecenter_snapshot" "acctest" {
%s
%s
name = "%s"
}
`, projectInfo(), regionInfo(), name)
}

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviders,
Steps: []resource.TestStep{
{
Config: tpl(snapshotOpts.Name),
Check: resource.ComposeTestCheckFunc(
testAccCheckResourceExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "name", snapshotOpts.Name),
resource.TestCheckResourceAttr(resourceName, "snapshot_id", snapshotID),
),
},
},
})

taskSnapshotsDelete, _, err := cfg.CloudClient.Snapshots.Delete(ctx, snapshotID)
if err != nil {
t.Fatal(err)
}
_, err = utilV2.WaitAndGetTaskInfo(ctx, cfg.CloudClient, taskSnapshotsDelete.Tasks[0])
if err != nil {
t.Fatal(err)
}

if err := utilV2.ResourceIsDeleted(ctx, cfg.CloudClient.Snapshots.Get, snapshotID); err != nil {
t.Fatal(err)
}

taskVolumesDelete, _, err := cfg.CloudClient.Volumes.Delete(ctx, volumeID)
if err != nil {
t.Fatal(err)
}
_, err = utilV2.WaitAndGetTaskInfo(ctx, cfg.CloudClient, taskVolumesDelete.Tasks[0])
if err != nil {
t.Fatal(err)
}

if err := utilV2.ResourceIsDeleted(ctx, cfg.CloudClient.Volumes.Get, volumeID); err != nil {
t.Fatal(err)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ require (
github.com/Edge-Center/edgecenter-storage-sdk-go v0.2.0
github.com/Edge-Center/edgecentercdn-go v0.1.5
github.com/Edge-Center/edgecentercloud-go v0.1.11
github.com/Edge-Center/edgecentercloud-go/v2 v2.0.21
github.com/Edge-Center/edgecentercloud-go/v2 v2.0.22
github.com/hashicorp/go-cty v1.4.1-0.20200723130312-85980079f637
github.com/hashicorp/terraform-plugin-sdk/v2 v2.29.0
github.com/mitchellh/mapstructure v1.5.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ github.com/Edge-Center/edgecentercdn-go v0.1.5 h1:142aCMrAngvrlLSHyyPM4ZCztcvdRt
github.com/Edge-Center/edgecentercdn-go v0.1.5/go.mod h1:RwEyxwPAmxor1mZKUTa2bIU2p5qM6kcAofUkaE4O1V4=
github.com/Edge-Center/edgecentercloud-go v0.1.11 h1:00h5o/71lEoSdU1B4AWmviuOfO28P6nsRP+afjIsW80=
github.com/Edge-Center/edgecentercloud-go v0.1.11/go.mod h1:kmXGtx0lL1ib+SPfJe/uIAyDHamquAvqiftoLSyhxF8=
github.com/Edge-Center/edgecentercloud-go/v2 v2.0.21 h1:EqRT5D2XjG0exGUekUSRcHz3qkg9TgmA7q6UFQoPgJw=
github.com/Edge-Center/edgecentercloud-go/v2 v2.0.21/go.mod h1:cj8TzP0EqbLMmejj0uql3ZgpTCzsdrQipS/mBamU+bE=
github.com/Edge-Center/edgecentercloud-go/v2 v2.0.22 h1:9w/PkjypiGsFD5B4KRRkp29eIwHY2o8+Uo2aKybZa/8=
github.com/Edge-Center/edgecentercloud-go/v2 v2.0.22/go.mod h1:cj8TzP0EqbLMmejj0uql3ZgpTCzsdrQipS/mBamU+bE=
github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=
github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95 h1:KLq8BE0KwCL+mmXnjLWEAOYO+2l2AE4YMmqG1ZpZHBs=
github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95/go.mod h1:EjAoLdwvbIOoOQr3ihjnSoLZRtE8azugULFRteWMNc0=
Expand Down

0 comments on commit 10d1acc

Please sign in to comment.