declarative

package
v0.15.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2024 License: Apache-2.0 Imports: 42 Imported by: 23

Documentation

Overview

application.go manages an Application[1]

[1] https://github.com/kubernetes-sigs/application

The declarative package contains tools and a controller compatible with http://sigs.k8s.io/controller-runtime to manage a Kubernetes deployment based off of a instance of a CustomResource in the cluster.

Copyright 2019 The Kubernetes Authors.

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 (
	ReconcileCount   = "reconcile_count"
	ReconcileFailure = "reconcile_failure_count"

	ManagedObjectsRecord = "managed_objects_record"
)
View Source
const (
	Declarative = "declarative_reconciler"
)

Variables

View Source
var Options struct {
	// Begin options are applied before evaluating controller specific options
	Begin []ReconcilerOption
	// End options are applied after evaluating controller specific options
	End []ReconcilerOption
}

Options are a set of reconcilerOptions applied to all controllers

Functions

func DefaultObjectOrder

func DefaultObjectOrder(ctx context.Context) func(o *manifest.Object) int

func ExtractApplication

func ExtractApplication(objects *manifest.Objects) (*manifest.Object, error)

ExtractApplication extracts a single app.k8s.io/Application from objects.

- 0 Application: (nil, nil) - 1 Application: (*app, nil) - >1 Application: (nil, err)

func GetMetricsDuration

func GetMetricsDuration() int

GetMetricsDuration function returns current metricsDuration of package-scoped internal variable of type *ObjectTracker. It is safe to call this function from multiple go routines with another go routines calling SetMetricsDuration function.

func GetObjectFromCluster

func GetObjectFromCluster(obj *manifest.Object, r *Reconciler) (*unstructured.Unstructured, error)

GetObjectFromCluster gets the current state of the object from the cluster.

deprecated: use LiveObjectReader instead when computing status

func SetMetricsDuration

func SetMetricsDuration(metricsDuration int)

SetMetricsDuration function sets metricsDuration of package scoped internal variable of type *ObjectTracker. It is safe to call this function from multiple go routines with another go routines calling GetMetricsDuration function.

func WatchAll

func WatchAll(config *rest.Config, ctrl controller.Controller, reconciler hookableReconciler, labelMaker LabelMaker) error

WatchAll creates a Watch on ctrl for all objects reconciled by recnl. Deprecated: prefer WatchChildren (and consider setting ScopeWatchesToNamespace)

func WatchChildren

func WatchChildren(options WatchChildrenOptions) error

WatchChildren sets up watching of the objects applied by a controller.

Types

type AfterApply

type AfterApply interface {
	AfterApply(ctx context.Context, op *ApplyOperation) error
}

AfterApply is implemented by hooks that want to be called after every apply operation

type AfterUpdateStatus

type AfterUpdateStatus interface {
	AfterUpdateStatus(ctx context.Context, op *UpdateStatusOperation) error
}

AfterUpdateStatus is implemented by hooks that want to be called after the update-status phase

type ApplyOperation

type ApplyOperation struct {
	// Subject is the object we are reconciling
	Subject DeclarativeObject

	// Objects is the set of objects we are applying
	Objects *manifest.Objects

	// ApplierOptions is the set of options passed to the applier
	ApplierOptions *applier.ApplierOptions
}

ApplyOperation contains the details of an Apply operation

type BeforeApply

type BeforeApply interface {
	BeforeApply(ctx context.Context, op *ApplyOperation) error
}

BeforeApply is implemented by hooks that want to be called before every apply operation

type BeforeUpdateStatus

type BeforeUpdateStatus interface {
	BeforeUpdateStatus(ctx context.Context, op *UpdateStatusOperation) error
}

BeforeUpdateStatus is implemented by hooks that want to be called before the update-status phase

type BuildStatus

type BuildStatus interface {
	// BuildStatus computes the new status after a reconcile operation.
	BuildStatus(ctx context.Context, statusInfo *StatusInfo) error
}

BuildStatus computes the new status after a reconcile operation.

type DeclarativeObject

type DeclarativeObject interface {
	runtime.Object
	metav1.Object
}

func SourceAsOwner

SourceAsOwner is a OwnerSelector that selects the source DeclarativeObject as the owner

type DynamicWatch

type DynamicWatch interface {
	// Add registers a watch for changes to 'trigger' filtered by 'options' to raise an event on 'target'.
	// If namespace is specified, the watch will be restricted to that namespace.
	Add(trigger schema.GroupVersionKind, options metav1.ListOptions, namespace string, target metav1.ObjectMeta) error
}

type ErrorResult

