Skip to content
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

feat(instance_image): support block snapshots #2823

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ require (
github.com/nats-io/jwt/v2 v2.7.2
github.com/nats-io/nats.go v1.37.0
github.com/robfig/cron/v3 v3.0.1
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.30.0.20241028153617-2a48843b5fcb
github.com/stretchr/testify v1.10.0
golang.org/x/crypto v0.29.0
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.30.0.20241129094524-023aa8142bc1
github.com/stretchr/testify v1.9.0
golang.org/x/crypto v0.28.0
gopkg.in/dnaeon/go-vcr.v3 v3.2.0
)

Expand Down
16 changes: 8 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,8 @@ github.com/posener/complete v1.2.3 h1:NP0eAhjcjImqslEwo/1hq7gpajME0fTLTezBKDqfXq
github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.30.0.20241028153617-2a48843b5fcb h1:OsRpbw60numCy/+3FS7UhZzkdiTu6OZwq29bb4b3gNo=
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.30.0.20241028153617-2a48843b5fcb/go.mod h1:3jrRJM7638J+P33hKy9MBvfOBxNo8pEGNQQoIv65Ihg=
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.30.0.20241129094524-023aa8142bc1 h1:0OKzyRfLH+dWSPOBvwbhNcBTbEiuNkv8mdYGev1+/1g=
github.com/scaleway/scaleway-sdk-go v1.0.0-beta.30.0.20241129094524-023aa8142bc1/go.mod h1:kAoejOVBg1E/aVAR6IwKWEmbLCEg2IXklzPAkxzAaXA=
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8=
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
Expand All @@ -261,8 +261,8 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI=
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
Expand Down Expand Up @@ -306,8 +306,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ=
golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
Expand Down Expand Up @@ -353,8 +353,8 @@ golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
golang.org/x/term v0.26.0 h1:WEQa6V3Gja/BhNxg540hBip/kkaYtRg3cxg4oXSw4AU=
golang.org/x/term v0.26.0/go.mod h1:Si5m1o57C5nBNQo5z1iq+XDijt21BDBDp2bK0QI8e3E=
golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24=
golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
Expand Down
2 changes: 1 addition & 1 deletion internal/services/block/snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ func ResourceBlockSnapshotDelete(ctx context.Context, d *schema.ResourceData, m
return diag.FromErr(err)
}

_, err = waitForBlockSnapshot(ctx, api, zone, id, d.Timeout(schema.TimeoutDelete))
_, err = waitForBlockSnapshotToBeAvailable(ctx, api, zone, id, d.Timeout(schema.TimeoutDelete))
if err != nil {
return diag.FromErr(err)
}
Expand Down
19 changes: 19 additions & 0 deletions internal/services/block/waiters.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,22 @@ func waitForBlockSnapshot(ctx context.Context, blockAPI *block.API, zone scw.Zon

return snapshot, err
}

