Skip to content

Commit

Permalink
refactor(api): split common package (#534)
Browse files Browse the repository at this point in the history
* refactor(api): split common package

Signed-off-by: Daniil Antoshin <[email protected]>
  • Loading branch information
danilrwx authored Dec 6, 2024
1 parent 64effd2 commit d2b7a8f
Show file tree
Hide file tree
Showing 120 changed files with 847 additions and 1,188 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,14 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package common
package annotations

import (
"errors"
"reflect"
"slices"
"strings"

corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/ptr"
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 (
Expand Down Expand Up @@ -78,25 +70,8 @@ const (
AppKubernetesManagedByLabel = "app.kubernetes.io/managed-by"
// AppKubernetesComponentLabel is the Kubernetes recommended component label
AppKubernetesComponentLabel = "app.kubernetes.io/component"

// QemuSubGid is the gid used as the qemu group in fsGroup
QemuSubGid = int64(107)
)

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")
)

// 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()[AnnPodRetainAfterCompletion] != "true" || obj.GetDeletionTimestamp() != nil
}

// AddAnnotation adds an annotation to an object
func AddAnnotation(obj metav1.Object, key, value string) {
if obj.GetAnnotations() == nil {
Expand All @@ -113,98 +88,6 @@ func AddLabel(obj metav1.Object, key, value string) {
obj.GetLabels()[key] = value
}

type UIDable interface {
GetUID() types.UID
}

// 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
}

// IsDataVolumeComplete returns true if a DataVolume is in 'Succeeded' phase, false if not.
func IsDataVolumeComplete(dv *cdiv1.DataVolume) bool {
return dv != nil && dv.Status.Phase == cdiv1.Succeeded
}

// IsPVCBound returns true if a PersistentVolumeClaim is in 'Bound' phase, false if not.
func IsPVCBound(pvc *corev1.PersistentVolumeClaim) bool {
return pvc != nil && pvc.Status.Phase == corev1.ClaimBound
}

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
}

// 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)
}
}

// ErrQuotaExceeded checked is the error is of exceeded quota
func ErrQuotaExceeded(err error) bool {
return strings.Contains(err.Error(), "exceeded quota:")
}

// 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) {
Expand All @@ -214,15 +97,11 @@ 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)
}

func NamespacedName(obj client.Object) types.NamespacedName {
return types.NamespacedName{Name: obj.GetName(), Namespace: obj.GetNamespace()}
}

func MatchLabels(labels, matchLabels map[string]string) bool {
for key, value := range matchLabels {
if labels[key] != value {
Expand Down
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 d2b7a8f

Please sign in to comment.