type ErrorResult struct {
	Result reconcile.Result
	Err    error
}

func (*ErrorResult) Error

func (e *ErrorResult) Error() string

type Hook

type Hook interface {
}

Hook is the base interface implemented by a hook

type ImageFunc

type ImageFunc func(registry, image string) string

type KnownErrorCode

type KnownErrorCode string
const (
	KnownErrorApplyFailed        KnownErrorCode = "FailedToApply"
	KnownErrorVersionCheckFailed KnownErrorCode = "VersionCheckFailed"
)

type LabelMaker

type LabelMaker = func(context.Context, DeclarativeObject) map[string]string

LabelMaker returns a fixed set of labels for a given DeclarativeObject

func SourceLabel

func SourceLabel(scheme *runtime.Scheme) LabelMaker

SourceLabel returns a fixed label based on the type and name of the DeclarativeObject

type LiveObjectReader

LiveObjectReader exposes the state of objects on the cluster after the apply operation. Currently this is done by querying the cluster, but we will move this to record the state of objects after applying them.

type ManifestController

type ManifestController interface {
	// ResolveManifest returns a raw manifest as a map[string]string for a given CR object
	ResolveManifest(ctx context.Context, object runtime.Object) (map[string]string, error)
}

type ManifestLoaderFunc

type ManifestLoaderFunc func() (ManifestController, error)
var DefaultManifestLoader ManifestLoaderFunc

DefaultManifestLoader is the manifest loader we use when a manifest loader is not otherwise configured

type ManifestOperation

type ManifestOperation = func(context.Context, DeclarativeObject, string) (string, error)

ManifestOperation is an operation that transforms raw string manifests before applying it

type ObjectTracker

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

Type ObjectTracker manages metricsDuration of k8s objects managed by controller(s)

func NewObjectTracker

func NewObjectTracker() *ObjectTracker

NewObjectTracker returns new instance of *ObjectTracker

func (*ObjectTracker) GetMetricsDuration

func (ot *ObjectTracker) GetMetricsDuration() int

GetMetricsDuration method returns current metricsDuration. It is safe to call this function from multiple go routines with another go routines calling SetMetricsDuration method.

func (*ObjectTracker) SetMetricsDuration

func (ot *ObjectTracker) SetMetricsDuration(metricsDuration int)

SetMetricsDuration method sets metricsDuration. It is safe to call this function from multiple go routines with another go routines calling GetMetricsDuration method..

type ObjectTransform

type ObjectTransform = func(context.Context, DeclarativeObject, *manifest.Objects) error

ObjectTransform is an operation that transforms the manifest objects before applying it

func AddAnnotations

func AddAnnotations(annotations map[string]string) ObjectTransform

AddAnnotations returns an ObjectTransform that adds annotations to all the objects

func AddLabels

func AddLabels(labels map[string]string) ObjectTransform

AddLabels returns an ObjectTransform that adds labels to all the objects

func ImageRegistryTransform

func ImageRegistryTransform(registry, imagePullSecret string) ObjectTransform

ImageRegistryTransform modifies all Pods to use registry for the image source and adds the imagePullSecret

func PrivateRegistryTransform

func PrivateRegistryTransform(registry, imagePullSecret string, imageFunc ImageFunc) ObjectTransform

PrivateRegistryTransform modifies all Pods to use registry for the image source and adds the imagePullSecret

type OwnerSelector

OwnerSelector selects a runtime.Object to be the owner of a given manifest.Object

type Preflight

type Preflight interface {
	// Preflight validates if the current state of the world is ready for reconciling.
	// Returning a non-nil error on this object will prevent Reconcile from running.
	// The caller is encouraged to surface the error status on the DeclarativeObject.
	Preflight(context.Context, DeclarativeObject) error
}

type PruneWhiteLister added in v0.13.0

type PruneWhiteLister interface {
	PruneWhiteList() []string
}

PruneWhiteLister is a trait for addon CRDs that determines which kind of resources should be pruned. It's useful when CR in installed by Addon and want to prune them automatically. The format of array item should be exactly like <group>/<version>/<kind> (core group using 'core' indeed). For example: ["core/v1/ConfigMap", "batch/v1/Job"]. Notice: kubeadm has a built-in prune white list, and it will be ignored if this method is implemented.

type Pruner added in v0.13.0

type Pruner interface {
	Prune() bool
}

Pruner is a trait for addon CRDs that determines whether pruning behavior should be enabled for the current CR. To enable this feature, it's necessary to enable WithApplyPrune. If WithApplyPrune is enabled but Pruner is not implemented, Prune behavior is assumed by default.