func waitForBlockSnapshotToBeAvailable(ctx context.Context, blockAPI *block.API, zone scw.Zone, id string, timeout time.Duration) (*block.Snapshot, error) {
retryInterval := defaultBlockRetryInterval
if transport.DefaultWaitRetryInterval != nil {
retryInterval = *transport.DefaultWaitRetryInterval
}

terminalStatus := block.SnapshotStatusAvailable
snapshot, err := blockAPI.WaitForSnapshot(&block.WaitForSnapshotRequest{
Zone: zone,
SnapshotID: id,
RetryInterval: &retryInterval,
Timeout: scw.TimeDurationPtr(timeout),

TerminalStatus: &terminalStatus,
}, scw.WithContext(ctx))

return snapshot, err
}
21 changes: 1 addition & 20 deletions internal/services/instance/helpers_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func reachState(ctx context.Context, api *BlockAndInstanceAPI, zone scw.Zone, se
if err != nil {
return err
}
} else if volume.State != instance.VolumeServerStateAvailable {
} else if volume.State != nil && *volume.State != instance.VolumeServerStateAvailable {
_, err = api.WaitForVolume(&instance.WaitForVolumeRequest{
Zone: zone,
VolumeID: volume.ID,
Expand Down Expand Up @@ -407,25 +407,6 @@ func (ph *privateNICsHandler) get(key string) (interface{}, error) {
}, nil
}

func getSnapshotsFromIDs(ctx context.Context, snapIDs []interface{}, instanceAPI *instance.API) ([]*instance.GetSnapshotResponse, error) {
snapResponses := []*instance.GetSnapshotResponse(nil)
for _, snapID := range snapIDs {
zone, id, err := zonal.ParseID(snapID.(string))
if err != nil {
return nil, err
}
snapshot, err := instanceAPI.GetSnapshot(&instance.GetSnapshotRequest{
Zone: zone,
SnapshotID: id,
}, scw.WithContext(ctx))
if err != nil {
return snapResponses, fmt.Errorf("extra volumes : could not find snapshot with id %s", snapID)
}
snapResponses = append(snapResponses, snapshot)
}
return snapResponses, nil
}

func formatImageLabel(imageUUID string) string {
return strings.ReplaceAll(imageUUID, "-", "_")
}
Expand Down
51 changes: 51 additions & 0 deletions internal/services/instance/helpers_instance_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ func (volume *UnknownVolume) IsAttached() bool {
return volume.ServerID != nil && *volume.ServerID != ""
}

type UnknownSnapshot struct {
Zone scw.Zone
ID string
Name string
VolumeType instance.VolumeVolumeType
}

func (api *BlockAndInstanceAPI) GetUnknownVolume(req *GetUnknownVolumeRequest, opts ...scw.RequestOption) (*UnknownVolume, error) {
getVolumeResponse, err := api.API.GetVolume(&instance.GetVolumeRequest{
Zone: req.Zone,
Expand Down Expand Up @@ -161,6 +168,50 @@ func (api *BlockAndInstanceAPI) ResizeUnknownVolume(req *ResizeUnknownVolumeRequ
return err
}

type GetUnknownSnapshotRequest struct {
Zone scw.Zone
SnapshotID string
}

func (api *BlockAndInstanceAPI) GetUnknownSnapshot(req *GetUnknownSnapshotRequest, opts ...scw.RequestOption) (*UnknownSnapshot, error) {
getSnapshotResponse, err := api.GetSnapshot(&instance.GetSnapshotRequest{
Zone: req.Zone,
SnapshotID: req.SnapshotID,
}, opts...)
notFoundErr := &scw.ResourceNotFoundError{}
if err != nil && !errors.As(err, &notFoundErr) {
return nil, err
}

if getSnapshotResponse != nil {
snap := &UnknownSnapshot{
Zone: getSnapshotResponse.Snapshot.Zone,
ID: getSnapshotResponse.Snapshot.ID,
Name: getSnapshotResponse.Snapshot.Name,
VolumeType: getSnapshotResponse.Snapshot.VolumeType,
}

return snap, nil
}

blockSnapshot, err := api.blockAPI.GetSnapshot(&block.GetSnapshotRequest{
Zone: req.Zone,
SnapshotID: req.SnapshotID,
}, opts...)
if err != nil {
return nil, err
}

snap := &UnknownSnapshot{
Zone: blockSnapshot.Zone,
ID: blockSnapshot.ID,
Name: blockSnapshot.Name,
VolumeType: instance.VolumeVolumeTypeSbsSnapshot,
}

return snap, nil
}

// newAPIWithZone returns a new instance API and the zone for a Create request
func instanceAndBlockAPIWithZone(d *schema.ResourceData, m interface{}) (*BlockAndInstanceAPI, scw.Zone, error) {
instanceAPI := instance.NewAPI(meta.ExtractScwClient(m))
Expand Down
29 changes: 11 additions & 18 deletions internal/services/instance/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/cdf"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/httperrors"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality/zonal"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/services/account"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/transport"
Expand Down Expand Up @@ -176,7 +177,7 @@ func ResourceImage() *schema.Resource {
}

func ResourceInstanceImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
instanceAPI, zone, err := newAPIWithZone(d, m)
api, zone, err := instanceAndBlockAPIWithZone(d, m)
if err != nil {
return diag.FromErr(err)
}
Expand All @@ -192,11 +193,7 @@ func ResourceInstanceImageCreate(ctx context.Context, d *schema.ResourceData, m

extraVolumesIDs, volumesExist := d.GetOk("additional_volume_ids")
if volumesExist {
snapResponses, err := getSnapshotsFromIDs(ctx, extraVolumesIDs.([]interface{}), instanceAPI)
if err != nil {
return diag.FromErr(err)
}
req.ExtraVolumes = expandImageExtraVolumesTemplates(snapResponses)
req.ExtraVolumes = expandImageExtraVolumesTemplates(locality.ExpandIDs(extraVolumesIDs))
}
tags, tagsExist := d.GetOk("tags")
if tagsExist {
Expand All @@ -206,14 +203,14 @@ func ResourceInstanceImageCreate(ctx context.Context, d *schema.ResourceData, m
req.Public = types.ExpandBoolPtr(types.GetBool(d, "public"))
}

res, err := instanceAPI.CreateImage(req, scw.WithContext(ctx))
res, err := api.CreateImage(req, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}

d.SetId(zonal.NewIDString(zone, res.Image.ID))

_, err = instanceAPI.WaitForImage(&instanceSDK.WaitForImageRequest{
_, err = api.WaitForImage(&instanceSDK.WaitForImageRequest{
ImageID: res.Image.ID,
Zone: zone,
RetryInterval: transport.DefaultWaitRetryInterval,
Expand Down Expand Up @@ -262,7 +259,7 @@ func ResourceInstanceImageRead(ctx context.Context, d *schema.ResourceData, m in
}

func ResourceInstanceImageUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
instanceAPI, zone, id, err := NewAPIWithZoneAndID(m, d.Id())
api, zone, id, err := instanceAndBlockAPIWithZoneAndID(m, d.Id())
if err != nil {
return diag.FromErr(err)
}
Expand All @@ -283,7 +280,7 @@ func ResourceInstanceImageUpdate(ctx context.Context, d *schema.ResourceData, m
}
req.Tags = types.ExpandUpdatedStringsPtr(d.Get("tags"))

image, err := instanceAPI.GetImage(&instanceSDK.GetImageRequest{
image, err := api.GetImage(&instanceSDK.GetImageRequest{
Zone: zone,
ImageID: id,
}, scw.WithContext(ctx))
Expand All @@ -292,11 +289,7 @@ func ResourceInstanceImageUpdate(ctx context.Context, d *schema.ResourceData, m
}

if d.HasChange("additional_volume_ids") {
snapResponses, err := getSnapshotsFromIDs(ctx, d.Get("additional_volume_ids").([]interface{}), instanceAPI)
if err != nil {
return diag.FromErr(err)
}
req.ExtraVolumes = expandImageExtraVolumesUpdateTemplates(snapResponses)
req.ExtraVolumes = expandImageExtraVolumesUpdateTemplates(locality.ExpandIDs(d.Get("additional_volume_ids")))
} else {
volTemplate := map[string]*instanceSDK.VolumeImageUpdateTemplate{}
for key, vol := range image.Image.ExtraVolumes {
Expand All @@ -315,17 +308,17 @@ func ResourceInstanceImageUpdate(ctx context.Context, d *schema.ResourceData, m
req.Arch = image.Image.Arch
}

_, err = waitForImage(ctx, instanceAPI, zone, id, d.Timeout(schema.TimeoutUpdate))
_, err = waitForImage(ctx, api.API, zone, id, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return diag.FromErr(err)
}

_, err = instanceAPI.UpdateImage(req, scw.WithContext(ctx))
_, err = api.UpdateImage(req, scw.WithContext(ctx))
if err != nil {
return diag.FromErr(fmt.Errorf("couldn't update image: %s", err))
}

_, err = waitForImage(ctx, instanceAPI, zone, id, d.Timeout(schema.TimeoutUpdate))
_, err = waitForImage(ctx, api.API, zone, id, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return diag.FromErr(err)
}
Expand Down
95 changes: 95 additions & 0 deletions internal/services/instance/image_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,101 @@ func TestAccImage_BlockVolume(t *testing.T) {
})
}

func TestAccImage_ExternalBlockVolume(t *testing.T) {
tt := acctest.NewTestTools(t)
defer tt.Cleanup()
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ProviderFactories: tt.ProviderFactories,
CheckDestroy: resource.ComposeTestCheckFunc(
isImageDestroyed(tt),
isSnapshotDestroyed(tt),
isVolumeDestroyed(tt),
),
Steps: []resource.TestStep{
{
Config: `
resource "scaleway_block_volume" "main" {
size_in_gb = 50
iops = 5000
}

resource "scaleway_block_snapshot" "main" {
volume_id = scaleway_block_volume.main.id
}
`,
},
{
Config: `
resource "scaleway_block_volume" "main" {
size_in_gb = 50
iops = 5000
}

resource "scaleway_block_volume" "additional1" {
size_in_gb = 50
iops = 5000
}

resource "scaleway_block_snapshot" "main" {
volume_id = scaleway_block_volume.main.id
}

resource "scaleway_block_snapshot" "additional1" {
volume_id = scaleway_block_volume.additional1.id
}

resource "scaleway_instance_image" "main" {
name = "tf-test-image-external-block-volume"
root_volume_id = scaleway_block_snapshot.main.id
additional_volume_ids = [scaleway_block_snapshot.additional1.id]
}
`,
Check: resource.ComposeTestCheckFunc(
instancechecks.DoesImageExists(tt, "scaleway_instance_image.main"),
resource.TestCheckResourceAttrPair("scaleway_instance_image.main", "root_volume_id", "scaleway_block_snapshot.main", "id"),
resource.TestCheckResourceAttr("scaleway_instance_image.main", "architecture", "x86_64"),
resource.TestCheckResourceAttr("scaleway_instance_image.main", "additional_volume_ids.#", "1"),
resource.TestCheckResourceAttrPair("scaleway_instance_image.main", "additional_volume_ids.0", "scaleway_block_snapshot.additional1", "id"),
),
},
{
Config: `
resource "scaleway_block_volume" "main" {
size_in_gb = 50
iops = 5000
}

resource "scaleway_block_volume" "additional1" {
size_in_gb = 50
iops = 5000
}

resource "scaleway_block_snapshot" "main" {
volume_id = scaleway_block_volume.main.id
}

resource "scaleway_block_snapshot" "additional1" {
volume_id = scaleway_block_volume.additional1.id
}

resource "scaleway_instance_image" "main" {
name = "tf-test-image-external-block-volume"
root_volume_id = scaleway_block_snapshot.main.id
additional_volume_ids = []
}
`,
Check: resource.ComposeTestCheckFunc(
instancechecks.DoesImageExists(tt, "scaleway_instance_image.main"),
resource.TestCheckResourceAttrPair("scaleway_instance_image.main", "root_volume_id", "scaleway_block_snapshot.main", "id"),
resource.TestCheckResourceAttr("scaleway_instance_image.main", "architecture", "x86_64"),
resource.TestCheckResourceAttr("scaleway_instance_image.main", "additional_volume_ids.#", "0"),
),
},
},
})
}

func TestAccImage_Server(t *testing.T) {
tt := acctest.NewTestTools(t)
defer tt.Cleanup()
Expand Down
Loading
Loading