kube

package
v1.18.2 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2026 License: Apache-2.0 Imports: 49 Imported by: 25

Documentation

Overview

Copyright The Velero Contributors.

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.

Copyright The Velero Contributors.

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.

Copyright The Velero Contributors.

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.

Index

Constants

View Source
const (
	NodeOSLinux   = "linux"
	NodeOSWindows = "windows"
	NodeOSLabel   = "kubernetes.io/os"
)
View Source
const (
	KubeAnnBindCompleted          = "pv.kubernetes.io/bind-completed"
	KubeAnnBoundByController      = "pv.kubernetes.io/bound-by-controller"
	KubeAnnDynamicallyProvisioned = "pv.kubernetes.io/provisioned-by"
	KubeAnnMigratedTo             = "pv.kubernetes.io/migrated-to"
	KubeAnnSelectedNode           = "volume.kubernetes.io/selected-node"
)

These annotations are taken from the Kubernetes persistent volume/persistent volume claim controller. They cannot be directly importing because they are part of the kubernetes/kubernetes package, and importing that package is unsupported. Their values are well-known and slow changing. They're duplicated here as constants to provide compile-time checking. Originals can be found in kubernetes/kubernetes/pkg/controller/volume/persistentvolume/util/util.go.

View Source
const VolumeSnapshotContentManagedByLabel = "snapshot.storage.kubernetes.io/managed-by"

VolumeSnapshotContentManagedByLabel is applied by the snapshot controller to the VolumeSnapshotContent object in case distributed snapshotting is enabled. The value contains the name of the node that handles the snapshot for the volume local to that node.

Variables

View Source
var ErrorPodVolumeIsNotPVC = errors.New("pod volume is not a PVC")

Functions

func AddAnnotations added in v1.14.0

func AddAnnotations(o *metav1.ObjectMeta, vals map[string]string)

AddAnnotations adds the supplied key-values to the annotations on the object

func AddLabels added in v1.14.0

func AddLabels(o *metav1.ObjectMeta, vals map[string]string)

AddLabels adds the supplied key-values to the labels on the object

func CollectPodLogs added in v1.15.0

func CollectPodLogs(ctx context.Context, podGetter corev1client.CoreV1Interface, pod string, namespace string, container string, output io.Writer) error

CollectPodLogs collects logs of the specified container of a pod and write to the output

func DeletePVAndPVCIfAny added in v1.12.3

func DeletePVAndPVCIfAny(ctx context.Context, client corev1client.CoreV1Interface, pvcName, pvcNamespace string, ensureTimeout time.Duration, log logrus.FieldLogger)

DeletePVAndPVCIfAny deletes PVC and delete the bound PV if it exists and log an error when the deletion fails. It first sets the reclaim policy of the PV to Delete, then PV will be deleted automatically when PVC is deleted. If ensureTimeout is not 0, it waits until the PVC is deleted or timeout.

func DeletePVIfAny added in v1.12.0

func DeletePVIfAny(ctx context.Context, pvGetter corev1client.CoreV1Interface, pvName string, log logrus.FieldLogger)

DeletePVIfAny deletes a PV by name if it exists, and log an error when the deletion fails

func DeletePodIfAny added in v1.12.0

func DeletePodIfAny(ctx context.Context, podGetter corev1client.CoreV1Interface, podName string, podNamespace string, log logrus.FieldLogger)

DeletePodIfAny deletes a pod by name if it exists, and log an error when the deletion fails

func DiagnosePV added in v1.15.1

func DiagnosePV(pv *corev1api.PersistentVolume) string

func DiagnosePVC added in v1.15.1

func DiagnosePVC(pvc *corev1api.PersistentVolumeClaim, events *corev1api.EventList) string

func DiagnosePod added in v1.15.1

func DiagnosePod(pod *corev1api.Pod, events *corev1api.EventList) string

func EnqueueRequestsFromMapUpdateFunc added in v1.11.0

func EnqueueRequestsFromMapUpdateFunc(fn handler.MapFunc) handler.EventHandler

