controllerutil

package
v0.8.3 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2024 License: AGPL-3.0 Imports: 49 Imported by: 3

Documentation

Index

Constants

View Source
const (
	// PodContainerFailedTimeout the timeout for container of pod failures, the component phase will be set to Failed/Abnormal after this time.
	PodContainerFailedTimeout = 10 * time.Second

	// PodScheduledFailedTimeout timeout for scheduling failure.
	PodScheduledFailedTimeout = 30 * time.Second
)
View Source
const (
	GenerateNameMaxRetryTimes = 1000000
)

Variables

View Source
var ErrFailedToAddFinalizer = errors.New("failed to add finalizer")

Functions

func BackgroundDeleteObject

func BackgroundDeleteObject(cli client.Client, ctx context.Context, obj client.Object) error

BackgroundDeleteObject deletes the object in the background, usually used in the Reconcile method

func BuildHostPortName added in v0.8.0

func BuildHostPortName(clusterName, compName, containerName, portName string) string

func BuildPodHostDNS

func BuildPodHostDNS(pod *corev1.Pod) string

BuildPodHostDNS builds the host dns of pod. ref: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/

func CheckAndPatchPayload added in v0.8.0

func CheckAndPatchPayload(item *v1alpha1.ConfigurationItemDetail, payloadID string, payload interface{}) (bool, error)

func CheckResourceExists

func CheckResourceExists(
	ctx context.Context,
	cli client.Client,
	key client.ObjectKey,
	obj client.Object) (bool, error)

CheckResourceExists checks whether resource exist or not.

func CheckedRequeueWithError

func CheckedRequeueWithError(err error, logger logr.Logger, msg string, keysAndValues ...interface{}) (reconcile.Result, error)

CheckedRequeueWithError passes the error through to the controller manager, it ignores unknown errors.

func CreateOrUpdatePodVolumes

func CreateOrUpdatePodVolumes(podSpec *corev1.PodSpec, volumes map[string]appsv1alpha1.ComponentTemplateSpec) error

func CreateOrUpdateVolume

func CreateOrUpdateVolume(volumes []corev1.Volume, volumeName string, createFn createVolumeFn, updateFn updateVolumeFn) ([]corev1.Volume, error)

func DeleteOwnedResources added in v0.8.3

func DeleteOwnedResources[T generics.Object, PT generics.PObject[T], L generics.ObjList[T], PL generics.PObjList[T, L]](ctx context.Context,
	cli client.Client,
	owner client.Object,
	resourceMatchLabels client.MatchingLabels,
	_ func(T, PT, L, PL)) error

DeleteOwnedResources deletes the matched resources which are owned by the owner.

func GeKubeRestConfig added in v0.7.4

func GeKubeRestConfig() *rest.Config

func GenShardingCompSpecList added in v0.8.2

func GenShardingCompSpecList(ctx context.Context, cli client.Reader,
	cluster *appsv1alpha1.Cluster, shardingSpec *appsv1alpha1.ShardingSpec) ([]*appsv1alpha1.ClusterComponentSpec, error)

func GetConfigSpecReconcilePhase

GetConfigSpecReconcilePhase gets the configuration phase

func GetContainerByConfigSpec

func GetContainerByConfigSpec(podSpec *corev1.PodSpec, configs []appsv1alpha1.ComponentConfigSpec) *corev1.Container

GetContainerByConfigSpec searches for container using the configmap of config from the pod

e.g.:
ClusterDefinition.configTemplateRef:
	 - Name: "mysql-8.0"
	   VolumeName: "mysql_config"

PodTemplate.containers[*].volumeMounts:
	 - mountPath: /data/config
	   name: mysql_config
	 - mountPath: /data
	   name: data
	 - mountPath: /log
	   name: log

func GetContainerByName

func GetContainerByName(containers []corev1.Container, name string) (int, *corev1.Container)

func GetContainerID

func GetContainerID(pod *corev1.Pod, containerName string) string

GetContainerID gets the containerID from pod by name

func GetContainersByConfigmap

func GetContainersByConfigmap(containers []corev1.Container, volumeName string, cmName string, filters ...containerNameFilter) []string

func GetCoreNum

func GetCoreNum(container corev1.Container) int64

GetCoreNum gets content of Resources.Limits.cpu

func GetIntOrPercentValue

func GetIntOrPercentValue(intOrStr *metautil.IntOrString) (int, bool, error)

func GetLorryContainer added in v0.8.0

func GetLorryContainer(containers []corev1.Container) *corev1.Container

func GetLorryContainerName added in v0.7.1

