kubernetes

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 29, 2025 License: Apache-2.0 Imports: 54 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var APIGroupControllerMap = map[string]map[string]versionutils.VersionRange{
	"internal/v1alpha1": {
		"storage-version-gc": {},
	},
	"admissionregistration/v1beta1": {
		"validatingadmissionpolicy-status-controller": {AddedInVersion: "1.28", RemovedInVersion: "1.30"},
	},
	"admissionregistration/v1": {
		"validatingadmissionpolicy-status-controller": {AddedInVersion: "1.30"},
	},
	"apps/v1": {
		"daemonset":   {},
		"deployment":  {},
		"replicaset":  {},
		"statefulset": {},
	},
	"apps/v1beta1": {
		"disruption": {},
	},
	"authentication/v1": {
		"attachdetach":              {},
		"persistentvolume-expander": {},
	},
	"authorization/v1": {
		"csrapproving": {},
	},
	"autoscaling/v1": {
		"horizontalpodautoscaling": {},
	},
	"autoscaling/v2": {
		"horizontalpodautoscaling": {},
	},
	"batch/v1": {
		"cronjob":            {},
		"job":                {},
		"ttl-after-finished": {},
	},
	"certificates/v1": {
		"csrapproving": {},
		"csrcleaner":   {},
		"csrsigning":   {},
	},
	"certificates/v1beta1": {
		"csrsigning": {},
	},
	"coordination/v1": {
		"nodelifecycle":      {},
		"storage-version-gc": {},
	},
	"discovery/v1": {
		"endpointslice":          {},
		"endpointslicemirroring": {},
	},
	"extensions/v1beta1": {
		"disruption": {},
	},
	"networking/v1alpha1": {
		"service-cidr-controller": {AddedInVersion: "1.29", RemovedInVersion: "1.31"},
	},
	"networking/v1beta1": {
		"service-cidr-controller": {AddedInVersion: "1.31"},
	},
	"policy/v1": {
		"disruption": {},
	},
	"rbac/v1": {
		"clusterrole-aggregation": {},
	},
	"resource/v1alpha2": {
		"resource-claim-controller": {AddedInVersion: "1.27", RemovedInVersion: "1.31"},
	},
	"resource/v1alpha3": {
		"resource-claim-controller": {AddedInVersion: "1.31"},
	},
	"storagemigration/v1alpha1": {
		"storage-version-migrator-controller": {AddedInVersion: "1.30"},
	},
	"v1": {
		"attachdetach":                         {},
		"bootstrapsigner":                      {},
		"cloud-node":                           {},
		"cloud-node-lifecycle":                 {},
		"cronjob":                              {},
		"csrapproving":                         {},
		"csrsigning":                           {},
		"daemonset":                            {},
		"deployment":                           {},
		"disruption":                           {},
		"endpoint":                             {},
		"endpointslice":                        {},
		"endpointslicemirroring":               {},
		"ephemeral-volume":                     {},
		"garbagecollector":                     {RemovedInVersion: "1.30"},
		"horizontalpodautoscaling":             {},
		"job":                                  {},
		"legacy-service-account-token-cleaner": {AddedInVersion: "1.28"},
		"namespace":                            {},
		"nodelifecycle":                        {},
		"persistentvolume-binder":              {},
		"persistentvolume-expander":            {},
		"podgc":                                {},
		"pv-protection":                        {},
		"pvc-protection":                       {},
		"replicaset":                           {},
		"replicationcontroller":                {},
		"resource-claim-controller":            {AddedInVersion: "1.27"},
		"resourcequota":                        {},
		"root-ca-cert-publisher":               {},
		"route":                                {},
		"service":                              {},
		"service-cidr-controller":              {AddedInVersion: "1.29"},
		"serviceaccount":                       {},
		"serviceaccount-token":                 {},
		"statefulset":                          {},
		"taint-eviction-controller":            {AddedInVersion: "1.29"},
		"tokencleaner":                         {},
		"ttl":                                  {},
		"ttl-after-finished":                   {},
	},
}