EnqueueRequestsFromMapUpdateFunc has the same purpose with handler.EnqueueRequestsFromMapFunc. It's simpler on Update event because mapAndEnqueue is called once with the new object. EnqueueRequestsFromMapFunc is called twice with the old and new object.

func EnsureDeletePVC added in v1.12.0

func EnsureDeletePVC(ctx context.Context, pvcGetter corev1client.CoreV1Interface, pvcName string, namespace string, timeout time.Duration) error

EnsureDeletePVC asserts the existence of a PVC by name, deletes it and waits for its disappearance and returns errors on any failure If timeout is 0, it doesn't wait and return nil

func EnsureDeletePod added in v1.12.0

func EnsureDeletePod(ctx context.Context, podGetter corev1client.CoreV1Interface, pod string, namespace string, timeout time.Duration) error

EnsureDeletePod asserts the existence of a pod by name, deletes it and waits for its disappearance and returns errors on any failure

func EnsureNamespaceExistsAndIsReady added in v0.11.0

func EnsureNamespaceExistsAndIsReady(namespace *corev1api.Namespace, client corev1client.NamespaceInterface, timeout time.Duration, resourceDeletionStatusTracker ResourceDeletionStatusTracker) (ready bool, nsCreated bool, err error)

EnsureNamespaceExistsAndIsReady attempts to create the provided Kubernetes namespace. It returns three values:

  • a bool indicating whether or not the namespace is ready,
  • a bool indicating whether or not the namespace was created
  • an error if one occurred.

examples:

namespace already exists and is not ready, this function will return (false, false, nil).
If the namespace exists and is marked for deletion, this function will wait up to the timeout for it to fully delete.

func EnsurePVDeleted added in v1.16.0

func EnsurePVDeleted(ctx context.Context, pvGetter corev1client.CoreV1Interface, pvName string, timeout time.Duration) error

EnsurePVDeleted ensures a PV has been deleted. This function is supposed to be called after EnsureDeletePVC If timeout is 0, it doesn't wait and return nil

func ExitPodWithMessage added in v1.17.0

func ExitPodWithMessage(logger logrus.FieldLogger, succeed bool, message string, a ...any)

func GetNodeOS added in v1.16.0

func GetNodeOS(ctx context.Context, nodeName string, nodeClient corev1client.CoreV1Interface) (string, error)

func GetPVAttachedNode added in v1.16.0

func GetPVAttachedNode(ctx context.Context, pv string, storageClient storagev1.StorageV1Interface) (string, error)

func GetPVAttachedNodes added in v1.17.1

func GetPVAttachedNodes(ctx context.Context, pv string, storageClient storagev1.StorageV1Interface) ([]string, error)

func GetPVCAttachingNodeOS added in v1.16.0

func GetPVCAttachingNodeOS(pvc *corev1api.PersistentVolumeClaim, nodeClient corev1client.CoreV1Interface,
	storageClient storagev1.StorageV1Interface, log logrus.FieldLogger) string

func GetPVCForPodVolume added in v1.14.0

func GetPVCForPodVolume(vol *corev1api.Volume, pod *corev1api.Pod, crClient crclient.Client) (*corev1api.PersistentVolumeClaim, error)

func GetPVForPVC added in v1.14.0

GetPVForPVC returns the PersistentVolume backing a PVC returns PV, error. PV will be nil on error

func GetPodContainerTerminateMessage added in v1.15.0

func GetPodContainerTerminateMessage(pod *corev1api.Pod, container string) string

GetPodContainerTerminateMessage returns the terminate message for a specific container of a pod

func GetPodPVCVolume added in v1.12.1

GetPodPVCVolume gets the PVC, PV and volume for a pod volume name. Returns pod volume in case of ErrorPodVolumeIsNotPVC error

func GetPodTerminateMessage added in v1.15.0

func GetPodTerminateMessage(pod *corev1api.Pod) string

GetPodTerminateMessage returns the terminate message for all containers of a pod