func GetLorryContainerName(pod *corev1.Pod) (string, error)

GetLorryContainerName gets the lorry container from pod

func GetLorryGRPCPort

func GetLorryGRPCPort(pod *corev1.Pod) (int32, error)

func GetLorryGRPCPortFromContainers added in v0.8.0

func GetLorryGRPCPortFromContainers(containers []corev1.Container) (int32, error)

func GetLorryHTTPPort

func GetLorryHTTPPort(pod *corev1.Pod) (int32, error)

func GetLorryHTTPPortFromContainers added in v0.8.0

func GetLorryHTTPPortFromContainers(containers []corev1.Container) (int32, error)

func GetMemorySize

func GetMemorySize(container corev1.Container) int64

GetMemorySize gets content of Resources.Limits.memory

func GetOriginalOrGeneratedComponentSpecByName added in v0.8.2

func GetOriginalOrGeneratedComponentSpecByName(ctx context.Context, cli client.Reader,
	cluster *appsv1alpha1.Cluster, componentName string) (*appsv1alpha1.ClusterComponentSpec, error)

GetOriginalOrGeneratedComponentSpecByName get an original or generated cluster component spec by componentName.

func GetParentNameAndOrdinal

func GetParentNameAndOrdinal(pod *corev1.Pod) (string, int)

GetParentNameAndOrdinal gets the name of pod's parent StatefulSet and pod's ordinal as extracted from its Name. If the Pod was not created by a StatefulSet, its parent is considered to be empty string, and its ordinal is considered to be -1.

func GetPodCondition

func GetPodCondition(status *corev1.PodStatus, conditionType corev1.PodConditionType) *corev1.PodCondition

func GetPodContainerWithVolumeMount

func GetPodContainerWithVolumeMount(podSpec *corev1.PodSpec, volumeName string) []*corev1.Container

GetPodContainerWithVolumeMount searches for containers mounting the volume

func GetPodListByStatefulSet added in v0.8.0

func GetPodListByStatefulSet(ctx context.Context, cli client.Client, stsObj *appsv1.StatefulSet) ([]corev1.Pod, error)

GetPodListByStatefulSet gets statefulSet pod list.

func GetPodListByStatefulSetWithSelector added in v0.8.0

func GetPodListByStatefulSetWithSelector(ctx context.Context, cli client.Client, stsObj *appsv1.StatefulSet, selector client.MatchingLabels) ([]corev1.Pod, error)

GetPodListByStatefulSetWithSelector gets statefulSet pod list.

func GetPodRevision

func GetPodRevision(pod *corev1.Pod) string

GetPodRevision gets the revision of Pod by inspecting the StatefulSetRevisionLabel. If pod has no revision empty string is returned.

func GetPortByPortName

func GetPortByPortName(containers []corev1.Container, portName string) (int32, error)

GetPortByPortName gets the Port from pod by name

func GetRequestMemorySize

func GetRequestMemorySize(container corev1.Container) int64

GetRequestMemorySize gets content of Resources.Limits.memory

func GetStorageSizeFromPersistentVolume

func GetStorageSizeFromPersistentVolume(pvc corev1.PersistentVolumeClaimTemplate) int64

GetStorageSizeFromPersistentVolume gets content of Resources.Requests.storage

func GetUncachedObjects

func GetUncachedObjects() []client.Object

GetUncachedObjects returns a list of K8s objects, for these object types, and their list types, client.Reader will read directly from the API server instead of the cache, which may not be up-to-date. see sigs.k8s.io/controller-runtime/pkg/client/split.go to understand how client works with this UncachedObjects filter.

func GetVolumeMountByVolume

func GetVolumeMountByVolume(container *corev1.Container, volumeName string) *corev1.VolumeMount

func GetVolumeMountName

func GetVolumeMountName(volumes []corev1.Volume, resourceName string) *corev1.Volume

GetVolumeMountName finds the volume with mount name

func HandleCRDeletion

func HandleCRDeletion(reqCtx RequestCtx,
	r client.Writer,
	cr client.Object,
	finalizer string,
	deletionHandler func() (*ctrl.Result, error)) (*ctrl.Result, error)

HandleCRDeletion handles CR deletion, adds finalizer if found a non-deleting object and removes finalizer during deletion process. Passes optional 'deletionHandler' func for external dependency deletion. Returns Result pointer if required to return out of outer 'Reconcile' reconciliation loop.

func IgnoreIsAlreadyExists

func IgnoreIsAlreadyExists(err error) error

IgnoreIsAlreadyExists returns errors if 'err' is not type of AlreadyExists