APIGroupControllerMap is a map for the Kubernetes API groups and the corresponding controllers for them.

View Source
var TLSCipherSuites = []string{
	"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
	"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
	"TLS_AES_128_GCM_SHA256",
	"TLS_AES_256_GCM_SHA384",
	"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
	"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
	"TLS_CHACHA20_POLY1305_SHA256",
	"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
	"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
}

TLSCipherSuites is a list of the wanted and acceptable cipher suits.

View Source
var (
	// WaitTimeout specifies the total time to wait for CRDs to become ready or to be deleted. Exposed for testing.
	WaitTimeout = 15 * time.Second
)

Functions

func AddEnvVar

func AddEnvVar(container *corev1.Container, envVar corev1.EnvVar, overwrite bool)

AddEnvVar adds the given EnvVar to the given Container if not present. If a EnvVar with the given name is already present it optionally overwrites the EnvVar according to the overwrite parameter.

func AddVolume

func AddVolume(podSpec *corev1.PodSpec, volume corev1.Volume, overwrite bool)

AddVolume adds the given Volume to the given PodSpec if not present. If a Volume with the given name is already present it optionally overwrites the Volume according to the overwrite parameter.

func AddVolumeMount

func AddVolumeMount(container *corev1.Container, volumeMount corev1.VolumeMount, overwrite bool)

AddVolumeMount adds the given VolumeMount to the given Container if not present. If a VolumeMount with the given name is already present it optionally overwrites the VolumeMount according to the overwrite parameter.

func ClientCertificateFromRESTConfig

func ClientCertificateFromRESTConfig(restConfig *rest.Config) (*tls.Certificate, error)

ClientCertificateFromRESTConfig returns the client certificate used inside a REST config.

func CurrentReplicaCountForDeployment

func CurrentReplicaCountForDeployment(ctx context.Context, c client.Client, namespace, deploymentName string) (int32, error)

CurrentReplicaCountForDeployment returns the current replicaCount for the given deployment.

func DNSNamesForService

func DNSNamesForService(name, namespace string) []string

DNSNamesForService returns the possible DNS names for a service with the given name and namespace.

func DeleteObject

func DeleteObject(ctx context.Context, c client.Writer, object client.Object) error

DeleteObject deletes a Kubernetes object. It ignores 'not found' and 'no match' errors.

func DeleteObjects

func DeleteObjects(ctx context.Context, c client.Writer, objects ...client.Object) error

DeleteObjects deletes a list of Kubernetes objects.

func DeleteObjectsFromListConditionally

func DeleteObjectsFromListConditionally(ctx context.Context, c client.Client, listObj client.ObjectList, predicateFn func(runtime.Object) bool) error

DeleteObjectsFromListConditionally takes a Kubernetes List object. It iterates over its items and, if provided, executes the predicate function. If it evaluates to true then the object will be deleted.

func DeleteSecretByReference

func DeleteSecretByReference(ctx context.Context, c client.Client, ref *corev1.SecretReference) error

DeleteSecretByReference deletes the secret referenced by the given secret reference.

func DeleteStalePods

func DeleteStalePods(ctx context.Context, log logr.Logger, c client.Client, pods []corev1.Pod) error

DeleteStalePods deletes stale pods.

func FQDNForService

func FQDNForService(name, namespace string) string

FQDNForService returns the fully qualified domain name of a service with the given name and namespace.

func FeatureGatesToCommandLineParameter

func FeatureGatesToCommandLineParameter(fg map[string]bool) string

FeatureGatesToCommandLineParameter transforms feature gates given as string/bool map to a command line parameter that is understood by Kubernetes components.

func FetchEventMessages

func FetchEventMessages(ctx context.Context, scheme *runtime.Scheme, reader client.Reader, obj client.Object, eventType string, eventsLimit int) (string, error)

FetchEventMessages gets events for the given object of the given `eventType` and returns them as a formatted output. The function expects that the given `obj` is specified with a proper `metav1.TypeMeta`.

func GetAdmissionPluginsForVersion

func GetAdmissionPluginsForVersion(v string) []gardencorev1beta1.AdmissionPlugin

