From c6c0374e25fd6827b266d9460713c17de37da91d Mon Sep 17 00:00:00 2001 From: Daniil Antoshin Date: Fri, 22 Nov 2024 17:23:02 +0200 Subject: [PATCH] refactor(api): split common Signed-off-by: Daniil Antoshin fix: lint Signed-off-by: Daniil Antoshin fix: remove package Signed-off-by: Daniil Antoshin --- .../pkg/common/annotations/annotations.go | 136 +++++++++++++++ .../filter.go => common/array/array.go} | 27 ++- .../pkg/common/common.go | 113 +++---------- .../pkg/common/consts.go | 112 +++++++++++++ .../humanize_bytes/humanize_bytes.go} | 51 +----- .../humanize_bytes/humanize_bytes_test.go} | 2 +- .../pkg/{ => common}/imageformat/format.go | 0 .../common/ingress/{util.go => ingress.go} | 0 .../{controller/common => common/ip}/ip.go | 2 +- .../pkg/common/kvvm/{util.go => kvvm.go} | 4 +- .../pkg/common/{ => merger}/merger.go | 2 +- .../pkg/common/{ => merger}/merger_test.go | 2 +- .../util.go => common/object/object.go} | 30 +++- .../pkg/common/{ => percent}/percent.go | 2 +- .../pkg/common/{ => percent}/percent_test.go | 2 +- .../pkg/common/pod/{util.go => pod.go} | 63 +++++++ .../pkg/common/pointer/pointer.go | 38 +++++ .../pkg/common/pvc/{util.go => pvc.go} | 0 .../pkg/{util => common/pwgen}/pwgen.go | 2 +- .../resource_builder/builder.go} | 10 +- .../pkg/common/vm/{util.go => vm.go} | 0 .../pkg/config/load_dvcr_settings.go | 2 +- .../pkg/controller/common/util.go | 4 +- .../controller/cvi/internal/source/http.go | 13 +- .../cvi/internal/source/object_ref.go | 20 ++- .../cvi/internal/source/object_ref_vd.go | 18 +- .../internal/source/object_ref_vi_on_pvc.go | 11 +- .../cvi/internal/source/registry.go | 16 +- .../controller/cvi/internal/source/sources.go | 4 +- .../controller/cvi/internal/source/upload.go | 13 +- .../pkg/controller/dvcr_data_source.go | 16 +- .../pkg/controller/gc/cron_source.go | 6 +- .../pkg/controller/importer/importer_pod.go | 18 +- .../pkg/controller/importer/settings.go | 6 +- .../pkg/controller/ipam/ipam.go | 4 +- .../pkg/controller/kvbuilder/dv.go | 8 +- .../pkg/controller/kvbuilder/kvvm.go | 81 ++++----- .../pkg/controller/kvbuilder/kvvm_utils.go | 16 +- .../controller/kvbuilder/last_applied_spec.go | 6 +- .../pkg/controller/monitoring/final_report.go | 4 +- .../pkg/controller/monitoring/progress.go | 6 +- .../pkg/controller/powerstate/operations.go | 6 +- .../controller/service/attachment_service.go | 12 +- .../pkg/controller/service/disk_service.go | 32 ++-- .../controller/service/importer_service.go | 4 +- .../controller/service/ip_address_service.go | 6 +- .../service/ip_address_service_test.go | 6 +- .../controller/service/protection_service.go | 4 +- .../pkg/controller/service/resource.go | 4 +- .../controller/service/restorer/restorer.go | 8 +- .../controller/service/snapshot_service.go | 14 +- .../pkg/controller/service/stat_service.go | 16 +- .../controller/service/uploader_service.go | 10 +- .../pkg/controller/service/vm_operation.go | 8 +- .../supplements/copier/auth_secret.go | 4 +- .../supplements/copier/ca_bundle_cm.go | 14 +- .../controller/supplements/copier/secret.go | 14 +- .../pkg/controller/supplements/ensure.go | 6 +- .../controller/uploader/uploader_ingress.go | 12 +- .../pkg/controller/uploader/uploader_pod.go | 14 +- .../controller/uploader/uploader_service.go | 10 +- .../controller/vd/internal/source/blank.go | 11 +- .../pkg/controller/vd/internal/source/http.go | 20 ++- .../vd/internal/source/object_ref.go | 4 +- .../vd/internal/source/object_ref_cvi.go | 19 ++- .../internal/source/object_ref_vdsnapshot.go | 13 +- .../vd/internal/source/object_ref_vi_dvcr.go | 19 ++- .../vd/internal/source/object_ref_vi_pvc.go | 15 +- .../controller/vd/internal/source/registry.go | 23 +-- .../controller/vd/internal/source/sources.go | 4 +- .../controller/vd/internal/source/upload.go | 20 ++- .../pkg/controller/vd/internal/stats.go | 4 +- .../vd/internal/storageclass_ready.go | 4 +- .../validators/iso_source_validator.go | 2 +- .../internal/validators/pvc_size_validator.go | 10 +- .../internal/watcher/storageclass_watcher.go | 8 +- .../vd/internal/watcher/vdsnapshot_watcher.go | 4 +- .../pkg/controller/vi/internal/source/http.go | 24 +-- .../vi/internal/source/object_ref.go | 39 ++--- .../vi/internal/source/object_ref_vd.go | 30 ++-- .../internal/source/object_ref_vi_on_pvc.go | 23 +-- .../controller/vi/internal/source/registry.go | 27 +-- .../controller/vi/internal/source/sources.go | 6 +- .../controller/vi/internal/source/upload.go | 24 +-- .../vi/internal/storageclass_ready.go | 4 +- .../internal/watcher/storageclass_watcher.go | 8 +- .../controller/vm/internal/block_device.go | 2 +- .../vm/internal/deletion_handler.go | 4 +- .../pkg/controller/vm/internal/lifecycle.go | 4 +- .../pkg/controller/vm/internal/state/state.go | 22 +-- .../pkg/controller/vm/internal/sync_kvvm.go | 4 +- .../controller/vm/internal/sync_metadata.go | 22 +-- .../vm/internal/validators/ipam_validator.go | 6 +- .../controller/vmclass/internal/deletion.go | 4 +- .../vmclass/internal/state/state.go | 15 +- .../controller/vmclass/vmclass_reconciler.go | 13 +- .../vmip/internal/iplease_handler.go | 8 +- .../vmip/internal/lifecycle_handler.go | 6 +- .../controller/vmip/internal/state/state.go | 16 +- .../pkg/controller/vmip/internal/util/util.go | 8 +- .../vmiplease/internal/state/state.go | 4 +- .../vmiplease/vmiplease_reconciler.go | 4 +- .../controller/vmiplease/vmiplease_webhook.go | 4 +- .../pkg/controller/vmop/internal/lifecycle.go | 4 +- .../controller/vmop/internal/state/state.go | 4 +- .../vmrestore/internal/life_cycle.go | 8 +- .../internal/restorer/provisioner_restorer.go | 4 +- .../internal/restorer/vd_restorer.go | 4 +- .../internal/restorer/vm_restorer.go | 4 +- .../internal/restorer/vmbda_restorer.go | 4 +- .../internal/restorer/vmip_restorer.go | 4 +- .../internal/vm_snapshot_ready_to_use.go | 4 +- .../pkg/monitoring/metrics/vd/scraper.go | 4 +- .../metrics/virtualmachine/scraper.go | 12 +- .../pkg/monitoring/metrics/vmbda/scraper.go | 4 +- .../pkg/monitoring/metrics/vmop/scraper.go | 4 +- .../pkg/sdk/framework/helper/resource.go | 157 ------------------ .../two_phase_reconciler/reconciler_core.go | 118 ------------- .../two_phase_reconciler/reconciler_state.go | 45 ----- .../two_phase_reconciler.go | 31 ---- .../pkg/sdk/testutil/reconcile_executor.go | 50 ------ 121 files changed, 983 insertions(+), 1067 deletions(-) create mode 100644 images/virtualization-artifact/pkg/common/annotations/annotations.go rename images/virtualization-artifact/pkg/{controller/common/filter.go => common/array/array.go} (65%) create mode 100644 images/virtualization-artifact/pkg/common/consts.go rename images/virtualization-artifact/pkg/{util/util.go => common/humanize_bytes/humanize_bytes.go} (55%) rename images/virtualization-artifact/pkg/{util/util_test.go => common/humanize_bytes/humanize_bytes_test.go} (98%) rename images/virtualization-artifact/pkg/{ => common}/imageformat/format.go (100%) rename images/virtualization-artifact/pkg/common/ingress/{util.go => ingress.go} (100%) rename images/virtualization-artifact/pkg/{controller/common => common/ip}/ip.go (98%) rename images/virtualization-artifact/pkg/common/kvvm/{util.go => kvvm.go} (96%) rename images/virtualization-artifact/pkg/common/{ => merger}/merger.go (99%) rename images/virtualization-artifact/pkg/common/{ => merger}/merger_test.go (98%) rename images/virtualization-artifact/pkg/{sdk/framework/helper/util.go => common/object/object.go} (80%) rename images/virtualization-artifact/pkg/common/{ => percent}/percent.go (98%) rename images/virtualization-artifact/pkg/common/{ => percent}/percent_test.go (98%) rename images/virtualization-artifact/pkg/common/pod/{util.go => pod.go} (54%) create mode 100644 images/virtualization-artifact/pkg/common/pointer/pointer.go rename images/virtualization-artifact/pkg/common/pvc/{util.go => pvc.go} (100%) rename images/virtualization-artifact/pkg/{util => common/pwgen}/pwgen.go (98%) rename images/virtualization-artifact/pkg/{sdk/framework/helper/resource_builder.go => common/resource_builder/builder.go} (88%) rename images/virtualization-artifact/pkg/common/vm/{util.go => vm.go} (100%) delete mode 100644 images/virtualization-artifact/pkg/sdk/framework/helper/resource.go delete mode 100644 images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/reconciler_core.go delete mode 100644 images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/reconciler_state.go delete mode 100644 images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/two_phase_reconciler.go delete mode 100644 images/virtualization-artifact/pkg/sdk/testutil/reconcile_executor.go diff --git a/images/virtualization-artifact/pkg/common/annotations/annotations.go b/images/virtualization-artifact/pkg/common/annotations/annotations.go new file mode 100644 index 000000000..a7221cd17 --- /dev/null +++ b/images/virtualization-artifact/pkg/common/annotations/annotations.go @@ -0,0 +1,136 @@ +/* +Copyright 2024 Flant JSC + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package annotations + +import ( + "slices" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/deckhouse/virtualization-controller/pkg/common/merger" +) + +const ( + CVIShortName = "cvi" + VDShortName = "vd" + VIShortName = "vi" + + // AnnAPIGroup is the APIGroup for virtualization-controller. + AnnAPIGroup = "virt.deckhouse.io" + + // AnnCreatedBy is a pod annotation indicating if the pod was created by the PVC + AnnCreatedBy = AnnAPIGroup + "/storage.createdByController" + + // AnnPodRetainAfterCompletion is PVC annotation for retaining transfer pods after completion + AnnPodRetainAfterCompletion = AnnAPIGroup + "/storage.pod.retainAfterCompletion" + + // AnnUploadURL provides a const for CVMI/VMI/VMD uploadURL annotation + AnnUploadURL = AnnAPIGroup + "/upload.url" + + // AnnDefaultStorageClass is the annotation indicating that a storage class is the default one. + AnnDefaultStorageClass = "storageclass.kubernetes.io/is-default-class" + + AnnAPIGroupV = "virtualization.deckhouse.io" + AnnVirtualDisk = "virtualdisk." + AnnAPIGroupV + AnnVirtualDiskVolumeMode = AnnVirtualDisk + "/volume-mode" + AnnVirtualDiskAccessMode = AnnVirtualDisk + "/access-mode" + AnnVirtualDiskBindingMode = AnnVirtualDisk + "/binding-mode" + + // AnnVMLastAppliedSpec is an annotation on KVVM. It contains a JSON with VM spec. + AnnVMLastAppliedSpec = AnnAPIGroup + "/vm.last-applied-spec" + + // LastPropagatedVMAnnotationsAnnotation is a marshalled map of previously applied virtual machine annotations. + LastPropagatedVMAnnotationsAnnotation = AnnAPIGroup + "/last-propagated-vm-annotations" + // LastPropagatedVMLabelsAnnotation is a marshalled map of previously applied virtual machine labels. + LastPropagatedVMLabelsAnnotation = AnnAPIGroup + "/last-propagated-vm-labels" + + // LabelsPrefix is a prefix for virtualization-controller labels. + LabelsPrefix = "virtualization.deckhouse.io" + + // LabelVirtualMachineUID is a label to link VirtualMachineIPAddress to VirtualMachine. + LabelVirtualMachineUID = LabelsPrefix + "/virtual-machine-uid" + + UploaderServiceLabel = "service" + + // AppKubernetesManagedByLabel is the Kubernetes recommended managed-by label + AppKubernetesManagedByLabel = "app.kubernetes.io/managed-by" + // AppKubernetesComponentLabel is the Kubernetes recommended component label + AppKubernetesComponentLabel = "app.kubernetes.io/component" +) + +// AddAnnotation adds an annotation to an object +func AddAnnotation(obj metav1.Object, key, value string) { + if obj.GetAnnotations() == nil { + obj.SetAnnotations(make(map[string]string)) + } + obj.GetAnnotations()[key] = value +} + +// AddLabel adds a label to an object +func AddLabel(obj metav1.Object, key, value string) { + if obj.GetLabels() == nil { + obj.SetLabels(make(map[string]string)) + } + obj.GetLabels()[key] = value +} + +// IsBound returns if the pvc is bound +// SetRecommendedLabels sets the recommended labels on CDI resources (does not get rid of existing ones) +func SetRecommendedLabels(obj metav1.Object, installerLabels map[string]string, controllerName string) { + staticLabels := map[string]string{ + AppKubernetesManagedByLabel: controllerName, + AppKubernetesComponentLabel: "storage", + } + + // Merge existing labels with static labels and add installer dynamic labels as well (/version, /part-of). + mergedLabels := merger.MergeLabels(obj.GetLabels(), staticLabels, installerLabels) + + obj.SetLabels(mergedLabels) +} + +func MatchLabels(labels, matchLabels map[string]string) bool { + for key, value := range matchLabels { + if labels[key] != value { + return false + } + } + return true +} + +func MatchExpressions(labels map[string]string, expressions []metav1.LabelSelectorRequirement) bool { + for _, expr := range expressions { + switch expr.Operator { + case metav1.LabelSelectorOpIn: + if !slices.Contains(expr.Values, labels[expr.Key]) { + return false + } + case metav1.LabelSelectorOpNotIn: + if slices.Contains(expr.Values, labels[expr.Key]) { + return false + } + case metav1.LabelSelectorOpExists: + if _, ok := labels[expr.Key]; !ok { + return false + } + case metav1.LabelSelectorOpDoesNotExist: + if _, ok := labels[expr.Key]; ok { + return false + } + } + } + return true +} diff --git a/images/virtualization-artifact/pkg/controller/common/filter.go b/images/virtualization-artifact/pkg/common/array/array.go similarity index 65% rename from images/virtualization-artifact/pkg/controller/common/filter.go rename to images/virtualization-artifact/pkg/common/array/array.go index 2082d9a63..4a4b05075 100644 --- a/images/virtualization-artifact/pkg/controller/common/filter.go +++ b/images/virtualization-artifact/pkg/common/array/array.go @@ -14,11 +14,30 @@ See the License for the specific language governing permissions and limitations under the License. */ -package common +package array -import ( - "slices" -) +import "slices" + +// SetArrayElem performs idempotent insert of new elem or optionally replace if it exists +func SetArrayElem[T any](elems []T, newElem T, matchFunc func(v1, v2 T) bool, replaceExisting bool) (res []T) { + isFound := false + for _, elem := range elems { + if matchFunc(elem, newElem) { + if replaceExisting { + res = append(res, newElem) + } else { + res = append(res, elem) + } + isFound = true + } else { + res = append(res, elem) + } + } + if !isFound { + res = append(res, newElem) + } + return +} type FilterFunc[T any] func(obj *T) (keep bool) diff --git a/images/virtualization-artifact/pkg/common/common.go b/images/virtualization-artifact/pkg/common/common.go index 3bfbfe8a5..bf356dfb9 100644 --- a/images/virtualization-artifact/pkg/common/common.go +++ b/images/virtualization-artifact/pkg/common/common.go @@ -16,97 +16,26 @@ limitations under the License. package common -const ( - // FilesystemOverheadVar provides a constant to capture our env variable "FILESYSTEM_OVERHEAD" - FilesystemOverheadVar = "FILESYSTEM_OVERHEAD" - // OwnerUID provides the UID of the owner entity (either PVC or DV) - OwnerUID = "OWNER_UID" - - // ImporterContainerName provides a constant to use as a name for importer Container - ImporterContainerName = "importer" - // UploaderContainerName provides a constant to use as a name for uploader Container - UploaderContainerName = "uploader" - // UploaderPortName provides a constant to use as a port name for uploader Service - UploaderPortName = "uploader" - // UploaderPort provides a constant to use as a port for uploader Service - UploaderPort = 80 - // ImporterPodImageNameVar is a name of variable with the image name for the importer Pod - ImporterPodImageNameVar = "IMPORTER_IMAGE" - // UploaderPodImageNameVar is a name of variable with the image name for the uploader Pod - UploaderPodImageNameVar = "UPLOADER_IMAGE" - // ImporterCertDir is where the configmap containing certs will be mounted - ImporterCertDir = "/certs" - // ImporterProxyCertDir is where the configmap containing proxy certs will be mounted - ImporterProxyCertDir = "/proxycerts/" - - // ImporterSource provides a constant to capture our env variable "IMPORTER_SOURCE" - ImporterSource = "IMPORTER_SOURCE" - // ImporterContentType provides a constant to capture our env variable "IMPORTER_CONTENTTYPE" - ImporterContentType = "IMPORTER_CONTENTTYPE" - // ImporterEndpoint provides a constant to capture our env variable "IMPORTER_ENDPOINT" - ImporterEndpoint = "IMPORTER_ENDPOINT" - // ImporterAccessKeyID provides a constant to capture our env variable "IMPORTER_ACCES_KEY_ID" - ImporterAccessKeyID = "IMPORTER_ACCESS_KEY_ID" - // ImporterSecretKey provides a constant to capture our env variable "IMPORTER_SECRET_KEY" - ImporterSecretKey = "IMPORTER_SECRET_KEY" - // ImporterImageSize provides a constant to capture our env variable "IMPORTER_IMAGE_SIZE" - ImporterImageSize = "IMPORTER_IMAGE_SIZE" - // ImporterCertDirVar provides a constant to capture our env variable "IMPORTER_CERT_DIR" - ImporterCertDirVar = "IMPORTER_CERT_DIR" - // InsecureTLSVar provides a constant to capture our env variable "INSECURE_TLS" - InsecureTLSVar = "INSECURE_TLS" - // ImporterDiskID provides a constant to capture our env variable "IMPORTER_DISK_ID" - ImporterDiskID = "IMPORTER_DISK_ID" - // ImporterUUID provides a constant to capture our env variable "IMPORTER_UUID" - ImporterUUID = "IMPORTER_UUID" - // ImporterReadyFile provides a constant to capture our env variable "IMPORTER_READY_FILE" - ImporterReadyFile = "IMPORTER_READY_FILE" - // ImporterDoneFile provides a constant to capture our env variable "IMPORTER_DONE_FILE" - ImporterDoneFile = "IMPORTER_DONE_FILE" - // ImporterBackingFile provides a constant to capture our env variable "IMPORTER_BACKING_FILE" - ImporterBackingFile = "IMPORTER_BACKING_FILE" - // ImporterThumbprint provides a constant to capture our env variable "IMPORTER_THUMBPRINT" - ImporterThumbprint = "IMPORTER_THUMBPRINT" - // ImportProxyHTTP provides a constant to capture our env variable "http_proxy" - ImportProxyHTTP = "http_proxy" - // ImportProxyHTTPS provides a constant to capture our env variable "https_proxy" - ImportProxyHTTPS = "https_proxy" - // ImportProxyNoProxy provides a constant to capture our env variable "no_proxy" - ImportProxyNoProxy = "no_proxy" - // ImporterProxyCertDirVar provides a constant to capture our env variable "IMPORTER_PROXY_CERT_DIR" - ImporterProxyCertDirVar = "IMPORTER_PROXY_CERT_DIR" - // ImporterExtraHeader provides a constant to include extra HTTP headers, as the prefix to a format string - ImporterExtraHeader = "IMPORTER_EXTRA_HEADER_" - // ImporterSecretExtraHeadersDir is where the secrets containing extra HTTP headers will be mounted - ImporterSecretExtraHeadersDir = "/extraheaders" - - // ImporterDestinationAuthConfigDir is a mount directory for auth Secret. - ImporterDestinationAuthConfigDir = "/dvcr-auth" - // ImporterDestinationAuthConfigVar is an environment variable with auth config file for Importer Pod. - ImporterDestinationAuthConfigVar = "IMPORTER_DESTINATION_AUTH_CONFIG" - // ImporterDestinationAuthConfigFile is a path to auth config file in mount directory. - ImporterDestinationAuthConfigFile = "/dvcr-auth/.dockerconfigjson" - // DestinationInsecureTLSVar is an environment variable for Importer Pod that defines whether DVCR is insecure. - DestinationInsecureTLSVar = "DESTINATION_INSECURE_TLS" - ImporterSHA256Sum = "IMPORTER_SHA256SUM" - ImporterMD5Sum = "IMPORTER_MD5SUM" - ImporterAuthConfigVar = "IMPORTER_AUTH_CONFIG" - ImporterAuthConfigDir = "/dvcr-src-auth" - ImporterAuthConfigFile = "/dvcr-src-auth/.dockerconfigjson" - ImporterDestinationEndpoint = "IMPORTER_DESTINATION_ENDPOINT" - - UploaderDestinationEndpoint = "UPLOADER_DESTINATION_ENDPOINT" - UploaderDestinationAuthConfigVar = "UPLOADER_DESTINATION_AUTH_CONFIG" - UploaderExtraHeader = "UPLOADER_EXTRA_HEADER_" - UploaderDestinationAuthConfigDir = "/dvcr-auth" - UploaderDestinationAuthConfigFile = "/dvcr-auth/.dockerconfigjson" - UploaderSecretExtraHeadersDir = "/extraheaders" - - DockerRegistrySchemePrefix = "docker://" - - VmBlockDeviceAttachedLimit = 16 +import ( + "errors" + "strings" +) - CmpLesser = -1 - CmpEqual = 0 - CmpGreater = 1 +var ( + // ErrUnknownValue is a variable of type `error` that represents an error message indicating an unknown value. + ErrUnknownValue = errors.New("unknown value") + // ErrUnknownType is a variable of type `error` that represents an error message indicating an unknown type. + ErrUnknownType = errors.New("unknown type") ) + +// ErrQuotaExceeded checked is the error is of exceeded quota +func ErrQuotaExceeded(err error) bool { + return strings.Contains(err.Error(), "exceeded quota:") +} + +func BoolFloat64(b bool) float64 { + if b { + return 1 + } + return 0 +} diff --git a/images/virtualization-artifact/pkg/common/consts.go b/images/virtualization-artifact/pkg/common/consts.go new file mode 100644 index 000000000..3bfbfe8a5 --- /dev/null +++ b/images/virtualization-artifact/pkg/common/consts.go @@ -0,0 +1,112 @@ +/* +Copyright 2024 Flant JSC + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package common + +const ( + // FilesystemOverheadVar provides a constant to capture our env variable "FILESYSTEM_OVERHEAD" + FilesystemOverheadVar = "FILESYSTEM_OVERHEAD" + // OwnerUID provides the UID of the owner entity (either PVC or DV) + OwnerUID = "OWNER_UID" + + // ImporterContainerName provides a constant to use as a name for importer Container + ImporterContainerName = "importer" + // UploaderContainerName provides a constant to use as a name for uploader Container + UploaderContainerName = "uploader" + // UploaderPortName provides a constant to use as a port name for uploader Service + UploaderPortName = "uploader" + // UploaderPort provides a constant to use as a port for uploader Service + UploaderPort = 80 + // ImporterPodImageNameVar is a name of variable with the image name for the importer Pod + ImporterPodImageNameVar = "IMPORTER_IMAGE" + // UploaderPodImageNameVar is a name of variable with the image name for the uploader Pod + UploaderPodImageNameVar = "UPLOADER_IMAGE" + // ImporterCertDir is where the configmap containing certs will be mounted + ImporterCertDir = "/certs" + // ImporterProxyCertDir is where the configmap containing proxy certs will be mounted + ImporterProxyCertDir = "/proxycerts/" + + // ImporterSource provides a constant to capture our env variable "IMPORTER_SOURCE" + ImporterSource = "IMPORTER_SOURCE" + // ImporterContentType provides a constant to capture our env variable "IMPORTER_CONTENTTYPE" + ImporterContentType = "IMPORTER_CONTENTTYPE" + // ImporterEndpoint provides a constant to capture our env variable "IMPORTER_ENDPOINT" + ImporterEndpoint = "IMPORTER_ENDPOINT" + // ImporterAccessKeyID provides a constant to capture our env variable "IMPORTER_ACCES_KEY_ID" + ImporterAccessKeyID = "IMPORTER_ACCESS_KEY_ID" + // ImporterSecretKey provides a constant to capture our env variable "IMPORTER_SECRET_KEY" + ImporterSecretKey = "IMPORTER_SECRET_KEY" + // ImporterImageSize provides a constant to capture our env variable "IMPORTER_IMAGE_SIZE" + ImporterImageSize = "IMPORTER_IMAGE_SIZE" + // ImporterCertDirVar provides a constant to capture our env variable "IMPORTER_CERT_DIR" + ImporterCertDirVar = "IMPORTER_CERT_DIR" + // InsecureTLSVar provides a constant to capture our env variable "INSECURE_TLS" + InsecureTLSVar = "INSECURE_TLS" + // ImporterDiskID provides a constant to capture our env variable "IMPORTER_DISK_ID" + ImporterDiskID = "IMPORTER_DISK_ID" + // ImporterUUID provides a constant to capture our env variable "IMPORTER_UUID" + ImporterUUID = "IMPORTER_UUID" + // ImporterReadyFile provides a constant to capture our env variable "IMPORTER_READY_FILE" + ImporterReadyFile = "IMPORTER_READY_FILE" + // ImporterDoneFile provides a constant to capture our env variable "IMPORTER_DONE_FILE" + ImporterDoneFile = "IMPORTER_DONE_FILE" + // ImporterBackingFile provides a constant to capture our env variable "IMPORTER_BACKING_FILE" + ImporterBackingFile = "IMPORTER_BACKING_FILE" + // ImporterThumbprint provides a constant to capture our env variable "IMPORTER_THUMBPRINT" + ImporterThumbprint = "IMPORTER_THUMBPRINT" + // ImportProxyHTTP provides a constant to capture our env variable "http_proxy" + ImportProxyHTTP = "http_proxy" + // ImportProxyHTTPS provides a constant to capture our env variable "https_proxy" + ImportProxyHTTPS = "https_proxy" + // ImportProxyNoProxy provides a constant to capture our env variable "no_proxy" + ImportProxyNoProxy = "no_proxy" + // ImporterProxyCertDirVar provides a constant to capture our env variable "IMPORTER_PROXY_CERT_DIR" + ImporterProxyCertDirVar = "IMPORTER_PROXY_CERT_DIR" + // ImporterExtraHeader provides a constant to include extra HTTP headers, as the prefix to a format string + ImporterExtraHeader = "IMPORTER_EXTRA_HEADER_" + // ImporterSecretExtraHeadersDir is where the secrets containing extra HTTP headers will be mounted + ImporterSecretExtraHeadersDir = "/extraheaders" + + // ImporterDestinationAuthConfigDir is a mount directory for auth Secret. + ImporterDestinationAuthConfigDir = "/dvcr-auth" + // ImporterDestinationAuthConfigVar is an environment variable with auth config file for Importer Pod. + ImporterDestinationAuthConfigVar = "IMPORTER_DESTINATION_AUTH_CONFIG" + // ImporterDestinationAuthConfigFile is a path to auth config file in mount directory. + ImporterDestinationAuthConfigFile = "/dvcr-auth/.dockerconfigjson" + // DestinationInsecureTLSVar is an environment variable for Importer Pod that defines whether DVCR is insecure. + DestinationInsecureTLSVar = "DESTINATION_INSECURE_TLS" + ImporterSHA256Sum = "IMPORTER_SHA256SUM" + ImporterMD5Sum = "IMPORTER_MD5SUM" + ImporterAuthConfigVar = "IMPORTER_AUTH_CONFIG" + ImporterAuthConfigDir = "/dvcr-src-auth" + ImporterAuthConfigFile = "/dvcr-src-auth/.dockerconfigjson" + ImporterDestinationEndpoint = "IMPORTER_DESTINATION_ENDPOINT" + + UploaderDestinationEndpoint = "UPLOADER_DESTINATION_ENDPOINT" + UploaderDestinationAuthConfigVar = "UPLOADER_DESTINATION_AUTH_CONFIG" + UploaderExtraHeader = "UPLOADER_EXTRA_HEADER_" + UploaderDestinationAuthConfigDir = "/dvcr-auth" + UploaderDestinationAuthConfigFile = "/dvcr-auth/.dockerconfigjson" + UploaderSecretExtraHeadersDir = "/extraheaders" + + DockerRegistrySchemePrefix = "docker://" + + VmBlockDeviceAttachedLimit = 16 + + CmpLesser = -1 + CmpEqual = 0 + CmpGreater = 1 +) diff --git a/images/virtualization-artifact/pkg/util/util.go b/images/virtualization-artifact/pkg/common/humanize_bytes/humanize_bytes.go similarity index 55% rename from images/virtualization-artifact/pkg/util/util.go rename to images/virtualization-artifact/pkg/common/humanize_bytes/humanize_bytes.go index d5a64e097..50315a607 100644 --- a/images/virtualization-artifact/pkg/util/util.go +++ b/images/virtualization-artifact/pkg/common/humanize_bytes/humanize_bytes.go @@ -14,62 +14,13 @@ See the License for the specific language governing permissions and limitations under the License. */ -package util +package humanize_bytes import ( "fmt" "math" ) -func CopyByPointer[T any](objP *T) *T { - copyObj := *objP - return ©Obj -} - -func ToPointersArray[T any](items []T) (res []*T) { - for _, item := range items { - res = append(res, GetPointer(item)) - } - return -} - -func GetPointer[T any](obj T) *T { - return &obj -} - -func IsEmpty[T comparable](v T) bool { - var empty T - return v == empty -} - -// SetArrayElem performs idempotent insert of new elem or optionally replace if it exists -func SetArrayElem[T any](elems []T, newElem T, matchFunc func(v1, v2 T) bool, replaceExisting bool) (res []T) { - isFound := false - for _, elem := range elems { - if matchFunc(elem, newElem) { - if replaceExisting { - res = append(res, newElem) - } else { - res = append(res, elem) - } - isFound = true - } else { - res = append(res, elem) - } - } - if !isFound { - res = append(res, newElem) - } - return -} - -func BoolFloat64(b bool) float64 { - if b { - return 1 - } - return 0 -} - func HumanizeIBytes(s uint64) string { sizes := []string{"B", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei"} return humanateBytes(s, 1024, sizes) diff --git a/images/virtualization-artifact/pkg/util/util_test.go b/images/virtualization-artifact/pkg/common/humanize_bytes/humanize_bytes_test.go similarity index 98% rename from images/virtualization-artifact/pkg/util/util_test.go rename to images/virtualization-artifact/pkg/common/humanize_bytes/humanize_bytes_test.go index 905c6a2c1..782b8eec9 100644 --- a/images/virtualization-artifact/pkg/util/util_test.go +++ b/images/virtualization-artifact/pkg/common/humanize_bytes/humanize_bytes_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package util +package humanize_bytes import ( "testing" diff --git a/images/virtualization-artifact/pkg/imageformat/format.go b/images/virtualization-artifact/pkg/common/imageformat/format.go similarity index 100% rename from images/virtualization-artifact/pkg/imageformat/format.go rename to images/virtualization-artifact/pkg/common/imageformat/format.go diff --git a/images/virtualization-artifact/pkg/common/ingress/util.go b/images/virtualization-artifact/pkg/common/ingress/ingress.go similarity index 100% rename from images/virtualization-artifact/pkg/common/ingress/util.go rename to images/virtualization-artifact/pkg/common/ingress/ingress.go diff --git a/images/virtualization-artifact/pkg/controller/common/ip.go b/images/virtualization-artifact/pkg/common/ip/ip.go similarity index 98% rename from images/virtualization-artifact/pkg/controller/common/ip.go rename to images/virtualization-artifact/pkg/common/ip/ip.go index 1d1334194..a15ca4ba8 100644 --- a/images/virtualization-artifact/pkg/controller/common/ip.go +++ b/images/virtualization-artifact/pkg/common/ip/ip.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package common +package ip import ( "net" diff --git a/images/virtualization-artifact/pkg/common/kvvm/util.go b/images/virtualization-artifact/pkg/common/kvvm/kvvm.go similarity index 96% rename from images/virtualization-artifact/pkg/common/kvvm/util.go rename to images/virtualization-artifact/pkg/common/kvvm/kvvm.go index 8a23662f9..fd0edca0d 100644 --- a/images/virtualization-artifact/pkg/common/kvvm/util.go +++ b/images/virtualization-artifact/pkg/common/kvvm/kvvm.go @@ -26,7 +26,7 @@ import ( virtv1 "kubevirt.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/object" ) // PatchRunStrategy returns JSON merge patch to set 'runStrategy' field to the desired value @@ -96,5 +96,5 @@ func DeletePodByKVVMI(ctx context.Context, cli client.Client, kvvmi *virtv1.Virt if pod == nil { return nil } - return helper.DeleteObject(ctx, cli, pod, opts) + return object.DeleteObject(ctx, cli, pod, opts) } diff --git a/images/virtualization-artifact/pkg/common/merger.go b/images/virtualization-artifact/pkg/common/merger/merger.go similarity index 99% rename from images/virtualization-artifact/pkg/common/merger.go rename to images/virtualization-artifact/pkg/common/merger/merger.go index baf5fb49e..0fdfd8720 100644 --- a/images/virtualization-artifact/pkg/common/merger.go +++ b/images/virtualization-artifact/pkg/common/merger/merger.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package common +package merger // MergeLabels merges maps of labels into one map. // Labels in the first argument are diff --git a/images/virtualization-artifact/pkg/common/merger_test.go b/images/virtualization-artifact/pkg/common/merger/merger_test.go similarity index 98% rename from images/virtualization-artifact/pkg/common/merger_test.go rename to images/virtualization-artifact/pkg/common/merger/merger_test.go index b0f60e3f4..e049c7149 100644 --- a/images/virtualization-artifact/pkg/common/merger_test.go +++ b/images/virtualization-artifact/pkg/common/merger/merger_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package common +package merger import ( "testing" diff --git a/images/virtualization-artifact/pkg/sdk/framework/helper/util.go b/images/virtualization-artifact/pkg/common/object/object.go similarity index 80% rename from images/virtualization-artifact/pkg/sdk/framework/helper/util.go rename to images/virtualization-artifact/pkg/common/object/object.go index 9b835c13d..9e756bddc 100644 --- a/images/virtualization-artifact/pkg/sdk/framework/helper/util.go +++ b/images/virtualization-artifact/pkg/common/object/object.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package helper +package object import ( "context" @@ -23,8 +23,11 @@ import ( "time" k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" ) func FetchObject[T client.Object](ctx context.Context, key types.NamespacedName, client client.Client, obj T, opts ...client.GetOption) (T, error) { @@ -124,3 +127,28 @@ func CleanupByName(ctx context.Context, client client.Client, key client.ObjectK func GetAge(obj client.Object) time.Duration { return time.Since(obj.GetCreationTimestamp().Time).Truncate(time.Second) } + +// ShouldCleanupSubResources returns whether sub resources should be deleted: +// - CVMI, VMI has no annotation to retain pod after import +// - CVMI, VMI is deleted +func ShouldCleanupSubResources(obj metav1.Object) bool { + return obj.GetAnnotations()[annotations.AnnPodRetainAfterCompletion] != "true" || obj.GetDeletionTimestamp() != nil +} + +func IsTerminating(obj client.Object) bool { + return !reflect.ValueOf(obj).IsNil() && obj.GetDeletionTimestamp() != nil +} + +func AnyTerminating(objs ...client.Object) bool { + for _, obj := range objs { + if IsTerminating(obj) { + return true + } + } + + return false +} + +func NamespacedName(obj client.Object) types.NamespacedName { + return types.NamespacedName{Name: obj.GetName(), Namespace: obj.GetNamespace()} +} diff --git a/images/virtualization-artifact/pkg/common/percent.go b/images/virtualization-artifact/pkg/common/percent/percent.go similarity index 98% rename from images/virtualization-artifact/pkg/common/percent.go rename to images/virtualization-artifact/pkg/common/percent/percent.go index d1617abde..e4c184d81 100644 --- a/images/virtualization-artifact/pkg/common/percent.go +++ b/images/virtualization-artifact/pkg/common/percent/percent.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package common +package percent import ( "fmt" diff --git a/images/virtualization-artifact/pkg/common/percent_test.go b/images/virtualization-artifact/pkg/common/percent/percent_test.go similarity index 98% rename from images/virtualization-artifact/pkg/common/percent_test.go rename to images/virtualization-artifact/pkg/common/percent/percent_test.go index 059b21787..a300ee49a 100644 --- a/images/virtualization-artifact/pkg/common/percent_test.go +++ b/images/virtualization-artifact/pkg/common/percent/percent_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package common +package percent import ( "fmt" diff --git a/images/virtualization-artifact/pkg/common/pod/util.go b/images/virtualization-artifact/pkg/common/pod/pod.go similarity index 54% rename from images/virtualization-artifact/pkg/common/pod/util.go rename to images/virtualization-artifact/pkg/common/pod/pod.go index c8c39aac1..2a1c19bff 100644 --- a/images/virtualization-artifact/pkg/common/pod/util.go +++ b/images/virtualization-artifact/pkg/common/pod/pod.go @@ -19,6 +19,7 @@ package pod import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" ) // MakeOwnerReference makes owner reference from a Pod @@ -76,3 +77,65 @@ func AddVolumeDevice(pod *corev1.Pod, container *corev1.Container, volume corev1 pod.Spec.Volumes = append(pod.Spec.Volumes, volume) container.VolumeDevices = append(container.VolumeDevices, volumeDevice) } + +// IsPodRunning returns true if a Pod is in 'Running' phase, false if not. +func IsPodRunning(pod *corev1.Pod) bool { + return pod != nil && pod.Status.Phase == corev1.PodRunning +} + +// IsPodStarted returns true if a Pod is in started state, false if not. +func IsPodStarted(pod *corev1.Pod) bool { + if pod == nil || pod.Status.StartTime == nil { + return false + } + + for _, cs := range pod.Status.ContainerStatuses { + if cs.Started == nil || !*cs.Started { + return false + } + } + + return true +} + +// IsPodComplete returns true if a Pod is in 'Succeeded' phase, false if not. +func IsPodComplete(pod *corev1.Pod) bool { + return pod != nil && pod.Status.Phase == corev1.PodSucceeded +} + +// QemuSubGid is the gid used as the qemu group in fsGroup +const QemuSubGid = int64(107) + +// SetRestrictedSecurityContext sets the pod security params to be compatible with restricted PSA +func SetRestrictedSecurityContext(podSpec *corev1.PodSpec) { + hasVolumeMounts := false + for _, containers := range [][]corev1.Container{podSpec.InitContainers, podSpec.Containers} { + for i := range containers { + container := &containers[i] + if container.SecurityContext == nil { + container.SecurityContext = &corev1.SecurityContext{} + } + container.SecurityContext.Capabilities = &corev1.Capabilities{ + Drop: []corev1.Capability{ + "ALL", + }, + } + container.SecurityContext.SeccompProfile = &corev1.SeccompProfile{ + Type: corev1.SeccompProfileTypeRuntimeDefault, + } + container.SecurityContext.AllowPrivilegeEscalation = ptr.To(false) + container.SecurityContext.RunAsNonRoot = ptr.To(true) + container.SecurityContext.RunAsUser = ptr.To(QemuSubGid) + if len(container.VolumeMounts) > 0 { + hasVolumeMounts = true + } + } + } + + if hasVolumeMounts { + if podSpec.SecurityContext == nil { + podSpec.SecurityContext = &corev1.PodSecurityContext{} + } + podSpec.SecurityContext.FSGroup = ptr.To(QemuSubGid) + } +} diff --git a/images/virtualization-artifact/pkg/common/pointer/pointer.go b/images/virtualization-artifact/pkg/common/pointer/pointer.go new file mode 100644 index 000000000..07280eb87 --- /dev/null +++ b/images/virtualization-artifact/pkg/common/pointer/pointer.go @@ -0,0 +1,38 @@ +/* +Copyright 2024 Flant JSC + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package pointer + +func CopyByPointer[T any](objP *T) *T { + copyObj := *objP + return ©Obj +} + +func ToPointersArray[T any](items []T) (res []*T) { + for _, item := range items { + res = append(res, GetPointer(item)) + } + return +} + +func GetPointer[T any](obj T) *T { + return &obj +} + +func IsEmpty[T comparable](v T) bool { + var empty T + return v == empty +} diff --git a/images/virtualization-artifact/pkg/common/pvc/util.go b/images/virtualization-artifact/pkg/common/pvc/pvc.go similarity index 100% rename from images/virtualization-artifact/pkg/common/pvc/util.go rename to images/virtualization-artifact/pkg/common/pvc/pvc.go diff --git a/images/virtualization-artifact/pkg/util/pwgen.go b/images/virtualization-artifact/pkg/common/pwgen/pwgen.go similarity index 98% rename from images/virtualization-artifact/pkg/util/pwgen.go rename to images/virtualization-artifact/pkg/common/pwgen/pwgen.go index 3dd1e8fd4..23317d2e6 100644 --- a/images/virtualization-artifact/pkg/util/pwgen.go +++ b/images/virtualization-artifact/pkg/common/pwgen/pwgen.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package util +package pwgen import "crypto/rand" diff --git a/images/virtualization-artifact/pkg/sdk/framework/helper/resource_builder.go b/images/virtualization-artifact/pkg/common/resource_builder/builder.go similarity index 88% rename from images/virtualization-artifact/pkg/sdk/framework/helper/resource_builder.go rename to images/virtualization-artifact/pkg/common/resource_builder/builder.go index 57eb38422..6c8fb2d3f 100644 --- a/images/virtualization-artifact/pkg/sdk/framework/helper/resource_builder.go +++ b/images/virtualization-artifact/pkg/common/resource_builder/builder.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package helper +package resource_builder import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -22,8 +22,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" - "github.com/deckhouse/virtualization-controller/pkg/util" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/array" ) type ResourceBuilderOptions struct { @@ -47,7 +47,7 @@ func (b *ResourceBuilder[T]) SetOwnerRef(obj metav1.Object, gvk schema.GroupVers } func (b *ResourceBuilder[T]) AddAnnotation(annotation, value string) { - common.AddAnnotation(b.Resource, annotation, value) + annotations.AddAnnotation(b.Resource, annotation, value) } func (b *ResourceBuilder[T]) AddFinalizer(finalizer string) { @@ -63,7 +63,7 @@ func (b *ResourceBuilder[T]) IsResourceExists() bool { } func SetOwnerRef(obj metav1.Object, ref metav1.OwnerReference) bool { - newOwnerRefs := util.SetArrayElem( + newOwnerRefs := array.SetArrayElem( obj.GetOwnerReferences(), ref, func(v1, v2 metav1.OwnerReference) bool { diff --git a/images/virtualization-artifact/pkg/common/vm/util.go b/images/virtualization-artifact/pkg/common/vm/vm.go similarity index 100% rename from images/virtualization-artifact/pkg/common/vm/util.go rename to images/virtualization-artifact/pkg/common/vm/vm.go diff --git a/images/virtualization-artifact/pkg/config/load_dvcr_settings.go b/images/virtualization-artifact/pkg/config/load_dvcr_settings.go index 98c20b3ed..04f92818a 100644 --- a/images/virtualization-artifact/pkg/config/load_dvcr_settings.go +++ b/images/virtualization-artifact/pkg/config/load_dvcr_settings.go @@ -24,7 +24,7 @@ import ( ) const ( - // DVCRAddressVar is an env variable holds address to DVCR registry. + // DVCRRegistryURLVar is an env variable holds address to DVCR registry. DVCRRegistryURLVar = "DVCR_REGISTRY_URL" // DVCRAuthSecretVar is an env variable holds the name of the Secret with DVCR auth credentials. DVCRAuthSecretVar = "DVCR_AUTH_SECRET" diff --git a/images/virtualization-artifact/pkg/controller/common/util.go b/images/virtualization-artifact/pkg/controller/common/util.go index 6e3b73426..a26792231 100644 --- a/images/virtualization-artifact/pkg/controller/common/util.go +++ b/images/virtualization-artifact/pkg/controller/common/util.go @@ -29,7 +29,7 @@ import ( cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/merger" ) const ( @@ -214,7 +214,7 @@ func SetRecommendedLabels(obj metav1.Object, installerLabels map[string]string, } // Merge existing labels with static labels and add installer dynamic labels as well (/version, /part-of). - mergedLabels := common.MergeLabels(obj.GetLabels(), staticLabels, installerLabels) + mergedLabels := merger.MergeLabels(obj.GetLabels(), staticLabels, installerLabels) obj.SetLabels(mergedLabels) } diff --git a/images/virtualization-artifact/pkg/controller/cvi/internal/source/http.go b/images/virtualization-artifact/pkg/controller/cvi/internal/source/http.go index 52e89b55d..92d677057 100644 --- a/images/virtualization-artifact/pkg/controller/cvi/internal/source/http.go +++ b/images/virtualization-artifact/pkg/controller/cvi/internal/source/http.go @@ -24,8 +24,11 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" @@ -69,7 +72,7 @@ func (ds HTTPDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualIma } }() - supgen := supplements.NewGenerator(common.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -92,7 +95,7 @@ func (ds HTTPDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualIma } return CleanUp(ctx, cvi, ds) - case common.IsTerminating(pod): + case object.IsTerminating(pod): cvi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -119,7 +122,7 @@ func (ds HTTPDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualIma log.Info("Create importer pod...", "progress", cvi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { cvi.Status.Phase = virtv2.ImageFailed @@ -190,7 +193,7 @@ func (ds HTTPDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualIma } func (ds HTTPDataSource) CleanUp(ctx context.Context, cvi *virtv2.ClusterVirtualImage) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) requeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { diff --git a/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref.go b/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref.go index 249a3859b..606f78204 100644 --- a/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref.go +++ b/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref.go @@ -26,16 +26,18 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/cvicondition" ) @@ -85,7 +87,7 @@ func (ds ObjectRefDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtu switch cvi.Spec.DataSource.ObjectRef.Kind { case virtv2.VirtualImageKind: viKey := types.NamespacedName{Name: cvi.Spec.DataSource.ObjectRef.Name, Namespace: cvi.Spec.DataSource.ObjectRef.Namespace} - vi, err := helper.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) + vi, err := object.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) if err != nil { return reconcile.Result{}, fmt.Errorf("unable to get VI %s: %w", viKey, err) } @@ -99,7 +101,7 @@ func (ds ObjectRefDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtu } case virtv2.VirtualDiskKind: vdKey := types.NamespacedName{Name: cvi.Spec.DataSource.ObjectRef.Name, Namespace: cvi.Spec.DataSource.ObjectRef.Namespace} - vd, err := helper.FetchObject(ctx, vdKey, ds.client, &virtv2.VirtualDisk{}) + vd, err := object.FetchObject(ctx, vdKey, ds.client, &virtv2.VirtualDisk{}) if err != nil { return reconcile.Result{}, fmt.Errorf("unable to get VD %s: %w", vdKey, err) } @@ -111,7 +113,7 @@ func (ds ObjectRefDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtu return ds.vdSyncer.Sync(ctx, cvi, vd, cb) } - supgen := supplements.NewGenerator(common.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -135,7 +137,7 @@ func (ds ObjectRefDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtu } return CleanUp(ctx, cvi, ds) - case common.IsTerminating(pod): + case object.IsTerminating(pod): cvi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -172,7 +174,7 @@ func (ds ObjectRefDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtu log.Info("Ready", "progress", cvi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { cvi.Status.Phase = virtv2.ImageFailed @@ -265,7 +267,7 @@ func (ds ObjectRefDataSource) CleanUp(ctx context.Context, cvi *virtv2.ClusterVi return reconcile.Result{}, err } - supgen := supplements.NewGenerator(common.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) objRefRequeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { @@ -283,7 +285,7 @@ func (ds ObjectRefDataSource) Validate(ctx context.Context, cvi *virtv2.ClusterV switch cvi.Spec.DataSource.ObjectRef.Kind { case virtv2.ClusterVirtualImageObjectRefKindVirtualImage: viKey := types.NamespacedName{Name: cvi.Spec.DataSource.ObjectRef.Name, Namespace: cvi.Spec.DataSource.ObjectRef.Namespace} - vi, err := helper.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) + vi, err := object.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) if err != nil { return fmt.Errorf("unable to get VI %s: %w", viKey, err) } diff --git a/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref_vd.go b/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref_vd.go index 590ca373b..2c28b48f6 100644 --- a/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref_vd.go +++ b/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref_vd.go @@ -26,15 +26,17 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/cvicondition" ) @@ -60,7 +62,7 @@ func NewObjectRefVirtualDisk(importerService Importer, client client.Client, con func (ds ObjectRefVirtualDisk) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualImage, vdRef *virtv2.VirtualDisk, cb *conditions.ConditionBuilder) (reconcile.Result, error) { log, ctx := logger.GetDataSourceContext(ctx, "objectref") - supgen := supplements.NewGenerator(cc.CVIShortName, cvi.Name, vdRef.Namespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, vdRef.Namespace, cvi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -83,7 +85,7 @@ func (ds ObjectRefVirtualDisk) Sync(ctx context.Context, cvi *virtv2.ClusterVirt } return CleanUp(ctx, cvi, ds) - case cc.IsTerminating(pod): + case object.IsTerminating(pod): cvi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -99,7 +101,7 @@ func (ds ObjectRefVirtualDisk) Sync(ctx context.Context, cvi *virtv2.ClusterVirt switch { case err == nil: // OK. - case cc.ErrQuotaExceeded(err): + case common.ErrQuotaExceeded(err): return setQuotaExceededPhaseCondition(cb, &cvi.Status.Phase, err, cvi.CreationTimestamp), nil default: setPhaseConditionToFailed(cb, &cvi.Status.Phase, fmt.Errorf("unexpected error: %w", err)) @@ -115,7 +117,7 @@ func (ds ObjectRefVirtualDisk) Sync(ctx context.Context, cvi *virtv2.ClusterVirt log.Info("Create importer pod...", "progress", cvi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case cc.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { cvi.Status.Phase = virtv2.ImageFailed @@ -215,7 +217,7 @@ func (ds ObjectRefVirtualDisk) Validate(ctx context.Context, cvi *virtv2.Cluster return fmt.Errorf("not a %s data source", virtv2.ClusterVirtualImageObjectRefKindVirtualDisk) } - vd, err := helper.FetchObject(ctx, types.NamespacedName{Name: cvi.Spec.DataSource.ObjectRef.Name, Namespace: cvi.Spec.DataSource.ObjectRef.Namespace}, ds.client, &virtv2.VirtualDisk{}) + vd, err := object.FetchObject(ctx, types.NamespacedName{Name: cvi.Spec.DataSource.ObjectRef.Name, Namespace: cvi.Spec.DataSource.ObjectRef.Namespace}, ds.client, &virtv2.VirtualDisk{}) if err != nil { return err } @@ -227,7 +229,7 @@ func (ds ObjectRefVirtualDisk) Validate(ctx context.Context, cvi *virtv2.Cluster if len(vd.Status.AttachedToVirtualMachines) != 0 { vmName := vd.Status.AttachedToVirtualMachines[0] - vm, err := helper.FetchObject(ctx, types.NamespacedName{Name: vmName.Name, Namespace: vd.Namespace}, ds.client, &virtv2.VirtualMachine{}) + vm, err := object.FetchObject(ctx, types.NamespacedName{Name: vmName.Name, Namespace: vd.Namespace}, ds.client, &virtv2.VirtualMachine{}) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref_vi_on_pvc.go b/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref_vi_on_pvc.go index c8998c8e3..e275575eb 100644 --- a/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref_vi_on_pvc.go +++ b/images/virtualization-artifact/pkg/controller/cvi/internal/source/object_ref_vi_on_pvc.go @@ -24,8 +24,11 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" @@ -55,7 +58,7 @@ func NewObjectRefVirtualImageOnPvc(importerService Importer, dvcrSettings *dvcr. func (ds ObjectRefVirtualImageOnPvc) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualImage, viRef *virtv2.VirtualImage, cb *conditions.ConditionBuilder) (reconcile.Result, error) { log, ctx := logger.GetDataSourceContext(ctx, "objectref") - supgen := supplements.NewGenerator(common.CVIShortName, cvi.Name, viRef.Namespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, viRef.Namespace, cvi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -78,7 +81,7 @@ func (ds ObjectRefVirtualImageOnPvc) Sync(ctx context.Context, cvi *virtv2.Clust } return CleanUp(ctx, cvi, ds) - case common.IsTerminating(pod): + case object.IsTerminating(pod): cvi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -110,7 +113,7 @@ func (ds ObjectRefVirtualImageOnPvc) Sync(ctx context.Context, cvi *virtv2.Clust log.Info("Create importer pod...", "progress", cvi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { cvi.Status.Phase = virtv2.ImageFailed diff --git a/images/virtualization-artifact/pkg/controller/cvi/internal/source/registry.go b/images/virtualization-artifact/pkg/controller/cvi/internal/source/registry.go index 7a069fc56..92dfe4d97 100644 --- a/images/virtualization-artifact/pkg/controller/cvi/internal/source/registry.go +++ b/images/virtualization-artifact/pkg/controller/cvi/internal/source/registry.go @@ -27,15 +27,17 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/cvicondition" ) @@ -76,7 +78,7 @@ func (ds RegistryDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtua } }() - supgen := supplements.NewGenerator(common.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -100,7 +102,7 @@ func (ds RegistryDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtua } return CleanUp(ctx, cvi, ds) - case common.IsTerminating(pod): + case object.IsTerminating(pod): cvi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -128,7 +130,7 @@ func (ds RegistryDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtua log.Info("Create importer pod...", "progress", cvi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { cvi.Status.Phase = virtv2.ImageFailed @@ -197,7 +199,7 @@ func (ds RegistryDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtua } func (ds RegistryDataSource) CleanUp(ctx context.Context, cvi *virtv2.ClusterVirtualImage) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) requeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { @@ -213,7 +215,7 @@ func (ds RegistryDataSource) Validate(ctx context.Context, cvi *virtv2.ClusterVi Namespace: cvi.Spec.DataSource.ContainerImage.ImagePullSecret.Namespace, Name: cvi.Spec.DataSource.ContainerImage.ImagePullSecret.Name, } - secret, err := helper.FetchObject[*corev1.Secret](ctx, secretName, ds.client, &corev1.Secret{}) + secret, err := object.FetchObject[*corev1.Secret](ctx, secretName, ds.client, &corev1.Secret{}) if err != nil { return fmt.Errorf("failed to get secret %s: %w", secretName, err) } diff --git a/images/virtualization-artifact/pkg/controller/cvi/internal/source/sources.go b/images/virtualization-artifact/pkg/controller/cvi/internal/source/sources.go index 2deb2b099..24ab8f5bf 100644 --- a/images/virtualization-artifact/pkg/controller/cvi/internal/source/sources.go +++ b/images/virtualization-artifact/pkg/controller/cvi/internal/source/sources.go @@ -24,7 +24,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" @@ -80,7 +80,7 @@ type Cleaner interface { } func CleanUp(ctx context.Context, cvi *virtv2.ClusterVirtualImage, c Cleaner) (reconcile.Result, error) { - if cc.ShouldCleanupSubResources(cvi) { + if object.ShouldCleanupSubResources(cvi) { return c.CleanUp(ctx, cvi) } diff --git a/images/virtualization-artifact/pkg/controller/cvi/internal/source/upload.go b/images/virtualization-artifact/pkg/controller/cvi/internal/source/upload.go index 44ede41bc..db911a30d 100644 --- a/images/virtualization-artifact/pkg/controller/cvi/internal/source/upload.go +++ b/images/virtualization-artifact/pkg/controller/cvi/internal/source/upload.go @@ -24,8 +24,11 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" @@ -69,7 +72,7 @@ func (ds UploadDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualI } }() - supgen := supplements.NewGenerator(common.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) pod, err := ds.uploaderService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -101,7 +104,7 @@ func (ds UploadDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualI } return CleanUp(ctx, cvi, ds) - case common.AnyTerminating(pod, svc, ing): + case object.AnyTerminating(pod, svc, ing): cvi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -127,7 +130,7 @@ func (ds UploadDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualI log.Info("Create uploader pod...", "progress", cvi.Status.Progress, "pod.phase", nil) return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { cvi.Status.Phase = virtv2.ImageFailed @@ -226,7 +229,7 @@ func (ds UploadDataSource) Sync(ctx context.Context, cvi *virtv2.ClusterVirtualI } func (ds UploadDataSource) CleanUp(ctx context.Context, cvi *virtv2.ClusterVirtualImage) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) + supgen := supplements.NewGenerator(annotations.CVIShortName, cvi.Name, ds.controllerNamespace, cvi.UID) requeue, err := ds.uploaderService.CleanUp(ctx, supgen) if err != nil { diff --git a/images/virtualization-artifact/pkg/controller/dvcr_data_source.go b/images/virtualization-artifact/pkg/controller/dvcr_data_source.go index 98dc332ad..d74970833 100644 --- a/images/virtualization-artifact/pkg/controller/dvcr_data_source.go +++ b/images/virtualization-artifact/pkg/controller/dvcr_data_source.go @@ -24,8 +24,8 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/object" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -50,7 +50,7 @@ func NewDVCRDataSourcesForCVMI(ctx context.Context, ds virtv2.ClusterVirtualImag vmiName := ds.ObjectRef.Name vmiNS := ds.ObjectRef.Namespace if vmiName != "" && vmiNS != "" { - vmi, err := helper.FetchObject(ctx, types.NamespacedName{Name: vmiName, Namespace: vmiNS}, client, &virtv2.VirtualImage{}) + vmi, err := object.FetchObject(ctx, types.NamespacedName{Name: vmiName, Namespace: vmiNS}, client, &virtv2.VirtualImage{}) if err != nil { return DVCRDataSource{}, err } @@ -67,7 +67,7 @@ func NewDVCRDataSourcesForCVMI(ctx context.Context, ds virtv2.ClusterVirtualImag case virtv2.ClusterVirtualImageObjectRefKindClusterVirtualImage: cvmiName := ds.ObjectRef.Name if cvmiName != "" { - cvmi, err := helper.FetchObject(ctx, types.NamespacedName{Name: cvmiName}, client, &virtv2.ClusterVirtualImage{}) + cvmi, err := object.FetchObject(ctx, types.NamespacedName{Name: cvmiName}, client, &virtv2.ClusterVirtualImage{}) if err != nil { return DVCRDataSource{}, err } @@ -98,7 +98,7 @@ func NewDVCRDataSourcesForVMI(ctx context.Context, ds virtv2.VirtualImageDataSou vmiName := ds.ObjectRef.Name vmiNS := obj.GetNamespace() if vmiName != "" && vmiNS != "" { - vmi, err := helper.FetchObject(ctx, types.NamespacedName{Name: vmiName, Namespace: vmiNS}, client, &virtv2.VirtualImage{}) + vmi, err := object.FetchObject(ctx, types.NamespacedName{Name: vmiName, Namespace: vmiNS}, client, &virtv2.VirtualImage{}) if err != nil { return DVCRDataSource{}, err } @@ -119,7 +119,7 @@ func NewDVCRDataSourcesForVMI(ctx context.Context, ds virtv2.VirtualImageDataSou case virtv2.VirtualImageObjectRefKindClusterVirtualImage: cvmiName := ds.ObjectRef.Name if cvmiName != "" { - cvmi, err := helper.FetchObject(ctx, types.NamespacedName{Name: cvmiName}, client, &virtv2.ClusterVirtualImage{}) + cvmi, err := object.FetchObject(ctx, types.NamespacedName{Name: cvmiName}, client, &virtv2.ClusterVirtualImage{}) if err != nil { return DVCRDataSource{}, err } @@ -150,7 +150,7 @@ func NewDVCRDataSourcesForVMD(ctx context.Context, ds *virtv2.VirtualDiskDataSou vmiName := ds.ObjectRef.Name vmiNS := obj.GetNamespace() if vmiName != "" && vmiNS != "" { - vmi, err := helper.FetchObject(ctx, types.NamespacedName{Name: vmiName, Namespace: vmiNS}, client, &virtv2.VirtualImage{}) + vmi, err := object.FetchObject(ctx, types.NamespacedName{Name: vmiName, Namespace: vmiNS}, client, &virtv2.VirtualImage{}) if err != nil { return DVCRDataSource{}, err } @@ -167,7 +167,7 @@ func NewDVCRDataSourcesForVMD(ctx context.Context, ds *virtv2.VirtualDiskDataSou case virtv2.VirtualDiskObjectRefKindClusterVirtualImage: cvmiName := ds.ObjectRef.Name if cvmiName != "" { - cvmi, err := helper.FetchObject(ctx, types.NamespacedName{Name: cvmiName}, client, &virtv2.ClusterVirtualImage{}) + cvmi, err := object.FetchObject(ctx, types.NamespacedName{Name: cvmiName}, client, &virtv2.ClusterVirtualImage{}) if err != nil { return DVCRDataSource{}, err } diff --git a/images/virtualization-artifact/pkg/controller/gc/cron_source.go b/images/virtualization-artifact/pkg/controller/gc/cron_source.go index 52f8266f3..736bc89b1 100644 --- a/images/virtualization-artifact/pkg/controller/gc/cron_source.go +++ b/images/virtualization-artifact/pkg/controller/gc/cron_source.go @@ -36,8 +36,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" ) var _ source.Source = &CronSource{} @@ -87,7 +87,7 @@ func DefaultGetOlder(objs client.ObjectList, ttl time.Duration, maxCount int, lo if !ok { return nil } - if helper.GetAge(obj) > ttl { + if object.GetAge(obj) > ttl { expiredItems = append(expiredItems, o) } else { notExpiredItems = append(notExpiredItems, o) @@ -103,7 +103,7 @@ func DefaultGetOlder(objs client.ObjectList, ttl time.Duration, maxCount int, lo aObj, _ := a.(client.Object) bObj, _ := b.(client.Object) - return cmp.Compare(helper.GetAge(aObj), helper.GetAge(bObj)) + return cmp.Compare(object.GetAge(aObj), object.GetAge(bObj)) }) expiredItems = append(expiredItems, notExpiredItems[maxCount:]...) } diff --git a/images/virtualization-artifact/pkg/controller/importer/importer_pod.go b/images/virtualization-artifact/pkg/controller/importer/importer_pod.go index 635b6ec68..71f5b2d60 100644 --- a/images/virtualization-artifact/pkg/controller/importer/importer_pod.go +++ b/images/virtualization-artifact/pkg/controller/importer/importer_pod.go @@ -27,10 +27,10 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - common "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/object" podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" ) const ( @@ -41,7 +41,7 @@ const ( caBundleVolName = "ca-bundle-vol" // AnnOwnerRef is used when owner is in a different namespace - AnnOwnerRef = cc.AnnAPIGroup + "/storage.ownerRef" + AnnOwnerRef = annotations.AnnAPIGroup + "/storage.ownerRef" // PodRunningReason is const that defines the pod was started as a reason // PodRunningReason = "Pod is running" @@ -128,7 +128,7 @@ func CleanupPod(ctx context.Context, client client.Client, pod *corev1.Pod) erro return nil } - return helper.CleanupObject(ctx, client, pod) + return object.CleanupObject(ctx, client, pod) } // makeImporterPodSpec creates and return the importer pod spec based on the passed-in endpoint, secret and pvc. @@ -142,7 +142,7 @@ func (imp *Importer) makeImporterPodSpec() *corev1.Pod { Name: imp.PodSettings.Name, Namespace: imp.PodSettings.Namespace, Annotations: map[string]string{ - cc.AnnCreatedBy: "yes", + annotations.AnnCreatedBy: "yes", }, // Labels: map[string]string{ // common.CDILabelKey: common.CDILabelValue, @@ -166,8 +166,8 @@ func (imp *Importer) makeImporterPodSpec() *corev1.Pod { }, } - cc.SetRecommendedLabels(pod, imp.PodSettings.InstallerLabels, imp.PodSettings.ControllerName) - cc.SetRestrictedSecurityContext(&pod.Spec) + annotations.SetRecommendedLabels(pod, imp.PodSettings.InstallerLabels, imp.PodSettings.ControllerName) + podutil.SetRestrictedSecurityContext(&pod.Spec) container := imp.makeImporterContainerSpec() imp.addVolumes(pod, container) @@ -412,5 +412,5 @@ type PodNamer interface { } func FindPod(ctx context.Context, client client.Client, name PodNamer) (*corev1.Pod, error) { - return helper.FetchObject(ctx, name.ImporterPod(), client, &corev1.Pod{}) + return object.FetchObject(ctx, name.ImporterPod(), client, &corev1.Pod{}) } diff --git a/images/virtualization-artifact/pkg/controller/importer/settings.go b/images/virtualization-artifact/pkg/controller/importer/settings.go index 25e93e391..097e708a6 100644 --- a/images/virtualization-artifact/pkg/controller/importer/settings.go +++ b/images/virtualization-artifact/pkg/controller/importer/settings.go @@ -18,7 +18,7 @@ package importer import ( "github.com/deckhouse/virtualization-controller/pkg/common" - "github.com/deckhouse/virtualization-controller/pkg/common/datasource" + datasource2 "github.com/deckhouse/virtualization-controller/pkg/common/datasource" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" virtv2alpha1 "github.com/deckhouse/virtualization/api/core/v1alpha2" @@ -100,14 +100,14 @@ func ApplyHTTPSourceSettings(podEnvVars *Settings, http *virtv2alpha1.DataSource } // ApplyRegistrySourceSettings updates importer Pod settings to use registry source. -func ApplyRegistrySourceSettings(podEnvVars *Settings, ctrImg *datasource.ContainerRegistry, supGen *supplements.Generator) { +func ApplyRegistrySourceSettings(podEnvVars *Settings, ctrImg *datasource2.ContainerRegistry, supGen *supplements.Generator) { podEnvVars.Source = SourceRegistry podEnvVars.Endpoint = common.DockerRegistrySchemePrefix + ctrImg.Image // Optional auth secret from imagePullSecret. if secretName := ctrImg.ImagePullSecret.Name; secretName != "" { // Copy imagePullSecret if resides in a different namespace. - if datasource.ShouldCopyImagePullSecret(ctrImg, supGen.Namespace) { + if datasource2.ShouldCopyImagePullSecret(ctrImg, supGen.Namespace) { imgPull := supGen.ImagePullSecret() podEnvVars.AuthSecret = imgPull.Name } else { diff --git a/images/virtualization-artifact/pkg/controller/ipam/ipam.go b/images/virtualization-artifact/pkg/controller/ipam/ipam.go index da6cd7df7..a2199fd3d 100644 --- a/images/virtualization-artifact/pkg/controller/ipam/ipam.go +++ b/images/virtualization-artifact/pkg/controller/ipam/ipam.go @@ -24,7 +24,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -61,7 +61,7 @@ func (m IPAM) CreateIPAddress(ctx context.Context, vm *virtv2.VirtualMachine, cl return client.Create(ctx, &virtv2.VirtualMachineIPAddress{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ - common.LabelVirtualMachineUID: string(vm.GetUID()), + annotations.LabelVirtualMachineUID: string(vm.GetUID()), }, GenerateName: GenerateName(vm), Namespace: vm.Namespace, diff --git a/images/virtualization-artifact/pkg/controller/kvbuilder/dv.go b/images/virtualization-artifact/pkg/controller/kvbuilder/dv.go index 9ba5f9eb8..ce1aac2b8 100644 --- a/images/virtualization-artifact/pkg/controller/kvbuilder/dv.go +++ b/images/virtualization-artifact/pkg/controller/kvbuilder/dv.go @@ -25,17 +25,17 @@ import ( "github.com/deckhouse/virtualization-controller/pkg/common" "github.com/deckhouse/virtualization-controller/pkg/common/pvc" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/resource_builder" ) // DV is a helper to construct DataVolume to import an image from DVCR onto PVC. type DV struct { - helper.ResourceBuilder[*cdiv1.DataVolume] + resource_builder.ResourceBuilder[*cdiv1.DataVolume] } func NewDV(name types.NamespacedName) *DV { return &DV{ - ResourceBuilder: helper.NewResourceBuilder( + ResourceBuilder: resource_builder.NewResourceBuilder( &cdiv1.DataVolume{ TypeMeta: metav1.TypeMeta{ Kind: "DataVolume", @@ -51,7 +51,7 @@ func NewDV(name types.NamespacedName) *DV { Spec: cdiv1.DataVolumeSpec{ Source: &cdiv1.DataVolumeSource{}, }, - }, helper.ResourceBuilderOptions{}, + }, resource_builder.ResourceBuilderOptions{}, ), } } diff --git a/images/virtualization-artifact/pkg/controller/kvbuilder/kvvm.go b/images/virtualization-artifact/pkg/controller/kvbuilder/kvvm.go index 9f2482e77..f40619efd 100644 --- a/images/virtualization-artifact/pkg/controller/kvbuilder/kvvm.go +++ b/images/virtualization-artifact/pkg/controller/kvbuilder/kvvm.go @@ -27,9 +27,10 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" virtv1 "kubevirt.io/api/core/v1" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" - "github.com/deckhouse/virtualization-controller/pkg/util" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/array" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" + "github.com/deckhouse/virtualization-controller/pkg/common/resource_builder" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -51,13 +52,13 @@ type KVVMOptions struct { } type KVVM struct { - helper.ResourceBuilder[*virtv1.VirtualMachine] + resource_builder.ResourceBuilder[*virtv1.VirtualMachine] opts KVVMOptions } func NewKVVM(currentKVVM *virtv1.VirtualMachine, opts KVVMOptions) *KVVM { return &KVVM{ - ResourceBuilder: helper.NewResourceBuilder(currentKVVM, helper.ResourceBuilderOptions{ResourceExists: true}), + ResourceBuilder: resource_builder.NewResourceBuilder(currentKVVM, resource_builder.ResourceBuilderOptions{ResourceExists: true}), opts: opts, } } @@ -65,7 +66,7 @@ func NewKVVM(currentKVVM *virtv1.VirtualMachine, opts KVVMOptions) *KVVM { func NewEmptyKVVM(name types.NamespacedName, opts KVVMOptions) *KVVM { return &KVVM{ opts: opts, - ResourceBuilder: helper.NewResourceBuilder( + ResourceBuilder: resource_builder.NewResourceBuilder( &virtv1.VirtualMachine{ TypeMeta: metav1.TypeMeta{ Kind: virtv1.VirtualMachineGroupVersionKind.Kind, @@ -78,7 +79,7 @@ func NewEmptyKVVM(name types.NamespacedName, opts KVVMOptions) *KVVM { Spec: virtv1.VirtualMachineSpec{ Template: &virtv1.VirtualMachineInstanceTemplateSpec{}, }, - }, helper.ResourceBuilderOptions{}, + }, resource_builder.ResourceBuilderOptions{}, ), } } @@ -128,18 +129,18 @@ func (b *KVVM) SetCPUModel(class *virtv2.VirtualMachineClass) error { func (b *KVVM) SetRunPolicy(runPolicy virtv2.RunPolicy) error { switch runPolicy { case virtv2.AlwaysOnPolicy: - b.Resource.Spec.RunStrategy = util.GetPointer(virtv1.RunStrategyAlways) + b.Resource.Spec.RunStrategy = pointer.GetPointer(virtv1.RunStrategyAlways) case virtv2.AlwaysOffPolicy: - b.Resource.Spec.RunStrategy = util.GetPointer(virtv1.RunStrategyHalted) + b.Resource.Spec.RunStrategy = pointer.GetPointer(virtv1.RunStrategyHalted) case virtv2.ManualPolicy: if !b.ResourceExists { // initialize only - b.Resource.Spec.RunStrategy = util.GetPointer(virtv1.RunStrategyManual) + b.Resource.Spec.RunStrategy = pointer.GetPointer(virtv1.RunStrategyManual) } case virtv2.AlwaysOnUnlessStoppedManually: if !b.ResourceExists { // initialize only - b.Resource.Spec.RunStrategy = util.GetPointer(virtv1.RunStrategyAlways) + b.Resource.Spec.RunStrategy = pointer.GetPointer(virtv1.RunStrategyAlways) } default: return fmt.Errorf("unexpected runPolicy %s. %w", runPolicy, common.ErrUnknownValue) @@ -291,7 +292,7 @@ func (b *KVVM) SetDisk(name string, opts SetDiskOptions) error { disk.BootOrder = &opts.BootOrder } - b.Resource.Spec.Template.Spec.Domain.Devices.Disks = util.SetArrayElem( + b.Resource.Spec.Template.Spec.Domain.Devices.Disks = array.SetArrayElem( b.Resource.Spec.Template.Spec.Domain.Devices.Disks, disk, func(v1, v2 virtv1.Disk) bool { return v1.Name == v2.Name @@ -368,7 +369,7 @@ func (b *KVVM) SetDisk(name string, opts SetDiskOptions) error { Name: name, VolumeSource: vs, } - b.Resource.Spec.Template.Spec.Volumes = util.SetArrayElem( + b.Resource.Spec.Template.Spec.Volumes = array.SetArrayElem( b.Resource.Spec.Template.Spec.Volumes, volume, func(v1, v2 virtv1.Volume) bool { return v1.Name == v2.Name @@ -384,7 +385,7 @@ func (b *KVVM) SetTablet(name string) { Type: virtv1.InputTypeTablet, } - b.Resource.Spec.Template.Spec.Domain.Devices.Inputs = util.SetArrayElem( + b.Resource.Spec.Template.Spec.Domain.Devices.Inputs = array.SetArrayElem( b.Resource.Spec.Template.Spec.Domain.Devices.Inputs, i, func(v1, v2 virtv1.Input) bool { return v1.Name == v2.Name @@ -423,34 +424,34 @@ func (b *KVVM) SetOsType(osType virtv2.OsType) error { b.Resource.Spec.Template.Spec.Domain.Machine = &virtv1.Machine{ Type: "q35", } - b.Resource.Spec.Template.Spec.Domain.Devices.AutoattachInputDevice = util.GetPointer(true) + b.Resource.Spec.Template.Spec.Domain.Devices.AutoattachInputDevice = pointer.GetPointer(true) b.Resource.Spec.Template.Spec.Domain.Devices.TPM = &virtv1.TPMDevice{} b.Resource.Spec.Template.Spec.Domain.Features = &virtv1.Features{ - ACPI: virtv1.FeatureState{Enabled: util.GetPointer(true)}, - APIC: &virtv1.FeatureAPIC{Enabled: util.GetPointer(true)}, - SMM: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, + ACPI: virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, + APIC: &virtv1.FeatureAPIC{Enabled: pointer.GetPointer(true)}, + SMM: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, Hyperv: &virtv1.FeatureHyperv{ - Frequencies: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, - IPI: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, - Reenlightenment: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, - Relaxed: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, - Reset: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, - Runtime: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, + Frequencies: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, + IPI: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, + Reenlightenment: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, + Relaxed: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, + Reset: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, + Runtime: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, Spinlocks: &virtv1.FeatureSpinlocks{ - Enabled: util.GetPointer(true), - Retries: util.GetPointer[uint32](8191), + Enabled: pointer.GetPointer(true), + Retries: pointer.GetPointer[uint32](8191), }, - TLBFlush: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, - VAPIC: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, - VPIndex: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, + TLBFlush: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, + VAPIC: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, + VPIndex: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, }, } if !b.opts.DisableHypervSyNIC { - b.Resource.Spec.Template.Spec.Domain.Features.Hyperv.SyNIC = &virtv1.FeatureState{Enabled: util.GetPointer(true)} + b.Resource.Spec.Template.Spec.Domain.Features.Hyperv.SyNIC = &virtv1.FeatureState{Enabled: pointer.GetPointer(true)} b.Resource.Spec.Template.Spec.Domain.Features.Hyperv.SyNICTimer = &virtv1.SyNICTimer{ - Enabled: util.GetPointer(true), - Direct: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, + Enabled: pointer.GetPointer(true), + Direct: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, } } @@ -458,11 +459,11 @@ func (b *KVVM) SetOsType(osType virtv2.OsType) error { b.Resource.Spec.Template.Spec.Domain.Machine = &virtv1.Machine{ Type: "q35", } - b.Resource.Spec.Template.Spec.Domain.Devices.AutoattachInputDevice = util.GetPointer(true) + b.Resource.Spec.Template.Spec.Domain.Devices.AutoattachInputDevice = pointer.GetPointer(true) b.Resource.Spec.Template.Spec.Domain.Devices.Rng = &virtv1.Rng{} b.Resource.Spec.Template.Spec.Domain.Features = &virtv1.Features{ - ACPI: virtv1.FeatureState{Enabled: util.GetPointer(true)}, - SMM: &virtv1.FeatureState{Enabled: util.GetPointer(true)}, + ACPI: virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, + SMM: &virtv1.FeatureState{Enabled: pointer.GetPointer(true)}, } default: return fmt.Errorf("unexpected os type %q. %w", osType, common.ErrUnknownType) @@ -497,7 +498,7 @@ func (b *KVVM) SetNetworkInterface(name string) { Pod: &virtv1.PodNetwork{}, }, } - b.Resource.Spec.Template.Spec.Networks = util.SetArrayElem( + b.Resource.Spec.Template.Spec.Networks = array.SetArrayElem( b.Resource.Spec.Template.Spec.Networks, net, func(v1, v2 virtv1.Network) bool { return v1.Name == v2.Name @@ -509,7 +510,7 @@ func (b *KVVM) SetNetworkInterface(name string) { Model: devPreset.InterfaceModel, } iface.InterfaceBindingMethod.Bridge = &virtv1.InterfaceBridge{} - b.Resource.Spec.Template.Spec.Domain.Devices.Interfaces = util.SetArrayElem( + b.Resource.Spec.Template.Spec.Domain.Devices.Interfaces = array.SetArrayElem( b.Resource.Spec.Template.Spec.Domain.Devices.Interfaces, iface, func(v1, v2 virtv1.Interface) bool { return v1.Name == v2.Name @@ -528,7 +529,7 @@ func (b *KVVM) SetBootloader(bootloader virtv2.BootloaderType) error { case virtv2.EFI: b.Resource.Spec.Template.Spec.Domain.Firmware.Bootloader = &virtv1.Bootloader{ EFI: &virtv1.EFI{ - SecureBoot: util.GetPointer(false), + SecureBoot: pointer.GetPointer(false), }, } case virtv2.EFIWithSecureBoot: @@ -536,10 +537,10 @@ func (b *KVVM) SetBootloader(bootloader virtv2.BootloaderType) error { b.Resource.Spec.Template.Spec.Domain.Features = &virtv1.Features{} } b.Resource.Spec.Template.Spec.Domain.Features.SMM = &virtv1.FeatureState{ - Enabled: util.GetPointer(true), + Enabled: pointer.GetPointer(true), } b.Resource.Spec.Template.Spec.Domain.Firmware.Bootloader = &virtv1.Bootloader{ - EFI: &virtv1.EFI{SecureBoot: util.GetPointer(true)}, + EFI: &virtv1.EFI{SecureBoot: pointer.GetPointer(true)}, } default: return fmt.Errorf("unexpected bootloader type %q. %w", bootloader, common.ErrUnknownType) diff --git a/images/virtualization-artifact/pkg/controller/kvbuilder/kvvm_utils.go b/images/virtualization-artifact/pkg/controller/kvbuilder/kvvm_utils.go index 553def917..9b963dc8c 100644 --- a/images/virtualization-artifact/pkg/controller/kvbuilder/kvvm_utils.go +++ b/images/virtualization-artifact/pkg/controller/kvbuilder/kvvm_utils.go @@ -23,10 +23,10 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" virtv1 "kubevirt.io/api/core/v1" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" "github.com/deckhouse/virtualization-controller/pkg/controller/ipam" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -130,7 +130,7 @@ func ApplyVirtualMachineSpec( virtv2.StoragePersistentVolumeClaim: // Attach PVC as ephemeral volume: its data will be restored to initial state on VM restart. if err := kvvm.SetDisk(name, SetDiskOptions{ - PersistentVolumeClaim: util.GetPointer(vi.Status.Target.PersistentVolumeClaim), + PersistentVolumeClaim: pointer.GetPointer(vi.Status.Target.PersistentVolumeClaim), IsEphemeral: true, Serial: name, BootOrder: bootOrder, @@ -139,7 +139,7 @@ func ApplyVirtualMachineSpec( } case virtv2.StorageContainerRegistry: if err := kvvm.SetDisk(name, SetDiskOptions{ - ContainerDisk: util.GetPointer(vi.Status.Target.RegistryURL), + ContainerDisk: pointer.GetPointer(vi.Status.Target.RegistryURL), IsCdrom: imageformat.IsISO(vi.Status.Format), Serial: name, BootOrder: bootOrder, @@ -158,7 +158,7 @@ func ApplyVirtualMachineSpec( name := GenerateCVMIDiskName(bd.Name) if err := kvvm.SetDisk(name, SetDiskOptions{ - ContainerDisk: util.GetPointer(cvi.Status.Target.RegistryURL), + ContainerDisk: pointer.GetPointer(cvi.Status.Target.RegistryURL), IsCdrom: imageformat.IsISO(cvi.Status.Format), Serial: name, BootOrder: bootOrder, @@ -178,7 +178,7 @@ func ApplyVirtualMachineSpec( name := GenerateVMDDiskName(bd.Name) if err := kvvm.SetDisk(name, SetDiskOptions{ - PersistentVolumeClaim: util.GetPointer(vd.Status.Target.PersistentVolumeClaim), + PersistentVolumeClaim: pointer.GetPointer(vd.Status.Target.PersistentVolumeClaim), Serial: name, BootOrder: bootOrder, }); err != nil { @@ -194,7 +194,7 @@ func ApplyVirtualMachineSpec( switch { case device.PVCName != "": if err := kvvm.SetDisk(device.VolumeName, SetDiskOptions{ - PersistentVolumeClaim: util.GetPointer(device.PVCName), + PersistentVolumeClaim: pointer.GetPointer(device.PVCName), IsHotplugged: true, }); err != nil { return err diff --git a/images/virtualization-artifact/pkg/controller/kvbuilder/last_applied_spec.go b/images/virtualization-artifact/pkg/controller/kvbuilder/last_applied_spec.go index 6a468812e..1a20be659 100644 --- a/images/virtualization-artifact/pkg/controller/kvbuilder/last_applied_spec.go +++ b/images/virtualization-artifact/pkg/controller/kvbuilder/last_applied_spec.go @@ -23,13 +23,13 @@ import ( virtv1 "kubevirt.io/api/core/v1" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization/api/core/v1alpha2" ) // LoadLastAppliedSpec loads VM spec from JSON in the last-applied-spec annotation. func LoadLastAppliedSpec(kvvm *virtv1.VirtualMachine) (*v1alpha2.VirtualMachineSpec, error) { - lastSpecJSON := kvvm.GetAnnotations()[common.AnnVMLastAppliedSpec] + lastSpecJSON := kvvm.GetAnnotations()[annotations.AnnVMLastAppliedSpec] if strings.TrimSpace(lastSpecJSON) == "" { return nil, nil } @@ -49,6 +49,6 @@ func SetLastAppliedSpec(kvvm *virtv1.VirtualMachine, vm *v1alpha2.VirtualMachine return fmt.Errorf("convert spec to JSON: %w", err) } - common.AddAnnotation(kvvm, common.AnnVMLastAppliedSpec, string(lastApplied)) + annotations.AddAnnotation(kvvm, annotations.AnnVMLastAppliedSpec, string(lastApplied)) return nil } diff --git a/images/virtualization-artifact/pkg/controller/monitoring/final_report.go b/images/virtualization-artifact/pkg/controller/monitoring/final_report.go index 9810e4a1d..6e2698b42 100644 --- a/images/virtualization-artifact/pkg/controller/monitoring/final_report.go +++ b/images/virtualization-artifact/pkg/controller/monitoring/final_report.go @@ -24,7 +24,7 @@ import ( corev1 "k8s.io/api/core/v1" - "github.com/deckhouse/virtualization-controller/pkg/util" + "github.com/deckhouse/virtualization-controller/pkg/common/humanize_bytes" ) // FinalReport example: { "source-image-size": 1111, "source-image-virtual-size": 8888, "source-image-format": "qcow2"} @@ -38,7 +38,7 @@ type FinalReport struct { } func (r *FinalReport) GetAverageSpeed() string { - return util.HumanizeIBytes(r.AverageSpeed) + "/s" + return humanize_bytes.HumanizeIBytes(r.AverageSpeed) + "/s" } func (r *FinalReport) GetAverageSpeedRaw() uint64 { diff --git a/images/virtualization-artifact/pkg/controller/monitoring/progress.go b/images/virtualization-artifact/pkg/controller/monitoring/progress.go index d98353b90..c908257db 100644 --- a/images/virtualization-artifact/pkg/controller/monitoring/progress.go +++ b/images/virtualization-artifact/pkg/controller/monitoring/progress.go @@ -29,7 +29,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/net" - "github.com/deckhouse/virtualization-controller/pkg/util" + "github.com/deckhouse/virtualization-controller/pkg/common/humanize_bytes" ) var httpClient *http.Client @@ -116,7 +116,7 @@ func (p *ImportProgress) ProgressRaw() float64 { // CurSpeed is a current speed in human-readable format with SI size. func (p *ImportProgress) CurSpeed() string { - return util.HumanizeIBytes(p.curSpeed) + "/s" + return humanize_bytes.HumanizeIBytes(p.curSpeed) + "/s" } // CurSpeedRaw is a current in bytes per second. @@ -126,7 +126,7 @@ func (p *ImportProgress) CurSpeedRaw() uint64 { // AvgSpeed is an average speed in human-readable format with SI size. func (p *ImportProgress) AvgSpeed() string { - return util.HumanizeIBytes(p.avgSpeed) + "/s" + return humanize_bytes.HumanizeIBytes(p.avgSpeed) + "/s" } // AvgSpeedRaw is an average speed in bytes per second. diff --git a/images/virtualization-artifact/pkg/controller/powerstate/operations.go b/images/virtualization-artifact/pkg/controller/powerstate/operations.go index 5666e87b5..37fbdda0f 100644 --- a/images/virtualization-artifact/pkg/controller/powerstate/operations.go +++ b/images/virtualization-artifact/pkg/controller/powerstate/operations.go @@ -25,7 +25,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" kvvmutil "github.com/deckhouse/virtualization-controller/pkg/common/kvvm" - "github.com/deckhouse/virtualization-controller/pkg/util" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" ) // StartVM starts VM via adding change request to the KVVM status. @@ -51,7 +51,7 @@ func StopVM(ctx context.Context, cl client.Client, kvvmi *kvv1.VirtualMachineIns return err } if force { - return kvvmutil.DeletePodByKVVMI(ctx, cl, kvvmi, &client.DeleteOptions{GracePeriodSeconds: util.GetPointer(int64(0))}) + return kvvmutil.DeletePodByKVVMI(ctx, cl, kvvmi, &client.DeleteOptions{GracePeriodSeconds: pointer.GetPointer(int64(0))}) } return nil } @@ -78,7 +78,7 @@ func RestartVM(ctx context.Context, cl client.Client, kvvm *kvv1.VirtualMachine, return err } if force { - return kvvmutil.DeletePodByKVVMI(ctx, cl, kvvmi, &client.DeleteOptions{GracePeriodSeconds: util.GetPointer(int64(0))}) + return kvvmutil.DeletePodByKVVMI(ctx, cl, kvvmi, &client.DeleteOptions{GracePeriodSeconds: pointer.GetPointer(int64(0))}) } return nil } diff --git a/images/virtualization-artifact/pkg/controller/service/attachment_service.go b/images/virtualization-artifact/pkg/controller/service/attachment_service.go index cbfaba70f..b9627a273 100644 --- a/images/virtualization-artifact/pkg/controller/service/attachment_service.go +++ b/images/virtualization-artifact/pkg/controller/service/attachment_service.go @@ -27,10 +27,10 @@ import ( virtv1 "kubevirt.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/kubevirt" "github.com/deckhouse/virtualization-controller/pkg/controller/kvapi" "github.com/deckhouse/virtualization-controller/pkg/controller/kvbuilder" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -269,23 +269,23 @@ func (s AttachmentService) IsConflictedAttachment(ctx context.Context, vmbda *vi } func (s AttachmentService) GetVirtualDisk(ctx context.Context, name, namespace string) (*virtv2.VirtualDisk, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualDisk{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualDisk{}) } func (s AttachmentService) GetPersistentVolumeClaim(ctx context.Context, vd *virtv2.VirtualDisk) (*corev1.PersistentVolumeClaim, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: vd.Namespace, Name: vd.Status.Target.PersistentVolumeClaim}, s.client, &corev1.PersistentVolumeClaim{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: vd.Namespace, Name: vd.Status.Target.PersistentVolumeClaim}, s.client, &corev1.PersistentVolumeClaim{}) } func (s AttachmentService) GetVirtualMachine(ctx context.Context, name, namespace string) (*virtv2.VirtualMachine, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualMachine{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualMachine{}) } func (s AttachmentService) GetKVVM(ctx context.Context, vm *virtv2.VirtualMachine) (*virtv1.VirtualMachine, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: vm.Namespace, Name: vm.Name}, s.client, &virtv1.VirtualMachine{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: vm.Namespace, Name: vm.Name}, s.client, &virtv1.VirtualMachine{}) } func (s AttachmentService) GetKVVMI(ctx context.Context, vm *virtv2.VirtualMachine) (*virtv1.VirtualMachineInstance, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: vm.Namespace, Name: vm.Name}, s.client, &virtv1.VirtualMachineInstance{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: vm.Namespace, Name: vm.Name}, s.client, &virtv1.VirtualMachineInstance{}) } func isSameBlockDeviceRefs(a, b virtv2.VMBDAObjectRef) bool { diff --git a/images/virtualization-artifact/pkg/controller/service/disk_service.go b/images/virtualization-artifact/pkg/controller/service/disk_service.go index 38a34d435..9c4388051 100644 --- a/images/virtualization-artifact/pkg/controller/service/disk_service.go +++ b/images/virtualization-artifact/pkg/controller/service/disk_service.go @@ -37,13 +37,13 @@ import ( cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" dvutil "github.com/deckhouse/virtualization-controller/pkg/common/datavolume" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" "github.com/deckhouse/virtualization-controller/pkg/controller/kvbuilder" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -275,7 +275,7 @@ func (s DiskService) Resize(ctx context.Context, pvc *corev1.PersistentVolumeCla } func (s DiskService) IsImportDone(dv *cdiv1.DataVolume, pvc *corev1.PersistentVolumeClaim) bool { - return common.IsDataVolumeComplete(dv) && common.IsPVCBound(pvc) + return dv != nil && dv.Status.Phase == cdiv1.Succeeded && pvc != nil && pvc.Status.Phase == corev1.ClaimBound } func (s DiskService) GetProgress(dv *cdiv1.DataVolume, prevProgress string, opts ...GetProgressOption) string { @@ -297,7 +297,7 @@ func (s DiskService) GetProgress(dv *cdiv1.DataVolume, prevProgress string, opts func (s DiskService) GetCapacity(pvc *corev1.PersistentVolumeClaim) string { if pvc != nil && pvc.Status.Phase == corev1.ClaimBound { - return util.GetPointer(pvc.Status.Capacity[corev1.ResourceStorage]).String() + return pointer.GetPointer(pvc.Status.Capacity[corev1.ResourceStorage]).String() } return "" @@ -355,7 +355,7 @@ func (s DiskService) parseVolumeMode(sc *storev1.StorageClass) (corev1.Persisten if sc == nil { return "", false } - switch sc.GetAnnotations()[common.AnnVirtualDiskVolumeMode] { + switch sc.GetAnnotations()[annotations.AnnVirtualDiskVolumeMode] { case string(corev1.PersistentVolumeBlock): return corev1.PersistentVolumeBlock, true case string(corev1.PersistentVolumeFilesystem): @@ -369,7 +369,7 @@ func (s DiskService) parseAccessMode(sc *storev1.StorageClass) (corev1.Persisten if sc == nil { return "", false } - switch sc.GetAnnotations()[common.AnnVirtualDiskAccessMode] { + switch sc.GetAnnotations()[annotations.AnnVirtualDiskAccessMode] { case string(corev1.ReadWriteOnce): return corev1.ReadWriteOnce, true case string(corev1.ReadWriteMany): @@ -383,7 +383,7 @@ func (s DiskService) parseImmediateBindingMode(sc *storev1.StorageClass) bool { if sc == nil { return false } - return sc.GetAnnotations()[common.AnnVirtualDiskBindingMode] == string(storev1.VolumeBindingImmediate) + return sc.GetAnnotations()[annotations.AnnVirtualDiskBindingMode] == string(storev1.VolumeBindingImmediate) } func (s DiskService) parseStorageCapabilities(status cdiv1.StorageProfileStatus) StorageCapabilities { @@ -418,23 +418,23 @@ func (s DiskService) parseStorageCapabilities(status cdiv1.StorageProfileStatus) } func (s DiskService) GetDataVolume(ctx context.Context, sup *supplements.Generator) (*cdiv1.DataVolume, error) { - return helper.FetchObject(ctx, sup.DataVolume(), s.client, &cdiv1.DataVolume{}) + return object.FetchObject(ctx, sup.DataVolume(), s.client, &cdiv1.DataVolume{}) } func (s DiskService) GetPersistentVolumeClaim(ctx context.Context, sup *supplements.Generator) (*corev1.PersistentVolumeClaim, error) { - return helper.FetchObject(ctx, sup.PersistentVolumeClaim(), s.client, &corev1.PersistentVolumeClaim{}) + return object.FetchObject(ctx, sup.PersistentVolumeClaim(), s.client, &corev1.PersistentVolumeClaim{}) } func (s DiskService) GetVolumeSnapshot(ctx context.Context, name, namespace string) (*vsv1.VolumeSnapshot, error) { - return helper.FetchObject(ctx, types.NamespacedName{Name: name, Namespace: namespace}, s.client, &vsv1.VolumeSnapshot{}) + return object.FetchObject(ctx, types.NamespacedName{Name: name, Namespace: namespace}, s.client, &vsv1.VolumeSnapshot{}) } func (s DiskService) GetVirtualImage(ctx context.Context, name, namespace string) (*virtv2.VirtualImage, error) { - return helper.FetchObject(ctx, types.NamespacedName{Name: name, Namespace: namespace}, s.client, &virtv2.VirtualImage{}) + return object.FetchObject(ctx, types.NamespacedName{Name: name, Namespace: namespace}, s.client, &virtv2.VirtualImage{}) } func (s DiskService) GetClusterVirtualImage(ctx context.Context, name string) (*virtv2.ClusterVirtualImage, error) { - return helper.FetchObject(ctx, types.NamespacedName{Name: name}, s.client, &virtv2.ClusterVirtualImage{}) + return object.FetchObject(ctx, types.NamespacedName{Name: name}, s.client, &virtv2.ClusterVirtualImage{}) } func (s DiskService) ListVirtualDiskSnapshots(ctx context.Context, namespace string) ([]virtv2.VirtualDiskSnapshot, error) { @@ -450,7 +450,7 @@ func (s DiskService) ListVirtualDiskSnapshots(ctx context.Context, namespace str } func (s DiskService) GetVirtualDiskSnapshot(ctx context.Context, name, namespace string) (*virtv2.VirtualDiskSnapshot, error) { - return helper.FetchObject(ctx, types.NamespacedName{Name: name, Namespace: namespace}, s.client, &virtv2.VirtualDiskSnapshot{}) + return object.FetchObject(ctx, types.NamespacedName{Name: name, Namespace: namespace}, s.client, &virtv2.VirtualDiskSnapshot{}) } func (s DiskService) CheckImportProcess(ctx context.Context, dv *cdiv1.DataVolume, pvc *corev1.PersistentVolumeClaim) error { @@ -476,7 +476,7 @@ func (s DiskService) CheckImportProcess(ctx context.Context, dv *cdiv1.DataVolum Name: dvutil.GetImporterPrimeName(pvc.UID), } - cdiImporterPrime, err := helper.FetchObject(ctx, key, s.client, &corev1.Pod{}) + cdiImporterPrime, err := object.FetchObject(ctx, key, s.client, &corev1.Pod{}) if err != nil { return err } @@ -512,7 +512,7 @@ func (s DiskService) GetDefaultStorageClass(ctx context.Context) (*storev1.Stora var defaultClasses []*storev1.StorageClass for idx := range scs.Items { - if scs.Items[idx].Annotations[common.AnnDefaultStorageClass] == "true" { + if scs.Items[idx].Annotations[annotations.AnnDefaultStorageClass] == "true" { defaultClasses = append(defaultClasses, &scs.Items[idx]) } } diff --git a/images/virtualization-artifact/pkg/controller/service/importer_service.go b/images/virtualization-artifact/pkg/controller/service/importer_service.go index 854836ccd..6af668a1a 100644 --- a/images/virtualization-artifact/pkg/controller/service/importer_service.go +++ b/images/virtualization-artifact/pkg/controller/service/importer_service.go @@ -25,8 +25,8 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" @@ -93,7 +93,7 @@ func (s ImporterService) CleanUp(ctx context.Context, sup *supplements.Generator } func (s ImporterService) DeletePod(ctx context.Context, obj ObjectKind, controllerName string) (bool, error) { - labelSelector := client.MatchingLabels{common.AppKubernetesManagedByLabel: controllerName} + labelSelector := client.MatchingLabels{annotations.AppKubernetesManagedByLabel: controllerName} podList := &corev1.PodList{} if err := s.client.List(ctx, podList, labelSelector); err != nil { diff --git a/images/virtualization-artifact/pkg/controller/service/ip_address_service.go b/images/virtualization-artifact/pkg/controller/service/ip_address_service.go index b1cf7a3d5..6c608bd44 100644 --- a/images/virtualization-artifact/pkg/controller/service/ip_address_service.go +++ b/images/virtualization-artifact/pkg/controller/service/ip_address_service.go @@ -25,7 +25,7 @@ import ( k8snet "k8s.io/utils/net" "github.com/deckhouse/deckhouse/pkg/log" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/ip" ) type IpAddressService struct { @@ -52,7 +52,7 @@ func NewIpAddressService( } } -func (s IpAddressService) IsAvailableAddress(address string, allocatedIPs common.AllocatedIPs) error { +func (s IpAddressService) IsAvailableAddress(address string, allocatedIPs ip.AllocatedIPs) error { ip, err := netip.ParseAddr(address) if err != nil || !ip.IsValid() { return errors.New("invalid IP address format") @@ -80,7 +80,7 @@ func (s IpAddressService) IsAvailableAddress(address string, allocatedIPs common return ErrIPAddressOutOfRange } -func (s IpAddressService) AllocateNewIP(allocatedIPs common.AllocatedIPs) (string, error) { +func (s IpAddressService) AllocateNewIP(allocatedIPs ip.AllocatedIPs) (string, error) { for _, cidr := range s.parsedCIDRs { for ip := cidr.Addr(); cidr.Contains(ip); ip = ip.Next() { if k8snet.RangeSize(toIPNet(cidr)) != 1 { diff --git a/images/virtualization-artifact/pkg/controller/service/ip_address_service_test.go b/images/virtualization-artifact/pkg/controller/service/ip_address_service_test.go index a071ded14..d22bd4ce8 100644 --- a/images/virtualization-artifact/pkg/controller/service/ip_address_service_test.go +++ b/images/virtualization-artifact/pkg/controller/service/ip_address_service_test.go @@ -23,21 +23,21 @@ import ( . "github.com/onsi/gomega" "github.com/deckhouse/deckhouse/pkg/log" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/ip" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) var _ = Describe("IpAddressService", func() { var ( ipService *IpAddressService - allocatedIPs common.AllocatedIPs + allocatedIPs ip.AllocatedIPs logger *log.Logger ) BeforeEach(func() { virtualMachineCIDRs := []string{"192.168.1.0/24"} ipService = NewIpAddressService(logger, virtualMachineCIDRs) - allocatedIPs = make(common.AllocatedIPs) + allocatedIPs = make(ip.AllocatedIPs) }) Describe("IsAvailableAddress", func() { diff --git a/images/virtualization-artifact/pkg/controller/service/protection_service.go b/images/virtualization-artifact/pkg/controller/service/protection_service.go index 46e5652d1..91b639369 100644 --- a/images/virtualization-artifact/pkg/controller/service/protection_service.go +++ b/images/virtualization-artifact/pkg/controller/service/protection_service.go @@ -25,7 +25,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/resource_builder" ) type ProtectionService struct { @@ -52,7 +52,7 @@ func (s ProtectionService) AddOwnerRef(ctx context.Context, owner client.Object, continue } - if helper.SetOwnerRef(obj, ownerRef) { + if resource_builder.SetOwnerRef(obj, ownerRef) { patch, err := GetPatchOwnerReferences(obj.GetOwnerReferences()) if err != nil { return err diff --git a/images/virtualization-artifact/pkg/controller/service/resource.go b/images/virtualization-artifact/pkg/controller/service/resource.go index 288d4768f..2eeeb76b2 100644 --- a/images/virtualization-artifact/pkg/controller/service/resource.go +++ b/images/virtualization-artifact/pkg/controller/service/resource.go @@ -29,9 +29,9 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/common/patch" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -78,7 +78,7 @@ func (r *Resource[T, ST]) Name() types.NamespacedName { } func (r *Resource[T, ST]) Fetch(ctx context.Context) error { - currentObj, err := helper.FetchObject(ctx, r.name, r.client, r.objFactory()) + currentObj, err := object.FetchObject(ctx, r.name, r.client, r.objFactory()) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/service/restorer/restorer.go b/images/virtualization-artifact/pkg/controller/service/restorer/restorer.go index 295831db0..72a16e40b 100644 --- a/images/virtualization-artifact/pkg/controller/service/restorer/restorer.go +++ b/images/virtualization-artifact/pkg/controller/service/restorer/restorer.go @@ -28,8 +28,8 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/service" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -123,7 +123,7 @@ func (r SecretRestorer) setVirtualMachineBlockDeviceAttachments(ctx context.Cont continue } - vmbda, err := helper.FetchObject(ctx, types.NamespacedName{ + vmbda, err := object.FetchObject(ctx, types.NamespacedName{ Name: bdr.VirtualMachineBlockDeviceAttachmentName, Namespace: vm.Namespace, }, r.client, &virtv2.VirtualMachineBlockDeviceAttachment{}) @@ -153,7 +153,7 @@ func (r SecretRestorer) setVirtualMachineBlockDeviceAttachments(ctx context.Cont } func (r SecretRestorer) setVirtualMachineIPAddress(ctx context.Context, secret *corev1.Secret, vm *virtv2.VirtualMachine, keepIPAddress virtv2.KeepIPAddress) error { - vmip, err := helper.FetchObject(ctx, types.NamespacedName{ + vmip, err := object.FetchObject(ctx, types.NamespacedName{ Namespace: vm.Namespace, Name: vm.Status.VirtualMachineIPAddress, }, r.client, &virtv2.VirtualMachineIPAddress{}) @@ -256,7 +256,7 @@ func (r SecretRestorer) setProvisioning(ctx context.Context, secret *corev1.Secr } secretKey := types.NamespacedName{Name: secretName, Namespace: vm.Namespace} - provisioner, err := helper.FetchObject(ctx, secretKey, r.client, &corev1.Secret{}) + provisioner, err := object.FetchObject(ctx, secretKey, r.client, &corev1.Secret{}) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/service/snapshot_service.go b/images/virtualization-artifact/pkg/controller/service/snapshot_service.go index f6b3566c5..d3bc03e5e 100644 --- a/images/virtualization-artifact/pkg/controller/service/snapshot_service.go +++ b/images/virtualization-artifact/pkg/controller/service/snapshot_service.go @@ -27,8 +27,8 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" "github.com/deckhouse/virtualization/api/client/kubeclient" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vmcondition" @@ -164,27 +164,27 @@ func (s *SnapshotService) DeleteVolumeSnapshot(ctx context.Context, vs *vsv1.Vol } func (s *SnapshotService) GetVirtualDisk(ctx context.Context, name, namespace string) (*virtv2.VirtualDisk, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualDisk{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualDisk{}) } func (s *SnapshotService) GetPersistentVolumeClaim(ctx context.Context, name, namespace string) (*corev1.PersistentVolumeClaim, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &corev1.PersistentVolumeClaim{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &corev1.PersistentVolumeClaim{}) } func (s *SnapshotService) GetVirtualDiskSnapshot(ctx context.Context, name, namespace string) (*virtv2.VirtualDiskSnapshot, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualDiskSnapshot{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualDiskSnapshot{}) } func (s *SnapshotService) GetVirtualMachine(ctx context.Context, name, namespace string) (*virtv2.VirtualMachine, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualMachine{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &virtv2.VirtualMachine{}) } func (s *SnapshotService) GetVolumeSnapshot(ctx context.Context, name, namespace string) (*vsv1.VolumeSnapshot, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &vsv1.VolumeSnapshot{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &vsv1.VolumeSnapshot{}) } func (s *SnapshotService) GetSecret(ctx context.Context, name, namespace string) (*corev1.Secret, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &corev1.Secret{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, s.client, &corev1.Secret{}) } func (s *SnapshotService) CreateVirtualDiskSnapshot(ctx context.Context, vdSnapshot *virtv2.VirtualDiskSnapshot) (*virtv2.VirtualDiskSnapshot, error) { diff --git a/images/virtualization-artifact/pkg/controller/service/stat_service.go b/images/virtualization-artifact/pkg/controller/service/stat_service.go index 437c0affc..ba5634193 100644 --- a/images/virtualization-artifact/pkg/controller/service/stat_service.go +++ b/images/virtualization-artifact/pkg/controller/service/stat_service.go @@ -29,10 +29,12 @@ import ( "github.com/deckhouse/deckhouse/pkg/log" "github.com/deckhouse/virtualization-controller/pkg/common" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/humanize_bytes" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/percent" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/monitoring" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -88,9 +90,9 @@ func (s StatService) GetSize(pod *corev1.Pod) virtv2.ImageStatusSize { unpackedSizeBytes := resource.NewQuantity(int64(finalReport.UnpackedSizeBytes), resource.BinarySI) return virtv2.ImageStatusSize{ - Stored: util.HumanizeIBytes(finalReport.StoredSizeBytes), + Stored: humanize_bytes.HumanizeIBytes(finalReport.StoredSizeBytes), StoredBytes: strconv.FormatUint(finalReport.StoredSizeBytes, 10), - Unpacked: util.HumanizeIBytes(uint64(unpackedSizeBytes.Value())), + Unpacked: humanize_bytes.HumanizeIBytes(uint64(unpackedSizeBytes.Value())), UnpackedBytes: strconv.FormatInt(unpackedSizeBytes.Value(), 10), } } @@ -181,7 +183,7 @@ type ScaleOption struct { } func (o ScaleOption) Apply(progress string) string { - return common.ScalePercentage(progress, o.Low, o.High) + return percent.ScalePercentage(progress, o.Low, o.High) } func (s StatService) GetProgress(ownerUID types.UID, pod *corev1.Pod, prevProgress string, opts ...GetProgressOption) string { @@ -245,7 +247,7 @@ func (s StatService) IsUploaderReady(pod *corev1.Pod, svc *corev1.Service, ing * return false } - return cc.IsPodRunning(pod) && cc.IsPodStarted(pod) && ing.Annotations[cc.AnnUploadURL] != "" + return podutil.IsPodRunning(pod) && podutil.IsPodStarted(pod) && ing.Annotations[annotations.AnnUploadURL] != "" } func (s StatService) IsUploadStarted(ownerUID types.UID, pod *corev1.Pod) bool { diff --git a/images/virtualization-artifact/pkg/controller/service/uploader_service.go b/images/virtualization-artifact/pkg/controller/service/uploader_service.go index 8e4758d3c..d99a37911 100644 --- a/images/virtualization-artifact/pkg/controller/service/uploader_service.go +++ b/images/virtualization-artifact/pkg/controller/service/uploader_service.go @@ -26,8 +26,8 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/controller/uploader" "github.com/deckhouse/virtualization-controller/pkg/dvcr" @@ -35,14 +35,14 @@ import ( ) type UploaderService struct { - dvcrSettings *dvcr.Settings client client.Client + dvcrSettings *dvcr.Settings + protection *ProtectionService image string - requirements corev1.ResourceRequirements pullPolicy string verbose string controllerName string - protection *ProtectionService + requirements corev1.ResourceRequirements } func NewUploaderService( @@ -192,7 +192,7 @@ func (s UploaderService) GetIngress(ctx context.Context, sup *supplements.Genera } func (s UploaderService) GetExternalURL(ctx context.Context, ing *netv1.Ingress) string { - url := ing.Annotations[cc.AnnUploadURL] + url := ing.Annotations[annotations.AnnUploadURL] if url == "" { logger.FromContext(ctx).Error("unexpected empty upload url, please report a bug") return "" diff --git a/images/virtualization-artifact/pkg/controller/service/vm_operation.go b/images/virtualization-artifact/pkg/controller/service/vm_operation.go index bd9b9040c..f4faa4dee 100644 --- a/images/virtualization-artifact/pkg/controller/service/vm_operation.go +++ b/images/virtualization-artifact/pkg/controller/service/vm_operation.go @@ -26,10 +26,10 @@ import ( virtv1 "kubevirt.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/powerstate" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" "github.com/deckhouse/virtualization/api/client/kubeclient" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vmopcondition" @@ -49,11 +49,11 @@ func NewVMOperationService(client client.Client, virtClient kubeclient.Client) V } func (s VMOperationService) getKVVM(ctx context.Context, vmNamespace, vmName string) (*virtv1.VirtualMachine, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: vmNamespace, Name: vmName}, s.client, &virtv1.VirtualMachine{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: vmNamespace, Name: vmName}, s.client, &virtv1.VirtualMachine{}) } func (s VMOperationService) getKVVMI(ctx context.Context, vmNamespace, vmName string) (*virtv1.VirtualMachineInstance, error) { - return helper.FetchObject(ctx, types.NamespacedName{Namespace: vmNamespace, Name: vmName}, s.client, &virtv1.VirtualMachineInstance{}) + return object.FetchObject(ctx, types.NamespacedName{Namespace: vmNamespace, Name: vmName}, s.client, &virtv1.VirtualMachineInstance{}) } func (s VMOperationService) Do(ctx context.Context, vmop *virtv2.VirtualMachineOperation) error { diff --git a/images/virtualization-artifact/pkg/controller/supplements/copier/auth_secret.go b/images/virtualization-artifact/pkg/controller/supplements/copier/auth_secret.go index 6834be6f3..cd461109c 100644 --- a/images/virtualization-artifact/pkg/controller/supplements/copier/auth_secret.go +++ b/images/virtualization-artifact/pkg/controller/supplements/copier/auth_secret.go @@ -23,7 +23,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "github.com/deckhouse/virtualization-controller/pkg/auth" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/object" ) // AuthSecret copies auth credentials from the source Secret into @@ -43,7 +43,7 @@ type AuthSecret struct { // a Secret with two fields: accessKeyId and secretKey. // ref is registry url or image name. It is used to select a desired auth pair from the config. func (a AuthSecret) CopyCDICompatible(ctx context.Context, client client.Client, ref string) error { - srcObj, err := helper.FetchObject(ctx, a.Source, client, &corev1.Secret{}) + srcObj, err := object.FetchObject(ctx, a.Source, client, &corev1.Secret{}) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/supplements/copier/ca_bundle_cm.go b/images/virtualization-artifact/pkg/controller/supplements/copier/ca_bundle_cm.go index 3bf9b28a8..53ea702b0 100644 --- a/images/virtualization-artifact/pkg/controller/supplements/copier/ca_bundle_cm.go +++ b/images/virtualization-artifact/pkg/controller/supplements/copier/ca_bundle_cm.go @@ -25,9 +25,9 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/common" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/merger" + "github.com/deckhouse/virtualization-controller/pkg/common/object" ) type CABundleConfigMap struct { @@ -58,7 +58,7 @@ func (c CABundleConfigMap) Create(ctx context.Context, client client.Client, caB func (c CABundleConfigMap) Copy(ctx context.Context, client client.Client) error { var caBundle string - srcObj, err := helper.FetchObject(ctx, c.SourceSecret, client, &corev1.Secret{}) + srcObj, err := object.FetchObject(ctx, c.SourceSecret, client, &corev1.Secret{}) if err != nil { return err } @@ -88,7 +88,7 @@ func (c CABundleConfigMap) makeConfigMap(caBundle string) *corev1.ConfigMap { Name: c.Destination.Name, Namespace: c.Destination.Namespace, Annotations: map[string]string{ - cc.AnnCreatedBy: "yes", + annotations.AnnCreatedBy: "yes", }, Labels: map[string]string{}, OwnerReferences: []metav1.OwnerReference{ @@ -103,11 +103,11 @@ func (c CABundleConfigMap) makeConfigMap(caBundle string) *corev1.ConfigMap { } if c.Labels != nil { - cm.Labels = common.MergeLabels(cm.GetLabels(), c.Labels) + cm.Labels = merger.MergeLabels(cm.GetLabels(), c.Labels) } if c.Annotations != nil { - cm.Annotations = common.MergeLabels(cm.GetAnnotations(), c.Annotations) + cm.Annotations = merger.MergeLabels(cm.GetAnnotations(), c.Annotations) } return cm diff --git a/images/virtualization-artifact/pkg/controller/supplements/copier/secret.go b/images/virtualization-artifact/pkg/controller/supplements/copier/secret.go index cbdeacf93..1b35c014a 100644 --- a/images/virtualization-artifact/pkg/controller/supplements/copier/secret.go +++ b/images/virtualization-artifact/pkg/controller/supplements/copier/secret.go @@ -25,9 +25,9 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/common" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/merger" + "github.com/deckhouse/virtualization-controller/pkg/common/object" ) // Secret copies or creates Secret from Source to Destination. @@ -53,7 +53,7 @@ func (s Secret) Create(ctx context.Context, client client.Client, data map[strin // Copy copies source Secret data and type as-is. func (s Secret) Copy(ctx context.Context, client client.Client) error { - srcObj, err := helper.FetchObject(ctx, s.Source, client, &corev1.Secret{}) + srcObj, err := object.FetchObject(ctx, s.Source, client, &corev1.Secret{}) if err != nil { return err } @@ -72,7 +72,7 @@ func (s Secret) makeSecret(data map[string][]byte, secretType corev1.SecretType) Name: s.Destination.Name, Namespace: s.Destination.Namespace, Annotations: map[string]string{ - cc.AnnCreatedBy: "yes", + annotations.AnnCreatedBy: "yes", }, Labels: map[string]string{}, }, @@ -87,11 +87,11 @@ func (s Secret) makeSecret(data map[string][]byte, secretType corev1.SecretType) } if s.Labels != nil { - secret.Labels = common.MergeLabels(secret.GetLabels(), s.Labels) + secret.Labels = merger.MergeLabels(secret.GetLabels(), s.Labels) } if s.Annotations != nil { - secret.Annotations = common.MergeLabels(secret.GetAnnotations(), s.Annotations) + secret.Annotations = merger.MergeLabels(secret.GetAnnotations(), s.Annotations) } return secret diff --git a/images/virtualization-artifact/pkg/controller/supplements/ensure.go b/images/virtualization-artifact/pkg/controller/supplements/ensure.go index 08f8e09fd..a7ff4cbd7 100644 --- a/images/virtualization-artifact/pkg/controller/supplements/ensure.go +++ b/images/virtualization-artifact/pkg/controller/supplements/ensure.go @@ -30,10 +30,10 @@ import ( "github.com/deckhouse/virtualization-controller/pkg/common/datasource" dvutil "github.com/deckhouse/virtualization-controller/pkg/common/datavolume" ingutil "github.com/deckhouse/virtualization-controller/pkg/common/ingress" + "github.com/deckhouse/virtualization-controller/pkg/common/object" podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements/copier" "github.com/deckhouse/virtualization-controller/pkg/dvcr" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" ) type DataSource interface { @@ -169,7 +169,7 @@ func CleanupForDataVolume(ctx context.Context, client client.Client, supGen *Gen // AuthSecret has type dockerconfigjson and should be transformed, so it always copied. if dvcrSettings.AuthSecret != "" { authSecret := supGen.DVCRAuthSecretForDV() - err := helper.CleanupByName(ctx, client, authSecret, &corev1.Secret{}) + err := object.CleanupByName(ctx, client, authSecret, &corev1.Secret{}) if err != nil && !k8serrors.IsNotFound(err) { return err } @@ -178,7 +178,7 @@ func CleanupForDataVolume(ctx context.Context, client client.Client, supGen *Gen // CABundle needs transformation, so it always copied. if dvcrSettings.CertsSecret != "" { caBundleCM := supGen.DVCRCABundleConfigMapForDV() - err := helper.CleanupByName(ctx, client, caBundleCM, &corev1.ConfigMap{}) + err := object.CleanupByName(ctx, client, caBundleCM, &corev1.ConfigMap{}) if err != nil && !k8serrors.IsNotFound(err) { return err } diff --git a/images/virtualization-artifact/pkg/controller/uploader/uploader_ingress.go b/images/virtualization-artifact/pkg/controller/uploader/uploader_ingress.go index a7fa70469..aadb1c542 100644 --- a/images/virtualization-artifact/pkg/controller/uploader/uploader_ingress.go +++ b/images/virtualization-artifact/pkg/controller/uploader/uploader_ingress.go @@ -26,9 +26,9 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "github.com/deckhouse/virtualization-controller/pkg/common" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" - "github.com/deckhouse/virtualization-controller/pkg/util" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + "github.com/deckhouse/virtualization-controller/pkg/common/pwgen" ) type IngressSettings struct { @@ -76,7 +76,7 @@ func (i *Ingress) makeSpec() *netv1.Ingress { Name: i.Settings.Name, Namespace: i.Settings.Namespace, Annotations: map[string]string{ - cc.AnnUploadURL: fmt.Sprintf("https://%s%s", i.Settings.Host, path), + annotations.AnnUploadURL: fmt.Sprintf("https://%s%s", i.Settings.Host, path), "nginx.ingress.kubernetes.io/ssl-redirect": "true", "nginx.ingress.kubernetes.io/proxy-body-size": "0", "nginx.ingress.kubernetes.io/rewrite-target": uploadPath, @@ -121,7 +121,7 @@ func (i *Ingress) makeSpec() *netv1.Ingress { } func (i *Ingress) generatePath() string { - return fmt.Sprintf(tmplIngressPath, util.AlphaNum(32)) + return fmt.Sprintf(tmplIngressPath, pwgen.AlphaNum(32)) } type IngressNamer interface { @@ -129,5 +129,5 @@ type IngressNamer interface { } func FindIngress(ctx context.Context, client client.Client, name IngressNamer) (*netv1.Ingress, error) { - return helper.FetchObject(ctx, name.UploaderIngress(), client, &netv1.Ingress{}) + return object.FetchObject(ctx, name.UploaderIngress(), client, &netv1.Ingress{}) } diff --git a/images/virtualization-artifact/pkg/controller/uploader/uploader_pod.go b/images/virtualization-artifact/pkg/controller/uploader/uploader_pod.go index 82477528f..056f42959 100644 --- a/images/virtualization-artifact/pkg/controller/uploader/uploader_pod.go +++ b/images/virtualization-artifact/pkg/controller/uploader/uploader_pod.go @@ -27,9 +27,9 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/object" podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" ) const ( @@ -88,10 +88,10 @@ func (p *Pod) makeSpec() *corev1.Pod { Name: p.PodSettings.Name, Namespace: p.PodSettings.Namespace, Annotations: map[string]string{ - cc.AnnCreatedBy: "yes", + annotations.AnnCreatedBy: "yes", }, Labels: map[string]string{ - cc.UploaderServiceLabel: p.PodSettings.ServiceName, + annotations.UploaderServiceLabel: p.PodSettings.ServiceName, }, OwnerReferences: []metav1.OwnerReference{ p.PodSettings.OwnerReference, @@ -107,8 +107,8 @@ func (p *Pod) makeSpec() *corev1.Pod { }, } - cc.SetRecommendedLabels(pod, p.PodSettings.InstallerLabels, p.PodSettings.ControllerName) - cc.SetRestrictedSecurityContext(&pod.Spec) + annotations.SetRecommendedLabels(pod, p.PodSettings.InstallerLabels, p.PodSettings.ControllerName) + podutil.SetRestrictedSecurityContext(&pod.Spec) container := p.makeUploaderContainerSpec() p.addVolumes(pod, container) @@ -193,5 +193,5 @@ type PodNamer interface { } func FindPod(ctx context.Context, client client.Client, name PodNamer) (*corev1.Pod, error) { - return helper.FetchObject(ctx, name.UploaderPod(), client, &corev1.Pod{}) + return object.FetchObject(ctx, name.UploaderPod(), client, &corev1.Pod{}) } diff --git a/images/virtualization-artifact/pkg/controller/uploader/uploader_service.go b/images/virtualization-artifact/pkg/controller/uploader/uploader_service.go index c2e9b6597..4766bdd51 100644 --- a/images/virtualization-artifact/pkg/controller/uploader/uploader_service.go +++ b/images/virtualization-artifact/pkg/controller/uploader/uploader_service.go @@ -26,8 +26,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "github.com/deckhouse/virtualization-controller/pkg/common" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/object" ) type ServiceSettings struct { @@ -64,7 +64,7 @@ func (s *Service) makeSpec() *corev1.Service { Name: s.Settings.Name, Namespace: s.Settings.Namespace, Annotations: map[string]string{ - cc.AnnCreatedBy: "yes", + annotations.AnnCreatedBy: "yes", }, Labels: map[string]string{}, OwnerReferences: []metav1.OwnerReference{ @@ -84,7 +84,7 @@ func (s *Service) makeSpec() *corev1.Service { }, }, Selector: map[string]string{ - cc.UploaderServiceLabel: s.Settings.Name, + annotations.UploaderServiceLabel: s.Settings.Name, }, Type: corev1.ServiceTypeClusterIP, }, @@ -98,5 +98,5 @@ type ServiceNamer interface { } func FindService(ctx context.Context, client client.Client, name ServiceNamer) (*corev1.Service, error) { - return helper.FetchObject(ctx, name.UploaderService(), client, &corev1.Service{}) + return object.FetchObject(ctx, name.UploaderService(), client, &corev1.Service{}) } diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/blank.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/blank.go index 813a1a630..eef7fdfb2 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/blank.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/blank.go @@ -25,7 +25,8 @@ import ( cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" @@ -61,7 +62,7 @@ func (ds BlankDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (rec cb := conditions.NewConditionBuilder(vdcondition.ReadyType).Generation(vd.Generation) defer func() { conditions.SetCondition(cb, &vd.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) dv, err := ds.diskService.GetDataVolume(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -95,7 +96,7 @@ func (ds BlankDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (rec } return CleanUpSupplements(ctx, vd, ds) - case common.AnyTerminating(dv, pvc): + case object.AnyTerminating(dv, pvc): log.Info("Waiting for supplements to be terminated") case dv == nil: log.Info("Start import to PVC") @@ -169,7 +170,7 @@ func (ds BlankDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (rec } func (ds BlankDataSource) CleanUp(ctx context.Context, vd *virtv2.VirtualDisk) (bool, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) requeue, err := ds.diskService.CleanUp(ctx, supgen) if err != nil { @@ -180,7 +181,7 @@ func (ds BlankDataSource) CleanUp(ctx context.Context, vd *virtv2.VirtualDisk) ( } func (ds BlankDataSource) CleanUpSupplements(ctx context.Context, vd *virtv2.VirtualDisk) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) requeue, err := ds.diskService.CleanUpSupplements(ctx, supgen) if err != nil { diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/http.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/http.go index acdaa2c12..a06ebfb97 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/http.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/http.go @@ -27,15 +27,17 @@ import ( cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" "github.com/deckhouse/virtualization-controller/pkg/logger" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vdcondition" @@ -74,7 +76,7 @@ func (ds HTTPDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (reco cb := conditions.NewConditionBuilder(vdcondition.ReadyType).Generation(vd.Generation) defer func() { conditions.SetCondition(cb, &vd.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -118,7 +120,7 @@ func (ds HTTPDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (reco } return CleanUpSupplements(ctx, vd, ds) - case common.AnyTerminating(pod, dv, pvc): + case object.AnyTerminating(pod, dv, pvc): log.Info("Waiting for supplements to be terminated") case pod == nil: log.Info("Start import to DVCR") @@ -144,7 +146,7 @@ func (ds HTTPDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (reco Message("DVCR Provisioner not found: create the new one.") return reconcile.Result{Requeue: true}, nil - case !common.IsPodComplete(pod): + case !podutil.IsPodComplete(pod): log.Info("Provisioning to DVCR is in progress", "podPhase", pod.Status.Phase) err = ds.statService.CheckPod(pod) @@ -281,7 +283,7 @@ func (ds HTTPDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (reco } func (ds HTTPDataSource) CleanUp(ctx context.Context, vd *virtv2.VirtualDisk) (bool, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) importerRequeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { @@ -301,7 +303,7 @@ func (ds HTTPDataSource) Validate(_ context.Context, _ *virtv2.VirtualDisk) erro } func (ds HTTPDataSource) CleanUpSupplements(ctx context.Context, vd *virtv2.VirtualDisk) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) importerRequeue, err := ds.importerService.CleanUpSupplements(ctx, supgen) if err != nil { @@ -338,7 +340,7 @@ func (ds HTTPDataSource) getSource(sup *supplements.Generator, dvcrSourceImageNa // The image was preloaded from source into dvcr. // We can't use the same data source a second time, but we can set dvcr as the data source. // Use DV name for the Secret with DVCR auth and the ConfigMap with DVCR CA Bundle. - url := cc.DockerRegistrySchemePrefix + dvcrSourceImageName + url := common.DockerRegistrySchemePrefix + dvcrSourceImageName secretName := sup.DVCRAuthSecretForDV().Name certConfigMapName := sup.DVCRCABundleConfigMapForDV().Name diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref.go index 928bbbf4a..9305fa5f9 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref.go @@ -23,7 +23,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" @@ -86,7 +86,7 @@ func (ds ObjectRefDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) } func (ds ObjectRefDataSource) CleanUp(ctx context.Context, vd *virtv2.VirtualDisk) (bool, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) requeue, err := ds.diskService.CleanUp(ctx, supgen) if err != nil { diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_cvi.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_cvi.go index 27fae0d60..ebc47910f 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_cvi.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_cvi.go @@ -27,14 +27,15 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - common2 "github.com/deckhouse/virtualization-controller/pkg/common" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vdcondition" ) @@ -72,7 +73,7 @@ func (ds ObjectRefClusterVirtualImage) Sync(ctx context.Context, vd *virtv2.Virt defer func() { conditions.SetCondition(cb, &vd.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) dv, err := ds.diskService.GetDataVolume(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -113,13 +114,13 @@ func (ds ObjectRefClusterVirtualImage) Sync(ctx context.Context, vd *virtv2.Virt } return CleanUpSupplements(ctx, vd, ds) - case common.AnyTerminating(dv, pvc): + case object.AnyTerminating(dv, pvc): log.Info("Waiting for supplements to be terminated") case dv == nil: log.Info("Start import to PVC") vd.Status.Progress = "0%" - vd.Status.SourceUID = util.GetPointer(cvi.GetUID()) + vd.Status.SourceUID = pointer.GetPointer(cvi.GetUID()) if imageformat.IsISO(cvi.Status.Format) { setPhaseConditionToFailed(cb, &vd.Status.Phase, ErrISOSourceNotSupported) @@ -213,7 +214,7 @@ func (ds ObjectRefClusterVirtualImage) Validate(ctx context.Context, vd *virtv2. } func (ds ObjectRefClusterVirtualImage) CleanUpSupplements(ctx context.Context, vd *virtv2.VirtualDisk) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) requeue, err := ds.diskService.CleanUpSupplements(ctx, supgen) if err != nil { @@ -224,7 +225,7 @@ func (ds ObjectRefClusterVirtualImage) CleanUpSupplements(ctx context.Context, v } func (ds ObjectRefClusterVirtualImage) getSource(sup *supplements.Generator, cvi *virtv2.ClusterVirtualImage) *cdiv1.DataVolumeSource { - url := common2.DockerRegistrySchemePrefix + cvi.Status.Target.RegistryURL + url := common.DockerRegistrySchemePrefix + cvi.Status.Target.RegistryURL secretName := sup.DVCRAuthSecretForDV().Name certConfigMapName := sup.DVCRCABundleConfigMapForDV().Name diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vdsnapshot.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vdsnapshot.go index f53ff8bf6..81f5339f2 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vdsnapshot.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vdsnapshot.go @@ -27,12 +27,13 @@ import ( "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vdcondition" ) @@ -54,7 +55,7 @@ func (ds ObjectRefVirtualDiskSnapshot) Sync(ctx context.Context, vd *virtv2.Virt log, ctx := logger.GetDataSourceContext(ctx, objectRefDataSource) - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) condition, _ := conditions.GetCondition(vdcondition.ReadyType, vd.Status.Conditions) cb := conditions.NewConditionBuilder(vdcondition.ReadyType).Generation(vd.Generation) @@ -85,13 +86,13 @@ func (ds ObjectRefVirtualDiskSnapshot) Sync(ctx context.Context, vd *virtv2.Virt } return reconcile.Result{}, nil - case common.IsTerminating(pvc): + case object.IsTerminating(pvc): log.Info("Waiting for supplements to be terminated") return reconcile.Result{Requeue: true}, nil case pvc == nil: log.Info("Start import to PVC") - namespacedName := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID).PersistentVolumeClaim() + namespacedName := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID).PersistentVolumeClaim() storageClassName := vs.Annotations["storageClass"] volumeMode := vs.Annotations["volumeMode"] @@ -151,7 +152,7 @@ func (ds ObjectRefVirtualDiskSnapshot) Sync(ctx context.Context, vd *virtv2.Virt Message("PVC has created: waiting to be Bound.") vd.Status.Progress = "0%" - vd.Status.SourceUID = util.GetPointer(vs.UID) + vd.Status.SourceUID = pointer.GetPointer(vs.UID) vd.Status.Capacity = ds.diskService.GetCapacity(pvc) vd.Status.Target.PersistentVolumeClaim = pvc.Name diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vi_dvcr.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vi_dvcr.go index 1005d8ba1..9d6417178 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vi_dvcr.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vi_dvcr.go @@ -27,14 +27,15 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - common2 "github.com/deckhouse/virtualization-controller/pkg/common" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vdcondition" ) @@ -71,7 +72,7 @@ func (ds ObjectRefVirtualImageDVCR) Sync(ctx context.Context, vd *virtv2.Virtual cb := conditions.NewConditionBuilder(vdcondition.ReadyType).Generation(vd.Generation) defer func() { conditions.SetCondition(cb, &vd.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) dv, err := ds.diskService.GetDataVolume(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -112,13 +113,13 @@ func (ds ObjectRefVirtualImageDVCR) Sync(ctx context.Context, vd *virtv2.Virtual } return CleanUpSupplements(ctx, vd, ds) - case common.AnyTerminating(dv, pvc): + case object.AnyTerminating(dv, pvc): log.Info("Waiting for supplements to be terminated") case dv == nil: log.Info("Start import to PVC") vd.Status.Progress = "0%" - vd.Status.SourceUID = util.GetPointer(vi.GetUID()) + vd.Status.SourceUID = pointer.GetPointer(vi.GetUID()) if imageformat.IsISO(vi.Status.Format) { setPhaseConditionToFailed(cb, &vd.Status.Phase, ErrISOSourceNotSupported) @@ -213,7 +214,7 @@ func (ds ObjectRefVirtualImageDVCR) Validate(ctx context.Context, vd *virtv2.Vir } func (ds ObjectRefVirtualImageDVCR) CleanUpSupplements(ctx context.Context, vd *virtv2.VirtualDisk) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) requeue, err := ds.diskService.CleanUpSupplements(ctx, supgen) if err != nil { @@ -224,7 +225,7 @@ func (ds ObjectRefVirtualImageDVCR) CleanUpSupplements(ctx context.Context, vd * } func (ds ObjectRefVirtualImageDVCR) getSource(sup *supplements.Generator, vi *virtv2.VirtualImage) *cdiv1.DataVolumeSource { - url := common2.DockerRegistrySchemePrefix + vi.Status.Target.RegistryURL + url := common.DockerRegistrySchemePrefix + vi.Status.Target.RegistryURL secretName := sup.DVCRAuthSecretForDV().Name certConfigMapName := sup.DVCRCABundleConfigMapForDV().Name diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vi_pvc.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vi_pvc.go index 385de139c..32d79b7e6 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vi_pvc.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/object_ref_vi_pvc.go @@ -26,13 +26,14 @@ import ( cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vdcondition" ) @@ -60,7 +61,7 @@ func (ds ObjectRefVirtualImagePVC) Sync(ctx context.Context, vd *virtv2.VirtualD cb := conditions.NewConditionBuilder(vdcondition.ReadyType).Generation(vd.Generation) defer func() { conditions.SetCondition(cb, &vd.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) dv, err := ds.diskService.GetDataVolume(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -101,13 +102,13 @@ func (ds ObjectRefVirtualImagePVC) Sync(ctx context.Context, vd *virtv2.VirtualD } return CleanUpSupplements(ctx, vd, ds) - case common.AnyTerminating(dv, pvc): + case object.AnyTerminating(dv, pvc): log.Info("Waiting for supplements to be terminated") case dv == nil: log.Info("Start import to PVC") vd.Status.Progress = "0%" - vd.Status.SourceUID = util.GetPointer(vi.GetUID()) + vd.Status.SourceUID = pointer.GetPointer(vi.GetUID()) if imageformat.IsISO(vi.Status.Format) { setPhaseConditionToFailed(cb, &vd.Status.Phase, ErrISOSourceNotSupported) @@ -208,7 +209,7 @@ func (ds ObjectRefVirtualImagePVC) Validate(ctx context.Context, vd *virtv2.Virt } func (ds ObjectRefVirtualImagePVC) CleanUpSupplements(ctx context.Context, vd *virtv2.VirtualDisk) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) diskRequeue, err := ds.diskService.CleanUpSupplements(ctx, supgen) if err != nil { diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/registry.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/registry.go index e0cbbf42e..66009ade8 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/registry.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/registry.go @@ -29,17 +29,18 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vdcondition" ) @@ -80,7 +81,7 @@ func (ds RegistryDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) ( cb := conditions.NewConditionBuilder(vdcondition.ReadyType).Generation(vd.Generation) defer func() { conditions.SetCondition(cb, &vd.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -124,7 +125,7 @@ func (ds RegistryDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) ( } return CleanUpSupplements(ctx, vd, ds) - case common.AnyTerminating(pod, dv, pvc): + case object.AnyTerminating(pod, dv, pvc): log.Info("Waiting for supplements to be terminated") case pod == nil: log.Info("Start import to DVCR") @@ -150,7 +151,7 @@ func (ds RegistryDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) ( Message("DVCR Provisioner not found: create the new one.") return reconcile.Result{Requeue: true}, nil - case !common.IsPodComplete(pod): + case !podutil.IsPodComplete(pod): log.Info("Provisioning to DVCR is in progress", "podPhase", pod.Status.Phase) err = ds.statService.CheckPod(pod) @@ -282,7 +283,7 @@ func (ds RegistryDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) ( } func (ds RegistryDataSource) CleanUp(ctx context.Context, vd *virtv2.VirtualDisk) (bool, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) importerRequeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { @@ -298,7 +299,7 @@ func (ds RegistryDataSource) CleanUp(ctx context.Context, vd *virtv2.VirtualDisk } func (ds RegistryDataSource) CleanUpSupplements(ctx context.Context, vd *virtv2.VirtualDisk) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) importerRequeue, err := ds.importerService.CleanUpSupplements(ctx, supgen) if err != nil { @@ -323,7 +324,7 @@ func (ds RegistryDataSource) Validate(ctx context.Context, vd *virtv2.VirtualDis Namespace: vd.GetNamespace(), Name: vd.Spec.DataSource.ContainerImage.ImagePullSecret.Name, } - secret, err := helper.FetchObject[*corev1.Secret](ctx, secretName, ds.client, &corev1.Secret{}) + secret, err := object.FetchObject[*corev1.Secret](ctx, secretName, ds.client, &corev1.Secret{}) if err != nil { return fmt.Errorf("failed to get secret %s: %w", secretName, err) } @@ -365,7 +366,7 @@ func (ds RegistryDataSource) getSource(sup *supplements.Generator, dvcrSourceIma // The image was preloaded from source into dvcr. // We can't use the same data source a second time, but we can set dvcr as the data source. // Use DV name for the Secret with DVCR auth and the ConfigMap with DVCR CA Bundle. - url := cc.DockerRegistrySchemePrefix + dvcrSourceImageName + url := common.DockerRegistrySchemePrefix + dvcrSourceImageName secretName := sup.DVCRAuthSecretForDV().Name certConfigMapName := sup.DVCRCABundleConfigMapForDV().Name diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/sources.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/sources.go index 928266920..3df01edaf 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/sources.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/sources.go @@ -28,7 +28,7 @@ import ( cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" @@ -92,7 +92,7 @@ type Cleaner interface { } func CleanUpSupplements(ctx context.Context, vd *virtv2.VirtualDisk, c Cleaner) (reconcile.Result, error) { - if cc.ShouldCleanupSubResources(vd) { + if object.ShouldCleanupSubResources(vd) { return c.CleanUpSupplements(ctx, vd) } diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/source/upload.go b/images/virtualization-artifact/pkg/controller/vd/internal/source/upload.go index 7ae4bcf8c..3b5eb91d3 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/source/upload.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/source/upload.go @@ -27,15 +27,17 @@ import ( cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - common2 "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/controller/uploader" "github.com/deckhouse/virtualization-controller/pkg/dvcr" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" "github.com/deckhouse/virtualization-controller/pkg/logger" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vdcondition" @@ -74,7 +76,7 @@ func (ds UploadDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (re cb := conditions.NewConditionBuilder(vdcondition.ReadyType).Generation(vd.Generation) defer func() { conditions.SetCondition(cb, &vd.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) pod, err := ds.uploaderService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -126,7 +128,7 @@ func (ds UploadDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (re } return CleanUpSupplements(ctx, vd, ds) - case common.AnyTerminating(pod, svc, ing, dv, pvc): + case object.AnyTerminating(pod, svc, ing, dv, pvc): log.Info("Waiting for supplements to be terminated") case pod == nil || svc == nil || ing == nil: log.Info("Start import to DVCR") @@ -152,7 +154,7 @@ func (ds UploadDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (re Message("DVCR Provisioner not found: create the new one.") return reconcile.Result{Requeue: true}, nil - case !common.IsPodComplete(pod): + case !podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { vd.Status.Phase = virtv2.DiskFailed @@ -315,7 +317,7 @@ func (ds UploadDataSource) Sync(ctx context.Context, vd *virtv2.VirtualDisk) (re } func (ds UploadDataSource) CleanUp(ctx context.Context, vd *virtv2.VirtualDisk) (bool, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) uploaderRequeue, err := ds.uploaderService.CleanUp(ctx, supgen) if err != nil { @@ -331,7 +333,7 @@ func (ds UploadDataSource) CleanUp(ctx context.Context, vd *virtv2.VirtualDisk) } func (ds UploadDataSource) CleanUpSupplements(ctx context.Context, vd *virtv2.VirtualDisk) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) uploaderRequeue, err := ds.uploaderService.CleanUpSupplements(ctx, supgen) if err != nil { @@ -371,7 +373,7 @@ func (ds UploadDataSource) getSource(sup *supplements.Generator, dvcrSourceImage // The image was preloaded from source into dvcr. // We can't use the same data source a second time, but we can set dvcr as the data source. // Use DV name for the Secret with DVCR auth and the ConfigMap with DVCR CA Bundle. - url := common2.DockerRegistrySchemePrefix + dvcrSourceImageName + url := common.DockerRegistrySchemePrefix + dvcrSourceImageName secretName := sup.DVCRAuthSecretForDV().Name certConfigMapName := sup.DVCRCABundleConfigMapForDV().Name diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/stats.go b/images/virtualization-artifact/pkg/controller/vd/internal/stats.go index 11406f954..1adceedaa 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/stats.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/stats.go @@ -24,7 +24,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" @@ -73,7 +73,7 @@ func (h StatsHandler) Handle(ctx context.Context, vd *virtv2.VirtualDisk) (recon return reconcile.Result{}, nil } - supgen := supplements.NewGenerator(common.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) var pod *corev1.Pod var err error diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/storageclass_ready.go b/images/virtualization-artifact/pkg/controller/vd/internal/storageclass_ready.go index fe8914f97..19534e387 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/storageclass_ready.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/storageclass_ready.go @@ -24,7 +24,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" @@ -55,7 +55,7 @@ func (h StorageClassReadyHandler) Handle(ctx context.Context, vd *virtv2.Virtual return reconcile.Result{}, nil } - supgen := supplements.NewGenerator(cc.VDShortName, vd.Name, vd.Namespace, vd.UID) + supgen := supplements.NewGenerator(annotations.VDShortName, vd.Name, vd.Namespace, vd.UID) pvc, err := h.service.GetPersistentVolumeClaim(ctx, supgen) if err != nil { return reconcile.Result{}, err diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/validators/iso_source_validator.go b/images/virtualization-artifact/pkg/controller/vd/internal/validators/iso_source_validator.go index 1b645248c..fff436613 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/validators/iso_source_validator.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/validators/iso_source_validator.go @@ -22,10 +22,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" "github.com/deckhouse/virtualization-controller/pkg/controller" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/vd/internal/source" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/validators/pvc_size_validator.go b/images/virtualization-artifact/pkg/controller/vd/internal/validators/pvc_size_validator.go index 1e2723687..a7c92d88e 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/validators/pvc_size_validator.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/validators/pvc_size_validator.go @@ -29,10 +29,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vdcondition" ) @@ -78,7 +78,7 @@ func (v *PVCSizeValidator) ValidateCreate(ctx context.Context, vd *virtv2.Virtua } case virtv2.VirtualDiskObjectRefKindVirtualDiskSnapshot: - vdSnapshot, err := helper.FetchObject(ctx, types.NamespacedName{ + vdSnapshot, err := object.FetchObject(ctx, types.NamespacedName{ Name: vd.Spec.DataSource.ObjectRef.Name, Namespace: vd.Namespace, }, v.client, &virtv2.VirtualDiskSnapshot{}) @@ -90,7 +90,7 @@ func (v *PVCSizeValidator) ValidateCreate(ctx context.Context, vd *virtv2.Virtua return nil, nil } - vs, err := helper.FetchObject(ctx, types.NamespacedName{ + vs, err := object.FetchObject(ctx, types.NamespacedName{ Name: vdSnapshot.Status.VolumeSnapshotName, Namespace: vdSnapshot.Namespace, }, v.client, &vsv1.VolumeSnapshot{}) @@ -174,7 +174,7 @@ func (v *PVCSizeValidator) ValidateUpdate(ctx context.Context, oldVD, newVD *vir } case virtv2.VirtualDiskObjectRefKindVirtualDiskSnapshot: - vdSnapshot, err := helper.FetchObject(ctx, types.NamespacedName{ + vdSnapshot, err := object.FetchObject(ctx, types.NamespacedName{ Name: newVD.Spec.DataSource.ObjectRef.Name, Namespace: newVD.Namespace, }, v.client, &virtv2.VirtualDiskSnapshot{}) @@ -186,7 +186,7 @@ func (v *PVCSizeValidator) ValidateUpdate(ctx context.Context, oldVD, newVD *vir return nil, nil } - vs, err := helper.FetchObject(ctx, types.NamespacedName{ + vs, err := object.FetchObject(ctx, types.NamespacedName{ Name: vdSnapshot.Status.VolumeSnapshotName, Namespace: vdSnapshot.Namespace, }, v.client, &vsv1.VolumeSnapshot{}) diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/watcher/storageclass_watcher.go b/images/virtualization-artifact/pkg/controller/vd/internal/watcher/storageclass_watcher.go index 82449c18b..5241e70a8 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/watcher/storageclass_watcher.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/watcher/storageclass_watcher.go @@ -34,7 +34,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/controller/indexer" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -64,8 +64,8 @@ func (w StorageClassWatcher) Watch(mgr manager.Manager, ctr controller.Controlle if !oldOk || !newOk { return false } - oldIsDefault, oldIsDefaultOk := oldSC.Annotations[common.AnnDefaultStorageClass] - newIsDefault, newIsDefaultOk := newSC.Annotations[common.AnnDefaultStorageClass] + oldIsDefault, oldIsDefaultOk := oldSC.Annotations[annotations.AnnDefaultStorageClass] + newIsDefault, newIsDefaultOk := newSC.Annotations[annotations.AnnDefaultStorageClass] switch { case oldIsDefaultOk && newIsDefaultOk: return oldIsDefault != newIsDefault @@ -102,7 +102,7 @@ func (w StorageClassWatcher) enqueueRequests(ctx context.Context, object client. vds.Items = []virtv2.VirtualDisk{} - isDefault, ok := sc.Annotations[common.AnnDefaultStorageClass] + isDefault, ok := sc.Annotations[annotations.AnnDefaultStorageClass] if ok && isDefault == "true" { err := w.client.List(ctx, &vds, &client.ListOptions{ FieldSelector: fields.OneTermEqualSelector(indexer.IndexFieldVDByStorageClass, indexer.DefaultStorageClass), diff --git a/images/virtualization-artifact/pkg/controller/vd/internal/watcher/vdsnapshot_watcher.go b/images/virtualization-artifact/pkg/controller/vd/internal/watcher/vdsnapshot_watcher.go index 215704349..e4fb95d2d 100644 --- a/images/virtualization-artifact/pkg/controller/vd/internal/watcher/vdsnapshot_watcher.go +++ b/images/virtualization-artifact/pkg/controller/vd/internal/watcher/vdsnapshot_watcher.go @@ -33,8 +33,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/indexer" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -70,7 +70,7 @@ func (w VirtualDiskSnapshotWatcher) enqueueRequests(ctx context.Context, obj cli } // 1. Need to reconcile the virtual disk from which the snapshot was taken. - vd, err := helper.FetchObject(ctx, types.NamespacedName{ + vd, err := object.FetchObject(ctx, types.NamespacedName{ Name: vdSnapshot.Spec.VirtualDiskName, Namespace: vdSnapshot.Namespace, }, w.client, &virtv2.VirtualDisk{}) diff --git a/images/virtualization-artifact/pkg/controller/vi/internal/source/http.go b/images/virtualization-artifact/pkg/controller/vi/internal/source/http.go index 73b73d094..8eeecc7d4 100644 --- a/images/virtualization-artifact/pkg/controller/vi/internal/source/http.go +++ b/images/virtualization-artifact/pkg/controller/vi/internal/source/http.go @@ -28,8 +28,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" @@ -71,7 +73,7 @@ func (ds HTTPDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.VirtualImag cb := conditions.NewConditionBuilder(vicondition.ReadyType).Generation(vi.Generation) defer func() { conditions.SetCondition(cb, &vi.Status.Conditions) }() - supgen := supplements.NewGenerator(cc.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -94,7 +96,7 @@ func (ds HTTPDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.VirtualImag } return CleanUpSupplements(ctx, vi, ds) - case cc.IsTerminating(pod): + case object.IsTerminating(pod): vi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -107,7 +109,7 @@ func (ds HTTPDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.VirtualImag switch { case err == nil: // OK. - case cc.ErrQuotaExceeded(err): + case common.ErrQuotaExceeded(err): return setQuotaExceededPhaseCondition(cb, &vi.Status.Phase, err, vi.CreationTimestamp), nil default: setPhaseConditionToFailed(cb, &vi.Status.Phase, fmt.Errorf("unexpected error: %w", err)) @@ -123,7 +125,7 @@ func (ds HTTPDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.VirtualImag log.Info("Create importer pod...", "progress", vi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case cc.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { vi.Status.Phase = virtv2.ImageFailed @@ -188,7 +190,7 @@ func (ds HTTPDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualImage cb := conditions.NewConditionBuilder(vicondition.ReadyType).Generation(vi.Generation) defer func() { conditions.SetCondition(cb, &vi.Status.Conditions) }() - supgen := supplements.NewGenerator(cc.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -232,7 +234,7 @@ func (ds HTTPDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualImage } return CleanUpSupplements(ctx, vi, ds) - case cc.AnyTerminating(pod, dv, pvc): + case object.AnyTerminating(pod, dv, pvc): log.Info("Waiting for supplements to be terminated") case pod == nil: vi.Status.Progress = ds.statService.GetProgress(vi.GetUID(), pod, vi.Status.Progress) @@ -242,7 +244,7 @@ func (ds HTTPDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualImage switch { case err == nil: // OK. - case cc.ErrQuotaExceeded(err): + case common.ErrQuotaExceeded(err): return setQuotaExceededPhaseCondition(cb, &vi.Status.Phase, err, vi.CreationTimestamp), nil default: setPhaseConditionToFailed(cb, &vi.Status.Phase, fmt.Errorf("unexpected error: %w", err)) @@ -258,7 +260,7 @@ func (ds HTTPDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualImage log.Info("Create importer pod...", "progress", vi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case !cc.IsPodComplete(pod): + case !podutil.IsPodComplete(pod): log.Info("Provisioning to DVCR is in progress", "podPhase", pod.Status.Phase) err = ds.statService.CheckPod(pod) @@ -370,7 +372,7 @@ func (ds HTTPDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualImage } func (ds HTTPDataSource) CleanUp(ctx context.Context, vi *virtv2.VirtualImage) (bool, error) { - supgen := supplements.NewGenerator(cc.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { @@ -386,7 +388,7 @@ func (ds HTTPDataSource) CleanUp(ctx context.Context, vi *virtv2.VirtualImage) ( } func (ds HTTPDataSource) CleanUpSupplements(ctx context.Context, vi *virtv2.VirtualImage) (reconcile.Result, error) { - supgen := supplements.NewGenerator(cc.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUpSupplements(ctx, supgen) if err != nil { diff --git a/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref.go b/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref.go index 6130d015e..bcbad6fcd 100644 --- a/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref.go +++ b/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref.go @@ -28,18 +28,19 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" "github.com/deckhouse/virtualization-controller/pkg/controller" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vicondition" ) @@ -94,7 +95,7 @@ func (ds ObjectRefDataSource) StoreToPVC(ctx context.Context, vi *virtv2.Virtual switch vi.Spec.DataSource.ObjectRef.Kind { case virtv2.VirtualImageKind: viKey := types.NamespacedName{Name: vi.Spec.DataSource.ObjectRef.Name, Namespace: vi.Namespace} - viRef, err := helper.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) + viRef, err := object.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) if err != nil { return reconcile.Result{}, fmt.Errorf("unable to get VI %s: %w", viKey, err) } @@ -108,7 +109,7 @@ func (ds ObjectRefDataSource) StoreToPVC(ctx context.Context, vi *virtv2.Virtual } case virtv2.VirtualDiskKind: viKey := types.NamespacedName{Name: vi.Spec.DataSource.ObjectRef.Name, Namespace: vi.Namespace} - vd, err := helper.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualDisk{}) + vd, err := object.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualDisk{}) if err != nil { return reconcile.Result{}, fmt.Errorf("unable to get VI %s: %w", viKey, err) } @@ -120,7 +121,7 @@ func (ds ObjectRefDataSource) StoreToPVC(ctx context.Context, vi *virtv2.Virtual return ds.vdSyncer.StoreToPVC(ctx, vi, vd, cb) } - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) dv, err := ds.diskService.GetDataVolume(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -148,7 +149,7 @@ func (ds ObjectRefDataSource) StoreToPVC(ctx context.Context, vi *virtv2.Virtual } return CleanUpSupplements(ctx, vi, ds) - case common.AnyTerminating(dv, pvc): + case object.AnyTerminating(dv, pvc): log.Info("Waiting for supplements to be terminated") case dv == nil: log.Info("Start import to PVC") @@ -167,7 +168,7 @@ func (ds ObjectRefDataSource) StoreToPVC(ctx context.Context, vi *virtv2.Virtual } vi.Status.Progress = "0%" - vi.Status.SourceUID = util.GetPointer(dvcrDataSource.GetUID()) + vi.Status.SourceUID = pointer.GetPointer(dvcrDataSource.GetUID()) var diskSize resource.Quantity diskSize, err = ds.getPVCSize(dvcrDataSource) @@ -258,7 +259,7 @@ func (ds ObjectRefDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtua switch vi.Spec.DataSource.ObjectRef.Kind { case virtv2.VirtualImageKind: viKey := types.NamespacedName{Name: vi.Spec.DataSource.ObjectRef.Name, Namespace: vi.Namespace} - viRef, err := helper.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) + viRef, err := object.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) if err != nil { return reconcile.Result{}, fmt.Errorf("unable to get VI %s: %w", viKey, err) } @@ -272,7 +273,7 @@ func (ds ObjectRefDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtua } case virtv2.VirtualDiskKind: viKey := types.NamespacedName{Name: vi.Spec.DataSource.ObjectRef.Name, Namespace: vi.Namespace} - vd, err := helper.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualDisk{}) + vd, err := object.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualDisk{}) if err != nil { return reconcile.Result{}, fmt.Errorf("unable to get VD %s: %w", viKey, err) } @@ -284,7 +285,7 @@ func (ds ObjectRefDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtua return ds.vdSyncer.StoreToDVCR(ctx, vi, vd, cb) } - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -307,7 +308,7 @@ func (ds ObjectRefDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtua } return CleanUpSupplements(ctx, vi, ds) - case common.IsTerminating(pod): + case object.IsTerminating(pod): vi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -320,7 +321,7 @@ func (ds ObjectRefDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtua return reconcile.Result{}, err } - vi.Status.SourceUID = util.GetPointer(dvcrDataSource.GetUID()) + vi.Status.SourceUID = pointer.GetPointer(dvcrDataSource.GetUID()) var envSettings *importer.Settings envSettings, err = ds.getEnvSettings(vi, supgen, dvcrDataSource) @@ -348,7 +349,7 @@ func (ds ObjectRefDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtua log.Info("Ready", "progress", vi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { vi.Status.Phase = virtv2.ImageFailed @@ -412,7 +413,7 @@ func (ds ObjectRefDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtua } func (ds ObjectRefDataSource) CleanUp(ctx context.Context, vi *virtv2.VirtualImage) (bool, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { @@ -435,7 +436,7 @@ func (ds ObjectRefDataSource) Validate(ctx context.Context, vi *virtv2.VirtualIm switch vi.Spec.DataSource.ObjectRef.Kind { case virtv2.VirtualImageObjectRefKindVirtualImage: viKey := types.NamespacedName{Name: vi.Spec.DataSource.ObjectRef.Name, Namespace: vi.Namespace} - viRef, err := helper.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) + viRef, err := object.FetchObject(ctx, viKey, ds.client, &virtv2.VirtualImage{}) if err != nil { return fmt.Errorf("unable to get VI %s: %w", viKey, err) } @@ -497,7 +498,7 @@ func (ds ObjectRefDataSource) getEnvSettings(vi *virtv2.VirtualImage, sup *suppl } func (ds ObjectRefDataSource) CleanUpSupplements(ctx context.Context, vi *virtv2.VirtualImage) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUpSupplements(ctx, supgen) if err != nil { @@ -534,7 +535,7 @@ func (ds ObjectRefDataSource) getSource(sup *supplements.Generator, dvcrDataSour return nil, errors.New("dvcr data source is not ready") } - url := cc.DockerRegistrySchemePrefix + dvcrDataSource.GetTarget() + url := common.DockerRegistrySchemePrefix + dvcrDataSource.GetTarget() secretName := sup.DVCRAuthSecretForDV().Name certConfigMapName := sup.DVCRCABundleConfigMapForDV().Name diff --git a/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref_vd.go b/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref_vd.go index 0dbdbceab..49a36563c 100644 --- a/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref_vd.go +++ b/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref_vd.go @@ -28,17 +28,19 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/imageformat" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" - "github.com/deckhouse/virtualization-controller/pkg/imageformat" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vicondition" ) @@ -73,7 +75,7 @@ func NewObjectRefVirtualDisk( func (ds ObjectRefVirtualDisk) StoreToDVCR(ctx context.Context, vi *virtv2.VirtualImage, vdRef *virtv2.VirtualDisk, cb *conditions.ConditionBuilder) (reconcile.Result, error) { log, ctx := logger.GetDataSourceContext(ctx, "objectref") - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vdRef.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vdRef.Namespace, vi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -96,7 +98,7 @@ func (ds ObjectRefVirtualDisk) StoreToDVCR(ctx context.Context, vi *virtv2.Virtu } return CleanUpSupplements(ctx, vi, ds) - case common.IsTerminating(pod): + case object.IsTerminating(pod): vi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -128,7 +130,7 @@ func (ds ObjectRefVirtualDisk) StoreToDVCR(ctx context.Context, vi *virtv2.Virtu log.Info("Create importer pod...", "progress", vi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { vi.Status.Phase = virtv2.ImageFailed @@ -204,7 +206,7 @@ func (ds ObjectRefVirtualDisk) StoreToDVCR(ctx context.Context, vi *virtv2.Virtu func (ds ObjectRefVirtualDisk) StoreToPVC(ctx context.Context, vi *virtv2.VirtualImage, vdRef *virtv2.VirtualDisk, cb *conditions.ConditionBuilder) (reconcile.Result, error) { log, ctx := logger.GetDataSourceContext(ctx, objectRefDataSource) - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) dv, err := ds.diskService.GetDataVolume(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -239,13 +241,13 @@ func (ds ObjectRefVirtualDisk) StoreToPVC(ctx context.Context, vi *virtv2.Virtua } return CleanUpSupplements(ctx, vi, ds) - case common.AnyTerminating(dv, pvc): + case object.AnyTerminating(dv, pvc): log.Info("Waiting for supplements to be terminated") case dv == nil: log.Info("Start import to PVC") vi.Status.Progress = "0%" - vi.Status.SourceUID = util.GetPointer(vdRef.GetUID()) + vi.Status.SourceUID = pointer.GetPointer(vdRef.GetUID()) source := &cdiv1.DataVolumeSource{ PVC: &cdiv1.DataVolumeSourcePVC{ @@ -318,7 +320,7 @@ func (ds ObjectRefVirtualDisk) StoreToPVC(ctx context.Context, vi *virtv2.Virtua } func (ds ObjectRefVirtualDisk) CleanUpSupplements(ctx context.Context, vi *virtv2.VirtualImage) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUpSupplements(ctx, supgen) if err != nil { @@ -334,7 +336,7 @@ func (ds ObjectRefVirtualDisk) CleanUpSupplements(ctx context.Context, vi *virtv } func (ds ObjectRefVirtualDisk) CleanUp(ctx context.Context, vi *virtv2.VirtualImage) (bool, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { @@ -367,7 +369,7 @@ func (ds ObjectRefVirtualDisk) Validate(ctx context.Context, vi *virtv2.VirtualI return fmt.Errorf("not a %s data source", virtv2.ClusterVirtualImageObjectRefKindVirtualDisk) } - vd, err := helper.FetchObject(ctx, types.NamespacedName{Name: vi.Spec.DataSource.ObjectRef.Name, Namespace: vi.Namespace}, ds.client, &virtv2.VirtualDisk{}) + vd, err := object.FetchObject(ctx, types.NamespacedName{Name: vi.Spec.DataSource.ObjectRef.Name, Namespace: vi.Namespace}, ds.client, &virtv2.VirtualDisk{}) if err != nil { return err } @@ -378,7 +380,7 @@ func (ds ObjectRefVirtualDisk) Validate(ctx context.Context, vi *virtv2.VirtualI if len(vd.Status.AttachedToVirtualMachines) > 0 { vmName := vd.Status.AttachedToVirtualMachines[0] - vm, err := helper.FetchObject(ctx, types.NamespacedName{Name: vmName.Name, Namespace: vd.Namespace}, ds.client, &virtv2.VirtualMachine{}) + vm, err := object.FetchObject(ctx, types.NamespacedName{Name: vmName.Name, Namespace: vd.Namespace}, ds.client, &virtv2.VirtualMachine{}) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref_vi_on_pvc.go b/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref_vi_on_pvc.go index b0bd54b28..b41cc43e7 100644 --- a/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref_vi_on_pvc.go +++ b/images/virtualization-artifact/pkg/controller/vi/internal/source/object_ref_vi_on_pvc.go @@ -27,15 +27,18 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" + "github.com/deckhouse/virtualization-controller/pkg/common/pointer" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vicondition" ) @@ -70,7 +73,7 @@ func NewObjectRefDataVirtualImageOnPVC( func (ds ObjectRefDataVirtualImageOnPVC) StoreToDVCR(ctx context.Context, vi, viRef *virtv2.VirtualImage, cb *conditions.ConditionBuilder) (reconcile.Result, error) { log, ctx := logger.GetDataSourceContext(ctx, "objectref") - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -93,7 +96,7 @@ func (ds ObjectRefDataVirtualImageOnPVC) StoreToDVCR(ctx context.Context, vi, vi } return CleanUpSupplements(ctx, vi, ds) - case common.IsTerminating(pod): + case object.IsTerminating(pod): vi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -125,7 +128,7 @@ func (ds ObjectRefDataVirtualImageOnPVC) StoreToDVCR(ctx context.Context, vi, vi log.Info("Create importer pod...", "progress", vi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { vi.Status.Phase = virtv2.ImageFailed @@ -184,7 +187,7 @@ func (ds ObjectRefDataVirtualImageOnPVC) StoreToDVCR(ctx context.Context, vi, vi func (ds ObjectRefDataVirtualImageOnPVC) StoreToPVC(ctx context.Context, vi, viRef *virtv2.VirtualImage, cb *conditions.ConditionBuilder) (reconcile.Result, error) { log, _ := logger.GetDataSourceContext(ctx, objectRefDataSource) - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) dv, err := ds.diskService.GetDataVolume(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -218,13 +221,13 @@ func (ds ObjectRefDataVirtualImageOnPVC) StoreToPVC(ctx context.Context, vi, viR } return CleanUpSupplements(ctx, vi, ds) - case common.AnyTerminating(dv, pvc): + case object.AnyTerminating(dv, pvc): log.Info("Waiting for supplements to be terminated") case dv == nil: log.Info("Start import to PVC") vi.Status.Progress = "0%" - vi.Status.SourceUID = util.GetPointer(viRef.GetUID()) + vi.Status.SourceUID = pointer.GetPointer(viRef.GetUID()) size, err := ds.getPVCSize(viRef.Status.Size) if err != nil { @@ -299,7 +302,7 @@ func (ds ObjectRefDataVirtualImageOnPVC) StoreToPVC(ctx context.Context, vi, viR } func (ds ObjectRefDataVirtualImageOnPVC) CleanUp(ctx context.Context, vi *virtv2.VirtualImage) (bool, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { @@ -328,7 +331,7 @@ func (ds ObjectRefDataVirtualImageOnPVC) getEnvSettings(vi *virtv2.VirtualImage, } func (ds ObjectRefDataVirtualImageOnPVC) CleanUpSupplements(ctx context.Context, vi *virtv2.VirtualImage) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUpSupplements(ctx, supgen) if err != nil { diff --git a/images/virtualization-artifact/pkg/controller/vi/internal/source/registry.go b/images/virtualization-artifact/pkg/controller/vi/internal/source/registry.go index 06dacc731..b26c64c46 100644 --- a/images/virtualization-artifact/pkg/controller/vi/internal/source/registry.go +++ b/images/virtualization-artifact/pkg/controller/vi/internal/source/registry.go @@ -29,16 +29,17 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/importer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" "github.com/deckhouse/virtualization-controller/pkg/dvcr" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vicondition" ) @@ -79,7 +80,7 @@ func (ds RegistryDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualI cb := conditions.NewConditionBuilder(vicondition.ReadyType).Generation(vi.Generation) defer func() { conditions.SetCondition(cb, &vi.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -123,7 +124,7 @@ func (ds RegistryDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualI } return CleanUpSupplements(ctx, vi, ds) - case common.AnyTerminating(pod, dv, pvc): + case object.AnyTerminating(pod, dv, pvc): log.Info("Waiting for supplements to be terminated") case pod == nil: log.Info("Start import to DVCR") @@ -149,7 +150,7 @@ func (ds RegistryDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualI Message("DVCR Provisioner not found: create the new one.") return reconcile.Result{Requeue: true}, nil - case !common.IsPodComplete(pod): + case !podutil.IsPodComplete(pod): log.Info("Provisioning to DVCR is in progress", "podPhase", pod.Status.Phase) err = ds.statService.CheckPod(pod) @@ -265,7 +266,7 @@ func (ds RegistryDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtual cb := conditions.NewConditionBuilder(vicondition.ReadyType).Generation(vi.Generation) defer func() { conditions.SetCondition(cb, &vi.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) pod, err := ds.importerService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -288,7 +289,7 @@ func (ds RegistryDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtual } return CleanUpSupplements(ctx, vi, ds) - case common.IsTerminating(pod): + case object.IsTerminating(pod): vi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -316,7 +317,7 @@ func (ds RegistryDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtual log.Info("Create importer pod...", "progress", vi.Status.Progress, "pod.phase", "nil") return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { vi.Status.Phase = virtv2.ImageFailed @@ -368,7 +369,7 @@ func (ds RegistryDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.Virtual } func (ds RegistryDataSource) CleanUp(ctx context.Context, vi *virtv2.VirtualImage) (bool, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUp(ctx, supgen) if err != nil { @@ -389,7 +390,7 @@ func (ds RegistryDataSource) Validate(ctx context.Context, vi *virtv2.VirtualIma Namespace: vi.GetNamespace(), Name: vi.Spec.DataSource.ContainerImage.ImagePullSecret.Name, } - secret, err := helper.FetchObject[*corev1.Secret](ctx, secretName, ds.client, &corev1.Secret{}) + secret, err := object.FetchObject[*corev1.Secret](ctx, secretName, ds.client, &corev1.Secret{}) if err != nil { return fmt.Errorf("failed to get secret %s: %w", secretName, err) } @@ -425,7 +426,7 @@ func (ds RegistryDataSource) getEnvSettings(vi *virtv2.VirtualImage, supgen *sup } func (ds RegistryDataSource) CleanUpSupplements(ctx context.Context, vi *virtv2.VirtualImage) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.importerService.CleanUpSupplements(ctx, supgen) if err != nil { @@ -458,7 +459,7 @@ func (ds RegistryDataSource) getSource(sup *supplements.Generator, dvcrSourceIma // The image was preloaded from source into dvcr. // We can't use the same data source a second time, but we can set dvcr as the data source. // Use DV name for the Secret with DVCR auth and the ConfigMap with DVCR CA Bundle. - url := cc.DockerRegistrySchemePrefix + dvcrSourceImageName + url := common.DockerRegistrySchemePrefix + dvcrSourceImageName secretName := sup.DVCRAuthSecretForDV().Name certConfigMapName := sup.DVCRCABundleConfigMapForDV().Name diff --git a/images/virtualization-artifact/pkg/controller/vi/internal/source/sources.go b/images/virtualization-artifact/pkg/controller/vi/internal/source/sources.go index 2d9ba7c88..ffb353894 100644 --- a/images/virtualization-artifact/pkg/controller/vi/internal/source/sources.go +++ b/images/virtualization-artifact/pkg/controller/vi/internal/source/sources.go @@ -27,7 +27,7 @@ import ( cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" @@ -86,7 +86,7 @@ type Cleaner interface { } func CleanUp(ctx context.Context, vi *virtv2.VirtualImage, c Cleaner) (bool, error) { - if cc.ShouldCleanupSubResources(vi) { + if object.ShouldCleanupSubResources(vi) { return c.CleanUp(ctx, vi) } @@ -94,7 +94,7 @@ func CleanUp(ctx context.Context, vi *virtv2.VirtualImage, c Cleaner) (bool, err } func CleanUpSupplements(ctx context.Context, vi *virtv2.VirtualImage, c Cleaner) (reconcile.Result, error) { - if cc.ShouldCleanupSubResources(vi) { + if object.ShouldCleanupSubResources(vi) { return c.CleanUpSupplements(ctx, vi) } diff --git a/images/virtualization-artifact/pkg/controller/vi/internal/source/upload.go b/images/virtualization-artifact/pkg/controller/vi/internal/source/upload.go index 3eacaa6e3..802cbc5d2 100644 --- a/images/virtualization-artifact/pkg/controller/vi/internal/source/upload.go +++ b/images/virtualization-artifact/pkg/controller/vi/internal/source/upload.go @@ -27,9 +27,11 @@ import ( cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/common/datasource" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" @@ -73,7 +75,7 @@ func (ds UploadDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualIma cb := conditions.NewConditionBuilder(vicondition.ReadyType).Generation(vi.Generation) defer func() { conditions.SetCondition(cb, &vi.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) pod, err := ds.uploaderService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -125,7 +127,7 @@ func (ds UploadDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualIma } return CleanUpSupplements(ctx, vi, ds) - case common.AnyTerminating(pod, svc, ing, dv, pvc): + case object.AnyTerminating(pod, svc, ing, dv, pvc): log.Info("Waiting for supplements to be terminated") case pod == nil || svc == nil || ing == nil: log.Info("Start import to DVCR") @@ -151,7 +153,7 @@ func (ds UploadDataSource) StoreToPVC(ctx context.Context, vi *virtv2.VirtualIma Message("DVCR Provisioner not found: create the new one.") return reconcile.Result{Requeue: true}, nil - case !common.IsPodComplete(pod): + case !podutil.IsPodComplete(pod): log.Info("Provisioning to DVCR is in progress", "podPhase", pod.Status.Phase) err = ds.statService.CheckPod(pod) @@ -298,7 +300,7 @@ func (ds UploadDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.VirtualIm cb := conditions.NewConditionBuilder(vicondition.ReadyType).Generation(vi.Generation) defer func() { conditions.SetCondition(cb, &vi.Status.Conditions) }() - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) pod, err := ds.uploaderService.GetPod(ctx, supgen) if err != nil { return reconcile.Result{}, err @@ -329,7 +331,7 @@ func (ds UploadDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.VirtualIm } return CleanUpSupplements(ctx, vi, ds) - case common.AnyTerminating(pod, svc, ing): + case object.AnyTerminating(pod, svc, ing): vi.Status.Phase = virtv2.ImagePending log.Info("Cleaning up...") @@ -355,7 +357,7 @@ func (ds UploadDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.VirtualIm log.Info("Create uploader pod...", "progress", vi.Status.Progress, "pod.phase", nil) return reconcile.Result{Requeue: true}, nil - case common.IsPodComplete(pod): + case podutil.IsPodComplete(pod): err = ds.statService.CheckPod(pod) if err != nil { vi.Status.Phase = virtv2.ImageFailed @@ -437,7 +439,7 @@ func (ds UploadDataSource) StoreToDVCR(ctx context.Context, vi *virtv2.VirtualIm } func (ds UploadDataSource) CleanUp(ctx context.Context, vi *virtv2.VirtualImage) (bool, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) importerRequeue, err := ds.uploaderService.CleanUp(ctx, supgen) if err != nil { @@ -470,7 +472,7 @@ func (ds UploadDataSource) getEnvSettings(vi *virtv2.VirtualImage, supgen *suppl } func (ds UploadDataSource) CleanUpSupplements(ctx context.Context, vi *virtv2.VirtualImage) (reconcile.Result, error) { - supgen := supplements.NewGenerator(common.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) uploaderRequeue, err := ds.uploaderService.CleanUpSupplements(ctx, supgen) if err != nil { @@ -503,7 +505,7 @@ func (ds UploadDataSource) getSource(sup *supplements.Generator, dvcrSourceImage // The image was preloaded from source into dvcr. // We can't use the same data source a second time, but we can set dvcr as the data source. // Use DV name for the Secret with DVCR auth and the ConfigMap with DVCR CA Bundle. - url := cc.DockerRegistrySchemePrefix + dvcrSourceImageName + url := common.DockerRegistrySchemePrefix + dvcrSourceImageName secretName := sup.DVCRAuthSecretForDV().Name certConfigMapName := sup.DVCRCABundleConfigMapForDV().Name diff --git a/images/virtualization-artifact/pkg/controller/vi/internal/storageclass_ready.go b/images/virtualization-artifact/pkg/controller/vi/internal/storageclass_ready.go index 0c53cedc6..bdf6a2039 100644 --- a/images/virtualization-artifact/pkg/controller/vi/internal/storageclass_ready.go +++ b/images/virtualization-artifact/pkg/controller/vi/internal/storageclass_ready.go @@ -24,7 +24,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/supplements" @@ -66,7 +66,7 @@ func (h StorageClassReadyHandler) Handle(ctx context.Context, vi *virtv2.Virtual return reconcile.Result{}, nil } - supgen := supplements.NewGenerator(cc.VIShortName, vi.Name, vi.Namespace, vi.UID) + supgen := supplements.NewGenerator(annotations.VIShortName, vi.Name, vi.Namespace, vi.UID) pvc, err := h.service.GetPersistentVolumeClaim(ctx, supgen) if err != nil { return reconcile.Result{}, err diff --git a/images/virtualization-artifact/pkg/controller/vi/internal/watcher/storageclass_watcher.go b/images/virtualization-artifact/pkg/controller/vi/internal/watcher/storageclass_watcher.go index 5a09a4352..aef1b74df 100644 --- a/images/virtualization-artifact/pkg/controller/vi/internal/watcher/storageclass_watcher.go +++ b/images/virtualization-artifact/pkg/controller/vi/internal/watcher/storageclass_watcher.go @@ -34,7 +34,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/controller/indexer" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -64,8 +64,8 @@ func (w StorageClassWatcher) Watch(mgr manager.Manager, ctr controller.Controlle if !oldOk || !newOk { return false } - oldIsDefault, oldIsDefaultOk := oldSC.Annotations[common.AnnDefaultStorageClass] - newIsDefault, newIsDefaultOk := newSC.Annotations[common.AnnDefaultStorageClass] + oldIsDefault, oldIsDefaultOk := oldSC.Annotations[annotations.AnnDefaultStorageClass] + newIsDefault, newIsDefaultOk := newSC.Annotations[annotations.AnnDefaultStorageClass] switch { case oldIsDefaultOk && newIsDefaultOk: return oldIsDefault != newIsDefault @@ -104,7 +104,7 @@ func (w StorageClassWatcher) enqueueRequests(ctx context.Context, object client. vis.Items = []virtv2.VirtualImage{} - isDefault, ok := sc.Annotations[common.AnnDefaultStorageClass] + isDefault, ok := sc.Annotations[annotations.AnnDefaultStorageClass] if ok && isDefault == "true" { err := w.client.List(ctx, &vis, &client.ListOptions{ FieldSelector: fields.OneTermEqualSelector(indexer.IndexFieldVIByStorageClass, indexer.DefaultStorageClass), diff --git a/images/virtualization-artifact/pkg/controller/vm/internal/block_device.go b/images/virtualization-artifact/pkg/controller/vm/internal/block_device.go index 4b1dab110..e9d4af7a9 100644 --- a/images/virtualization-artifact/pkg/controller/vm/internal/block_device.go +++ b/images/virtualization-artifact/pkg/controller/vm/internal/block_device.go @@ -30,7 +30,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/kvbuilder" "github.com/deckhouse/virtualization-controller/pkg/controller/service" diff --git a/images/virtualization-artifact/pkg/controller/vm/internal/deletion_handler.go b/images/virtualization-artifact/pkg/controller/vm/internal/deletion_handler.go index 4d1b545f1..2bcd40587 100644 --- a/images/virtualization-artifact/pkg/controller/vm/internal/deletion_handler.go +++ b/images/virtualization-artifact/pkg/controller/vm/internal/deletion_handler.go @@ -25,10 +25,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/vm/internal/state" "github.com/deckhouse/virtualization-controller/pkg/logger" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -67,7 +67,7 @@ func (h *DeletionHandler) Handle(ctx context.Context, s state.VirtualMachineStat return reconcile.Result{}, fmt.Errorf("failed to update finalizer on the KVVM %q: %w", kvvm.GetName(), err) } if kvvm != nil { - err = helper.DeleteObject(ctx, h.client, kvvm) + err = object.DeleteObject(ctx, h.client, kvvm) if err != nil { return reconcile.Result{}, err } diff --git a/images/virtualization-artifact/pkg/controller/vm/internal/lifecycle.go b/images/virtualization-artifact/pkg/controller/vm/internal/lifecycle.go index 94e1ff1a6..ad7b2a95c 100644 --- a/images/virtualization-artifact/pkg/controller/vm/internal/lifecycle.go +++ b/images/virtualization-artifact/pkg/controller/vm/internal/lifecycle.go @@ -28,7 +28,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + podutil "github.com/deckhouse/virtualization-controller/pkg/common/pod" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/vm/internal/state" @@ -176,7 +176,7 @@ func (h *LifeCycleHandler) syncPodStarted(vm *virtv2.VirtualMachine, kvvm *virtv cb := conditions.NewConditionBuilder(vmcondition.TypePodStarted).Generation(vm.GetGeneration()) - if common.IsPodStarted(pod) { + if podutil.IsPodStarted(pod) { cb.Status(metav1.ConditionTrue).Reason(vmcondition.ReasonPodStarted) conditions.SetCondition(cb, &vm.Status.Conditions) return diff --git a/images/virtualization-artifact/pkg/controller/vm/internal/state/state.go b/images/virtualization-artifact/pkg/controller/vm/internal/state/state.go index bffa9e950..b14d41fdd 100644 --- a/images/virtualization-artifact/pkg/controller/vm/internal/state/state.go +++ b/images/virtualization-artifact/pkg/controller/vm/internal/state/state.go @@ -28,11 +28,11 @@ import ( virtv1 "kubevirt.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" kvvmutil "github.com/deckhouse/virtualization-controller/pkg/common/kvvm" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/powerstate" "github.com/deckhouse/virtualization-controller/pkg/controller/service" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -94,7 +94,7 @@ func (s *state) KVVM(ctx context.Context) (*virtv1.VirtualMachine, error) { s.mu.Lock() defer s.mu.Unlock() - kvvm, err := helper.FetchObject(ctx, s.vm.Name(), s.client, &virtv1.VirtualMachine{}) + kvvm, err := object.FetchObject(ctx, s.vm.Name(), s.client, &virtv1.VirtualMachine{}) if err != nil { return nil, fmt.Errorf("failed to fetch KVVM: %w", err) } @@ -112,7 +112,7 @@ func (s *state) KVVMI(ctx context.Context) (*virtv1.VirtualMachineInstance, erro s.mu.Lock() defer s.mu.Unlock() - kvvmi, err := helper.FetchObject(ctx, s.vm.Name(), s.client, &virtv1.VirtualMachineInstance{}) + kvvmi, err := object.FetchObject(ctx, s.vm.Name(), s.client, &virtv1.VirtualMachineInstance{}) if err != nil { return nil, fmt.Errorf("failed to fetch KVVMI: %w", err) } @@ -187,7 +187,7 @@ func (s *state) VMBDAList(ctx context.Context) ([]virtv2.VirtualMachineBlockDevi } func (s *state) VirtualDisk(ctx context.Context, name string) (*virtv2.VirtualDisk, error) { - return helper.FetchObject(ctx, types.NamespacedName{ + return object.FetchObject(ctx, types.NamespacedName{ Name: name, Namespace: s.vm.Current().GetNamespace(), }, s.client, &virtv2.VirtualDisk{}) @@ -206,7 +206,7 @@ func (s *state) VirtualDisksByName(ctx context.Context) (map[string]*virtv2.Virt for _, bd := range s.vm.Current().Spec.BlockDeviceRefs { switch bd.Kind { case virtv2.DiskDevice: - vmd, err := helper.FetchObject(ctx, types.NamespacedName{ + vmd, err := object.FetchObject(ctx, types.NamespacedName{ Name: bd.Name, Namespace: s.vm.Current().GetNamespace(), }, s.client, &virtv2.VirtualDisk{}) @@ -238,7 +238,7 @@ func (s *state) VirtualImagesByName(ctx context.Context) (map[string]*virtv2.Vir for _, bd := range s.vm.Current().Spec.BlockDeviceRefs { switch bd.Kind { case virtv2.ImageDevice: - vi, err := helper.FetchObject(ctx, types.NamespacedName{ + vi, err := object.FetchObject(ctx, types.NamespacedName{ Name: bd.Name, Namespace: s.vm.Current().GetNamespace(), }, s.client, &virtv2.VirtualImage{}) @@ -270,7 +270,7 @@ func (s *state) ClusterVirtualImagesByName(ctx context.Context) (map[string]*vir for _, bd := range s.vm.Current().Spec.BlockDeviceRefs { switch bd.Kind { case virtv2.ClusterImageDevice: - cvi, err := helper.FetchObject(ctx, types.NamespacedName{ + cvi, err := object.FetchObject(ctx, types.NamespacedName{ Name: bd.Name, Namespace: s.vm.Current().GetNamespace(), }, s.client, &virtv2.ClusterVirtualImage{}) @@ -306,7 +306,7 @@ func (s *state) IPAddress(ctx context.Context) (*virtv2.VirtualMachineIPAddress, err := s.client.List(ctx, vmipList, &client.ListOptions{ Namespace: s.vm.Current().GetNamespace(), - LabelSelector: labels.SelectorFromSet(map[string]string{common.LabelVirtualMachineUID: string(s.vm.Current().GetUID())}), + LabelSelector: labels.SelectorFromSet(map[string]string{annotations.LabelVirtualMachineUID: string(s.vm.Current().GetUID())}), }) if err != nil { return nil, fmt.Errorf("failed to list VirtualMachineIPAddress: %w", err) @@ -321,7 +321,7 @@ func (s *state) IPAddress(ctx context.Context) (*virtv2.VirtualMachineIPAddress, } else { vmipKey := types.NamespacedName{Name: vmipName, Namespace: s.vm.Current().GetNamespace()} - ipAddress, err := helper.FetchObject(ctx, vmipKey, s.client, &virtv2.VirtualMachineIPAddress{}) + ipAddress, err := object.FetchObject(ctx, vmipKey, s.client, &virtv2.VirtualMachineIPAddress{}) if err != nil { return nil, fmt.Errorf("failed to fetch VirtualMachineIPAddress: %w", err) } @@ -340,7 +340,7 @@ func (s *state) Class(ctx context.Context) (*virtv2.VirtualMachineClass, error) } className := s.vm.Current().Spec.VirtualMachineClassName classKey := types.NamespacedName{Name: className} - class, err := helper.FetchObject(ctx, classKey, s.client, &virtv2.VirtualMachineClass{}) + class, err := object.FetchObject(ctx, classKey, s.client, &virtv2.VirtualMachineClass{}) if err != nil { return nil, fmt.Errorf("failed to fetch VirtualMachineClass: %w", err) } diff --git a/images/virtualization-artifact/pkg/controller/vm/internal/sync_kvvm.go b/images/virtualization-artifact/pkg/controller/vm/internal/sync_kvvm.go index 6360cea4d..c4bf24dc0 100644 --- a/images/virtualization-artifact/pkg/controller/vm/internal/sync_kvvm.go +++ b/images/virtualization-artifact/pkg/controller/vm/internal/sync_kvvm.go @@ -32,8 +32,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" kvvmutil "github.com/deckhouse/virtualization-controller/pkg/common/kvvm" + "github.com/deckhouse/virtualization-controller/pkg/common/object" vmutil "github.com/deckhouse/virtualization-controller/pkg/common/vm" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/kvbuilder" "github.com/deckhouse/virtualization-controller/pkg/controller/powerstate" @@ -330,7 +330,7 @@ func (h *SyncKvvmHandler) makeKVVMFromVMSpec(ctx context.Context, s state.Virtua return nil, nil } current := s.VirtualMachine().Current() - kvvmName := common.NamespacedName(current) + kvvmName := object.NamespacedName(current) kvvmOpts := kvbuilder.KVVMOptions{ EnableParavirtualization: current.Spec.EnableParavirtualization, diff --git a/images/virtualization-artifact/pkg/controller/vm/internal/sync_metadata.go b/images/virtualization-artifact/pkg/controller/vm/internal/sync_metadata.go index 3a214e4bc..e088f5fe5 100644 --- a/images/virtualization-artifact/pkg/controller/vm/internal/sync_metadata.go +++ b/images/virtualization-artifact/pkg/controller/vm/internal/sync_metadata.go @@ -27,8 +27,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - merger "github.com/deckhouse/virtualization-controller/pkg/common" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/merger" "github.com/deckhouse/virtualization-controller/pkg/controller/vm/internal/state" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -170,8 +170,8 @@ func PropagateVMMetadata(vm *virtv2.VirtualMachine, kvvm *virtv1.VirtualMachine, func GetLastPropagatedLabels(kvvm *virtv1.VirtualMachine) (map[string]string, error) { var lastPropagatedLabels map[string]string - if kvvm.Annotations[common.LastPropagatedVMLabelsAnnotation] != "" { - err := json.Unmarshal([]byte(kvvm.Annotations[common.LastPropagatedVMLabelsAnnotation]), &lastPropagatedLabels) + if kvvm.Annotations[annotations.LastPropagatedVMLabelsAnnotation] != "" { + err := json.Unmarshal([]byte(kvvm.Annotations[annotations.LastPropagatedVMLabelsAnnotation]), &lastPropagatedLabels) if err != nil { return nil, err } @@ -188,19 +188,19 @@ func SetLastPropagatedLabels(kvvm *virtv1.VirtualMachine, vm *virtv2.VirtualMach newAnnoValue := string(data) - if kvvm.Annotations[common.LastPropagatedVMLabelsAnnotation] == newAnnoValue { + if kvvm.Annotations[annotations.LastPropagatedVMLabelsAnnotation] == newAnnoValue { return false, nil } - common.AddAnnotation(kvvm, common.LastPropagatedVMLabelsAnnotation, newAnnoValue) + annotations.AddAnnotation(kvvm, annotations.LastPropagatedVMLabelsAnnotation, newAnnoValue) return true, nil } func GetLastPropagatedAnnotations(kvvm *virtv1.VirtualMachine) (map[string]string, error) { var lastPropagatedAnno map[string]string - if kvvm.Annotations[common.LastPropagatedVMAnnotationsAnnotation] != "" { - err := json.Unmarshal([]byte(kvvm.Annotations[common.LastPropagatedVMAnnotationsAnnotation]), &lastPropagatedAnno) + if kvvm.Annotations[annotations.LastPropagatedVMAnnotationsAnnotation] != "" { + err := json.Unmarshal([]byte(kvvm.Annotations[annotations.LastPropagatedVMAnnotationsAnnotation]), &lastPropagatedAnno) if err != nil { return nil, err } @@ -217,11 +217,11 @@ func SetLastPropagatedAnnotations(kvvm *virtv1.VirtualMachine, vm *virtv2.Virtua newAnnoValue := string(data) - if kvvm.Annotations[common.LastPropagatedVMAnnotationsAnnotation] == newAnnoValue { + if kvvm.Annotations[annotations.LastPropagatedVMAnnotationsAnnotation] == newAnnoValue { return false, nil } - common.AddAnnotation(kvvm, common.LastPropagatedVMAnnotationsAnnotation, newAnnoValue) + annotations.AddAnnotation(kvvm, annotations.LastPropagatedVMAnnotationsAnnotation, newAnnoValue) return true, nil } @@ -230,7 +230,7 @@ func RemoveNonPropagatableAnnotations(anno map[string]string) map[string]string res := make(map[string]string) for k, v := range anno { - if k == common.LastPropagatedVMAnnotationsAnnotation || k == common.LastPropagatedVMLabelsAnnotation { + if k == annotations.LastPropagatedVMAnnotationsAnnotation || k == annotations.LastPropagatedVMLabelsAnnotation { continue } diff --git a/images/virtualization-artifact/pkg/controller/vm/internal/validators/ipam_validator.go b/images/virtualization-artifact/pkg/controller/vm/internal/validators/ipam_validator.go index eb986aa7a..6208e5425 100644 --- a/images/virtualization-artifact/pkg/controller/vm/internal/validators/ipam_validator.go +++ b/images/virtualization-artifact/pkg/controller/vm/internal/validators/ipam_validator.go @@ -24,8 +24,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/vm/internal" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -45,7 +45,7 @@ func (v *IPAMValidator) ValidateCreate(ctx context.Context, vm *v1alpha2.Virtual } vmipKey := types.NamespacedName{Name: vmipName, Namespace: vm.Namespace} - vmip, err := helper.FetchObject(ctx, vmipKey, v.client, &v1alpha2.VirtualMachineIPAddress{}) + vmip, err := object.FetchObject(ctx, vmipKey, v.client, &v1alpha2.VirtualMachineIPAddress{}) if err != nil { return nil, fmt.Errorf("unable to get referenced VirtualMachineIPAddress %s: %w", vmipKey, err) } @@ -73,7 +73,7 @@ func (v *IPAMValidator) ValidateUpdate(ctx context.Context, oldVM, newVM *v1alph } vmipKey := types.NamespacedName{Name: newVM.Spec.VirtualMachineIPAddress, Namespace: newVM.Namespace} - vmip, err := helper.FetchObject(ctx, vmipKey, v.client, &v1alpha2.VirtualMachineIPAddress{}) + vmip, err := object.FetchObject(ctx, vmipKey, v.client, &v1alpha2.VirtualMachineIPAddress{}) if err != nil { return nil, fmt.Errorf("unable to get VirtualMachineIPAddress %s: %w", vmipKey, err) } diff --git a/images/virtualization-artifact/pkg/controller/vmclass/internal/deletion.go b/images/virtualization-artifact/pkg/controller/vmclass/internal/deletion.go index 77978202b..263799517 100644 --- a/images/virtualization-artifact/pkg/controller/vmclass/internal/deletion.go +++ b/images/virtualization-artifact/pkg/controller/vmclass/internal/deletion.go @@ -28,7 +28,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/deckhouse/deckhouse/pkg/log" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/vmclass/internal/state" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -63,7 +63,7 @@ func (h *DeletionHandler) Handle(ctx context.Context, s state.VirtualMachineClas return reconcile.Result{}, err } if len(vms) > 0 { - msg := fmt.Sprintf("VirtualMachineClass cannot be deleted, there are VMs that use it. %s...", common.NamespacedName(&vms[0])) + msg := fmt.Sprintf("VirtualMachineClass cannot be deleted, there are VMs that use it. %s...", object.NamespacedName(&vms[0])) h.logger.Info(msg) h.recorder.Event(changed, corev1.EventTypeWarning, virtv2.ReasonVMClassInUse, msg) return reconcile.Result{RequeueAfter: 60 * time.Second}, nil diff --git a/images/virtualization-artifact/pkg/controller/vmclass/internal/state/state.go b/images/virtualization-artifact/pkg/controller/vmclass/internal/state/state.go index 358d11ccc..13e950e88 100644 --- a/images/virtualization-artifact/pkg/controller/vmclass/internal/state/state.go +++ b/images/virtualization-artifact/pkg/controller/vmclass/internal/state/state.go @@ -26,7 +26,8 @@ import ( virtv1 "kubevirt.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/array" "github.com/deckhouse/virtualization-controller/pkg/controller/indexer" "github.com/deckhouse/virtualization-controller/pkg/controller/service" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" @@ -68,8 +69,8 @@ func (s *state) VirtualMachines(ctx context.Context) ([]virtv2.VirtualMachine, e return vms.Items, nil } -func nodeFilter(nodes []corev1.Node, filters ...common.FilterFunc[corev1.Node]) []corev1.Node { - return common.Filter[corev1.Node](nodes, filters...) +func nodeFilter(nodes []corev1.Node, filters ...array.FilterFunc[corev1.Node]) []corev1.Node { + return array.Filter[corev1.Node](nodes, filters...) } func (s *state) Nodes(ctx context.Context) ([]corev1.Node, error) { @@ -85,7 +86,7 @@ func (s *state) Nodes(ctx context.Context) ([]corev1.Node, error) { if err != nil { return nil, err } - filters := []common.FilterFunc[corev1.Node]{ + filters := []array.FilterFunc[corev1.Node]{ func(node *corev1.Node) (keep bool) { _, found := virtHandlerNodes[node.GetName()] return found @@ -98,7 +99,7 @@ func (s *state) Nodes(ctx context.Context) ([]corev1.Node, error) { case virtv2.CPUTypeDiscovery: matchLabels = curr.Spec.CPU.Discovery.NodeSelector.MatchLabels filters = append(filters, func(node *corev1.Node) bool { - return common.MatchExpressions(node.GetLabels(), curr.Spec.CPU.Discovery.NodeSelector.MatchExpressions) + return annotations.MatchExpressions(node.GetLabels(), curr.Spec.CPU.Discovery.NodeSelector.MatchExpressions) }) case virtv2.CPUTypeModel: matchLabels = map[string]string{virtv1.CPUModelLabel + curr.Spec.CPU.Model: "true"} @@ -151,9 +152,9 @@ func (s *state) AvailableNodes(nodes []corev1.Node) ([]corev1.Node, error) { nodeSelector := s.vmClass.Current().Spec.NodeSelector - filters := []common.FilterFunc[corev1.Node]{ + filters := []array.FilterFunc[corev1.Node]{ func(node *corev1.Node) bool { - return common.MatchLabels(node.GetLabels(), nodeSelector.MatchLabels) + return annotations.MatchLabels(node.GetLabels(), nodeSelector.MatchLabels) }, } diff --git a/images/virtualization-artifact/pkg/controller/vmclass/vmclass_reconciler.go b/images/virtualization-artifact/pkg/controller/vmclass/vmclass_reconciler.go index 7e33e924c..a75b2662b 100644 --- a/images/virtualization-artifact/pkg/controller/vmclass/vmclass_reconciler.go +++ b/images/virtualization-artifact/pkg/controller/vmclass/vmclass_reconciler.go @@ -33,7 +33,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/vmclass/internal/state" "github.com/deckhouse/virtualization-controller/pkg/logger" @@ -67,8 +68,8 @@ func (r *Reconciler) SetupController(_ context.Context, mgr manager.Manager, ctr } if err := ctr.Watch( source.Kind(mgr.GetCache(), &corev1.Node{}), - handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, object client.Object) []reconcile.Request { - node, ok := object.(*corev1.Node) + handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, obj client.Object) []reconcile.Request { + node, ok := obj.(*corev1.Node) if !ok { return nil } @@ -83,11 +84,11 @@ func (r *Reconciler) SetupController(_ context.Context, mgr manager.Manager, ctr for _, class := range classList.Items { if slices.Contains(class.Status.AvailableNodes, node.GetName()) { result = append(result, reconcile.Request{ - NamespacedName: common.NamespacedName(&class), + NamespacedName: object.NamespacedName(&class), }) continue } - if !common.MatchLabels(node.GetLabels(), class.Spec.NodeSelector.MatchLabels) { + if !annotations.MatchLabels(node.GetLabels(), class.Spec.NodeSelector.MatchLabels) { continue } ns, err := nodeaffinity.NewNodeSelector(&corev1.NodeSelector{ @@ -97,7 +98,7 @@ func (r *Reconciler) SetupController(_ context.Context, mgr manager.Manager, ctr continue } result = append(result, reconcile.Request{ - NamespacedName: common.NamespacedName(&class), + NamespacedName: object.NamespacedName(&class), }) } return result diff --git a/images/virtualization-artifact/pkg/controller/vmip/internal/iplease_handler.go b/images/virtualization-artifact/pkg/controller/vmip/internal/iplease_handler.go index 9b431a200..b1581f690 100644 --- a/images/virtualization-artifact/pkg/controller/vmip/internal/iplease_handler.go +++ b/images/virtualization-artifact/pkg/controller/vmip/internal/iplease_handler.go @@ -27,7 +27,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/ip" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/vmip/internal/state" @@ -106,7 +106,7 @@ func (h IPLeaseHandler) Handle(ctx context.Context, state state.VMIPState) (reco return reconcile.Result{}, err } - vmipStatus.Address = common.LeaseNameToIP(lease.Name) + vmipStatus.Address = ip.LeaseNameToIP(lease.Name) return reconcile.Result{}, nil } } @@ -150,14 +150,14 @@ func (h IPLeaseHandler) createNewLease(ctx context.Context, state state.VMIPStat conditionBound.Status(metav1.ConditionFalse). Reason(vmipcondition.VirtualMachineIPAddressLeaseAlreadyExists). Message(fmt.Sprintf("VirtualMachineIPAddressLease %s is bound to another VirtualMachineIPAddress", - common.IpToLeaseName(vmipStatus.Address))) + ip.IpToLeaseName(vmipStatus.Address))) h.recorder.Event(vmip, corev1.EventTypeWarning, vmipcondition.VirtualMachineIPAddressLeaseAlreadyExists.String(), msg) } conditions.SetCondition(conditionBound, &vmipStatus.Conditions) return reconcile.Result{}, nil } - leaseName := common.IpToLeaseName(vmipStatus.Address) + leaseName := ip.IpToLeaseName(vmipStatus.Address) log.Info("Create lease", "leaseName", leaseName, diff --git a/images/virtualization-artifact/pkg/controller/vmip/internal/lifecycle_handler.go b/images/virtualization-artifact/pkg/controller/vmip/internal/lifecycle_handler.go index d596bc602..3bcd8e066 100644 --- a/images/virtualization-artifact/pkg/controller/vmip/internal/lifecycle_handler.go +++ b/images/virtualization-artifact/pkg/controller/vmip/internal/lifecycle_handler.go @@ -24,7 +24,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/ip" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/vmip/internal/state" "github.com/deckhouse/virtualization-controller/pkg/controller/vmip/internal/util" @@ -87,7 +87,7 @@ func (h *LifecycleHandler) Handle(ctx context.Context, state state.VMIPState) (r conditionBound.Status(metav1.ConditionFalse). Reason(vmipcondition.VirtualMachineIPAddressLeaseLost). Message(fmt.Sprintf("VirtualMachineIPAddressLease %s doesn't exist", - common.IpToLeaseName(vmipStatus.Address))) + ip.IpToLeaseName(vmipStatus.Address))) } case lease == nil: @@ -109,7 +109,7 @@ func (h *LifecycleHandler) Handle(ctx context.Context, state state.VMIPState) (r case util.IsBoundLease(lease, vmip): if vmipStatus.Phase != virtv2.VirtualMachineIPAddressPhaseBound { vmipStatus.Phase = virtv2.VirtualMachineIPAddressPhaseBound - vmipStatus.Address = common.LeaseNameToIP(lease.Name) + vmipStatus.Address = ip.LeaseNameToIP(lease.Name) conditionBound.Status(metav1.ConditionTrue). Reason(vmipcondition.Bound) } diff --git a/images/virtualization-artifact/pkg/controller/vmip/internal/state/state.go b/images/virtualization-artifact/pkg/controller/vmip/internal/state/state.go index ffc3f93f0..2304c938b 100644 --- a/images/virtualization-artifact/pkg/controller/vmip/internal/state/state.go +++ b/images/virtualization-artifact/pkg/controller/vmip/internal/state/state.go @@ -24,12 +24,12 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/ip" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/indexer" "github.com/deckhouse/virtualization-controller/pkg/controller/ipam" "github.com/deckhouse/virtualization-controller/pkg/controller/vmip/internal/util" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" "github.com/deckhouse/virtualization/api/core/v1alpha2/vmiplcondition" ) @@ -39,7 +39,7 @@ type VMIPState interface { VirtualMachineIPLease(ctx context.Context) (*virtv2.VirtualMachineIPAddressLease, error) VirtualMachine(ctx context.Context) (*virtv2.VirtualMachine, error) - AllocatedIPs() common.AllocatedIPs + AllocatedIPs() ip.AllocatedIPs } type state struct { @@ -47,7 +47,7 @@ type state struct { vmip *virtv2.VirtualMachineIPAddress lease *virtv2.VirtualMachineIPAddressLease vm *virtv2.VirtualMachine - allocatedIPs common.AllocatedIPs + allocatedIPs ip.AllocatedIPs } func New(c client.Client, vmip *virtv2.VirtualMachineIPAddress) VMIPState { @@ -65,11 +65,11 @@ func (s *state) VirtualMachineIPLease(ctx context.Context) (*virtv2.VirtualMachi var err error - leaseName := common.IpToLeaseName(s.vmip.Status.Address) + leaseName := ip.IpToLeaseName(s.vmip.Status.Address) if leaseName != "" { leaseKey := types.NamespacedName{Name: leaseName} - s.lease, err = helper.FetchObject(ctx, leaseKey, s.client, &virtv2.VirtualMachineIPAddressLease{}) + s.lease, err = object.FetchObject(ctx, leaseKey, s.client, &virtv2.VirtualMachineIPAddressLease{}) if err != nil { return nil, fmt.Errorf("unable to get Lease %s: %w", leaseKey, err) } @@ -113,7 +113,7 @@ func (s *state) VirtualMachine(ctx context.Context) (*virtv2.VirtualMachine, err var err error if s.vmip.Status.VirtualMachine != "" { vmKey := types.NamespacedName{Name: s.vmip.Status.VirtualMachine, Namespace: s.vmip.Namespace} - vm, err := helper.FetchObject(ctx, vmKey, s.client, &virtv2.VirtualMachine{}) + vm, err := object.FetchObject(ctx, vmKey, s.client, &virtv2.VirtualMachine{}) if err != nil { return nil, fmt.Errorf("unable to get VM %s: %w", vmKey, err) } @@ -147,6 +147,6 @@ func (s *state) VirtualMachine(ctx context.Context) (*virtv2.VirtualMachine, err return s.vm, nil } -func (s *state) AllocatedIPs() common.AllocatedIPs { +func (s *state) AllocatedIPs() ip.AllocatedIPs { return s.allocatedIPs } diff --git a/images/virtualization-artifact/pkg/controller/vmip/internal/util/util.go b/images/virtualization-artifact/pkg/controller/vmip/internal/util/util.go index 9f767b0e1..777ee1441 100644 --- a/images/virtualization-artifact/pkg/controller/vmip/internal/util/util.go +++ b/images/virtualization-artifact/pkg/controller/vmip/internal/util/util.go @@ -22,11 +22,11 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/ip" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) -func GetAllocatedIPs(ctx context.Context, apiClient client.Client, vmipType virtv2.VirtualMachineIPAddressType) (common.AllocatedIPs, error) { +func GetAllocatedIPs(ctx context.Context, apiClient client.Client, vmipType virtv2.VirtualMachineIPAddressType) (ip.AllocatedIPs, error) { var leases virtv2.VirtualMachineIPAddressLeaseList err := apiClient.List(ctx, &leases) @@ -34,13 +34,13 @@ func GetAllocatedIPs(ctx context.Context, apiClient client.Client, vmipType virt return nil, fmt.Errorf("error getting leases: %w", err) } - allocatedIPs := make(common.AllocatedIPs, len(leases.Items)) + allocatedIPs := make(ip.AllocatedIPs, len(leases.Items)) for _, lease := range leases.Items { l := lease if vmipType == virtv2.VirtualMachineIPAddressTypeStatic && l.Status.Phase == virtv2.VirtualMachineIPAddressLeasePhaseReleased { continue } else { - allocatedIPs[common.LeaseNameToIP(lease.Name)] = &l + allocatedIPs[ip.LeaseNameToIP(lease.Name)] = &l } } diff --git a/images/virtualization-artifact/pkg/controller/vmiplease/internal/state/state.go b/images/virtualization-artifact/pkg/controller/vmiplease/internal/state/state.go index ce9d0a78b..7986606ee 100644 --- a/images/virtualization-artifact/pkg/controller/vmiplease/internal/state/state.go +++ b/images/virtualization-artifact/pkg/controller/vmiplease/internal/state/state.go @@ -23,7 +23,7 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/object" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -58,7 +58,7 @@ func (s *state) VirtualMachineIPAddress(ctx context.Context) (*virtv2.VirtualMac if s.lease.Spec.VirtualMachineIPAddressRef != nil { vmipKey := types.NamespacedName{Name: s.lease.Spec.VirtualMachineIPAddressRef.Name, Namespace: s.lease.Spec.VirtualMachineIPAddressRef.Namespace} - s.vmip, err = helper.FetchObject(ctx, vmipKey, s.client, &virtv2.VirtualMachineIPAddress{}) + s.vmip, err = object.FetchObject(ctx, vmipKey, s.client, &virtv2.VirtualMachineIPAddress{}) if err != nil { return nil, fmt.Errorf("unable to get VirtualMachineIP %s: %w", vmipKey, err) } diff --git a/images/virtualization-artifact/pkg/controller/vmiplease/vmiplease_reconciler.go b/images/virtualization-artifact/pkg/controller/vmiplease/vmiplease_reconciler.go index 3e61b8ed1..7bc4ed6e4 100644 --- a/images/virtualization-artifact/pkg/controller/vmiplease/vmiplease_reconciler.go +++ b/images/virtualization-artifact/pkg/controller/vmiplease/vmiplease_reconciler.go @@ -32,7 +32,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/ip" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/vmiplease/internal/state" "github.com/deckhouse/virtualization-controller/pkg/logger" @@ -85,7 +85,7 @@ func (r *Reconciler) enqueueRequestsFromVMIP(_ context.Context, obj client.Objec return []reconcile.Request{ { NamespacedName: types.NamespacedName{ - Name: common.IpToLeaseName(vmip.Status.Address), + Name: ip.IpToLeaseName(vmip.Status.Address), }, }, } diff --git a/images/virtualization-artifact/pkg/controller/vmiplease/vmiplease_webhook.go b/images/virtualization-artifact/pkg/controller/vmiplease/vmiplease_webhook.go index 0a6223f99..66db25ff7 100644 --- a/images/virtualization-artifact/pkg/controller/vmiplease/vmiplease_webhook.go +++ b/images/virtualization-artifact/pkg/controller/vmiplease/vmiplease_webhook.go @@ -25,7 +25,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" "github.com/deckhouse/deckhouse/pkg/log" - "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/ip" "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -45,7 +45,7 @@ func (v *Validator) ValidateCreate(_ context.Context, obj runtime.Object) (admis v.log.Info("Validate VirtualMachineIpAddressLease creating", "name", lease.Name) - if !isValidAddressFormat(common.LeaseNameToIP(lease.Name)) { + if !isValidAddressFormat(ip.LeaseNameToIP(lease.Name)) { return nil, fmt.Errorf("the lease address is not a valid textual representation of an IP address") } diff --git a/images/virtualization-artifact/pkg/controller/vmop/internal/lifecycle.go b/images/virtualization-artifact/pkg/controller/vmop/internal/lifecycle.go index bd88e2873..fb6ac3881 100644 --- a/images/virtualization-artifact/pkg/controller/vmop/internal/lifecycle.go +++ b/images/virtualization-artifact/pkg/controller/vmop/internal/lifecycle.go @@ -23,7 +23,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" - cc "github.com/deckhouse/virtualization-controller/pkg/controller/common" + "github.com/deckhouse/virtualization-controller/pkg/common/annotations" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/vmop/internal/state" @@ -106,7 +106,7 @@ func (h LifecycleHandler) Handle(ctx context.Context, s state.VMOperationState) &changed.Status.Conditions) return reconcile.Result{}, nil } - cc.AddLabel(changed, cc.LabelVirtualMachineUID, string(vm.GetUID())) + annotations.AddLabel(changed, annotations.LabelVirtualMachineUID, string(vm.GetUID())) if changed.Status.Phase == virtv2.VMOPPhaseInProgress { log.Debug("Operation in progress, check if VM is completed", "vm.phase", vm.Status.Phase, "vmop.phase", changed.Status.Phase) diff --git a/images/virtualization-artifact/pkg/controller/vmop/internal/state/state.go b/images/virtualization-artifact/pkg/controller/vmop/internal/state/state.go index e02b28a84..a826d631b 100644 --- a/images/virtualization-artifact/pkg/controller/vmop/internal/state/state.go +++ b/images/virtualization-artifact/pkg/controller/vmop/internal/state/state.go @@ -23,8 +23,8 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/service" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -54,7 +54,7 @@ func (s *state) VirtualMachine(ctx context.Context) (*virtv2.VirtualMachine, err vmName := s.vmop.Current().Spec.VirtualMachine vmNs := s.vmop.Current().GetNamespace() - vm, err := helper.FetchObject(ctx, + vm, err := object.FetchObject(ctx, types.NamespacedName{Name: vmName, Namespace: vmNs}, s.client, &virtv2.VirtualMachine{}) diff --git a/images/virtualization-artifact/pkg/controller/vmrestore/internal/life_cycle.go b/images/virtualization-artifact/pkg/controller/vmrestore/internal/life_cycle.go index 0d17b5b63..6d36e3cd2 100644 --- a/images/virtualization-artifact/pkg/controller/vmrestore/internal/life_cycle.go +++ b/images/virtualization-artifact/pkg/controller/vmrestore/internal/life_cycle.go @@ -28,10 +28,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" "github.com/deckhouse/virtualization-controller/pkg/controller/service" "github.com/deckhouse/virtualization-controller/pkg/controller/vmrestore/internal/restorer" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" vmrestorecondition "github.com/deckhouse/virtualization/api/core/v1alpha2/vm-restore-condition" ) @@ -90,7 +90,7 @@ func (h LifeCycleHandler) Handle(ctx context.Context, vmRestore *virtv2.VirtualM } vmSnapshotKey := types.NamespacedName{Namespace: vmRestore.Namespace, Name: vmRestore.Spec.VirtualMachineSnapshotName} - vmSnapshot, err := helper.FetchObject(ctx, vmSnapshotKey, h.client, &virtv2.VirtualMachineSnapshot{}) + vmSnapshot, err := object.FetchObject(ctx, vmSnapshotKey, h.client, &virtv2.VirtualMachineSnapshot{}) if err != nil { setPhaseConditionToFailed(cb, &vmRestore.Status.Phase, err) return reconcile.Result{}, err @@ -103,7 +103,7 @@ func (h LifeCycleHandler) Handle(ctx context.Context, vmRestore *virtv2.VirtualM } restorerSecretKey := types.NamespacedName{Namespace: vmSnapshot.Namespace, Name: vmSnapshot.Status.VirtualMachineSnapshotSecretName} - restorerSecret, err := helper.FetchObject(ctx, restorerSecretKey, h.client, &corev1.Secret{}) + restorerSecret, err := object.FetchObject(ctx, restorerSecretKey, h.client, &corev1.Secret{}) if err != nil { setPhaseConditionToFailed(cb, &vmRestore.Status.Phase, err) return reconcile.Result{}, err @@ -219,7 +219,7 @@ func (h LifeCycleHandler) getVirtualDisks(ctx context.Context, vmSnapshot *virtv for _, vdSnapshotName := range vmSnapshot.Status.VirtualDiskSnapshotNames { vdSnapshotKey := types.NamespacedName{Namespace: vmSnapshot.Namespace, Name: vdSnapshotName} - vdSnapshot, err := helper.FetchObject(ctx, vdSnapshotKey, h.client, &virtv2.VirtualDiskSnapshot{}) + vdSnapshot, err := object.FetchObject(ctx, vdSnapshotKey, h.client, &virtv2.VirtualDiskSnapshot{}) if err != nil { return nil, fmt.Errorf("failed to fetch the virtual disk snapshot %q: %w", vdSnapshotKey.Name, err) } diff --git a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/provisioner_restorer.go b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/provisioner_restorer.go index a31d0e689..33ef8c59e 100644 --- a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/provisioner_restorer.go +++ b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/provisioner_restorer.go @@ -27,7 +27,7 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/object" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -64,7 +64,7 @@ func (v *ProvisionerOverrideValidator) Override(rules []virtv2.NameReplacement) func (v *ProvisionerOverrideValidator) Validate(ctx context.Context) error { secretKey := types.NamespacedName{Namespace: v.secret.Namespace, Name: v.secret.Name} - existed, err := helper.FetchObject(ctx, secretKey, v.client, &corev1.Secret{}) + existed, err := object.FetchObject(ctx, secretKey, v.client, &corev1.Secret{}) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vd_restorer.go b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vd_restorer.go index 17a2d06c6..731deef9f 100644 --- a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vd_restorer.go +++ b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vd_restorer.go @@ -24,7 +24,7 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/object" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -58,7 +58,7 @@ func (v VirtualDiskOverrideValidator) Override(rules []virtv2.NameReplacement) { func (v VirtualDiskOverrideValidator) Validate(ctx context.Context) error { vdKey := types.NamespacedName{Namespace: v.vd.Namespace, Name: v.vd.Name} - existed, err := helper.FetchObject(ctx, vdKey, v.client, &virtv2.VirtualDisk{}) + existed, err := object.FetchObject(ctx, vdKey, v.client, &virtv2.VirtualDisk{}) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vm_restorer.go b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vm_restorer.go index 099907077..90ab2f235 100644 --- a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vm_restorer.go +++ b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vm_restorer.go @@ -24,7 +24,7 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/object" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -67,7 +67,7 @@ func (v *VirtualMachineOverrideValidator) Override(rules []virtv2.NameReplacemen func (v *VirtualMachineOverrideValidator) Validate(ctx context.Context) error { vmKey := types.NamespacedName{Namespace: v.vm.Namespace, Name: v.vm.Name} - existed, err := helper.FetchObject(ctx, vmKey, v.client, &virtv2.VirtualMachine{}) + existed, err := object.FetchObject(ctx, vmKey, v.client, &virtv2.VirtualMachine{}) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vmbda_restorer.go b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vmbda_restorer.go index c6877f090..6978583a7 100644 --- a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vmbda_restorer.go +++ b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vmbda_restorer.go @@ -24,7 +24,7 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" + "github.com/deckhouse/virtualization-controller/pkg/common/object" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -63,7 +63,7 @@ func (v *VirtualMachineBlockDeviceAttachmentsOverrideValidator) Override(rules [ func (v *VirtualMachineBlockDeviceAttachmentsOverrideValidator) Validate(ctx context.Context) error { vmbdaKey := types.NamespacedName{Namespace: v.vmbda.Namespace, Name: v.vmbda.Name} - existed, err := helper.FetchObject(ctx, vmbdaKey, v.client, &virtv2.VirtualMachineBlockDeviceAttachment{}) + existed, err := object.FetchObject(ctx, vmbdaKey, v.client, &virtv2.VirtualMachineBlockDeviceAttachment{}) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vmip_restorer.go b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vmip_restorer.go index 5807af94f..26c7df8e2 100644 --- a/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vmip_restorer.go +++ b/images/virtualization-artifact/pkg/controller/vmrestore/internal/restorer/vmip_restorer.go @@ -25,8 +25,8 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/indexer" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -60,7 +60,7 @@ func (v *VirtualMachineIPAddressOverrideValidator) Override(rules []virtv2.NameR func (v *VirtualMachineIPAddressOverrideValidator) Validate(ctx context.Context) error { vmipKey := types.NamespacedName{Namespace: v.vmip.Namespace, Name: v.vmip.Name} - existed, err := helper.FetchObject(ctx, vmipKey, v.client, &virtv2.VirtualMachineIPAddress{}) + existed, err := object.FetchObject(ctx, vmipKey, v.client, &virtv2.VirtualMachineIPAddress{}) if err != nil { return err } diff --git a/images/virtualization-artifact/pkg/controller/vmrestore/internal/vm_snapshot_ready_to_use.go b/images/virtualization-artifact/pkg/controller/vmrestore/internal/vm_snapshot_ready_to_use.go index ca0eb1e5a..80aea3ac3 100644 --- a/images/virtualization-artifact/pkg/controller/vmrestore/internal/vm_snapshot_ready_to_use.go +++ b/images/virtualization-artifact/pkg/controller/vmrestore/internal/vm_snapshot_ready_to_use.go @@ -25,8 +25,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/deckhouse/virtualization-controller/pkg/common/object" "github.com/deckhouse/virtualization-controller/pkg/controller/conditions" - "github.com/deckhouse/virtualization-controller/pkg/sdk/framework/helper" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" vmrestorecondition "github.com/deckhouse/virtualization/api/core/v1alpha2/vm-restore-condition" "github.com/deckhouse/virtualization/api/core/v1alpha2/vmscondition" @@ -56,7 +56,7 @@ func (h VirtualMachineSnapshotReadyToUseHandler) Handle(ctx context.Context, vmR } vmSnapshotKey := types.NamespacedName{Name: vmRestore.Spec.VirtualMachineSnapshotName, Namespace: vmRestore.Namespace} - vmSnapshot, err := helper.FetchObject(ctx, vmSnapshotKey, h.client, &virtv2.VirtualMachineSnapshot{}) + vmSnapshot, err := object.FetchObject(ctx, vmSnapshotKey, h.client, &virtv2.VirtualMachineSnapshot{}) if err != nil { return reconcile.Result{}, err } diff --git a/images/virtualization-artifact/pkg/monitoring/metrics/vd/scraper.go b/images/virtualization-artifact/pkg/monitoring/metrics/vd/scraper.go index e88b38006..e452c146b 100644 --- a/images/virtualization-artifact/pkg/monitoring/metrics/vd/scraper.go +++ b/images/virtualization-artifact/pkg/monitoring/metrics/vd/scraper.go @@ -22,8 +22,8 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/virtualization-controller/pkg/common" "github.com/deckhouse/virtualization-controller/pkg/monitoring/metrics/promutil" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -64,7 +64,7 @@ func (s *scraper) updateMetricDiskStatusPhase(m *dataMetric) { for _, p := range phases { s.defaultUpdate(MetricDiskStatusPhase, - util.BoolFloat64(p.value), m, p.name) + common.BoolFloat64(p.value), m, p.name) } } diff --git a/images/virtualization-artifact/pkg/monitoring/metrics/virtualmachine/scraper.go b/images/virtualization-artifact/pkg/monitoring/metrics/virtualmachine/scraper.go index 4f17611c1..18b37b46c 100644 --- a/images/virtualization-artifact/pkg/monitoring/metrics/virtualmachine/scraper.go +++ b/images/virtualization-artifact/pkg/monitoring/metrics/virtualmachine/scraper.go @@ -22,8 +22,8 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/virtualization-controller/pkg/common" "github.com/deckhouse/virtualization-controller/pkg/monitoring/metrics/promutil" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -74,7 +74,7 @@ func (s *scraper) updateMetricVirtualMachineStatusPhase(m *dataMetric) { } for _, p := range phases { s.defaultUpdate(MetricVirtualMachineStatusPhase, - util.BoolFloat64(p.value), m, p.name) + common.BoolFloat64(p.value), m, p.name) } } @@ -115,12 +115,12 @@ func (s *scraper) updateMetricVirtualMachineConfigurationMemorySizeBytes(m *data func (s *scraper) updateMetricVirtualMachineAwaitingRestartToApplyConfiguration(m *dataMetric) { s.defaultUpdate(MetricVirtualMachineAwaitingRestartToApplyConfiguration, - util.BoolFloat64(m.AwaitingRestartToApplyConfiguration), m) + common.BoolFloat64(m.AwaitingRestartToApplyConfiguration), m) } func (s *scraper) updateMetricVirtualMachineConfigurationApplied(m *dataMetric) { s.defaultUpdate(MetricVirtualMachineConfigurationApplied, - util.BoolFloat64(m.ConfigurationApplied), m) + common.BoolFloat64(m.ConfigurationApplied), m) } func (s *scraper) updateMetricVirtualMachineConfigurationRunPolicy(m *dataMetric) { @@ -136,13 +136,13 @@ func (s *scraper) updateMetricVirtualMachineConfigurationRunPolicy(m *dataMetric } for _, p := range policies { s.defaultUpdate(MetricVirtualMachineConfigurationRunPolicy, - util.BoolFloat64(p.value), m, p.name) + common.BoolFloat64(p.value), m, p.name) } } func (s *scraper) updateMetricVirtualMachinePod(m *dataMetric) { for _, p := range m.Pods { - s.defaultUpdate(MetricVirtualMachinePod, util.BoolFloat64(p.Active), m, p.Name) + s.defaultUpdate(MetricVirtualMachinePod, common.BoolFloat64(p.Active), m, p.Name) } } diff --git a/images/virtualization-artifact/pkg/monitoring/metrics/vmbda/scraper.go b/images/virtualization-artifact/pkg/monitoring/metrics/vmbda/scraper.go index f5a9eb2c4..45139d73a 100644 --- a/images/virtualization-artifact/pkg/monitoring/metrics/vmbda/scraper.go +++ b/images/virtualization-artifact/pkg/monitoring/metrics/vmbda/scraper.go @@ -22,8 +22,8 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/deckhouse/deckhouse/pkg/log" + "github.com/deckhouse/virtualization-controller/pkg/common" "github.com/deckhouse/virtualization-controller/pkg/monitoring/metrics/promutil" - "github.com/deckhouse/virtualization-controller/pkg/util" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -60,7 +60,7 @@ func (s *scraper) updateMetricVMBDAStatusPhase(m *dataMetric) { for _, p := range phases { s.defaultUpdate(MetricVMBDAStatusPhase, - util.BoolFloat64(p.value), m, p.name) + common.BoolFloat64(p.value), m, p.name) } } diff --git a/images/virtualization-artifact/pkg/monitoring/metrics/vmop/scraper.go b/images/virtualization-artifact/pkg/monitoring/metrics/vmop/scraper.go index 16c63de0e..c748e1ade 100644 --- a/images/virtualization-artifact/pkg/monitoring/metrics/vmop/scraper.go +++ b/images/virtualization-artifact/pkg/monitoring/metrics/vmop/scraper.go @@ -22,7 +22,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/deckhouse/deckhouse/pkg/log" - "github.com/deckhouse/virtualization-controller/pkg/util" + "github.com/deckhouse/virtualization-controller/pkg/common" virtv2 "github.com/deckhouse/virtualization/api/core/v1alpha2" ) @@ -57,7 +57,7 @@ func (s *scraper) updateMetricVMOPStatusPhase(m *dataMetric) { for _, p := range phases { s.defaultUpdate(MetricVMOPStatusPhase, - util.BoolFloat64(p.value), m, p.name) + common.BoolFloat64(p.value), m, p.name) } } diff --git a/images/virtualization-artifact/pkg/sdk/framework/helper/resource.go b/images/virtualization-artifact/pkg/sdk/framework/helper/resource.go deleted file mode 100644 index 29be13443..000000000 --- a/images/virtualization-artifact/pkg/sdk/framework/helper/resource.go +++ /dev/null @@ -1,157 +0,0 @@ -/* -Copyright 2024 Flant JSC - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package helper - -import ( - "context" - "fmt" - "reflect" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - - "github.com/deckhouse/deckhouse/pkg/log" -) - -type Object[T, ST any] interface { - comparable - client.Object - DeepCopy() T - GetObjectMeta() metav1.Object -} - -type ObjectStatusGetter[T, ST any] func(obj T) ST - -type ObjectFactory[T any] func() T - -type Resource[T Object[T, ST], ST any] struct { - name types.NamespacedName - currentObj T - changedObj T - emptyObj T - - objFactory ObjectFactory[T] - objStatusGetter ObjectStatusGetter[T, ST] - log *log.Logger - client client.Client - cache cache.Cache -} - -func NewResource[T Object[T, ST], ST any](name types.NamespacedName, logger *log.Logger, client client.Client, cache cache.Cache, objFactory ObjectFactory[T], objStatusGetter ObjectStatusGetter[T, ST]) *Resource[T, ST] { - return &Resource[T, ST]{ - name: name, - log: logger, - client: client, - cache: cache, - objFactory: objFactory, - objStatusGetter: objStatusGetter, - } -} - -func (r *Resource[T, ST]) getObjStatus(obj T) (ret ST) { - if obj != r.emptyObj { - ret = r.objStatusGetter(obj) - } - return -} - -func (r *Resource[T, ST]) Name() types.NamespacedName { - return r.name -} - -func (r *Resource[T, ST]) Fetch(ctx context.Context) error { - currentObj, err := FetchObject(ctx, r.name, r.client, r.objFactory()) - if err != nil { - return err - } - r.log.Debug("Resource.Fetch", "name", r.name.String()) - r.log.Debug("Resource.Fetch", "name", r.name.String(), "obj", currentObj, "status", r.getObjStatus(currentObj)) - - r.currentObj = currentObj - if r.IsEmpty() { - r.changedObj = r.emptyObj - } else { - r.changedObj = currentObj.DeepCopy() - } - return nil -} - -func (r *Resource[T, ST]) IsEmpty() bool { - return r.currentObj == r.emptyObj -} - -func (r *Resource[T, ST]) IsStatusChanged() bool { - return !reflect.DeepEqual(r.getObjStatus(r.currentObj), r.getObjStatus(r.changedObj)) -} - -func (r *Resource[T, ST]) Current() T { - return r.currentObj -} - -func (r *Resource[T, ST]) Changed() T { - return r.changedObj -} - -func (r *Resource[T, ST]) UpdateMeta(ctx context.Context) error { - if r.IsEmpty() { - return nil - } - - r.log.Debug("UpdateMeta obj meta before update", "currentObj", r.currentObj.GetObjectMeta(), "changedObj", r.changedObj.GetObjectMeta()) - if !reflect.DeepEqual(r.getObjStatus(r.currentObj), r.getObjStatus(r.changedObj)) { - return fmt.Errorf("status update is not allowed in the meta updater: %#v changed to %#v", r.getObjStatus(r.currentObj), r.getObjStatus(r.changedObj)) - } - if !reflect.DeepEqual(r.currentObj.GetObjectMeta(), r.changedObj.GetObjectMeta()) { - if err := r.client.Update(ctx, r.changedObj); err != nil { - return fmt.Errorf("error updating: %w", err) - } - r.currentObj = r.changedObj.DeepCopy() - r.log.Debug("UpdateMeta applied", "obj", r.currentObj.GetObjectKind().GroupVersionKind().Kind+"/"+r.currentObj.GetName()) - r.log.Debug("UpdateMeta obj meta after update", "changedObj.ObjectMeta", r.changedObj.GetObjectMeta()) - } else { - r.log.Debug("UpdateMeta skipped: no changes", "currentObj.ObjectMeta", r.currentObj.GetObjectMeta()) - } - return nil -} - -func (r *Resource[T, ST]) UpdateStatus(ctx context.Context) error { - if r.IsEmpty() { - return nil - } - - r.log.Debug("UpdateStatus obj before status update", "currentObj.Status", r.getObjStatus(r.currentObj), "changedObj.Status", r.getObjStatus(r.changedObj)) - if !reflect.DeepEqual(r.currentObj.GetObjectMeta(), r.changedObj.GetObjectMeta()) { - return fmt.Errorf("meta update is not allowed in the status updater: %#v changed to %#v", r.currentObj.GetObjectMeta(), r.changedObj.GetObjectMeta()) - } - if !reflect.DeepEqual(r.getObjStatus(r.currentObj), r.getObjStatus(r.changedObj)) { - if err := r.client.Status().Update(ctx, r.changedObj); err != nil { - return fmt.Errorf("error updating status subresource: %w", err) - } - if err := r.client.Update(ctx, r.changedObj); err != nil { - return fmt.Errorf("error updating: %w", err) - } - r.currentObj = r.changedObj.DeepCopy() - - r.log.Debug("UpdateStatus applied", "obj", r.currentObj.GetObjectKind().GroupVersionKind().Kind+"/"+r.currentObj.GetName()) - r.log.Debug("UpdateStatus obj after status update", "changedObj.Status", r.getObjStatus(r.changedObj)) - } else { - r.log.Debug("UpdateStatus skipped: no changes", "currentObj.Status", r.getObjStatus(r.currentObj)) - } - return nil -} diff --git a/images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/reconciler_core.go b/images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/reconciler_core.go deleted file mode 100644 index a5a9398d7..000000000 --- a/images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/reconciler_core.go +++ /dev/null @@ -1,118 +0,0 @@ -/* -Copyright 2024 Flant JSC - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package two_phase_reconciler - -import ( - "context" - "fmt" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/tools/record" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - "github.com/deckhouse/deckhouse/pkg/log" -) - -type ReconcilerOptions struct { - Client client.Client - Cache cache.Cache - Recorder record.EventRecorder - Scheme *runtime.Scheme - Log *log.Logger -} - -type ReconcilerCore[T ReconcilerState] struct { - Reconciler TwoPhaseReconciler[T] - StateFactory ReconcilerStateFactory[T] - ReconcilerOptions -} - -func NewReconcilerCore[T ReconcilerState](reconciler TwoPhaseReconciler[T], stateFactory ReconcilerStateFactory[T], opts ReconcilerOptions) *ReconcilerCore[T] { - return &ReconcilerCore[T]{ - Reconciler: reconciler, - StateFactory: stateFactory, - ReconcilerOptions: opts, - } -} - -func (r *ReconcilerCore[T]) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) { - r.ReconcilerOptions.Log.Debug(fmt.Sprintf("Start Reconcile for %s", req.String()), "obj", req.String()) - state := r.StateFactory(req.NamespacedName, r.Log, r.Client, r.Cache) - - if err := state.Reload(ctx, req, r.Log, r.Client); err != nil { - return reconcile.Result{}, fmt.Errorf("unable to reload reconciler state: %w", err) - } - - var res *reconcile.Result - var resErr error - - if state.ShouldReconcile(r.Log) { - syncErr := r.sync(ctx, req, state) - resErr = syncErr - res = state.GetReconcilerResult() - if res != nil { - r.Log.Debug(fmt.Sprintf("Reconcile result after Sync: %+v", res), "obj", req.String()) - } - } else { - r.Log.Debug("No Sync required", "obj", req.String()) - } - - if state.ShouldReconcile(r.Log) { - updateStatusErr := r.updateStatus(ctx, req, state) - if res == nil { - res = state.GetReconcilerResult() - } - if resErr == nil { - resErr = updateStatusErr - } - } else { - r.Log.Debug("No UpdateStatus after Sync", "obj", req.String()) - } - - if res == nil { - res = &reconcile.Result{} - } - r.Log.Debug(fmt.Sprintf("Reconcile result after UpdateStatus: %+v", res), "obj", req.String()) - - return *res, resErr -} - -func (r *ReconcilerCore[T]) sync(ctx context.Context, req reconcile.Request, state T) error { - r.ReconcilerOptions.Log.Debug("Call Sync", "obj", req.String()) - if err := r.Reconciler.Sync(ctx, req, state, r.ReconcilerOptions); err != nil { - return err - } - r.ReconcilerOptions.Log.Debug("Call ApplySync", "obj", req.String()) - if err := state.ApplySync(ctx, r.Log); err != nil { - return fmt.Errorf("unable to apply sync changes: %w", err) - } - return nil -} - -func (r *ReconcilerCore[T]) updateStatus(ctx context.Context, req reconcile.Request, state T) error { - r.ReconcilerOptions.Log.Debug("Call UpdateStatus", "obj", req.String()) - if err := r.Reconciler.UpdateStatus(ctx, req, state, r.ReconcilerOptions); err != nil { - return fmt.Errorf("update status phase failed: %w", err) - } - r.ReconcilerOptions.Log.Debug("Call ApplyUpdateStatus", "obj", req.String()) - if err := state.ApplyUpdateStatus(ctx, r.Log); err != nil { - return fmt.Errorf("apply update status failed: %w", err) - } - return nil -} diff --git a/images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/reconciler_state.go b/images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/reconciler_state.go deleted file mode 100644 index 9bd772deb..000000000 --- a/images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/reconciler_state.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2024 Flant JSC - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package two_phase_reconciler - -import ( - "context" - - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - "github.com/deckhouse/deckhouse/pkg/log" -) - -type ReconcilerStateFactory[T ReconcilerState] func(name types.NamespacedName, logger *log.Logger, client client.Client, cache cache.Cache) T - -type ReconcilerState interface { - ReconcilerStateApplier - - SetReconcilerResult(result *reconcile.Result) - GetReconcilerResult() *reconcile.Result - - Reload(ctx context.Context, req reconcile.Request, logger *log.Logger, client client.Client) error - ShouldReconcile(log *log.Logger) bool -} - -type ReconcilerStateApplier interface { - ApplySync(ctx context.Context, log *log.Logger) error - ApplyUpdateStatus(ctx context.Context, log *log.Logger) error -} diff --git a/images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/two_phase_reconciler.go b/images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/two_phase_reconciler.go deleted file mode 100644 index a7bc773db..000000000 --- a/images/virtualization-artifact/pkg/sdk/framework/two_phase_reconciler/two_phase_reconciler.go +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright 2024 Flant JSC - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package two_phase_reconciler - -import ( - "context" - - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" -) - -type TwoPhaseReconciler[T ReconcilerState] interface { - SetupController(ctx context.Context, mgr manager.Manager, ctr controller.Controller) error - Sync(ctx context.Context, req reconcile.Request, state T, opts ReconcilerOptions) error - UpdateStatus(ctx context.Context, req reconcile.Request, state T, opts ReconcilerOptions) error -} diff --git a/images/virtualization-artifact/pkg/sdk/testutil/reconcile_executor.go b/images/virtualization-artifact/pkg/sdk/testutil/reconcile_executor.go deleted file mode 100644 index 358a81ea6..000000000 --- a/images/virtualization-artifact/pkg/sdk/testutil/reconcile_executor.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2024 Flant JSC - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package testutil - -import ( - "context" - - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/reconcile" -) - -type ReconcileExecutor struct { - Name types.NamespacedName - - LastReconcileResult *reconcile.Result -} - -func NewReconcileExecutor(name types.NamespacedName) *ReconcileExecutor { - return &ReconcileExecutor{ - Name: name, - } -} - -func (e *ReconcileExecutor) Execute(ctx context.Context, reconciler reconcile.Reconciler) error { - for { - res, err := reconciler.Reconcile(ctx, reconcile.Request{NamespacedName: e.Name}) - if err != nil { - return err - } - e.LastReconcileResult = &res - - if !res.Requeue { - return nil - } - } -}