func GetSecret added in v1.6.0

func GetSecret(client kbclient.Client, namespace, name string) (*corev1api.Secret, error)

func GetSecretKey added in v1.6.0

func GetSecretKey(client kbclient.Client, namespace string, selector *corev1api.SecretKeySelector) ([]byte, error)

func GetVolumeDirectory added in v0.9.0

func GetVolumeDirectory(ctx context.Context, log logrus.FieldLogger, pod *corev1api.Pod, volumeName string, kubeClient kubernetes.Interface) (string, error)

GetVolumeDirectory gets the name of the directory on the host, under /var/lib/kubelet/pods/<podUID>/volumes/, where the specified volume lives. For volumes with a CSIVolumeSource, append "/mount" to the directory name.

func GetVolumeMode added in v1.12.1

func GetVolumeMode(ctx context.Context, log logrus.FieldLogger, pod *corev1api.Pod, volumeName string, kubeClient kubernetes.Interface) (
	uploader.PersistentVolumeMode, error)

GetVolumeMode gets the uploader.PersistentVolumeMode of the volume.

func GetVolumeTopology added in v1.18.1

func GetVolumeTopology(ctx context.Context, volumeClient corev1client.CoreV1Interface, storageClient storagev1.StorageV1Interface, pvName string, scName string) (*corev1api.NodeSelector, error)

func HasBackupLabel added in v1.14.0

func HasBackupLabel(o *metav1.ObjectMeta, backupName string) bool

func HasNodeWithOS added in v1.16.0

func HasNodeWithOS(ctx context.Context, os string, nodeClient corev1client.CoreV1Interface) error

func IsCRDReady added in v1.3.0

func IsCRDReady(crd *unstructured.Unstructured) (bool, error)

IsCRDReady triggers IsV1Beta1CRDReady/IsV1CRDReady according to the version of the input param

func IsLinuxNode added in v1.16.0

func IsLinuxNode(ctx context.Context, nodeName string, client client.Client) error

func IsPVCBound added in v1.12.0

func IsPVCBound(pvc *corev1api.PersistentVolumeClaim) bool

IsPVCBound returns true if the specified PVC has been bound

func IsPodRunning added in v1.10.0

func IsPodRunning(pod *corev1api.Pod) error

IsPodRunning does a well-rounded check to make sure the specified pod is running stably. If not, return the error found

func IsPodScheduled added in v1.11.0

func IsPodScheduled(pod *corev1api.Pod) error

IsPodScheduled does a well-rounded check to make sure the specified pod has been scheduled into a node and in a stable status. If not, return the error found

func IsPodUnrecoverable added in v1.13.0

func IsPodUnrecoverable(pod *corev1api.Pod, log logrus.FieldLogger) (bool, string)

IsPodUnrecoverable checks if the pod is in an abnormal state and could not be recovered It could not cover all the cases but we could add more cases in the future

func IsV1Beta1CRDReady added in v1.6.3

func IsV1Beta1CRDReady(crd *apiextv1beta1.CustomResourceDefinition) bool

IsV1Beta1CRDReady checks a v1beta1 CRD to see if it's ready, with both the Established and NamesAccepted conditions.

func IsV1CRDReady added in v1.6.3

func IsV1CRDReady(crd *apiextv1.CustomResourceDefinition) bool

IsV1CRDReady checks a v1 CRD to see if it's ready, with both the Established and NamesAccepted conditions.

func MakePodPVCAttachment added in v1.12.1

func MakePodPVCAttachment(volumeName string, volumeMode *corev1api.PersistentVolumeMode, readOnly bool) ([]corev1api.VolumeMount, []corev1api.VolumeDevice, string)

MakePodPVCAttachment returns the volume mounts and devices for a pod needed to attach a PVC

func NamespaceAndName added in v0.4.0

func NamespaceAndName(objMeta metav1.Object) string

NamespaceAndName returns a string in the format <namespace>/<name>

func NewAllEventPredicate added in v1.10.0

