kube

package
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2023 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package kube contains utility types and methods for managing kubernetes state.

Index

Constants

View Source
const (
	ControllerLabel = "app.kubernetes.io/created-by"
	InstanceLabel   = "app.kubernetes.io/instance"
	NameLabel       = "app.kubernetes.io/name"
	VersionLabel    = "app.kubernetes.io/version"
	ComponentLabel  = "app.kubernetes.io/component"

	// RevisionLabel denotes the resource's revision, typically a hex-encoded hash. Used to detect resource changes for updates.
	RevisionLabel = "app.kubernetes.io/revision"
)

Recommended labels. See: https://kubernetes.io/docs/concepts/overview/working-with-objects/common-labels/

View Source
const (
	EventWarning = "Warning"
	EventNormal  = "Normal"
)

The two accepted event types for recording events.

View Source
const (
	ControllerOwnerField = ".metadata.controller"
)

Fields.

View Source
const (
	// OrdinalAnnotation denotes the resource's ordinal position.
	// This annotation key must never be changed, or it will be a backward breaking change for operator upgrades.
	OrdinalAnnotation = "app.kubernetes.io/ordinal"
)

Variables

This section is empty.

Functions

func ApplyStrategicMergePatch added in v0.11.0

func ApplyStrategicMergePatch[T any](target, patch T) error

ApplyStrategicMergePatch applies a strategic merge patch to a target object. Inspired by: https://github.com/kubernetes/apiserver/blob/45f55ded302a02ed2023e8b45bd241cf7d81169e/pkg/endpoints/handlers/patch.go

func AvailablePods

func AvailablePods(pods []*corev1.Pod, minReady time.Duration, now time.Time) []*corev1.Pod

AvailablePods returns pods which are available as defined in IsPodAvailable.

func ComputeRollout

func ComputeRollout(maxUnavail *intstr.IntOrString, desired, ready int) int

ComputeRollout returns the number of replicas allowed to be updated to keep within a max unavailable threshold. Example: If max unavailable is 5 with a desired replica count of 10, that means rollout cannot happen until 6 or more replicas are ready. The replicas must stay within the minimum threshold of 5 ready replicas.

If "maxUnavail" is nil, defaults to 25% and string value must be a percentage. "desired" must be >= 1 and "ready" must be >= 0 or else this function panics.

func IgnoreAlreadyExists

func IgnoreAlreadyExists(err error) error

IgnoreAlreadyExists returns nil if err reason is "already exists".

func IgnoreNotFound

func IgnoreNotFound(err error) error

IgnoreNotFound returns nil if err reason is "not found".

func IndexOwner

func IndexOwner[T client.Object](kind string) client.IndexerFunc

IndexOwner returns field values for indexing "child" resources that are "owned" by a controller (typically the CRD such as CosmosFullNode). Indexing is required for client.Client methods such as listing resources.

It returns a field to index only if all are true: 1) resource is part of cosmosv1.GroupVersion. 2) resource is owned by a controller equal to "kind".

func IsAlreadyExists

func IsAlreadyExists(err error) bool

IsAlreadyExists determines if the error indicates that a specified resource already exists. It supports wrapped errors and returns false when the error is nil.

func IsJobFinished

func IsJobFinished(job *batchv1.Job) bool

IsJobFinished checks whether the given Job has finished execution. It does not discriminate between successful and failed terminations.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the err reason is "not found".

func IsPodAvailable

func IsPodAvailable(pod *corev1.Pod, minReady time.Duration, now time.Time) bool

IsPodAvailable returns true if a pod is available; false otherwise. Precondition for an available pod is that it must be ready. Additionally, there are two cases when a pod can be considered available: 1. minReady == 0, or 2. LastTransitionTime (is set) + minReadySeconds < current time

Much of this code was vendored from the kubernetes codebase.

func MustToInt

func MustToInt(s string) int64

MustToInt converts s to int64 or panics on failure.

func ParseImageVersion

func ParseImageVersion(imageRef string) string

ParseImageVersion parses the version (aka tag) out of imageRef. As an example, "busybox:stable" would return "stable". If no tag, defaults to "latest".

func RecentVolumeSnapshot added in v0.9.0

func RecentVolumeSnapshot(ctx context.Context, lister Lister, namespace string, selector map[string]string) (*snapshotv1.VolumeSnapshot, error)

RecentVolumeSnapshot finds the most recent, ready to use VolumeSnapshot. This function may not work well given very large lists and therefore assumes a reasonable number of VolumeSnapshots. If you must search among many VolumeSnapshots, consider refactoring to use Limit and Continue features of listing.

func ToIntegerValue

func ToIntegerValue[T constraints.Signed](n T) string

ToIntegerValue converts n to a base 10 integer string.

func ToLabelKey

func ToLabelKey(val string) string