func InVolumeSnapshotV1Beta1

func InVolumeSnapshotV1Beta1() bool

func InitHostPortManager added in v0.8.0

func InitHostPortManager(cli client.Client) error

func InjectZeroResourcesLimitsIfEmpty

func InjectZeroResourcesLimitsIfEmpty(c *corev1.Container)

func IsApplyConfigChanged

func IsApplyConfigChanged(configMap *corev1.ConfigMap, item v1alpha1.ConfigurationItemDetail) bool

IsApplyConfigChanged checks if the configuration is changed

func IsAvailable

func IsAvailable(pod *corev1.Pod, minReadySeconds int32) bool

func IsDelayedRequeueError

func IsDelayedRequeueError(err error) bool

func IsMatchConfigVersion

func IsMatchConfigVersion(obj client.Object, labelKey string, version string) bool

func IsMemberOf added in v0.8.0

func IsMemberOf(set *appsv1.StatefulSet, pod *corev1.Pod) bool

IsMemberOf tests if pod is a member of set.

func IsNil

func IsNil(i interface{}) bool

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the specified error is the error type of ErrorTypeNotFound.

func IsPodFailedAndTimedOut added in v0.8.2

func IsPodFailedAndTimedOut(pod *corev1.Pod) (bool, bool, string)

IsPodFailedAndTimedOut checks if the pod is failed and timed out.

func IsRequeueError

func IsRequeueError(err error) bool

IsRequeueError checks if the error is the RequeueError.

func IsRerender

func IsRerender(configMap *corev1.ConfigMap, item v1alpha1.ConfigurationItemDetail) bool

IsRerender checks if the configuration template is changed

func IsTargetError

func IsTargetError(err error, errorType ErrorType) bool

IsTargetError checks if the error is the target error.

func IsVolumeSnapshotEnabled

func IsVolumeSnapshotEnabled(ctx context.Context, cli client.Client, pvName string) (bool, error)

IsVolumeSnapshotEnabled checks if the CSI supports the volume snapshot.

func ListShardingCompNames added in v0.8.2

func ListShardingCompNames(ctx context.Context, cli client.Reader,
	cluster *appsv1alpha1.Cluster, shardingSpec *appsv1alpha1.ShardingSpec) ([]string, error)

func ManagedByKubeBlocksFilterPredicate

func ManagedByKubeBlocksFilterPredicate(object client.Object) bool

ManagedByKubeBlocksFilterPredicate provides filter predicate for objects managed by kubeBlocks.

func MergeAndValidateConfigs

func MergeAndValidateConfigs(configConstraint v1alpha1.ConfigConstraintSpec, baseConfigs map[string]string, cmKey []string, updatedParams []core.ParamPairs) (map[string]string, error)

MergeAndValidateConfigs merges and validates configuration files

func MergeMetadataMapInplace added in v0.8.2

func MergeMetadataMapInplace(originalMap map[string]string, targetMap *map[string]string)

MergeMetadataMapInplace merges two map[string]string, the targetMap will be updated.

func MergeMetadataMaps added in v0.8.2

func MergeMetadataMaps(originalMap map[string]string, targetMaps ...map[string]string) map[string]string

MergeMetadataMaps merges targetMaps into originalMap if item not exist in originalMap and return the merged map.

func NewDelayedRequeueError

func NewDelayedRequeueError(after time.Duration, reason string) error

NewDelayedRequeueError creates a delayed requeue error which only returns in the last step of the DAG.

func NewEncryptor

func NewEncryptor(encryptionKey string) *encryptor

func NewRequeueError

func NewRequeueError(after time.Duration, reason string) error

func ParseParentNameAndOrdinal added in v0.8.0

func ParseParentNameAndOrdinal(s string) (string, int32)

ParseParentNameAndOrdinal gets the name of cluster-component and StatefulSet's ordinal as extracted from its Name. If the StatefulSet's Name was not match a statefulSetRegex, its parent is considered to be empty string, and its ordinal is considered to be -1.

func PodIsControlledByLatestRevision

func PodIsControlledByLatestRevision(pod *corev1.Pod, sts *appsv1.StatefulSet) bool

PodIsControlledByLatestRevision checks if the pod is controlled by latest controller revision.

func PodIsReady

func PodIsReady(pod *corev1.Pod) bool

PodIsReady checks if pod is ready

func PodIsReadyWithLabel

func PodIsReadyWithLabel(pod corev1.Pod) bool

PodIsReadyWithLabel checks if pod is ready for ConsensusSet/ReplicationSet component, it will be available when the pod is ready and labeled with role.