func NewAllEventPredicate(f func(object client.Object) bool) predicate.Predicate

NewAllEventPredicate creates a new Predicate that checks all the events with the provided func

func NewCreateEventPredicate added in v1.11.0

func NewCreateEventPredicate(
	f func(object client.Object) bool,
) predicate.Predicate

func NewGenericEventPredicate added in v1.10.0

func NewGenericEventPredicate(f func(object client.Object) bool) predicate.Predicate

NewGenericEventPredicate creates a new Predicate that checks the Generic event with the provided func

func NewUpdateEventPredicate added in v1.11.0

func NewUpdateEventPredicate(
	f func(objectOld client.Object, objectNew client.Object) bool,
) predicate.Predicate

NewUpdateEventPredicate creates a new Predicate that checks the Update event with the provided func

func ParseCPUAndMemoryResources added in v1.18.1

func ParseCPUAndMemoryResources(cpuRequest, memRequest, cpuLimit, memLimit string) (corev1api.ResourceRequirements, error)

ParseCPUAndMemoryResources is a helper function that parses CPU and memory requests and limits, using default values for ephemeral storage.

func ParseResourceRequirements added in v1.0.1

func ParseResourceRequirements(
	cpuRequest,
	memRequest,
	ephemeralStorageRequest,
	cpuLimit,
	memLimit,
	ephemeralStorageLimit string,
) (corev1api.ResourceRequirements, error)

ParseResourceRequirements takes a set of CPU, memory, ephemeral storage requests and limit string values and returns a ResourceRequirements struct to be used in a Container. An error is returned if we cannot parse the request/limit.

func ParseSecurityContext added in v1.5.0

func ParseSecurityContext(runAsUser string, runAsGroup string, allowPrivilegeEscalation string, secCtx string) (corev1api.SecurityContext, error)

func PatchResource added in v1.11.0

func PatchResource(original, updated client.Object, kbClient client.Client) error

func PatchResourceWithRetries added in v1.15.0

func PatchResourceWithRetries(maxDuration time.Duration, original, updated client.Object, kbClient client.Client, retriable func(error) bool) error

PatchResourceWithRetries patches the original resource with the updated resource, retrying when the provided retriable function returns true.

func PatchResourceWithRetriesOnErrors added in v1.15.0

func PatchResourceWithRetriesOnErrors(maxDuration time.Duration, original, updated client.Object, kbClient client.Client) error

PatchResourceWithRetriesOnErrors patches the original resource with the updated resource, retrying when the operation returns an error.

func RebindPVC added in v1.12.0

RebindPVC rebinds a PVC by modifying its VolumeName to the specific PV

func ResetPVBinding added in v1.12.0

ResetPVBinding resets the binding info of a PV and adds the required labels so as to make it ready for binding

func SetPVReclaimPolicy added in v1.12.0

SetPVReclaimPolicy sets the specified reclaim policy to a PV

func SinglePathMatch added in v1.9.1

func SinglePathMatch(path string, fs filesystem.Interface, log logrus.FieldLogger) (string, error)

SinglePathMatch checks whether pass-in volume path is valid. Check whether there is only one match by the path's pattern.

func ToSystemAffinity added in v1.15.0

func ToSystemAffinity(loadAffinity *LoadAffinity, volumeTopology *corev1api.NodeSelector) *corev1api.Affinity

func TypedEnqueueRequestsFromMapUpdateFunc added in v1.16.0

func TypedEnqueueRequestsFromMapUpdateFunc[object any, request comparable](fn handler.TypedMapFunc[object, request]) handler.TypedEventHandler[object, request]

func ValidatePriorityClass added in v1.17.0

func ValidatePriorityClass(ctx context.Context, kubeClient kubernetes.Interface, priorityClassName string, logger logrus.FieldLogger) bool

ValidatePriorityClass checks if the specified priority class exists in the cluster Returns true if the priority class exists or if priorityClassName is empty Returns false if the priority class doesn't exist or validation fails Logs warnings when the priority class doesn't exist

