cronjob

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package cronjob provides a builder and resource for managing Kubernetes CronJobs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultDeleteOnSuspendHandler

func DefaultDeleteOnSuspendHandler(_ *batchv1.CronJob) bool

DefaultDeleteOnSuspendHandler provides the default decision of whether to delete the CronJob when the parent component is suspended.

It always returns false, meaning the CronJob is kept in the cluster with spec.suspend set to true.

func DefaultGraceStatusHandler

func DefaultGraceStatusHandler(_ *batchv1.CronJob) (concepts.GraceStatusWithReason, error)

DefaultGraceStatusHandler provides the default health assessment of a CronJob when the component's grace period has expired.

It always reports Healthy. A CronJob is a passive scheduler — once it exists, it is functioning correctly regardless of whether it has fired yet. The schedule interval may be longer than the grace period (e.g. monthly), so waiting for the first execution would produce false degradation signals.

This function is used as the default handler by the Resource if no custom handler is registered via Builder.WithCustomGraceStatus. It can be reused within custom handlers to augment the default behavior.

func DefaultOperationalStatusHandler

func DefaultOperationalStatusHandler(
	_ concepts.ConvergingOperation, _ *batchv1.CronJob,
) (concepts.OperationalStatusWithReason, error)

DefaultOperationalStatusHandler is the default logic for determining if a CronJob is operational.

It always reports Operational. A CronJob is a passive scheduler: once it exists in the cluster it is functioning correctly regardless of whether it has fired yet. The schedule interval may be longer than the component's grace period, so treating a never-scheduled CronJob as Pending would produce false degradation signals. Failures are reported on the spawned Job resources, not on the CronJob itself.

Users who need visibility into whether the CronJob has executed can override this handler via Builder.WithCustomOperationalStatus.

func DefaultSuspendMutationHandler

func DefaultSuspendMutationHandler(mutator *Mutator) error

DefaultSuspendMutationHandler provides the default mutation applied to a CronJob when the component is suspended.

It sets spec.suspend to true, which prevents the CronJob from creating new Job objects.

func DefaultSuspensionStatusHandler

func DefaultSuspensionStatusHandler(cj *batchv1.CronJob) (concepts.SuspensionStatusWithReason, error)

DefaultSuspensionStatusHandler monitors the progress of the suspension process.

It reports Suspended when spec.suspend is true and no active jobs are running. It reports Suspending when spec.suspend is true but active jobs are still running.

func ExtractInto added in v0.18.0

func ExtractInto[V any](b *Builder, cell *concepts.Data[V], fn func(batchv1.CronJob) (V, error))

ExtractInto declares that this CronJob produces the value of cell. fn computes the value from a copy of the reconciled CronJob; the framework stores it in the cell and marks it present, immediately after the CronJob is applied or fetched. Extracting several values means several ExtractInto calls, one per cell. This is a package-level function because Go methods cannot introduce the extra type parameter V.

Types

type Builder

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

Builder is a configuration helper for creating and customizing a CronJob Resource.

It provides a fluent API for registering mutations, status handlers, and declared data extractions. This builder ensures that the resulting Resource is properly initialized and validated before use in a reconciliation loop.

func NewBuilder

func NewBuilder(cj *batchv1.CronJob) *Builder

NewBuilder initializes a new Builder with the provided CronJob object.

The CronJob object passed here serves as the "desired base state". During reconciliation, the Resource will attempt to make the cluster's state match this base state, modified by any registered mutations.

The provided CronJob must have at least a Name and Namespace set, which is validated during the Build() call.

func (*Builder) Build

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

Build validates the configuration and returns the initialized Resource.

It ensures that:

  • A base CronJob object was provided.
  • The CronJob has both a name and a namespace set.

If validation fails, an error is returned and the Resource should not be used.

func (*Builder) WithCustomGraceStatus

func (b *Builder) WithCustomGraceStatus(
	handler func(*batchv1.CronJob) (concepts.GraceStatusWithReason, error),
) *Builder

WithCustomGraceStatus overrides the default logic for assessing the health of the CronJob when the component's grace period has expired.

The default behavior uses DefaultGraceStatusHandler, which always reports Healthy. A CronJob is a passive scheduler — once it exists and is not suspended, it is functioning correctly regardless of whether it has fired yet.

If you want to augment the default behavior, you can call DefaultGraceStatusHandler within your custom handler.

func (*Builder) WithCustomOperationalStatus

func (b *Builder) WithCustomOperationalStatus(
	handler func(concepts.ConvergingOperation, *batchv1.CronJob) (concepts.OperationalStatusWithReason, error),
) *Builder