type Reconciled

type Reconciled interface {
	// Reconciled is triggered when Reconciliation has occured.
	// The caller is encouraged to determine and surface the health of the reconcilation
	// on the DeclarativeObject.
	//
	// Deprecated: Prefer the BuildStatus method
	Reconciled(ctx context.Context, subject DeclarativeObject, manifest *manifest.Objects, err error) error
}

type Reconciler

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

func (*Reconciler) AddHook

func (r *Reconciler) AddHook(hook Hook)

AddHook provides a Hook that will be notified of significant events

func (*Reconciler) BuildDeploymentObjects

func (r *Reconciler) BuildDeploymentObjects(ctx context.Context, name types.NamespacedName, instance DeclarativeObject) (*manifest.Objects, error)

BuildDeploymentObjects performs all manifest operations to build a final set of objects for deployment

func (*Reconciler) BuildDeploymentObjectsWithFs

func (r *Reconciler) BuildDeploymentObjectsWithFs(ctx context.Context, name types.NamespacedName, instance DeclarativeObject, fs filesys.FileSystem) (*manifest.Objects, error)

BuildDeploymentObjectsWithFs is the implementation of BuildDeploymentObjects, supporting saving to a filesystem for kustomize If fs is provided, the transformed manifests will be saved to that filesystem

func (*Reconciler) CollectMetrics

func (r *Reconciler) CollectMetrics() bool

CollectMetrics determines whether metrics of declarative reconciler is enabled

func (*Reconciler) Init

func (r *Reconciler) Init(mgr manager.Manager, prototype DeclarativeObject, opts ...ReconcilerOption) error

func (*Reconciler) IsKustomizeOptionUsed

func (r *Reconciler) IsKustomizeOptionUsed() bool

IsKustomizeOptionUsed checks if the option for Kustomize build is used for creating manifests

func (*Reconciler) Reconcile

func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error)

+rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete

func (*Reconciler) SetSink deprecated

func (r *Reconciler) SetSink(sink Sink)

SetSink provides a Sink that will be notified for all deployments

Deprecated: prefer WithHook

type ReconcilerOption

type ReconcilerOption func(params reconcilerParams) reconcilerParams

ReconcilerOption implements the options pattern for reconcilers

func WithApplier added in v0.13.0

func WithApplier(applier applier.Applier) ReconcilerOption

WithApplier allows us to select a different applier strategy

func WithApplyKustomize

func WithApplyKustomize() ReconcilerOption

WithApplyKustomize run kustomize build to create final manifest

func WithApplyPrune

func WithApplyPrune() ReconcilerOption

WithApplyPrune turns on the --prune behavior of kubectl apply. This behavior deletes any objects that exist in the API server that are not deployed by the current version of the manifest which match a label specific to the addon instance.

This option requires WithLabels to be used

func WithApplyValidation

func WithApplyValidation() ReconcilerOption

WithApplyValidation enables validation with kubectl apply

func WithCascadingStrategy

func WithCascadingStrategy(cs metav1.DeletionPropagation) ReconcilerOption

WithCascadingStrategy allows us to select a different CascadingStrategy, which ultimately sets the PropagationPolicy

func WithHook

func WithHook(hook Hook) ReconcilerOption

WithHook allows for us to intercept and inject behaviours at various points in the lifecycle

func WithLabels

func WithLabels(labelMaker LabelMaker) ReconcilerOption

WithLabels sets a fixed set of labels configured provided by a LabelMaker to all deployment objecs for a given DeclarativeObject

func WithManagedApplication

func WithManagedApplication(labelMaker LabelMaker) ReconcilerOption

WithManagedApplication is a transform that will modify the Application object in the deployment to match the configuration of the rest of the deployment.

func WithManifestController

func WithManifestController(mc ManifestController) ReconcilerOption

WithManifestController overrides the default source for loading manifests

func WithObjectTransform

func WithObjectTransform(operations ...ObjectTransform) ReconcilerOption

WithObjectTransform adds the specified ObjectTransforms to the chain of manifest changes

func WithOwner

func WithOwner(ownerFn OwnerSelector) ReconcilerOption

WithOwner sets an owner ref on each deployed object by the OwnerSelector

func WithPreserveNamespace

func WithPreserveNamespace() ReconcilerOption

WithPreserveNamespace preserves the namespaces defined in the deployment manifest instead of matching the namespace of the DeclarativeObject

func WithRawManifestOperation

func WithRawManifestOperation(operations ...ManifestOperation) ReconcilerOption

WithRawManifestOperation adds the specific ManifestOperations to the chain of manifest changes