func ValidatePriorityClassWithClient added in v1.17.0

func ValidatePriorityClassWithClient(ctx context.Context, cli client.Client, priorityClassName string) error

ValidatePriorityClassWithClient checks if the specified priority class exists in the cluster using controller-runtime client Returns nil if the priority class exists or if priorityClassName is empty Returns error if the priority class doesn't exist or validation fails

func VerifyJSONConfigs added in v1.17.0

func VerifyJSONConfigs(ctx context.Context, namespace string, crClient client.Client, configName string, configType any) error

func WaitPVBound added in v1.12.0

func WaitPVBound(ctx context.Context, pvGetter corev1client.CoreV1Interface, pvName string, pvcName string, pvcNamespace string, timeout time.Duration) (*corev1api.PersistentVolume, error)

WaitPVBound wait for binding of a PV specified by name and returns the bound PV object

func WaitPVCBound added in v1.12.0

func WaitPVCBound(ctx context.Context, pvcGetter corev1client.CoreV1Interface,
	pvGetter corev1client.CoreV1Interface, pvc string, namespace string, timeout time.Duration) (*corev1api.PersistentVolume, error)

WaitPVCBound wait for binding of a PVC specified by name and returns the bound PV object

func WaitPVCConsumed added in v1.12.0

func WaitPVCConsumed(
	ctx context.Context,
	pvcGetter corev1client.CoreV1Interface,
	pvc string, namespace string,
	storageClient storagev1.StorageV1Interface,
	timeout time.Duration,
	ignoreConsume bool,
) (string, *corev1api.PersistentVolumeClaim, error)

WaitPVCConsumed waits for a PVC to be consumed by a pod so that the selected node is set by the pod scheduling; or does nothing if the consuming doesn't affect the PV provision. The latest PVC and the selected node will be returned.

func WithLinuxNode added in v1.16.0

func WithLinuxNode(ctx context.Context, client client.Client, log logrus.FieldLogger) bool

func WithWindowsNode added in v1.16.0

func WithWindowsNode(ctx context.Context, client client.Client, log logrus.FieldLogger) bool

Types

type Client added in v1.15.0

type Client interface {
	client.Reader
	client.Writer
	client.StatusClient
	client.SubResourceClientConstructor

	// Scheme returns the scheme this client is using.
	Scheme() *runtime.Scheme
	// RESTMapper returns the rest this client is using.
	RESTMapper() meta.RESTMapper
	// GroupVersionKindFor returns the GroupVersionKind for the given object.
	GroupVersionKindFor(obj runtime.Object) (schema.GroupVersionKind, error)
	// IsObjectNamespaced returns true if the GroupVersionKind of the object is namespaced.
	IsObjectNamespaced(obj runtime.Object) (bool, error)
}

Client knows how to perform CRUD operations on Kubernetes objects.

type EventRecorder added in v1.15.0

type EventRecorder interface {
	Event(object runtime.Object, warning bool, reason string, message string, a ...any)
	EndingEvent(object runtime.Object, warning bool, reason string, message string, a ...any)
	Shutdown()
}

func NewEventRecorder added in v1.15.0

func NewEventRecorder(kubeClient kubernetes.Interface, scheme *runtime.Scheme, eventSource string, eventNode string, log logrus.FieldLogger) EventRecorder

type FalsePredicate added in v1.10.0

type FalsePredicate struct{}

FalsePredicate always returns false for all kinds of events

func (FalsePredicate) Create added in v1.10.0

Create always returns false

func (FalsePredicate) Delete added in v1.10.0

Delete always returns false

func (FalsePredicate) Generic added in v1.10.0

Generic always returns false

func (FalsePredicate) Update added in v1.10.0

Update always returns false

type InternalLW added in v1.12.0

type InternalLW struct {
	Client     kbclient.WithWatch
	Namespace  string
	ObjectList kbclient.ObjectList
}

func (*InternalLW) List added in v1.12.0

func (lw *InternalLW) List(options metav1.ListOptions) (runtime.Object, error)