WithCustomOperationalStatus overrides the default logic for determining if the CronJob is operational.

func (*Builder) WithCustomSuspendDeletionDecision

func (b *Builder) WithCustomSuspendDeletionDecision(
	handler func(*batchv1.CronJob) bool,
) *Builder

WithCustomSuspendDeletionDecision overrides the decision of whether to delete the CronJob when the component is suspended.

func (*Builder) WithCustomSuspendMutation

func (b *Builder) WithCustomSuspendMutation(
	handler func(*Mutator) error,
) *Builder

WithCustomSuspendMutation defines how the CronJob should be modified when the component is suspended.

func (*Builder) WithCustomSuspendStatus

func (b *Builder) WithCustomSuspendStatus(
	handler func(*batchv1.CronJob) (concepts.SuspensionStatusWithReason, error),
) *Builder

WithCustomSuspendStatus overrides how the progress of suspension is reported.

func (*Builder) WithDataGuard added in v0.18.0

func (b *Builder) WithDataGuard(cells ...concepts.DataCell) *Builder

WithDataGuard declares that the CronJob reads the given data cells and must not be applied until every one of them is set. The framework generates the guard and its reason (waiting for data "<name>"), and component Build validates that a producer for each cell is registered earlier. Data guards are evaluated before any custom guard registered with WithGuard.

func (*Builder) WithGuard added in v0.4.0

func (b *Builder) WithGuard(
	guard func(batchv1.CronJob) (concepts.GuardStatusWithReason, error),
) *Builder

WithGuard registers a guard precondition that is evaluated before the CronJob is applied during reconciliation. If the guard returns Blocked, the CronJob and all resources registered after it are skipped until the guard clears. Passing nil clears any previously registered guard.

func (*Builder) WithMetricsIdentifier added in v0.20.0

func (b *Builder) WithMetricsIdentifier(identifier string) *Builder

WithMetricsIdentifier sets the CronJob's identifier for resource-level metrics, used as the value of the `resource` label on ocf_resource_apply_total and ocf_resource_apply_errors_total.

It is a Prometheus label value, not a Kubernetes name: it must be low-cardinality and stable across reconciles, never derived from a per-owner value such as the owning custom resource's name. When unset, the resource is labelled `cronjob`. Build rejects a blank identifier.

func (*Builder) WithMutation

func (b *Builder) WithMutation(ms ...Mutation) *Builder

WithMutation registers one or more feature-based mutations for the CronJob.

Mutations are applied sequentially during the Mutate() phase of reconciliation.

func (*Builder) WithOptionalData added in v0.18.0

func (b *Builder) WithOptionalData(cells ...concepts.DataCell) *Builder

WithOptionalData declares that the CronJob reads the given data cells without gating on them. Component Build still validates that a producer is registered earlier, and the dependency stays visible to introspection. Consumers in this mode use Get and skip quietly when a cell is absent.

type Mutation

type Mutation feature.Mutation[*Mutator]

Mutation defines a mutation that is applied to a CronJob Mutator only if its associated feature.VersionGate is enabled.

type Mutator

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

Mutator is a high-level helper for modifying a Kubernetes CronJob.

It uses a "plan-and-apply" pattern: mutations are recorded first, and then applied to the CronJob in a single controlled pass when Apply() is called.

The Mutator maintains feature boundaries: each feature's mutations are planned together and applied in the order the features were registered.

func NewMutator

func NewMutator(current *batchv1.CronJob) *Mutator

NewMutator creates a new Mutator for the given CronJob. The constructor creates the initial feature scope, so mutations can be registered immediately.

func (*Mutator) Apply

func (m *Mutator) Apply() error

Apply executes all recorded mutation intents on the underlying CronJob.

Execution Order: Features are applied in the order they were registered. Within each feature, mutations are applied in this fixed category order:

  1. Object metadata edits
  2. CronJobSpec edits
  3. JobSpec edits
  4. Pod template metadata edits
  5. Pod spec edits
  6. Regular container presence operations
  7. Regular container edits
  8. Init container presence operations
  9. Init container edits

func (*Mutator) EditContainers

func (m *Mutator) EditContainers(selector selectors.ContainerSelector, edit func(*editors.ContainerEditor) error)

EditContainers records a mutation for containers matching the given selector.

Selector matching is evaluated against a snapshot taken after the current feature's container presence operations are applied. If either selector or edit function is nil, the registration is ignored.

func (*Mutator) EditCronJobSpec

func (m *Mutator) EditCronJobSpec(edit func(*editors.CronJobSpecEditor) error)

EditCronJobSpec records a mutation for the CronJob's top-level spec.

If the edit function is nil, the registration is ignored.

