reconciler

package
v0.28.6 Latest Latest
Warning

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

Go to latest
Published: May 22, 2022 License: Apache-2.0 Imports: 36 Imported by: 0

README

ResourceReconciler

ResourceReconciler reconciles a single Kubernetes object against the API Server.

It creates the object if it doesn't exist or removes it in case its desired state is absent.

It uses the ObjectMatcher library to be able to tell if an already existing object needs to be updated or not.

It depends on logr logger and the controller-runtime client that is available in a typical kubebuilder or operator-sdk project.

Example:

package main

import (
	corev1 "k8s.io/api/core/v1"
	github.com/go-logr/logr
	"github.com/banzaicloud/operator-tools/pkg/reconciler"
	runtimeClient "sigs.k8s.io/controller-runtime/pkg/client"
)

func example(client runtimeClient.Client, logger logr.Logger) {
  resourceReconciler := reconciler.NewReconcilerWith(client, reconciler.WithLog(logger))
  
  serviceObject := &corev1.Service{
    Spec: corev1.ServiceSpec{
      ...
    },
  }
  
  result, err := resourceReconciler.ReconcileResource(serviceObject, reconciler.StatePresent)
}

Documentation

Index

Constants

View Source
const (
	ReconciledObjectStateAbsent  reconciledObjectState = "Absent"
	ReconciledObjectStatePresent reconciledObjectState = "Present"
	ReconciledObjectStatePurged  reconciledObjectState = "Purged"
)
View Source
const (
	DefaultRecreateRequeueDelay int32              = 10
	StateCreated                StaticDesiredState = "Created"
	StateAbsent                 StaticDesiredState = "Absent"
	StatePresent                StaticDesiredState = "Present"
)

Variables

View Source
var DefaultBackoff = wait.Backoff{
	Duration: time.Second * 5,
	Factor:   1,
	Jitter:   0,
	Steps:    12,
}
View Source
var DefaultRecreateEnabledGroupKinds = []schema.GroupKind{
	{Group: "", Kind: "Service"},
	{Group: "apps", Kind: "StatefulSet"},
	{Group: "apps", Kind: "DaemonSet"},
	{Group: "apps", Kind: "Deployment"},
}

Functions

func EnqueueByOwnerAnnotationMapper

func EnqueueByOwnerAnnotationMapper() handler.MapFunc

func IgnoreManagedFields

func IgnoreManagedFields() patch.CalculateOption

func IstioSidecarInjectorExistsCheck

func IstioSidecarInjectorExistsCheck(c client.Client, namespace string) wait.CustomResourceConditionCheck

func KeepLabelsAndAnnotationsModifer

func KeepLabelsAndAnnotationsModifer(current, desired runtime.Object) error

func KeepServiceAccountTokenReferences

func KeepServiceAccountTokenReferences(current, desired runtime.Object) error

func MatchImmutableErrorMessages

func MatchImmutableErrorMessages(errorMessage string) bool

func MatchImmutableNoStatefulSet

func MatchImmutableNoStatefulSet(errorMessage string) bool

func ServiceIPModifier

func ServiceIPModifier(current, desired runtime.Object) error

Types

type CombinedResult

type CombinedResult struct {
	Result reconcile.Result
	Err    error
}

Collects results and errors of all subcomponents instead of failing and bailing out immediately

func (*CombinedResult) Combine

func (c *CombinedResult) Combine(sub *reconcile.Result, err error)

func (*CombinedResult) CombineErr

func (c *CombinedResult) CombineErr(err error)

type ComponentLifecycle

type ComponentLifecycle interface {
	OnFinished(object runtime.Object) error
}

type ComponentReconciler

type ComponentReconciler interface {
	Reconcile(object runtime.Object) (*reconcile.Result, error)
	RegisterWatches(*builder.Builder)
}

type ComponentReconcilers

type ComponentReconcilers []ComponentReconciler

ComponentReconcilers is a list of component reconcilers that support getting components in Install and Uninstall order.

func (ComponentReconcilers) Get

type ComponentWithStatus

type ComponentWithStatus interface {
	Update(object runtime.Object, status types.ReconcileStatus, msg string) error
	IsSkipped(object runtime.Object) bool
	IsEnabled(object runtime.Object) bool
}

type ConditionChecker

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

func NewConditionChecker

func NewConditionChecker(client client.Client, scheme *runtime.Scheme, log logr.Logger) *ConditionChecker

func (*ConditionChecker) CheckResourceConditions

func (c *ConditionChecker) CheckResourceConditions(conditions []ResourceCondition, backoff *wait.Backoff) error

type ConditionType

type ConditionType string

type DefaultReconciledComponent

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

func (*DefaultReconciledComponent) PurgeTypes

func (*DefaultReconciledComponent) RegisterWatches

func (d *DefaultReconciledComponent) RegisterWatches(b *builder.Builder)

func (*DefaultReconciledComponent) ResourceBuilders

func (d *DefaultReconciledComponent) ResourceBuilders(parent ResourceOwner, object interface{}) []ResourceBuilder

type DesiredState

type DesiredState interface {
	BeforeUpdate(current, desired runtime.Object) error
	BeforeCreate(desired runtime.Object) error
	BeforeDelete(current runtime.Object) error
}

type DesiredStateHook

type DesiredStateHook func(object runtime.Object) error

func (DesiredStateHook) BeforeCreate

func (d DesiredStateHook) BeforeCreate(desired runtime.Object) error

func (DesiredStateHook) BeforeDelete

func (d DesiredStateHook) BeforeDelete(current runtime.Object) error

func (DesiredStateHook) BeforeUpdate

func (d DesiredStateHook) BeforeUpdate(current, desired runtime.Object) error

type DesiredStateShouldCreate

type DesiredStateShouldCreate interface {
	ShouldCreate(desired runtime.Object) (bool, error)
}

type DesiredStateShouldDelete

type DesiredStateShouldDelete interface {
	ShouldDelete(desired runtime.Object) (bool, error)
}

type DesiredStateShouldUpdate

type DesiredStateShouldUpdate interface {
	ShouldUpdate(current, desired runtime.Object) (bool, error)
}

type DesiredStateWithCreateOptions

type DesiredStateWithCreateOptions interface {
	GetCreateOptions() []client.CreateOption
}

type DesiredStateWithDeleteOptions

type DesiredStateWithDeleteOptions interface {
	GetDeleteOptions() []client.DeleteOption
}

type DesiredStateWithGetter

type DesiredStateWithGetter interface {
	GetDesiredState() DesiredState
}

type DesiredStateWithStaticState

type DesiredStateWithStaticState interface {
	DesiredState() StaticDesiredState
}

type DesiredStateWithUpdateOptions

type DesiredStateWithUpdateOptions interface {
	GetUpdateOptions() []client.UpdateOption
}

type Dispatcher

type Dispatcher struct {
	client.Client
	Log                  logr.Logger
	ResourceGetter       func(req ctrl.Request) (runtime.Object, error)
	ResourceFilter       func(runtime.Object) (bool, error)
	CompletionHandler    func(runtime.Object, ctrl.Result, error) (ctrl.Result, error)
	ComponentReconcilers ComponentReconcilers
	// ForceResourceOrder can be used to force a given resource ordering regardless of an object being deleted with
	// finalizers.
	ForceResourceOrder utils.ResourceOrder
}

Dispatcher orchestrates reconciliation of multiple ComponentReconciler objects focusing on handing off reconciled object to all of its components and calculating an aggregated result to return. It requires a ResourceGetter callback and optionally can leverage a ResourceFilter and a CompletionHandler

func (*Dispatcher) Handle

func (r *Dispatcher) Handle(object runtime.Object) (ctrl.Result, error)

Handle receives a single object and dispatches it to all the components Components need to understand how to interpret the object

func (*Dispatcher) Reconcile

func (r *Dispatcher) Reconcile(_ context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile implements reconcile.Reconciler in a generic way from the controller-runtime library

func (*Dispatcher) RegisterWatches

func (r *Dispatcher) RegisterWatches(b *builder.Builder) *builder.Builder

RegisterWatches dispatches the watch registration builder to all its components

func (*Dispatcher) SetupAdditionalWatches

func (r *Dispatcher) SetupAdditionalWatches(c controller.Controller) error

SetupAdditionalWatches dispatches the controller for watch registration to all its components

type DynamicDesiredState

type DynamicDesiredState struct {
	DesiredState     DesiredState
	BeforeCreateFunc func(desired runtime.Object) error
	BeforeUpdateFunc func(current, desired runtime.Object) error
	BeforeDeleteFunc func(current runtime.Object) error
	CreateOptions    []runtimeClient.CreateOption
	UpdateOptions    []runtimeClient.UpdateOption
	DeleteOptions    []runtimeClient.DeleteOption
	ShouldCreateFunc func(desired runtime.Object) (bool, error)
	ShouldUpdateFunc func(current, desired runtime.Object) (bool, error)
	ShouldDeleteFunc func(desired runtime.Object) (bool, error)
}

func (DynamicDesiredState) BeforeCreate

func (s DynamicDesiredState) BeforeCreate(desired runtime.Object) error

func (DynamicDesiredState) BeforeDelete

func (s DynamicDesiredState) BeforeDelete(current runtime.Object) error

func (DynamicDesiredState) BeforeUpdate

func (s DynamicDesiredState) BeforeUpdate(current, desired runtime.Object) error

func (DynamicDesiredState) GetCreateptions

func (s DynamicDesiredState) GetCreateptions() []runtimeClient.CreateOption

func (DynamicDesiredState) GetDeleteOptions

func (s DynamicDesiredState) GetDeleteOptions() []runtimeClient.DeleteOption

func (DynamicDesiredState) GetDesiredState

func (s DynamicDesiredState) GetDesiredState() DesiredState

func (DynamicDesiredState) GetUpdateOptions

func (s DynamicDesiredState) GetUpdateOptions() []runtimeClient.UpdateOption

func (DynamicDesiredState) ShouldCreate

func (s DynamicDesiredState) ShouldCreate(desired runtime.Object) (bool, error)

func (DynamicDesiredState) ShouldDelete

func (s DynamicDesiredState) ShouldDelete(desired runtime.Object) (bool, error)

func (DynamicDesiredState) ShouldUpdate

func (s DynamicDesiredState) ShouldUpdate(current, desired runtime.Object) (bool, error)

type ErrorMessageCondition

type ErrorMessageCondition func(string) bool

type GenericResourceReconciler

type GenericResourceReconciler struct {
	Log     logr.Logger
	Client  client.Client
	Options ReconcilerOpts
}

GenericResourceReconciler generic resource reconciler

func NewGenericReconciler

func NewGenericReconciler(c client.Client, log logr.Logger, opts ReconcilerOpts) *GenericResourceReconciler

NewGenericReconciler returns GenericResourceReconciler Deprecated, use NewReconcilerWith

func (*GenericResourceReconciler) CreateIfNotExist

func (r *GenericResourceReconciler) CreateIfNotExist(desired runtime.Object, desiredState DesiredState) (bool, runtime.Object, error)

func (*GenericResourceReconciler) CreateResource

func (r *GenericResourceReconciler) CreateResource(desired runtime.Object) error

CreateResource creates a resource if it doesn't exist

func (*GenericResourceReconciler) ReconcileResource

func (r *GenericResourceReconciler) ReconcileResource(desired runtime.Object, desiredState DesiredState) (*reconcile.Result, error)

ReconcileResource reconciles various kubernetes types

type MultipleDesiredStates

type MultipleDesiredStates []DesiredState

func (MultipleDesiredStates) BeforeCreate

func (s MultipleDesiredStates) BeforeCreate(desired runtime.Object) error

func (MultipleDesiredStates) BeforeDelete

func (s MultipleDesiredStates) BeforeDelete(desired runtime.Object) error

func (MultipleDesiredStates) BeforeUpdate

func (s MultipleDesiredStates) BeforeUpdate(current, desired runtime.Object) error

func (MultipleDesiredStates) GetCreateptions

func (s MultipleDesiredStates) GetCreateptions() []runtimeClient.CreateOption

func (MultipleDesiredStates) GetDeleteOptions

func (s MultipleDesiredStates) GetDeleteOptions() []runtimeClient.DeleteOption

func (MultipleDesiredStates) GetDesiredState

func (s MultipleDesiredStates) GetDesiredState() DesiredState

func (MultipleDesiredStates) GetUpdateOptions

func (s MultipleDesiredStates) GetUpdateOptions() []runtimeClient.UpdateOption

func (MultipleDesiredStates) ShouldCreate

func (s MultipleDesiredStates) ShouldCreate(desired runtime.Object) (bool, error)

func (MultipleDesiredStates) ShouldDelete

func (s MultipleDesiredStates) ShouldDelete(desired runtime.Object) (bool, error)

func (MultipleDesiredStates) ShouldUpdate

func (s MultipleDesiredStates) ShouldUpdate(current, desired runtime.Object) (bool, error)

type NativeReconciledComponent

type NativeReconciledComponent interface {
	ResourceBuilders(parent ResourceOwner, object interface{}) []ResourceBuilder
	RegisterWatches(*builder.Builder)
	PurgeTypes() []schema.GroupVersionKind
}

func NewReconciledComponent

func NewReconciledComponent(b ResourceBuilders, w func(b *builder.Builder), p func() []schema.GroupVersionKind) NativeReconciledComponent

type NativeReconciler

type NativeReconciler struct {
	*GenericResourceReconciler
	client.Client
	// contains filtered or unexported fields
}

func NewNativeReconciler

func NewNativeReconciler(
	componentName string,
	rec *GenericResourceReconciler,
	client client.Client,
	reconciledComponent NativeReconciledComponent,
	resourceTranslate func(runtime.Object) (parent ResourceOwner, config interface{}),
	opts ...NativeReconcilerOpt) *NativeReconciler

func NewNativeReconcilerWithDefaults

func NewNativeReconcilerWithDefaults(
	component string,
	client client.Client,
	scheme *runtime.Scheme,
	logger logr.Logger,
	resourceBuilders ResourceBuilders,
	purgeTypes PurgeTypesFunc,
	resourceTranslate ResourceTranslate,
	opts ...NativeReconcilerOpt,
) *NativeReconciler

func (*NativeReconciler) GetReconciledObjectWithState

func (rec *NativeReconciler) GetReconciledObjectWithState(state reconciledObjectState) []runtime.Object

func (*NativeReconciler) Reconcile

func (rec *NativeReconciler) Reconcile(owner runtime.Object) (*reconcile.Result, error)

func (*NativeReconciler) RegisterWatches

func (rec *NativeReconciler) RegisterWatches(b *builder.Builder)

type NativeReconcilerOpt

type NativeReconcilerOpt func(*NativeReconciler)

func NativeReconcilerSetControllerRef

func NativeReconcilerSetControllerRef() NativeReconcilerOpt

func NativeReconcilerSetRESTMapper

func NativeReconcilerSetRESTMapper(mapper meta.RESTMapper) NativeReconcilerOpt

func NativeReconcilerWithModifier

func NativeReconcilerWithModifier(modifierFunc resources.ObjectModifierWithParentFunc) NativeReconcilerOpt

func NativeReconcilerWithRetriableErrorFunc

func NativeReconcilerWithRetriableErrorFunc(retriableErrorFunc func(error) bool) NativeReconcilerOpt

func NativeReconcilerWithRetryBackoff

func NativeReconcilerWithRetryBackoff(backoff wait.Backoff) NativeReconcilerOpt

func NativeReconcilerWithScheme

func NativeReconcilerWithScheme(scheme *runtime.Scheme) NativeReconcilerOpt

func NativeReconcilerWithWait

func NativeReconcilerWithWait(backoff *wait.Backoff) NativeReconcilerOpt

type ObjectKeyWithGVK

type ObjectKeyWithGVK struct {
	ObjectKey client.ObjectKey        `json:"objectKey,omitempty"`
	GVK       schema.GroupVersionKind `json:"gvk,omitempty"`
}

type PendingStatusPredicate

type PendingStatusPredicate struct {
	predicate.Funcs
}

func (PendingStatusPredicate) Update

type PurgeTypesFunc

type PurgeTypesFunc func() []schema.GroupVersionKind

type ReconcileRetry

type ReconcileRetry struct {
	MaxRetries  int
	DefaultWait time.Duration
}

func (*ReconcileRetry) Reconcile

func (r *ReconcileRetry) Reconcile(component func() (*reconcile.Result, error)) error

type ReconcilerOpts

type ReconcilerOpts struct {
	Log    logr.Logger
	Scheme *runtime.Scheme
	// Enable recreating workloads and services when the API server rejects an update
	EnableRecreateWorkloadOnImmutableFieldChange bool
	// Custom log message to help when a workload or service needs to be recreated
	EnableRecreateWorkloadOnImmutableFieldChangeHelp string
	// The delay in seconds to wait before checking back after deleting the resource (10s by default)
	RecreateRequeueDelay *int32
	// List of callbacks evaluated to decide whether a given gvk is enabled to be recreated or not
	RecreateEnabledResourceCondition RecreateResourceCondition
	// Immediately recreate the resource instead of deleting and returning with a requeue
	RecreateImmediately bool
	// Configure the recreate PropagationPolicy. "Orphan" avoids deleting pods simultaneously.
	RecreatePropagationPolicy client.PropagationPolicy
	// Check the update error message contains this substring before recreate. Default: "immutable"
	RecreateErrorMessageSubstring *string
	// Custom logic to decide if an error message indicates a resource should be recreated.
	// Takes precedence over RecreateErrorMessageSubstring if set.
	RecreateErrorMessageCondition ErrorMessageCondition
	// K8s object matcher patch maker implementation
	PatchMaker patch.Maker
	// K8s object matcher patch calculate options
	PatchCalculateOptions []patch.CalculateOption
}

Recommended to use NewReconcilerWith + ResourceReconcilerOptions

type RecreateResourceCondition

type RecreateResourceCondition func(kind schema.GroupVersionKind, status metav1.Status) bool

type ResourceBuilder

type ResourceBuilder func() (runtime.Object, DesiredState, error)

func GetResourceBuildersFromObjects

func GetResourceBuildersFromObjects(objects []runtime.Object, state DesiredState, modifierFuncs ...resources.ObjectModifierFunc) ([]ResourceBuilder, error)

type ResourceBuilders

type ResourceBuilders func(parent ResourceOwner, object interface{}) []ResourceBuilder

type ResourceCondition

type ResourceCondition struct {
	ID           string                              `json:"id,omitempty"`
	Description  string                              `json:"shortDescription,omitempty"`
	Checks       []wait.ResourceConditionCheck       `json:"checks,omitempty"`
	CustomChecks []wait.CustomResourceConditionCheck `json:"customChecks,omitempty"`
	Object       *ObjectKeyWithGVK                   `json:"object,omitempty"`
}

type ResourceOwner

type ResourceOwner interface {
	// to be aware of metadata
	metav1.Object
	// to be aware of the owner's type
	runtime.Object
}

type ResourceOwnerWithControlNamespace

type ResourceOwnerWithControlNamespace interface {
	ResourceOwner
	// control namespace dictates where namespaced objects should belong to
	GetControlNamespace() string
}

type ResourceReconciler

type ResourceReconciler interface {
	CreateIfNotExist(runtime.Object, DesiredState) (created bool, object runtime.Object, err error)
	ReconcileResource(runtime.Object, DesiredState) (*reconcile.Result, error)
}

func NewReconcilerWith

func NewReconcilerWith(client client.Client, opts ...ResourceReconcilerOption) ResourceReconciler

type ResourceReconcilerOption

type ResourceReconcilerOption func(*ReconcilerOpts)

func WithEnableRecreateWorkload

func WithEnableRecreateWorkload() ResourceReconcilerOption

func WithLog

func WithPatchCalculateOptions

func WithPatchCalculateOptions(options ...patch.CalculateOption) ResourceReconcilerOption

Set patch maker calculate options

func WithPatchMaker

func WithPatchMaker(maker patch.Maker) ResourceReconcilerOption

Set patch maker implementation

func WithRecreateEnabledFor

func WithRecreateEnabledFor(condition RecreateResourceCondition) ResourceReconcilerOption

Use this option for the legacy behaviour

func WithRecreateEnabledForAll

func WithRecreateEnabledForAll() ResourceReconcilerOption

Use this option for the legacy behaviour

func WithRecreateEnabledForNothing

func WithRecreateEnabledForNothing() ResourceReconcilerOption

Matches no GVK

func WithRecreateErrorMessageCondition

func WithRecreateErrorMessageCondition(condition ErrorMessageCondition) ResourceReconcilerOption

Recreate only if the error message contains the given substring

func WithRecreateErrorMessageIgnored

func WithRecreateErrorMessageIgnored() ResourceReconcilerOption

Disable checking the error message before recreating resources

func WithRecreateErrorMessageSubstring

func WithRecreateErrorMessageSubstring(substring string) ResourceReconcilerOption

Recreate only if the error message contains the given substring

func WithRecreateImmediately

func WithRecreateImmediately() ResourceReconcilerOption

Recreate workloads immediately without waiting for dependents to get GCd

func WithRecreateRequeueDelay

func WithRecreateRequeueDelay(delay int32) ResourceReconcilerOption

Apply the given amount of delay before recreating a resource after it has been removed

func WithScheme

func WithScheme(scheme *runtime.Scheme) ResourceReconcilerOption

type ResourceTranslate

type ResourceTranslate func(runtime.Object) (parent ResourceOwner, config interface{})

type SkipCreatePredicate

type SkipCreatePredicate struct {
	predicate.Funcs
}

func (SkipCreatePredicate) Create

type SkipDeletePredicate

type SkipDeletePredicate struct {
	predicate.Funcs
}

func (SkipDeletePredicate) Delete

type SkipUpdatePredicate

type SkipUpdatePredicate struct {
	predicate.Funcs
}

func (SkipUpdatePredicate) Update

type SpecChangePredicate

type SpecChangePredicate struct {
	predicate.Funcs
	// contains filtered or unexported fields
}

func (SpecChangePredicate) Update

type StaticDesiredState

type StaticDesiredState string

func (StaticDesiredState) BeforeCreate

func (s StaticDesiredState) BeforeCreate(desired runtime.Object) error

func (StaticDesiredState) BeforeDelete

func (s StaticDesiredState) BeforeDelete(current runtime.Object) error

func (StaticDesiredState) BeforeUpdate

func (s StaticDesiredState) BeforeUpdate(current, desired runtime.Object) error

type Watches

type Watches interface {
	SetupAdditionalWatches(c controller.Controller) error
}

Jump to

Keyboard shortcuts

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