func Reconciled

func Reconciled() (reconcile.Result, error)

Reconciled returns an empty result with nil error to signal a successful reconcile to the controller manager

func RecordCreatedEvent

func RecordCreatedEvent(r record.EventRecorder, cr client.Object)

RecordCreatedEvent records an event when a CR created successfully

func Requeue

func Requeue(logger logr.Logger, msg string, keysAndValues ...interface{}) (reconcile.Result, error)

func RequeueAfter

func RequeueAfter(duration time.Duration, logger logr.Logger, msg string, keysAndValues ...interface{}) (reconcile.Result, error)

func RequeueWithError

func RequeueWithError(err error, logger logr.Logger, msg string, keysAndValues ...interface{}) (reconcile.Result, error)

RequeueWithError requeues when an error occurs

func RequeueWithErrorAndRecordEvent

func RequeueWithErrorAndRecordEvent(obj client.Object, recorder record.EventRecorder, err error, logger logr.Logger) (reconcile.Result, error)

RequeueWithErrorAndRecordEvent requeues when an error occurs. if it is an unknown error, triggers an event

func ResolveContainerDefaultFields added in v0.8.0

func ResolveContainerDefaultFields(container corev1.Container, pcontainer *corev1.Container)

ResolveContainerDefaultFields set default value for some known fields of proto Container @pcontainer.

func ResolvePodSpecDefaultFields added in v0.8.0

func ResolvePodSpecDefaultFields(obj corev1.PodSpec, pobj *corev1.PodSpec)

ResolvePodSpecDefaultFields set default value for some known fields of proto PodSpec @pobj.

func ResultToP

func ResultToP(res reconcile.Result, err error) (*reconcile.Result, error)

ResultToP converts a Result object to a pointer.

func SetControllerReference

func SetControllerReference(owner, object metav1.Object) error

func SetOwnerReference

func SetOwnerReference(owner, object metav1.Object) error

func SetOwnership

func SetOwnership(owner, obj client.Object, scheme *runtime.Scheme, finalizer string, useOwnerReference ...bool) error

SetOwnership provides helper function controllerutil.SetControllerReference/controllerutil.SetOwnerReference and controllerutil.AddFinalizer if not exists.

func ValidateReferenceCR

func ValidateReferenceCR(reqCtx RequestCtx, cli client.Client, obj client.Object,
	labelKey string, recordEvent func(), objLists ...client.ObjectList) (*ctrl.Result, error)

ValidateReferenceCR validates existing referencing CRs, if exists, requeue reconcile after 30 seconds

func WorkloadFilterPredicate

func WorkloadFilterPredicate(object client.Object) bool

WorkloadFilterPredicate provides filter predicate for workload objects, i.e., deployment/statefulset/pod/pvc.

Types

type ByPodName

type ByPodName []corev1.Pod

ByPodName sorts a list of jobs by pod name

func (ByPodName) Len

func (c ByPodName) Len() int

Len returns the length of byPodName for sort.Sort

func (ByPodName) Less

func (c ByPodName) Less(i, j int) bool

Less defines compare method for sort.Sort

func (ByPodName) Swap

func (c ByPodName) Swap(i, j int)

Swap swaps the items for sort.Sort

type DelayedRequeueError

type DelayedRequeueError interface {
	RequeueError
	Delayed()
}

type DescendingOrdinalSts added in v0.8.0

type DescendingOrdinalSts []*appsv1.StatefulSet

DescendingOrdinalSts is a sort.Interface that Sorts a list of StatefulSet based on the ordinals extracted from the statefulSet.

type Error

type Error struct {
	Type    ErrorType
	Message string
}

func NewError

func NewError(errorType ErrorType, message string) *Error

func NewErrorf

func NewErrorf(errorType ErrorType, format string, a ...any) *Error

func NewFatalError

func NewFatalError(message string) *Error

NewFatalError returns a new Error with ErrorTypeFatal

func NewNotFound

func NewNotFound(format string, a ...any) *Error

NewNotFound returns a new Error with ErrorTypeNotFound.

func UnwrapControllerError

func UnwrapControllerError(err error) *Error

UnwrapControllerError unwraps the Controller error from target error.

func (*Error) Error

func (v *Error) Error() string

Error implements the error interface.

type ErrorType

type ErrorType string

ErrorType is explicit error type.