func (*Mutator) EditInitContainers

func (m *Mutator) EditInitContainers(selector selectors.ContainerSelector, edit func(*editors.ContainerEditor) error)

EditInitContainers records a mutation for init containers matching the given selector.

Selector matching is evaluated against a snapshot taken after the current feature's init container presence operations are applied. If either selector or edit function is nil, the registration is ignored.

func (*Mutator) EditJobSpec

func (m *Mutator) EditJobSpec(edit func(*editors.JobSpecEditor) error)

EditJobSpec records a mutation for the CronJob's embedded job template spec.

If the edit function is nil, the registration is ignored.

func (*Mutator) EditObjectMetadata

func (m *Mutator) EditObjectMetadata(edit func(*editors.ObjectMetaEditor) error)

EditObjectMetadata records a mutation for the CronJob's own metadata.

If the edit function is nil, the registration is ignored.

func (*Mutator) EditPodSpec

func (m *Mutator) EditPodSpec(edit func(*editors.PodSpecEditor) error)

EditPodSpec records a mutation for the CronJob's pod spec.

If the edit function is nil, the registration is ignored.

func (*Mutator) EditPodTemplateMetadata

func (m *Mutator) EditPodTemplateMetadata(edit func(*editors.ObjectMetaEditor) error)

EditPodTemplateMetadata records a mutation for the CronJob's pod template metadata.

If the edit function is nil, the registration is ignored.

func (*Mutator) EnsureContainer

func (m *Mutator) EnsureContainer(container corev1.Container)

EnsureContainer records that a regular container must be present in the CronJob. If a container with the same name exists, it is replaced; otherwise, it is appended.

func (*Mutator) EnsureContainerArg

func (m *Mutator) EnsureContainerArg(arg string)

EnsureContainerArg records that a command-line argument must be present in all containers of the CronJob.

func (*Mutator) EnsureContainerEnvVar

func (m *Mutator) EnsureContainerEnvVar(ev corev1.EnvVar)

EnsureContainerEnvVar records that an environment variable must be present in all containers of the CronJob.

func (*Mutator) EnsureInitContainer

func (m *Mutator) EnsureInitContainer(container corev1.Container)

EnsureInitContainer records that an init container must be present in the CronJob. If an init container with the same name exists, it is replaced; otherwise, it is appended.

func (*Mutator) NextFeature

func (m *Mutator) NextFeature()

NextFeature advances to a new feature planning scope. All subsequent mutation registrations will be grouped into this scope until NextFeature is called again.

The first scope is created automatically by NewMutator. This method is called by the framework between mutations to maintain per-feature ordering semantics.

func (*Mutator) RemoveContainer

func (m *Mutator) RemoveContainer(name string)

RemoveContainer records that a regular container should be removed by name.

func (*Mutator) RemoveContainerArg

func (m *Mutator) RemoveContainerArg(arg string)

RemoveContainerArg records that a command-line argument should be removed from all containers of the CronJob.

func (*Mutator) RemoveContainerArgs

func (m *Mutator) RemoveContainerArgs(args []string)

RemoveContainerArgs records that multiple command-line arguments should be removed from all containers of the CronJob.

func (*Mutator) RemoveContainerEnvVar

func (m *Mutator) RemoveContainerEnvVar(name string)

RemoveContainerEnvVar records that an environment variable should be removed from all containers of the CronJob.

func (*Mutator) RemoveContainerEnvVars

func (m *Mutator) RemoveContainerEnvVars(names []string)

RemoveContainerEnvVars records that multiple environment variables should be removed from all containers of the CronJob.

func (*Mutator) RemoveContainers

func (m *Mutator) RemoveContainers(names []string)

RemoveContainers records that multiple regular containers should be removed by name.

func (*Mutator) RemoveInitContainer

func (m *Mutator) RemoveInitContainer(name string)

RemoveInitContainer records that an init container should be removed by name.

func (*Mutator) RemoveInitContainers

func (m *Mutator) RemoveInitContainers(names []string)

RemoveInitContainers records that multiple init containers should be removed by name.

type Resource

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

Resource is a high-level abstraction for managing a Kubernetes CronJob within a controller's reconciliation loop.

It implements several component interfaces to integrate with the operator-component-framework:

  • component.Resource: for basic identity and mutation behavior.
  • concepts.Operational: for operational status tracking.
  • concepts.Graceful: for health assessment after grace period expiry.
  • concepts.Suspendable: for controlled suspension via spec.suspend.
  • concepts.Guardable: for conditional reconciliation based on a guard precondition.
  • concepts.DataExtractable: for exporting information after successful reconciliation.
  • concepts.ObservationRecorder: for surfacing live cluster state to declared data extractions on read-only reconciliation.

