Refactor method to reduce its Cognitive Complexity
Two functions are refactored and simplified in
pkg/virt-controller/watch/vm.go file: "handleVolumeRequests"
and "updateVirtualMachine".
Was detected by SonarCloud code scan as a code smell issue.
@@ -555,23 +555,25 @@ func (c *VMController) handleVolumeRequests(vm *virtv1.VirtualMachine, vmi *virt
for i, request := range vm.Status.VolumeRequests {
vmCopy.Spec.Template.Spec = *controller.ApplyVolumeRequestOnVMISpec(&vmCopy.Spec.Template.Spec, &vm.Status.VolumeRequests[i])
- if vmi != nil && vmi.DeletionTimestamp == nil {
- if request.AddVolumeOptions != nil {
- _, exists := vmiVolumeMap[request.AddVolumeOptions.Name]
- if !exists {
- err := c.clientset.VirtualMachineInstance(vmi.Namespace).AddVolume(vmi.Name, request.AddVolumeOptions)
- if err != nil {
- return err
+ if vmi == nil || vmi.DeletionTimestamp != nil {
+ continue
}
+
+ if request.AddVolumeOptions != nil {
+ if _, exists := vmiVolumeMap[request.AddVolumeOptions.Name]; exists {
+ continue
}
- } else if request.RemoveVolumeOptions != nil {
- _, exists := vmiVolumeMap[request.RemoveVolumeOptions.Name]
- if exists {
- err := c.clientset.VirtualMachineInstance(vmi.Namespace).RemoveVolume(vmi.Name, request.RemoveVolumeOptions)
- if err != nil {
+
+ if err := c.clientset.VirtualMachineInstance(vmi.Namespace).AddVolume(vmi.Name, request.AddVolumeOptions); err != nil {
return err
}
+ } else if request.RemoveVolumeOptions != nil {
+ if _, exists := vmiVolumeMap[request.RemoveVolumeOptions.Name]; !exists {
+ continue
}
+
+ if err := c.clientset.VirtualMachineInstance(vmi.Namespace).RemoveVolume(vmi.Name, request.RemoveVolumeOptions); err != nil {
+ return err
}
}
}
@@ -988,9 +990,12 @@ func (c *VMController) updateVirtualMachine(old, cur interface{}) {
return
}
- // Otherwise, it's an orphan. If anything changed, sync matching controllers
- // to see if anyone wants to adopt it now.
- if labelChanged || controllerRefChanged {
+ isOrphan := !labelChanged && !controllerRefChanged
+ if isOrphan {
+ return
+ }
+
+ // If anything changed, sync matching controllers to see if anyone wants to adopt it now.
vms := c.getMatchingControllers(curVMI)
if len(vms) == 0 {
return
@@ -1000,7 +1005,6 @@ func (c *VMController) updateVirtualMachine(old, cur interface{}) {
c.enqueueVm(vm)
}
}
-}
// When a vmi is deleted, enqueue the VirtualMachine that manages the vmi and update its expectations.
// obj could be an *v1.VirtualMachineInstance, or a DeletionFinalStateUnknown marker item.