const (
	// ErrorWaitCacheRefresh waits for synchronization of the corresponding object cache in client-go from ApiServer.
	ErrorWaitCacheRefresh ErrorType = "WaitCacheRefresh"
	// ErrorTypeNotFound not found any resource.
	ErrorTypeNotFound ErrorType = "NotFound"

	ErrorTypeRequeue ErrorType = "Requeue" // requeue for reconcile.

	ErrorTypeFatal ErrorType = "Fatal" // fatal error

	// ErrorType for cluster controller
	ErrorTypeBackupFailed  ErrorType = "BackupFailed"
	ErrorTypeRestoreFailed ErrorType = "RestoreFailed"
	ErrorTypeNeedWaiting   ErrorType = "NeedWaiting" // waiting for next reconcile

	// ErrorType for preflight
	ErrorTypePreflightCommon = "PreflightCommon"
	ErrorTypeSkipPreflight   = "SkipPreflight"
)

type PortManager added in v0.8.0

type PortManager struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func GetPortManager added in v0.8.0

func GetPortManager() *PortManager

func NewPortManager added in v0.8.0

func NewPortManager(includes []PortRange, excludes []PortRange, cli client.Client) (*PortManager, error)

NewPortManager creates a new PortManager TODO[ziang] Putting all the port information in one configmap may have performance issues and is not secure enough. There is a risk of accidental deletion leading to the loss of cluster port information.

func (*PortManager) AllocatePort added in v0.8.0

func (pm *PortManager) AllocatePort(key string) (int32, error)

func (*PortManager) NeedAllocate added in v0.8.0

func (pm *PortManager) NeedAllocate(port int32) bool

func (*PortManager) ReleaseByPrefix added in v0.8.0

func (pm *PortManager) ReleaseByPrefix(prefix string) error

func (*PortManager) ReleasePort added in v0.8.0

func (pm *PortManager) ReleasePort(key string) error

func (*PortManager) ReleasePorts added in v0.8.0

func (pm *PortManager) ReleasePorts(keys []string) error

func (*PortManager) UsePort added in v0.8.0

func (pm *PortManager) UsePort(key string, port int32) error

type PortRange added in v0.8.1

type PortRange struct {
	Min int32
	Max int32
}

type RequestCtx

type RequestCtx struct {
	Ctx      context.Context
	Req      ctrl.Request
	Log      logr.Logger
	Recorder record.EventRecorder
}

RequestCtx wrapper for reconcile procedure context parameters

func (*RequestCtx) Event

func (r *RequestCtx) Event(object runtime.Object, eventtype, reason, message string)

Event is wrapper for Recorder.Event, if Recorder is nil, then it's no-op.

func (*RequestCtx) Eventf

func (r *RequestCtx) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{})

Eventf is wrapper for Recorder.Eventf, if Recorder is nil, then it's no-op.

func (*RequestCtx) UpdateCtxValue

func (r *RequestCtx) UpdateCtxValue(key, val any) context.Context

UpdateCtxValue updates Context value, returns parent Context.

func (*RequestCtx) WithValue

func (r *RequestCtx) WithValue(key, val any) context.Context

WithValue returns a copy of parent in which the value associated with key is val.

type RequeueError

type RequeueError interface {
	RequeueAfter() time.Duration
	Reason() string
}

type Result

type Result struct {
	Phase      v1alpha1.ConfigurationPhase `json:"phase"`
	Revision   string                      `json:"revision"`
	Policy     string                      `json:"policy"`
	ExecResult string                      `json:"execResult"`

	SucceedCount  int32 `json:"succeedCount"`
	ExpectedCount int32 `json:"expectedCount"`

	Retry   bool   `json:"retry"`
	Failed  bool   `json:"failed"`
	Message string `json:"message"`
}

type VolumeSnapshotCompatClient

type VolumeSnapshotCompatClient struct {
	client.Client
	roclient.ReadonlyClient
	Ctx context.Context
}

VolumeSnapshotCompatClient client is compatible with VolumeSnapshot v1 and v1beta1

func (*VolumeSnapshotCompatClient) CheckResourceExists

func (c *VolumeSnapshotCompatClient) CheckResourceExists(key client.ObjectKey, obj client.Object) (bool, error)

CheckResourceExists checks whether resource exist or not.

func (*VolumeSnapshotCompatClient) Create

func (*VolumeSnapshotCompatClient) Delete

func (c *VolumeSnapshotCompatClient) Delete(snapshot client.Object) error

func (*VolumeSnapshotCompatClient) Get

func (*VolumeSnapshotCompatClient) List

func (*VolumeSnapshotCompatClient) Patch

func (c *VolumeSnapshotCompatClient) Patch(snapshot client.Object, deepCopy client.Object, opts ...client.PatchOption) error

Jump to

Keyboard shortcuts

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