ToLabelKey normalizes val per kubernetes label constraints to a max of 63 characters. See: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set.

func ToName

func ToName(val string) string

ToName normalizes val per kubernetes name constraints to a max of 253 characters. See: https://unofficial-kubernetes.readthedocs.io/en/latest/concepts/overview/working-with-objects/names/

func VolumeSnapshotIsReady

func VolumeSnapshotIsReady(status *snapshotv1.VolumeSnapshotStatus) bool

VolumeSnapshotIsReady returns true if the snapshot is ready to use.

Types

type Diff

type Diff[T Resource] struct {
	// contains filtered or unexported fields
}

Diff computes steps needed to bring a current state equal to a new state.

func NewDiff

func NewDiff[T Resource](revisionLabelKey string, current, want []T) *Diff[T]

NewDiff creates a valid Diff where ordinal positioning is not required. See NewOrdinalDiff for further details, ignoring requirements for ordinal annotations.

func NewOrdinalDiff

func NewOrdinalDiff[T Resource](ordinalAnnotationKey string, revisionLabelKey string, current, want []T) *Diff[T]

NewOrdinalDiff creates a valid Diff where ordinal positioning is required. It computes differences between the "current" state needed to reconcile to the "want" state.

Diff expects resources with annotations denoting ordinal positioning similar to a StatefulSet. E.g. pod-0, pod-1, pod-2. The "ordinalAnnotationKey" allows Diff to sort resources deterministically. Therefore, resources must have ordinalAnnotationKey set to an integer value such as "0", "1", "2" otherwise this function panics.

Diff also expects "revisionLabelKey" which is a label with a revision that is expected to change if the resource has changed. A short hash is a common value for this label. We cannot simply diff the annotations and/or labels in case a 3rd party injects annotations or labels. For example, GKE injects other annotations beyond our control.

For Updates to work properly, Diff uses ObjectHasChanges. Concretely, to detect updates the recommended path is changing annotations or labels.

There are several O(N) or O(2N) operations where N = number of resources. However, we expect N to be small.

func (*Diff[T]) Creates

func (diff *Diff[T]) Creates() []T

Creates returns a list of resources that should be created from scratch.

func (*Diff[T]) Deletes

func (diff *Diff[T]) Deletes() []T

Deletes returns a list of resources that should be deleted.

func (*Diff[T]) Updates

func (diff *Diff[T]) Updates() []T

Updates returns a list of resources that should be updated.

type EventReporter added in v0.9.2

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

EventReporter both logs and records events.

func NewEventReporter added in v0.9.2

func NewEventReporter(logger Logger, recorder record.EventRecorder, resource runtime.Object) EventReporter

func (EventReporter) Error added in v0.9.2

func (r EventReporter) Error(err error, msg string, keysAndValues ...interface{})

Error logs as an error log entry.

func (EventReporter) Info added in v0.9.2

func (r EventReporter) Info(msg string, keysAndValues ...interface{})

Info logs as an info log entry.

func (EventReporter) RecordError added in v0.9.2

func (r EventReporter) RecordError(reason string, err error)

RecordError records a warning event.

func (EventReporter) RecordInfo added in v0.9.2

func (r EventReporter) RecordInfo(reason, msg string)

RecordInfo records a normal event.

type Lister added in v0.9.0

type Lister interface {
	List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error
}

Lister can list resources, subset of client.Client.

type Logger added in v0.9.2

type Logger interface {
	Info(msg string, keysAndValues ...interface{})
	Error(err error, msg string, keysAndValues ...interface{})
}

Logger is a structured logger

type ReconcileError

type ReconcileError interface {
	error
	// IsTransient returns true if the error is temporary.
	IsTransient() bool
}

ReconcileError is a controller-specific error.

func TransientError

func TransientError(err error) ReconcileError

TransientError can be recovered or retried.

func UnrecoverableError

func UnrecoverableError(err error) ReconcileError

UnrecoverableError cannot be recovered and should not be retried.

type ReconcileErrors

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

ReconcileErrors is a collection of ReconcileError

func (*ReconcileErrors) Any

func (errs *ReconcileErrors) Any() bool

Any returns true if any errors were collected.

func (*ReconcileErrors) Append

func (errs *ReconcileErrors) Append(err ReconcileError)

Append adds the ReconcileError.

func (*ReconcileErrors) Error

func (errs *ReconcileErrors) Error() string

func (*ReconcileErrors) IsTransient

func (errs *ReconcileErrors) IsTransient() bool

IsTransient returns true if all errors are transient. False if at least one is not transient.

type Reporter added in v0.9.2

type Reporter interface {
	Logger
	RecordInfo(reason, msg string)
	RecordError(reason string, err error)
}

Reporter logs and reports various events.

type Resource

type Resource = client.Object

Resource is a kubernetes resource.

Jump to

Keyboard shortcuts

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