func WithReconcileMetrics

func WithReconcileMetrics(metricsDuration int, ot *ObjectTracker) ReconcilerOption

WithReconcileMetrics enables metrics of declarative reconciler. If metricsDuration is positive, metrics will be removed from Prometheus registry when metricsDuration times reconciliation has happened since k8s object related to that metrics is deleted and that k8s object hasn't been handled in those reconciliations. If metricsDuration is less than or equal to 0, metrics won't be removed.

Argument ot specifies which ObjectTracker manages metrics of k8s objects. This enables specifying different metricsDuration for each set of k8s objects managed by different controllers, but all metrics are registered against manager's Prometheus registry. If ot is nil, package-scoped internal variable is used.

If WithReconcileMetrics is called multiple times with same ot argument, largest metricsDuration is set against that ot.

func WithStatus

func WithStatus(status Status) ReconcilerOption

WithStatus provides a Status interface that will be used during Reconcile

type Sink

type Sink interface {
	// Notify tells the Sink that all objs have been created
	Notify(ctx context.Context, dest DeclarativeObject, objs *manifest.Objects) error
}

type Status

type Status interface {
	Reconciled
	Preflight
	VersionCheck

	// BuildStatus computes the new status for the object after a reconcile operation,
	// and writes it into statusInfo.Subject.
	// This function is should broadly map any reconciliation errors into the status,
	// and if no errors were reported should check that the applied objects are healthy and ready.
	// If this function returns a nil error, changes to the `status` of the object
	// will then be written back to the kube-apiserver.
	// If this function returns an error, the reconciliation function will return
	// an error without updating the status to the apiserver, the interpretation is that
	// we were unable to compute a new status.
	BuildStatus(ctx context.Context, statusInfo *StatusInfo) error
}

Status provides health and readiness information for a given DeclarativeObject

type StatusBuilder

type StatusBuilder struct {
	// ReconciledImpl is called after reconciliation
	//
	// Deprecated: Prefer the BuildStatus method
	ReconciledImpl Reconciled

	PreflightImpl    Preflight
	VersionCheckImpl VersionCheck

	// BuildStatus computes the status after a reconcile operation
	BuildStatusImpl BuildStatus
}

StatusBuilder provides a pluggable implementation of Status

func (*StatusBuilder) BuildStatus

func (s *StatusBuilder) BuildStatus(ctx context.Context, statusInfo *StatusInfo) error

func (*StatusBuilder) Preflight

func (s *StatusBuilder) Preflight(ctx context.Context, src DeclarativeObject) error

func (*StatusBuilder) Reconciled

func (s *StatusBuilder) Reconciled(ctx context.Context, src DeclarativeObject, objs *manifest.Objects, err error) error

func (*StatusBuilder) VersionCheck

func (s *StatusBuilder) VersionCheck(ctx context.Context, src DeclarativeObject, objs *manifest.Objects) (bool, error)

type StatusInfo

type StatusInfo struct {
	Subject DeclarativeObject

	// Manifest contains the set of desired-state for objects that we applied (or tried to).
	Manifest *manifest.Objects

	LiveObjects LiveObjectReader
	KnownError  KnownErrorCode
	Err         error
}

type UpdateStatusOperation

type UpdateStatusOperation struct {
	// Subject is the object we are reconciling
	Subject DeclarativeObject
}

UpdateStatusOperation contains the details of an Apply operation

type VersionCheck

type VersionCheck interface {
	// VersionCheck checks if the version of the operator is greater than or equal to the
	// version requested by objects in the manifest, if it isn't it updates the status and
	// events and stops reconciling
	VersionCheck(context.Context, DeclarativeObject, *manifest.Objects) (bool, error)
}

type WatchChildrenOptions

type WatchChildrenOptions struct {
	// Manager is used as a factory for the default RESTConfig and the RESTMapper.
	Manager ctrl.Manager

	// RESTConfig is the configuration for connecting to the cluster.
	RESTConfig *rest.Config

	// LabelMaker is used to build the labels we should watch on.
	LabelMaker LabelMaker

	// Controller contains the controller itself
	Controller controller.Controller

	// Reconciler lets us hook into the post-apply lifecycle event.
	Reconciler hookableReconciler

	// ScopeWatchesToNamespace controls whether watches are per-namespace.
	// This allows for more narrowly scoped RBAC permissions, at the cost of more watches.
	ScopeWatchesToNamespace bool
}

WatchChildrenOptions configures how we want to watch children.

Directories

Path Synopsis
pkg

Jump to

Keyboard shortcuts

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