Skip to content
Merged
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
30 changes: 25 additions & 5 deletions cmd/virtwork/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -286,13 +286,17 @@ func runE(cmd *cobra.Command, args []string) error {
res := w.VMResources()

// Record workload in audit
dvTemplatesForAudit, err := w.DataVolumeTemplates()
if err != nil {
return fmt.Errorf("building data volume templates for %q: %w", name, err)
}
wlID, _ := auditor.RecordWorkload(ctx, execID, audit.WorkloadRecord{
WorkloadType: name,
Enabled: true,
VMCount: vmCount,
CPUCores: res.CPUCores,
Memory: res.Memory,
HasDataDisk: len(w.DataVolumeTemplates()) > 0,
HasDataDisk: len(dvTemplatesForAudit) > 0,
DataDiskSize: cfg.DataDiskSize,
RequiresService: w.RequiresService(),
})
Expand All @@ -308,8 +312,12 @@ func runE(cmd *cobra.Command, args []string) error {
vmName := fmt.Sprintf("virtwork-%s-%d", name, i)

// Namespace DataVolume names to avoid collisions across VMs
dvts, err := w.DataVolumeTemplates()
if err != nil {
return fmt.Errorf("building data volume templates for %q vm %s: %w", name, vmName, err)
}
dvTemplates, extraVols := namespaceDataVolumes(
w.DataVolumeTemplates(),
dvts,
w.ExtraVolumes(),
vmName,
)
Expand Down Expand Up @@ -359,8 +367,14 @@ func runE(cmd *cobra.Command, args []string) error {
}

// Namespace DataVolume names to avoid collisions across VMs
dvts, err := w.DataVolumeTemplates()
if err != nil {
return fmt.Errorf(
"building data volume templates for %q role %q vm %s: %w", name, role, vmName, err,
)
}
dvTemplates, extraVols := namespaceDataVolumes(
w.DataVolumeTemplates(),
dvts,
w.ExtraVolumes(),
vmName,
)
Expand Down Expand Up @@ -496,7 +510,10 @@ func runE(cmd *cobra.Command, args []string) error {
for _, plan := range plans {
p := plan // capture loop variable
g.Go(func() error {
vmObj := vm.BuildVMSpec(*p.vmSpec)
vmObj, err := vm.BuildVMSpec(*p.vmSpec)
if err != nil {
return fmt.Errorf("building VM spec for %q: %w", p.vmName, err)
}
if err := vm.CreateVM(gctx, c, vmObj); err != nil {
_ = auditor.RecordEvent(ctx, execID, audit.EventRecord{
EventType: "vm_failed",
Expand Down Expand Up @@ -746,7 +763,10 @@ func printDryRun(logger *slog.Logger, plans []vmPlan) error {
logger.Info("dry run mode", slog.Int("total_vms", len(plans)))

for _, p := range plans {
vmObj := vm.BuildVMSpec(*p.vmSpec)
vmObj, err := vm.BuildVMSpec(*p.vmSpec)
if err != nil {
return fmt.Errorf("building VM spec for %q: %w", p.vmName, err)
}
data, err := sigyaml.Marshal(vmObj)
if err != nil {
return fmt.Errorf("marshaling VM spec for %q: %w", p.vmName, err)
Expand Down
20 changes: 14 additions & 6 deletions cmd/virtwork/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ var _ = Describe("Run orchestration", func() {
Expect(err).NotTo(HaveOccurred())

res := w.VMResources()
vmSpec := vm.BuildVMSpec(vm.VMSpecOpts{
vmSpec, err := vm.BuildVMSpec(vm.VMSpecOpts{
Name: "virtwork-cpu-0",
Namespace: constants.DefaultNamespace,
ContainerDiskImage: constants.DefaultContainerDiskImage,
Expand All @@ -377,6 +377,7 @@ var _ = Describe("Run orchestration", func() {
constants.LabelComponent: "cpu",
},
})
Expect(err).NotTo(HaveOccurred())
Expect(vmSpec).NotTo(BeNil())
Expect(vmSpec.Name).To(Equal("virtwork-cpu-0"))
Expect(vmSpec.Namespace).To(Equal(constants.DefaultNamespace))
Expand All @@ -401,7 +402,7 @@ var _ = Describe("Run orchestration", func() {
Expect(err).NotTo(HaveOccurred())

res := w.VMResources()
vmSpec := vm.BuildVMSpec(vm.VMSpecOpts{
vmSpec, err := vm.BuildVMSpec(vm.VMSpecOpts{
Name: "virtwork-cpu-0",
Namespace: constants.DefaultNamespace,
ContainerDiskImage: constants.DefaultContainerDiskImage,
Expand All @@ -414,6 +415,7 @@ var _ = Describe("Run orchestration", func() {
constants.LabelComponent: "cpu",
},
})
Expect(err).NotTo(HaveOccurred())

// Verify spec can be marshaled (simulating dry-run output)
var buf bytes.Buffer
Expand Down Expand Up @@ -464,7 +466,7 @@ var _ = Describe("Run orchestration", func() {
Expect(err).NotTo(HaveOccurred())

res := w.VMResources()
vmSpec := vm.BuildVMSpec(vm.VMSpecOpts{
vmSpec, err := vm.BuildVMSpec(vm.VMSpecOpts{
Name: "virtwork-cpu-0",
Namespace: constants.DefaultNamespace,
ContainerDiskImage: constants.DefaultContainerDiskImage,
Expand All @@ -477,6 +479,7 @@ var _ = Describe("Run orchestration", func() {
constants.LabelComponent: "cpu",
},
})
Expect(err).NotTo(HaveOccurred())

err = vm.CreateVM(ctx, c, vmSpec)
Expect(err).NotTo(HaveOccurred())
Expand Down Expand Up @@ -718,7 +721,7 @@ var _ = Describe("CLI end-to-end scenarios", func() {
Expect(err).NotTo(HaveOccurred())

res := w.VMResources()
vmSpec := vm.BuildVMSpec(vm.VMSpecOpts{
vmSpec, err := vm.BuildVMSpec(vm.VMSpecOpts{
Name: "virtwork-cpu-0",
Namespace: constants.DefaultNamespace,
ContainerDiskImage: constants.DefaultContainerDiskImage,
Expand All @@ -731,6 +734,7 @@ var _ = Describe("CLI end-to-end scenarios", func() {
constants.LabelComponent: "cpu",
},
})
Expect(err).NotTo(HaveOccurred())

var buf bytes.Buffer
fmt.Fprintf(&buf, "--- Dry Run ---\n")
Expand Down Expand Up @@ -819,6 +823,7 @@ var _ = Describe("CLI end-to-end scenarios", func() {
})

var _ = Describe("DataVolume namespacing for multi-VM deployments", func() {
// nolint: dupl
Context("when deploying multiple VMs of disk workload", func() {
It("should return base DataVolume template name", func() {
registry := workloads.DefaultRegistry()
Expand All @@ -836,7 +841,8 @@ var _ = Describe("DataVolume namespacing for multi-VM deployments", func() {
)
Expect(err).NotTo(HaveOccurred())

dvTemplates := w.DataVolumeTemplates()
dvTemplates, err := w.DataVolumeTemplates()
Expect(err).NotTo(HaveOccurred())
Expect(dvTemplates).To(HaveLen(1))
Expect(dvTemplates[0].Name).To(Equal("virtwork-disk-data"))

Expand All @@ -846,6 +852,7 @@ var _ = Describe("DataVolume namespacing for multi-VM deployments", func() {
})
})

// nolint:dupl
Context("when deploying multiple VMs of database workload", func() {
It("should return base DataVolume template name", func() {
registry := workloads.DefaultRegistry()
Expand All @@ -863,7 +870,8 @@ var _ = Describe("DataVolume namespacing for multi-VM deployments", func() {
)
Expect(err).NotTo(HaveOccurred())

dvTemplates := w.DataVolumeTemplates()
dvTemplates, err := w.DataVolumeTemplates()
Expect(err).NotTo(HaveOccurred())
Expect(dvTemplates).To(HaveLen(1))
Expect(dvTemplates[0].Name).To(Equal("virtwork-database-data"))

Expand Down
12 changes: 9 additions & 3 deletions internal/cleanup/cleanup_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ var _ = Describe("CleanupAll [integration]", func() {

It("should delete VMs by managed-by label", func() {
opts := testutil.DefaultVMOpts("cleanup-vm-0", namespace)
Expect(vm.CreateVM(ctx, c, vm.BuildVMSpec(opts))).To(Succeed())
vmObj, err := vm.BuildVMSpec(opts)
Expect(err).NotTo(HaveOccurred())
Expect(vm.CreateVM(ctx, c, vmObj)).To(Succeed())

result, err := cleanup.CleanupAll(ctx, c, &config.Config{Namespace: namespace}, false, "")
Expect(err).NotTo(HaveOccurred())
Expand Down Expand Up @@ -127,7 +129,9 @@ var _ = Describe("CleanupAll [integration]", func() {
It("should report accurate counts for mixed resources", func() {
// Create a VM, a service, and a secret
opts := testutil.DefaultVMOpts("cleanup-mix-vm", namespace)
Expect(vm.CreateVM(ctx, c, vm.BuildVMSpec(opts))).To(Succeed())
vmObj, err := vm.BuildVMSpec(opts)
Expect(err).NotTo(HaveOccurred())
Expect(vm.CreateVM(ctx, c, vmObj)).To(Succeed())

svc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Expand Down Expand Up @@ -174,7 +178,9 @@ var _ = Describe("CleanupAll [integration]", func() {

It("should be idempotent when run twice", func() {
opts := testutil.DefaultVMOpts("cleanup-idem-vm", namespace)
Expect(vm.CreateVM(ctx, c, vm.BuildVMSpec(opts))).To(Succeed())
vmObj, err := vm.BuildVMSpec(opts)
Expect(err).NotTo(HaveOccurred())
Expect(vm.CreateVM(ctx, c, vmObj)).To(Succeed())

result1, err := cleanup.CleanupAll(ctx, c, &config.Config{Namespace: namespace}, false, "")
Expect(err).NotTo(HaveOccurred())
Expand Down
14 changes: 10 additions & 4 deletions internal/cleanup/cleanup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ var _ = Describe("PreviewCleanup", func() {
for _, el := range extraLabels {
maps.Copy(l, el)
}
return vm.BuildVMSpec(vm.VMSpecOpts{
v, err := vm.BuildVMSpec(vm.VMSpecOpts{
Name: name,
Namespace: namespace,
ContainerDiskImage: "test-image",
Expand All @@ -55,6 +55,8 @@ var _ = Describe("PreviewCleanup", func() {
Memory: "1Gi",
Labels: l,
})
Expect(err).NotTo(HaveOccurred())
return v
}

newManagedSecret := func(name string, extraLabels ...map[string]string) *corev1.Secret {
Expand Down Expand Up @@ -163,7 +165,7 @@ var _ = Describe("PreviewCleanup", func() {

It("should not count unmanaged resources", func() {
managedVM := newManagedVM("managed-vm")
unmanagedVM := vm.BuildVMSpec(vm.VMSpecOpts{
unmanagedVM, err := vm.BuildVMSpec(vm.VMSpecOpts{
Name: "unmanaged-vm",
Namespace: namespace,
ContainerDiskImage: "test-image",
Expand All @@ -174,6 +176,7 @@ var _ = Describe("PreviewCleanup", func() {
constants.LabelManagedBy: "other-tool",
},
})
Expect(err).NotTo(HaveOccurred())
c := fake.NewClientBuilder().
WithScheme(scheme).
WithObjects(managedVM, unmanagedVM).
Expand Down Expand Up @@ -226,7 +229,7 @@ var _ = Describe("CleanupAll", func() {
})

newManagedVM := func(name string) *kubevirtv1.VirtualMachine {
return vm.BuildVMSpec(vm.VMSpecOpts{
v, err := vm.BuildVMSpec(vm.VMSpecOpts{
Name: name,
Namespace: namespace,
ContainerDiskImage: "test-image",
Expand All @@ -235,6 +238,8 @@ var _ = Describe("CleanupAll", func() {
Memory: "1Gi",
Labels: labels,
})
Expect(err).NotTo(HaveOccurred())
return v
}

newManagedSecret := func(name string) *corev1.Secret {
Expand Down Expand Up @@ -476,7 +481,7 @@ var _ = Describe("CleanupAll", func() {
It("should use correct managed-by=virtwork label selector", func() {
// Create a managed VM and an unmanaged VM
managedVM := newManagedVM("managed-vm")
unmanagedVM := vm.BuildVMSpec(vm.VMSpecOpts{
unmanagedVM, err := vm.BuildVMSpec(vm.VMSpecOpts{
Name: "unmanaged-vm",
Namespace: namespace,
ContainerDiskImage: "test-image",
Expand All @@ -487,6 +492,7 @@ var _ = Describe("CleanupAll", func() {
constants.LabelManagedBy: "other-tool",
},
})
Expect(err).NotTo(HaveOccurred())
// Create a managed service and an unmanaged service
managedSvc := newManagedService("managed-svc")
unmanagedSvc := &corev1.Service{
Expand Down
23 changes: 17 additions & 6 deletions internal/vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type VMSpecOpts struct {
// BuildVMSpec constructs a KubeVirt VirtualMachine from the given options.
// It configures a containerDisk for the OS image, cloudInitNoCloud for userdata,
// masquerade networking, and virtio disk bus.
func BuildVMSpec(opts VMSpecOpts) *kubevirtv1.VirtualMachine {
func BuildVMSpec(opts VMSpecOpts) (*kubevirtv1.VirtualMachine, error) {
runStrategy := kubevirtv1.RunStrategyAlways

disks := []kubevirtv1.Disk{
Expand Down Expand Up @@ -98,6 +98,11 @@ func BuildVMSpec(opts VMSpecOpts) *kubevirtv1.VirtualMachine {
}
volumes = append(volumes, opts.ExtraVolumes...)

memQty, err := resource.ParseQuantity(opts.Memory)
if err != nil {
return nil, fmt.Errorf("invalid memory %q (expected a quantity like 512Mi, 2Gi, or 4G): %w", opts.Memory, err)
}

return &kubevirtv1.VirtualMachine{
TypeMeta: metav1.TypeMeta{
APIVersion: kubevirtv1.SchemeGroupVersion.String(),
Expand All @@ -122,7 +127,7 @@ func BuildVMSpec(opts VMSpecOpts) *kubevirtv1.VirtualMachine {
},
Resources: kubevirtv1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceMemory: resource.MustParse(opts.Memory),
corev1.ResourceMemory: memQty,
},
},
Devices: kubevirtv1.Devices{
Expand Down Expand Up @@ -150,12 +155,18 @@ func BuildVMSpec(opts VMSpecOpts) *kubevirtv1.VirtualMachine {
},
DataVolumeTemplates: opts.DataVolumeTemplates,
},
}
}, nil
}

// BuildDataVolumeTemplate constructs a DataVolumeTemplateSpec for a blank disk
// with the given name and size.
func BuildDataVolumeTemplate(name, size string) kubevirtv1.DataVolumeTemplateSpec {
func BuildDataVolumeTemplate(name, size string) (kubevirtv1.DataVolumeTemplateSpec, error) {
sizeQty, err := resource.ParseQuantity(size)
if err != nil {
return kubevirtv1.DataVolumeTemplateSpec{}, fmt.Errorf(
"invalid disk size %q (expected a quantity like 10Gi, 500Mi, or 1Ti): %w", size, err,
)
}
return kubevirtv1.DataVolumeTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Expand All @@ -167,12 +178,12 @@ func BuildDataVolumeTemplate(name, size string) kubevirtv1.DataVolumeTemplateSpe
Storage: &cdiv1beta1.StorageSpec{
Resources: corev1.VolumeResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceStorage: resource.MustParse(size),
corev1.ResourceStorage: sizeQty,
},
},
},
},
}
}, nil
}

// CreateVM creates a VirtualMachine. AlreadyExists errors are treated as
Expand Down
Loading
Loading