GetAdmissionPluginsForVersion returns the set of default admission plugins for the given Kubernetes version. If the given Kubernetes version does not explicitly define admission plugins the set of names for the next available version will be returned (e.g., for version X not defined the set of version X-1 will be returned).

func GetContainerResourcesInStatefulSet

func GetContainerResourcesInStatefulSet(ctx context.Context, k8sClient client.Client, key client.ObjectKey) (map[string]*corev1.ResourceRequirements, error)

GetContainerResourcesInStatefulSet returns the containers resources in StatefulSet.

func GetDeploymentForPod

func GetDeploymentForPod(ctx context.Context, reader client.Reader, namespace string, podOwnerReferences []metav1.OwnerReference) (*appsv1.Deployment, error)

GetDeploymentForPod returns the deployment the pod belongs to by traversing its metadata.

func GetLoadBalancerIngress

func GetLoadBalancerIngress(ctx context.Context, c client.Client, service *corev1.Service) (string, error)

GetLoadBalancerIngress takes a context, a client, a service object. It gets the `service` and queries for a load balancer's technical name (ip address or hostname). It returns the value of the technical name whereby it always prefers the hostname (if given) over the IP address. The passed `service` instance is updated with the information received from the API server.

func GetManagedSeedByName

func GetManagedSeedByName(ctx context.Context, c client.Client, name string) (*seedmanagementv1alpha1.ManagedSeed, error)

GetManagedSeedByName tries to read a ManagedSeed in the garden namespace. If it's not found then `nil` is returned.

func GetManagedSeedWithReader

func GetManagedSeedWithReader(ctx context.Context, r client.Reader, shootNamespace, shootName string) (*seedmanagementv1alpha1.ManagedSeed, error)

GetManagedSeedWithReader gets the ManagedSeed resource for the given shoot namespace and name, by searching for all ManagedSeeds in the shoot namespace that have spec.shoot.name set to the shoot name. If no such ManagedSeeds are found, nil is returned.

func GetNodeSelectorRequirementForZones

func GetNodeSelectorRequirementForZones(isZonePinningEnabled bool, zones []string) *corev1.NodeSelectorRequirement

GetNodeSelectorRequirementForZones returns a node selector requirement to ensure all pods are scheduled only on nodes in the provided zones. If no zones are provided then nothing is done. Note that the returned requirement should be added to all existing node selector terms in the spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms field of pods because the various node selector terms are evaluated with the OR operator.

func GetPodLogs

func GetPodLogs(ctx context.Context, podInterface corev1client.PodInterface, name string, options *corev1.PodLogOptions) ([]byte, error)

GetPodLogs retrieves the pod logs of the pod of the given name with the given options.

func GetReplicaCount

func GetReplicaCount(failureToleranceType *gardencorev1beta1.FailureToleranceType, componentType string) *int32

GetReplicaCount returns the replica count based on the criteria, failure tolerance type, and component type.

func GetSecretByReference

func GetSecretByReference(ctx context.Context, c client.Reader, ref *corev1.SecretReference) (*corev1.Secret, error)

GetSecretByReference returns the secret referenced by the given secret reference.

func GetSecretMetadataByReference

func GetSecretMetadataByReference(ctx context.Context, c client.Reader, ref *corev1.SecretReference) (*metav1.PartialObjectMetadata, error)

GetSecretMetadataByReference returns the secret referenced by the given secret reference.

func GetTopologySpreadConstraints

func GetTopologySpreadConstraints(
	replicas int32,
	maxReplicas int32,
	labelSelector metav1.LabelSelector,
	numberOfZones int32,
	failureToleranceType *gardencorev1beta1.FailureToleranceType,
	enforceSpreadAcrossHosts bool,
) []corev1.TopologySpreadConstraint