func (*Resource) ConsumedData added in v0.18.0

func (r *Resource) ConsumedData() []concepts.DataConsumption

ConsumedData returns the CronJob's declared data reads. It satisfies concepts.DataConsumer for component topology validation and introspection.

func (*Resource) ConvergingStatus

ConvergingStatus reports the CronJob's operational status.

By default, it uses DefaultOperationalStatusHandler, which reports Pending when the CronJob has never been scheduled and Operational when it has scheduled at least once.

func (*Resource) DeleteOnSuspend

func (r *Resource) DeleteOnSuspend() bool

DeleteOnSuspend determines whether the CronJob should be deleted from the cluster when the parent component is suspended.

By default, it returns false — the CronJob is kept with spec.suspend set to true.

func (*Resource) ExtractData

func (r *Resource) ExtractData() error

ExtractData executes registered data extraction functions to harvest information from the reconciled CronJob.

func (*Resource) FiringSet added in v0.14.0

func (r *Resource) FiringSet() ([]string, error)

FiringSet returns the Names of registered mutations whose gate is enabled for the version the CronJob was built at. It satisfies concepts.MutationInspector.

func (*Resource) GraceStatus

func (r *Resource) GraceStatus() (concepts.GraceStatusWithReason, error)

GraceStatus reports the health of the CronJob after the component's grace period has expired.

By default, it uses DefaultGraceStatusHandler, which always reports Healthy. A CronJob is a passive scheduler — once it exists and is not suspended, it is functioning correctly regardless of whether it has fired yet.

func (*Resource) GuardStatus added in v0.4.0

func (r *Resource) GuardStatus() (concepts.GuardStatusWithReason, error)

GuardStatus evaluates the resource's guard precondition. If no guard was registered, the resource is unconditionally unblocked.

func (*Resource) Identity

func (r *Resource) Identity() string

Identity returns a unique identifier for the CronJob in the format "batch/v1/CronJob/<namespace>/<name>".

func (*Resource) MetricsIdentifier added in v0.20.0

func (r *Resource) MetricsIdentifier() string

MetricsIdentifier returns the identifier set with Builder.WithMetricsIdentifier, or an empty string when none was set, in which case the framework labels the resource with its lowercased kind. It satisfies concepts.MetricsIdentifiable.

func (*Resource) Mutate

func (r *Resource) Mutate(current client.Object) error

Mutate transforms the current state of a Kubernetes CronJob into the desired state.

The mutation process follows a specific order:

  1. Feature Mutations: All registered feature-based mutations are applied.
  2. Suspension: If the resource is in a suspending state, the suspension logic (setting spec.suspend = true) is applied.

func (*Resource) Object

func (r *Resource) Object() (client.Object, error)

Object returns a copy of the underlying Kubernetes CronJob object.

func (*Resource) Preview added in v0.11.0

func (r *Resource) Preview() (client.Object, error)

Preview renders the CronJob as a client.Object with feature mutations applied, without modifying the resource's internal state. It satisfies the component's Previewable capability so the component can assemble a cluster-free preview.

Suspension mutations are not applied; the preview reflects content state only. Callers needing the concrete type can type-assert the returned object.

func (*Resource) ProducedData added in v0.18.0

func (r *Resource) ProducedData() []concepts.DataCell

ProducedData returns the cells this CronJob declares extractions into. It satisfies concepts.DataProducer for component topology validation and introspection.

func (*Resource) RecordObservation added in v0.9.1

func (r *Resource) RecordObservation(observed client.Object) error

RecordObservation stores the supplied object as the resource's most recently observed cluster state. The framework invokes this on read-only resources after fetching them so that declared data extractions observe the live object rather than the inert base used to construct the resource.

func (*Resource) RegisteredMutations added in v0.14.0

func (r *Resource) RegisteredMutations() []string

RegisteredMutations returns the deduplicated Names of every mutation registered on the CronJob, independent of version. It satisfies concepts.MutationInspector so the resource can be introspected for version-matrix golden generation.

func (*Resource) Suspend

func (r *Resource) Suspend() error

Suspend triggers the suspension of the CronJob.

It registers a mutation that will be executed during the next Mutate call. The default behavior sets spec.suspend to true.

func (*Resource) SuspensionStatus

func (r *Resource) SuspensionStatus() (concepts.SuspensionStatusWithReason, error)

SuspensionStatus monitors the progress of the suspension process.

By default, it uses DefaultSuspensionStatusHandler, which reports Suspended when spec.suspend is true and no active jobs are running.

Jump to

Keyboard shortcuts

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