From 6c1e56253a672fe8ec396790bf28244597e57da9 Mon Sep 17 00:00:00 2001 From: Tamas Kiss Date: Sat, 8 Apr 2023 20:53:34 +0200 Subject: [PATCH] feat: allow setting capacity on external sources prompting volume resize fixes: #52 --- builder/libvirt/volume/external.go | 22 ++++++++++++++++++++++ builder/libvirt/volume/volume.go | 16 ++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/builder/libvirt/volume/external.go b/builder/libvirt/volume/external.go index 9e74110..72b445b 100644 --- a/builder/libvirt/volume/external.go +++ b/builder/libvirt/volume/external.go @@ -70,6 +70,8 @@ func (vs *ExternalVolumeSource) PrepareVolume(pctx *PreparationContext) multiste return pctx.HaltOnError(err, "preparing volume: %s", err) } + storageTargetCapacity := pctx.VolumeDefinition.Capacity + pctx.VolumeDefinition.Allocation = &libvirtxml.StorageVolumeSize{ Value: uint64(stat.Size()), Unit: "B", @@ -110,5 +112,25 @@ func (vs *ExternalVolumeSource) PrepareVolume(pctx *PreparationContext) multiste log.Printf("Error while refreshing volume definition: %s\n", err) } + if storageTargetCapacity != nil { + pctx.Ui.Message(fmt.Sprintf( + "Resizing volume %s/%s to meet capacity %d%s", + pctx.VolumeConfig.Pool, + pctx.VolumeConfig.Name, + storageTargetCapacity.Value, + storageTargetCapacity.Unit, + )) + multiplier, err := unitToMultiplier(storageTargetCapacity.Unit) + if err != nil { + return pctx.HaltOnError(err, "Error during volume resize: %s", err) + } + targetCapacityInBytes := storageTargetCapacity.Value * uint64(multiplier) + + err = pctx.Driver.StorageVolResize(*pctx.VolumeRef, targetCapacityInBytes, 0) + if err != nil { + return pctx.HaltOnError(err, "Error during volume resize: %s", err) + } + } + return multistep.ActionContinue } diff --git a/builder/libvirt/volume/volume.go b/builder/libvirt/volume/volume.go index 522dce6..8eaf7c6 100644 --- a/builder/libvirt/volume/volume.go +++ b/builder/libvirt/volume/volume.go @@ -275,3 +275,19 @@ func fmtReadPostfixedValue(s string) (value uint64, unit string, err error) { } return } + +func unitToMultiplier(unit string) (value int64, err error) { + switch unit { + case "B": + value = 1 + case "KiB": + value = 1024 + case "Mib": + value = 1024 * 1024 + case "Gib": + value = 1024 * 1024 * 1024 + default: + err = fmt.Errorf("unknown unit %s", unit) + } + return +}