func (*InternalLW) Watch added in v1.12.0

func (lw *InternalLW) Watch(options metav1.ListOptions) (watch.Interface, error)

type LoadAffinity added in v1.15.0

type LoadAffinity struct {
	// NodeSelector specifies the label selector to match nodes
	NodeSelector metav1.LabelSelector `json:"nodeSelector"`

	// StorageClass specifies the VGDPs the LoadAffinity applied to. If the StorageClass doesn't have value, it applies to all. If not, it applies to only the VGDPs that use this StorageClass.
	StorageClass string `json:"storageClass"`
}

func GetLoadAffinityByStorageClass added in v1.17.0

func GetLoadAffinityByStorageClass(
	affinityList []*LoadAffinity,
	scName string,
	logger logrus.FieldLogger,
) *LoadAffinity

GetLoadAffinityByStorageClass retrieves the LoadAffinity from the parameter affinityList. The function first try to find by the scName. If there is no such LoadAffinity, it will try to get the LoadAffinity whose StorageClass has no value.

type PeriodicalEnqueueSource added in v1.9.0

type PeriodicalEnqueueSource struct {
	client.Client
	// contains filtered or unexported fields
}

PeriodicalEnqueueSource is an implementation of interface sigs.k8s.io/controller-runtime/pkg/source/Source It reads the specific resources from Kubernetes/cache and enqueues them into the queue to trigger the reconcile logic periodically

func NewPeriodicalEnqueueSource added in v1.9.0

func NewPeriodicalEnqueueSource(
	logger logrus.FieldLogger,
	client client.Client,
	objList client.ObjectList,
	period time.Duration,
	option PeriodicalEnqueueSourceOption) *PeriodicalEnqueueSource

func (*PeriodicalEnqueueSource) Start added in v1.9.0

Start enqueue items periodically

func (*PeriodicalEnqueueSource) String added in v1.9.3

func (p *PeriodicalEnqueueSource) String() string

type PeriodicalEnqueueSourceOption added in v1.10.0

type PeriodicalEnqueueSourceOption struct {
	OrderFunc  func(objList client.ObjectList) client.ObjectList
	Predicates []predicate.Predicate // the predicates only apply to the GenericEvent
}

type PodResources added in v1.15.0

type PodResources struct {
	CPURequest              string `json:"cpuRequest,omitempty"`
	CPULimit                string `json:"cpuLimit,omitempty"`
	MemoryRequest           string `json:"memoryRequest,omitempty"`
	MemoryLimit             string `json:"memoryLimit,omitempty"`
	EphemeralStorageRequest string `json:"ephemeralStorageRequest,omitempty"`
	EphemeralStorageLimit   string `json:"ephemeralStorageLimit,omitempty"`
}

type ResourceDeletionStatusTracker added in v1.16.0

type ResourceDeletionStatusTracker interface {
	// Add informs the tracker that a polling is in progress to check namespace deletion status.
	Add(kind, ns, name string)
	// Delete informs the tracker that a namespace deletion is completed.
	Delete(kind, ns, name string)
	// Contains returns true if the tracker is tracking the namespace deletion progress.
	Contains(kind, ns, name string) bool
}

resourceDeletionStatusTracker keeps track of items pending deletion.

func NewResourceDeletionStatusTracker added in v1.16.0

func NewResourceDeletionStatusTracker() ResourceDeletionStatusTracker

NewResourceDeletionStatusTracker returns a new ResourceDeletionStatusTracker.

type SpecChangePredicate added in v1.9.1

type SpecChangePredicate struct {
	predicate.Funcs
}

SpecChangePredicate implements a default update predicate function on Spec change As Velero doesn't enable subresource in CRDs, we cannot use the object's metadata.generation field to check the spec change More details about the generation field refer to https://github.com/kubernetes-sigs/controller-runtime/blob/v0.12.2/pkg/predicate/predicate.go#L156

func (SpecChangePredicate) Update added in v1.9.1

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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