GetTopologySpreadConstraints adds topology spread constraints based on the passed `failureToleranceType`. This is only done when the number of replicas is greater than 1 (otherwise, it doesn't make sense to add spread constraints).

func HasDeploymentRolloutCompleted

func HasDeploymentRolloutCompleted(ctx context.Context, c client.Client, namespace, name string) (bool, error)

HasDeploymentRolloutCompleted checks for the number of updated & available replicas to be equal to the deployment's desired replicas count. Thus confirming a successful rollout of the deployment.

func HasEnvVar

func HasEnvVar(container corev1.Container, name string) bool

HasEnvVar checks if the given container has an EnvVar with the given name.

func HasMetaDataAnnotation

func HasMetaDataAnnotation(meta metav1.Object, key, value string) bool

HasMetaDataAnnotation checks if the passed meta object has the given key, value set in the annotations section.

func IsNodeLabelAllowedForKubelet

func IsNodeLabelAllowedForKubelet(key string) bool

IsNodeLabelAllowedForKubelet determines whether kubelet is allowed by the NodeRestriction admission plugin to set a label on its own Node object with the given key. See https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#noderestriction.

func LookupObject

func LookupObject(ctx context.Context, c client.Client, apiReader client.Reader, key client.ObjectKey, obj client.Object) error

LookupObject retrieves an obj for the given object key dealing with potential stale cache that still does not contain the obj. It first tries to retrieve the obj using the given cached client. If the object key is not found, then it does live lookup from the API server using the given apiReader.

func MakeUnique

func MakeUnique(obj runtime.Object) error

MakeUnique takes either a *corev1.ConfigMap or a *corev1.Secret object and makes it immutable, i.e., it sets .immutable=true, computes a checksum based on .data, and appends the first 8 characters of the computed checksum to the name of the object. Additionally, it injects the `resources.gardener.cloud/garbage-collectable-reference=true` label.

func MapStringBoolToCommandLineParameter

func MapStringBoolToCommandLineParameter(m map[string]bool, param string) string

MapStringBoolToCommandLineParameter transforms a string/bool map to a command line parameter that is understood by Kubernetes components.

func MergeOwnerReferences

func MergeOwnerReferences(references []metav1.OwnerReference, newReferences ...metav1.OwnerReference) []metav1.OwnerReference

MergeOwnerReferences merges the newReferences with the list of existing references.

func MostRecentCompleteLogs

func MostRecentCompleteLogs(
	ctx context.Context,
	podInterface corev1client.PodInterface,
	pod *corev1.Pod,
	containerName string,
	tailLines,
	headBytes *int64,
) (
	string,
	error,
)

MostRecentCompleteLogs returns the logs of the pod/container in case it is not running. If the pod/container is running then the logs of the previous pod/container are being returned.

func NewKubeconfig

func NewKubeconfig(contextName string, cluster clientcmdv1.Cluster, authInfo clientcmdv1.AuthInfo) *clientcmdv1.Config

NewKubeconfig returns a new kubeconfig structure.

func NewestObject

func NewestObject(ctx context.Context, c client.Reader, listObj client.ObjectList, filterFn func(client.Object) bool, listOpts ...client.ListOption) (client.Object, error)

NewestObject returns the most recently created object based on the provided list object type. If a filter function is provided then it will be applied for each object right after listing all objects. If no object remains then nil is returned. The Items field in the list object will be populated with the result returned from the server after applying the filter function (if provided).

func NewestPodForDeployment

func NewestPodForDeployment(ctx context.Context, c client.Reader, deployment *appsv1.Deployment) (*corev1.Pod, error)

NewestPodForDeployment returns the most recently created Pod object for the given deployment.

func ObjectKeyForCreateWebhooks

func ObjectKeyForCreateWebhooks(obj client.Object, req admission.Request) client.ObjectKey

ObjectKeyForCreateWebhooks creates an object key for an object handled by webhooks registered for CREATE verbs.

func ObjectKeyFromSecretRef

func ObjectKeyFromSecretRef(ref corev1.SecretReference) client.ObjectKey

ObjectKeyFromSecretRef returns an ObjectKey for the given SecretReference.

func OwnedBy

func OwnedBy(obj client.Object, apiVersion, kind, name string, uid types.UID) bool

OwnedBy checks if the given object's owner reference contains an entry with the provided attributes.

func PodManagedByDaemonSet

func PodManagedByDaemonSet(pod *corev1.Pod) bool

PodManagedByDaemonSet returns 'true' if the given pod is managed by a DaemonSet, determined by the existing owner references.

func ReadLeaderElectionRecord

func ReadLeaderElectionRecord(ctx context.Context, c client.Client, lock, namespace, name string) (*resourcelock.LeaderElectionRecord, error)

ReadLeaderElectionRecord returns the leader election record for a given lock type and a namespace/name combination.

func ReconcileServicePorts

func ReconcileServicePorts(existingPorts []corev1.ServicePort, desiredPorts []corev1.ServicePort, desiredServiceType corev1.ServiceType) []corev1.ServicePort

ReconcileServicePorts reconciles the existing service ports with the desired ports. This means that it takes the existing port (identified by name), and applies the settings from the desired port to it. This way it can keep fields that are defaulted by controllers, e.g. the node port. However, it does not keep ports that are not part of the desired list.

func ResourcesExist

func ResourcesExist(ctx context.Context, reader client.Reader, objList client.ObjectList, scheme *runtime.Scheme, listOpts ...client.ListOption) (bool, error)

ResourcesExist checks if there is at least one object of the given objList.

func ScaleDeployment

func ScaleDeployment(ctx context.Context, c client.Client, key client.ObjectKey, replicas int32) error

ScaleDeployment scales a Deployment.

func ScaleStatefulSet

func ScaleStatefulSet(ctx context.Context, c client.Client, key client.ObjectKey, replicas int32) error

ScaleStatefulSet scales a StatefulSet.

func ScaleStatefulSetAndWaitUntilScaled

func ScaleStatefulSetAndWaitUntilScaled(ctx context.Context, c client.Client, key client.ObjectKey, replicas int32) error

ScaleStatefulSetAndWaitUntilScaled scales a StatefulSet and wait until is scaled.

func SetAlwaysAllowEviction

func SetAlwaysAllowEviction(pdb *policyv1.PodDisruptionBudget, kubernetesVersion *semver.Version)

SetAlwaysAllowEviction sets the UnhealthyPodEvictionPolicy field to AlwaysAllow if the kubernetes version is >= 1.26.

func SetAnnotationAndUpdate

func SetAnnotationAndUpdate(ctx context.Context, c client.Client, obj client.Object, key, value string) error

SetAnnotationAndUpdate sets the annotation on the given object and updates it.

func SetMetaDataAnnotation

func SetMetaDataAnnotation(meta metav1.Object, key, value string)

SetMetaDataAnnotation sets the annotation on the given object. If the given Object did not yet have annotations, they are initialized.

func SetMetaDataLabel

func SetMetaDataLabel(meta metav1.Object, key, value string)

SetMetaDataLabel sets the key value pair in the labels section of the given Object. If the given Object did not yet have labels, they are initialized.

func TolerationForTaint

func TolerationForTaint(taint corev1.Taint) corev1.Toleration

TolerationForTaint returns the corresponding toleration for the given taint.

func TruncateLabelValue

func TruncateLabelValue(s string) string

TruncateLabelValue truncates a string at 63 characters so it's suitable for a label value.

func ValidDeploymentContainerImageVersion

func ValidDeploymentContainerImageVersion(deploymentToCheck *appsv1.Deployment, containerName, minimumVersion string) (bool, error)

ValidDeploymentContainerImageVersion validates compliance of a deployment container image to a minimum version

func VisitContainers

func VisitContainers(podSpec *corev1.PodSpec, visit func(*corev1.Container), containerNames ...string)

VisitContainers calls the given visitor for all (init) containers in the given PodSpec. If containerNames are given it only visits (init) containers with matching names. The visitor may mutate the Container.

func VisitPodSpec

func VisitPodSpec(obj runtime.Object, visit func(*corev1.PodSpec)) error

VisitPodSpec calls the given visitor for the PodSpec contained in the given object. The visitor may mutate the PodSpec.

func WaitUntilCRDManifestsDestroyed

func WaitUntilCRDManifestsDestroyed(ctx context.Context, c client.Client, crdNames ...string) error

WaitUntilCRDManifestsDestroyed takes CRD names and waits for them to be gone with a timeout of 15 seconds.

func WaitUntilCRDManifestsReady

func WaitUntilCRDManifestsReady(ctx context.Context, c client.Client, crdNames ...string) error

WaitUntilCRDManifestsReady takes names of CRDs and waits for them to get ready with a timeout of 15 seconds.

func WaitUntilDeploymentRolloutIsComplete

func WaitUntilDeploymentRolloutIsComplete(ctx context.Context, client client.Client, namespace string, name string, interval, timeout time.Duration) error

WaitUntilDeploymentRolloutIsComplete waits for the number of updated & available replicas to be equal to the deployment's desired replicas count. It keeps retrying until timeout

func WaitUntilDeploymentScaledToDesiredReplicas

func WaitUntilDeploymentScaledToDesiredReplicas(ctx context.Context, client client.Client, key types.NamespacedName, desiredReplicas int32) error

WaitUntilDeploymentScaledToDesiredReplicas waits for the number of available replicas to be equal to the deployment's desired replicas count.

func WaitUntilLoadBalancerIsReady

func WaitUntilLoadBalancerIsReady(
	ctx context.Context,
	log logr.Logger,
	c client.Client,
	namespace, name string,
	timeout time.Duration,
) (
	string,
	error,
)

WaitUntilLoadBalancerIsReady waits until the given external load balancer has been created (i.e., its ingress information has been updated in the service status).

func WaitUntilResourceDeleted

func WaitUntilResourceDeleted(ctx context.Context, c client.Client, obj client.Object, interval time.Duration) error

WaitUntilResourceDeleted waits until it has been deleted. It respects the given interval. Timeout must be provided via the context.

func WaitUntilResourceDeletedWithDefaults

func WaitUntilResourceDeletedWithDefaults(ctx context.Context, c client.Client, obj client.Object) error

WaitUntilResourceDeletedWithDefaults deletes the given resource and then waits until it has been deleted. It uses a default interval and timeout

func WaitUntilResourcesDeleted

func WaitUntilResourcesDeleted(ctx context.Context, c client.Client, list client.ObjectList, interval time.Duration, opts ...client.ListOption) error

WaitUntilResourcesDeleted waits until the given resources are gone. It respects the given interval and timeout.

func WaitUntilStatefulSetScaledToDesiredReplicas

func WaitUntilStatefulSetScaledToDesiredReplicas(ctx context.Context, client client.Client, key types.NamespacedName, desiredReplicas int32) error

WaitUntilStatefulSetScaledToDesiredReplicas waits for the number of available replicas to be equal to the StatefulSet's desired replicas count.

Types

type ComparableTolerations

type ComparableTolerations struct {
	// contains filtered or unexported fields
}

ComparableTolerations contains information to transform an ordinary 'corev1.Toleration' object to a semantically comparable object that is fully compatible with the 'comparable' Golang interface, see https://github.com/golang/go/blob/de6abd78893e91f26337eb399644b7a6bc3ea583/src/builtin/builtin.go#L102.

func (*ComparableTolerations) Transform

func (c *ComparableTolerations) Transform(toleration corev1.Toleration) corev1.Toleration

Transform takes a toleration object and exchanges the 'TolerationSeconds' pointer if set. The int64 value will be the same but pointers will be **reused** for all passed tolerations that have the same underlying toleration seconds value.

type SortBy

type SortBy func(o1, o2 client.Object) bool

SortBy the type of a "less" function that defines the ordering of its object arguments.

func ByCreationTimestamp

func ByCreationTimestamp() SortBy

ByCreationTimestamp returns a comparison function for sorting by creation timestamp.

func ByName

func ByName() SortBy

ByName returns a comparison function for sorting by name.

func (SortBy) Sort

func (sortBy SortBy) Sort(objList runtime.Object)

Sort sorts the items in the provided list objects according to the sort-by function.

Directories

Path Synopsis
mock
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL