component

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package component provides the core framework for managing Kubernetes resources as logical components.

Index

Constants

View Source
const (
	// Unknown indicates that the component has not been reconciled yet.
	Unknown Status = "Unknown"
	// Error indicates that resource errors happened during reconciliation.
	Error Status = "Error"

	// Healthy indicates that the component is fully provisioned and operating as expected.
	Healthy = Status(concepts.AliveConvergingStatusHealthy)
	// AliveCreating indicates that the resource are being created.
	AliveCreating = Status(concepts.AliveConvergingStatusCreating)
	// AliveScaling indicates that the resources are being scaled.
	AliveScaling = Status(concepts.AliveConvergingStatusScaling)
	// AliveUpdating indicates that the resources are being updated.
	AliveUpdating = Status(concepts.AliveConvergingStatusUpdating)
	// AliveFailing indicates that the resources are failing to converge.
	AliveFailing = Status(concepts.AliveConvergingStatusFailing)

	// Operational indicates that the resources are operational.
	Operational = Status(concepts.OperationalStatusOperational)
	// OperationPending indicates that operational resources are pending and not yet operational.
	OperationPending = Status(concepts.OperationalStatusPending)
	// OperationFailing indicates that operational resources are failing to become operational.
	OperationFailing = Status(concepts.OperationalStatusFailing)

	// Completed indicates that completable resources successfully completed their task.
	Completed = Status(concepts.CompletionStatusCompleted)
	// CompletionPending indicates that completable resources are still pending.
	CompletionPending = Status(concepts.CompletionStatusPending)
	// CompletionRunning indicates that completable tasks are still running.
	CompletionRunning = Status(concepts.CompletionStatusRunning)
	// CompletionFailing indicates that completable tasks are failing.
	CompletionFailing = Status(concepts.CompletionStatusFailing)

	// GuardBlocked indicates that a resource's guard precondition is not yet met.
	// The resource and all resources after it in registration order are waiting.
	GuardBlocked = Status(concepts.GuardStatusBlocked)

	// PendingSuspension indicates that the component is aware of the suspension request but has yet to begin suspension.
	PendingSuspension = Status(concepts.SuspensionStatusPending)
	// Suspending indicates that the component is converging towards a suspended state but is not yet fully suspended.
	Suspending = Status(concepts.SuspensionStatusSuspending)
	// Suspended indicates that the component is suspended.
	Suspended = Status(concepts.SuspensionStatusSuspended)

	// Degraded indicates that the component is degraded but operational.
	Degraded = Status(concepts.GraceStatusDegraded)
	// Down indicates that component is down and not operational.
	Down = Status(concepts.GraceStatusDown)
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

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

Builder implements the fluent API for constructing and validating a Component. It ensures that a component is configured with consistent rules before it is used in a reconciliation loop.

func NewComponentBuilder

func NewComponentBuilder() *Builder

NewComponentBuilder initializes a new Builder for creating a Component.

A Component manages a single condition on an owning object (the OperatorCRD) and aggregates the lifecycle, readiness, and suspension state of all registered resources.

func (*Builder) Build

func (b *Builder) Build() (*Component, error)

Build finalizes the component configuration and validates all settings and resources added.

If any validation errors occurred during the fluent configuration (e.g., duplicate resources or invalid grace periods), Build returns a single aggregated error containing all failures using errors.Join.

Returns:

  • *Component: The fully configured and validated component instance on success.
  • error: An aggregated error containing all validation failures, or nil if successful.

func (*Builder) Suspend added in v0.2.0

func (b *Builder) Suspend(suspend bool) *Builder

Suspend allows marking the component as suspended.

By default, the component is not suspended, which equates to passing false to this method. When true is passed, all resource within the component that implement the concepts.Suspendable interface are suspended.

func (*Builder) WithConditionType

func (b *Builder) WithConditionType(conditionType ConditionType) *Builder

WithConditionType sets the Kubernetes condition type associated with this component.

This condition type will be updated on the owning object's status to reflect the aggregate state of all resources managed by this component.

Parameters:

  • conditionType: The condition name (e.g., "WebInterfaceReady").

If the condition type is empty, a validation error is recorded and will be returned by Build().

func (*Builder) WithGracePeriod

func (b *Builder) WithGracePeriod(gracePeriod time.Duration) *Builder

WithGracePeriod configures a grace duration for the component's convergence to a Ready state.

When a component is not Ready, it is considered to be in a Progressing state (e.g., Creating, Updating, Scaling). The grace period defines how long the component is allowed to remain in these Progressing states before it is considered Degraded or Down.

Once the grace period expires:

  • If the aggregate resource state is Down or Degraded, the component condition transitions to that state.
  • Resources that implement the Alive interface provide their specific grace status used for this aggregation.

Parameters:

  • gracePeriod: The duration to allow for convergence. Must be non-negative.

func (*Builder) WithName

func (b *Builder) WithName(name string) *Builder

WithName sets the name of the component for logging and status identification.

The name is used as the field name in the aggregation of status conditions and must be unique within the owning reconciler.

Parameters:

  • name: A non-empty string identifying the component.

If the name is empty, a validation error is recorded and will be returned by Build().

func (*Builder) WithResource

func (b *Builder) WithResource(resource Resource, options ResourceOptions) *Builder

WithResource registers a Kubernetes resource to be managed by this component.

If a resource with the same Identity() is already registered, a validation error is recorded and will be returned by Build().

type Component

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

Component represents a logical grouping of Kubernetes resources that are reconciled together and reported as a single condition on an owning object.

A component is responsible for:

  • Creating, updating, or reading its registered resources
  • Aggregating resource-level readiness into a single converging status
  • Managing optional grace-period behavior for degraded or down states
  • Handling suspension, including mutation-based suspension and optional deletion

Each Component manages exactly one condition type on the owner and is reconciled independently of other components. Resources are registered during construction using WithResource and the configuration is finalized by calling Build().

func (*Component) GetCondition

func (c *Component) GetCondition(owner OperatorCRD) Condition

GetCondition returns the current component condition from the owner object. It returns a synthetic "Unknown" condition if the condition is not yet present on the owner.

Note: Always reconcile before retrieving this condition to ensure it reflects the latest cluster state; otherwise, it may be stale.

func (*Component) GetName

func (c *Component) GetName() string

GetName returns the name of the component, which is used for logging and identification.

func (*Component) Reconcile

func (c *Component) Reconcile(ctx context.Context, rec ReconcileContext) error

Reconcile converges the component to the desired state.

A component manages its own condition on the parent and updates it accordingly to represent currently observable facts about the component status.

Reconciliation follows these steps:

  1. Suspension check: If the component is marked as suspended, it performs suspension of all managed (non-read-only) resources. Guards are not evaluated. The status is updated to reflect suspension progress (PendingSuspension, Suspending, or Suspended), and then deletion resources are processed.

  2. Resource reconciliation: All non-delete resources are processed sequentially in registration order, regardless of whether they are managed or read-only. For each resource: - Its guard (if any) is evaluated. A blocked guard stops processing of that resource and all subsequent resources. - The resource is either applied (managed) or fetched (read-only). - Its data extractors run immediately, making extracted data available to subsequent resources' guards and mutations.

  3. Status Aggregation: Collects converging status from all processed resources (including any blocked guard result).

  4. Condition Update: Derives a new component condition using a stateful progression model that considers the aggregate resource status, the previous condition, and the configured grace period to avoid churn.

  5. Resource Deletion: Finally, it deletes any resources registered for deletion.

type Condition

type Condition metav1.Condition

Condition is a type alias for metav1.Condition. It represents a single condition for a component.

func (Condition) ComponentStatus

func (c Condition) ComponentStatus() Status

ComponentStatus returns the component's internal status (Reason) from the condition.

func (Condition) ConditionType

func (c Condition) ConditionType() ConditionType

ConditionType returns the component-specific type for the condition.

type ConditionType

type ConditionType string

ConditionType represents the type of condition in the Kubernetes status. It is used to identify the specific component's condition on the owner CRD.

type OperatorCRD

type OperatorCRD interface {
	client.Object

	// GetStatusConditions returns a pointer to the slice of status conditions.
	// This is used to read and update the component's status condition on the owner.
	GetStatusConditions() *[]metav1.Condition
	// GetKind returns the string representation of the CRD's Kind.
	GetKind() string
}

OperatorCRD defines the interface for the custom resource that owns the component. It must support status conditions and provide its kind for recording purposes.

type ParticipationMode added in v0.2.0

type ParticipationMode string

ParticipationMode describes in what way the resource participates in the component health aggregation.

const (
	// ParticipationModeRequired The resource must be in a 'Healthy', 'Completed' or 'Operational' state for the
	// component to be considered healthy.
	//
	//  - concepts.Alive: It must be 'Healthy'
	//  - concepts.Operational: It must be 'Operational'
	//  - concepts.Completable: It must be 'Completed'
	//  - If the resource is static (not implementing any of the concepts mentioned), the mode only
	//    takes effect when the resource has a guard. A guarded static resource can report Blocked,
	//    which participates in health aggregation.
	ParticipationModeRequired ParticipationMode = "Required"
	// ParticipationModeAuxiliary The resource is auxiliary and not part of component health evaluation.
	ParticipationModeAuxiliary ParticipationMode = "Auxiliary"
)

type ReconcileContext

type ReconcileContext struct {
	// Client is the Kubernetes client for resource operations.
	Client client.Client
	// Scheme is the runtime scheme for the operator.
	Scheme *runtime.Scheme
	// Recorder is the event recorder for publishing Kubernetes events.
	Recorder record.EventRecorder
	// Metrics is the recorder for status condition metrics.
	Metrics Recorder
	// Owner is the custom resource that owns and is updated by the components.
	Owner OperatorCRD
}

ReconcileContext carries the dependencies and target object for a reconciliation loop.

type Recorder

type Recorder interface {
	// RecordConditionFor records a condition change for a specific object and kind.
	RecordConditionFor(
		kind string, object ocm.ObjectLike,
		conditionType, conditionStatus, conditionReason string, lastTransitionTime time.Time,
		extraLabelValues ...string,
	)
}

Recorder is an interface for recording status condition changes as metrics.

type Resource

type Resource interface {
	// Mutate applies all applicable mutations on the resource retrieved from the kubernetes api.
	//
	// If the object exists: `current` is the object fetched from the API server.
	// If it does not exist: `current` is the same base object returned by Object() and passed into CreateOrUpdate,
	// not a fetched server object.
	//
	// The Resource implementation is responsible for applying all desired fields from its
	// internal core state to the current resource before proceeding with feature mutations.
	//
	// The mutations are applied every time the component is reconciled.
	Mutate(current client.Object) error
	// Object returns a copy of the managed Kubernetes resource.
	//
	// The returned object's state depends on the reconciliation phase:
	//   - Before reconciliation: Represents the baseline state before any mutations or side effects.
	//   - After reconciliation: Represents the state as applied to the Kubernetes API, including all mutations.
	//
	// This method is primarily intended for use by the Component reconciler. Implementers should
	// avoid calling this directly to retrieve data; instead, use provided patterns like DataExtractable.
	Object() (client.Object, error)
	// Identity returns a unique identifier for the resource in the format <apiVersion>/<kind>/<name>.
	Identity() string
}

Resource is a generic interface for handling Kubernetes resources within a Component. Implementations of this interface wrap a specific Kubernetes object and define how it participates in the component's lifecycle.

type ResourceOptions added in v0.2.0

type ResourceOptions struct {
	// Delete If true, the resource is marked for deletion during reconciliation.
	Delete bool
	// ReadOnly If true, the resource is read-only
	ReadOnly bool
	// ParticipationMode describes in what way the resource participates in the component health aggregation.
	// All resources default to ParticipationModeRequired when not otherwise specified.
	//
	// If the resource is static (not implementing any of the interfaces mentioned), the mode only
	// takes effect when the resource has a guard. A guarded static resource can report Blocked,
	// which participates in health aggregation. An unguarded static resource produces no
	// converging status, so the mode has no observable effect.
	ParticipationMode ParticipationMode
}

ResourceOptions defines configuration for how a Kubernetes resource is managed within a component. It controls the resource's lifecycle (creation, deletion, or read-only) and its participation in the component's health aggregation.

func ResourceOptionsFor added in v0.3.0

func ResourceOptionsFor(f feature.Gate) (ResourceOptions, error)

ResourceOptionsFor is a convenience function that creates ResourceOptions gated by a single feature.Gate.

When the feature is enabled, the resource is created with default options (read-write, participation mode deferred to WithResource defaults). When disabled, the resource is marked for deletion.

A nil feature is treated as unconditionally enabled.

This is equivalent to:

NewResourceOptionsBuilder().WithFeatureGate(f).Build()

type ResourceOptionsBuilder added in v0.3.0

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

ResourceOptionsBuilder constructs a ResourceOptions value, optionally integrating with the feature gating system to control whether a resource is created or deleted based on feature state.

When a feature is set and evaluates to disabled, the resource is marked for deletion regardless of other settings (ReadOnly, ParticipationMode). Additional boolean conditions added via When follow the same semantics: if any condition is false, the resource is deleted.

func NewResourceOptionsBuilder added in v0.3.0

func NewResourceOptionsBuilder() *ResourceOptionsBuilder

NewResourceOptionsBuilder creates a new ResourceOptionsBuilder with default settings. Without any modifiers, Build returns a ResourceOptions equivalent to the zero value (create, required, read-write).

func (*ResourceOptionsBuilder) Auxiliary added in v0.3.0

Auxiliary sets the participation mode to Auxiliary, meaning the resource does not affect the component's health aggregation.

This is equivalent to setting ParticipationMode to ParticipationModeAuxiliary.

func (*ResourceOptionsBuilder) Build added in v0.3.0

Build evaluates the configured feature and truth conditions and returns the resulting ResourceOptions.

Feature evaluation can fail (e.g., version constraint parsing errors), in which case Build returns the error. If no feature is set and no When conditions are configured, Build always succeeds.

Resolution rules:

  • If the feature is non-nil and Enabled() returns false, Delete is true.
  • If any When condition evaluates to false, Delete is true.
  • If Delete is true, ReadOnly is forced to false (deletion takes precedence).
  • ParticipationMode is preserved regardless of deletion state.

func (*ResourceOptionsBuilder) ReadOnly added in v0.3.0

ReadOnly marks the resource as read-only. The component will fetch the resource's current state but will not create or update it.

If the resource is also gated by a disabled feature or a When condition that evaluates to false, deletion takes precedence over read-only mode.

func (*ResourceOptionsBuilder) When added in v0.5.0

When adds a boolean condition that must be true for the resource to be created. If the condition is false, the resource is marked for deletion, following the same semantics as a disabled feature.

Calls are additive: all values passed through When must be true for the resource to be created. Conditions are evaluated with AND logic alongside any configured feature.

func (*ResourceOptionsBuilder) WithFeatureGate added in v0.3.0

WithFeatureGate sets a feature.Gate that gates the resource's existence.

When the feature evaluates to disabled, the resulting ResourceOptions will have Delete set to true, causing the component to remove the resource from the cluster. When enabled, the resource is created normally.

A nil feature is treated as unconditionally enabled (no gating).

type Status

type Status string

Status represents the internal state of a component. It is used as the Reason in a Kubernetes condition and provides a standardized way to reflect the health and progress of a component.

func (Status) Healthy added in v0.2.0

func (s Status) Healthy() bool

Healthy returns true if the status signals healthiness.

func (Status) Priority added in v0.2.0

func (s Status) Priority() int

Priority returns the aggregation priority of a component Status.

The returned value is used when multiple component statuses must be collapsed into a single overall status (for example by a parent component or system-level status aggregator). The status with the highest Priority() should be selected as the representative state.

The ordering reflects the most meaningful explanation of the system's current state:

Unknown or unrecognized statuses return 0 and therefore do not influence aggregation.

Directories

Path Synopsis
Package concepts defines the core concepts for the operator component framework.
Package concepts defines the core concepts for the operator component framework.

Jump to

Keyboard shortcuts

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