Skip to content

Commit

Permalink
refactor(api): split common
Browse files Browse the repository at this point in the history
Signed-off-by: Daniil Antoshin <[email protected]>

fix: lint

Signed-off-by: Daniil Antoshin <[email protected]>

fix: remove package

Signed-off-by: Daniil Antoshin <[email protected]>
  • Loading branch information
danilrwx committed Nov 26, 2024
1 parent 7f0f09d commit c6c0374
Show file tree
Hide file tree
Showing 121 changed files with 983 additions and 1,067 deletions.
136 changes: 136 additions & 0 deletions images/virtualization-artifact/pkg/common/annotations/annotations.go
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
113 changes: 21 additions & 92 deletions images/virtualization-artifact/pkg/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Loading

0 comments on commit c6c0374

Please sign in to comment.