controller

package
v0.0.4 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	RequeueOnRefreshTimeout       = time.Second
	LoadReplicaStateTimeout       = 10 * time.Second
	TLSFileMode             int32 = 0444
	DefaultUser             int64 = 101
)
View Source
const (
	DefaultProbeCPULimit      = "1"
	DefaultProbeCPURequest    = "250m"
	DefaultProbeMemoryLimit   = "1Gi"
	DefaultProbeMemoryRequest = "256Mi"
)

Variables

View Source
var (
	// DefaultLivenessProbeSettings defines default settings for Kubernetes liveness probes.
	//nolint: mnd // Magic numbers are used as constants.
	DefaultLivenessProbeSettings = corev1.Probe{
		InitialDelaySeconds: 60,
		TimeoutSeconds:      10,
		PeriodSeconds:       5,
		FailureThreshold:    10,
		SuccessThreshold:    1,
	}

	// DefaultReadinessProbeSettings defines default settings for Kubernetes liveness probes.
	//nolint: mnd // Magic numbers are used as constants.
	DefaultReadinessProbeSettings = corev1.Probe{
		InitialDelaySeconds: 5,
		TimeoutSeconds:      10,
		PeriodSeconds:       1,
		SuccessThreshold:    5,
		FailureThreshold:    10,
	}
)

Functions

func ApplyContainerTemplateOverrides added in v0.0.4

func ApplyContainerTemplateOverrides(container *corev1.Container, t *v1.ContainerTemplateSpec) (corev1.Container, error)

ApplyContainerTemplateOverrides merges the user-provided ContainerTemplateSpec onto an operator-generated Container using strategic merge patch with corev1.Container semantics. t is treated as read-only; it is only marshaled, never written to. VolumeMounts are handled separately to allow multiple mounts at the same path; handled by ProjectVolumes.

func ApplyPodTemplateOverrides added in v0.0.4

func ApplyPodTemplateOverrides(podSpec *corev1.PodSpec, t *v1.PodTemplateSpec) (corev1.PodSpec, error)

ApplyPodTemplateOverrides merges the user-provided PodTemplateSpec onto an operator-generated PodSpec using strategic merge patch with corev1.PodSpec semantics. t is treated as read-only; it is only marshaled, never written to.

Volumes and Affinity are handled manually before SMP and excluded from the patch:

  • Volumes are replaced by name
  • Affinity term lists are concatenated.

func CheckPodError

func CheckPodError(ctx context.Context, log util.Logger, client client.Client, sts *appsv1.StatefulSet) (bool, error)

CheckPodError checks if the pod of the given StatefulSet have permanent errors preventing it from starting.

func ClusterSizeCondition added in v0.0.4

func ClusterSizeCondition(existing, expected int) metav1.Condition

ClusterSizeCondition evaluates ClusterSizeAligned.

func ConfigSyncCondition added in v0.0.4

func ConfigSyncCondition(notUpdatedIDs []string) metav1.Condition

ConfigSyncCondition evaluates ConfigurationInSync.

func HealthyCondition added in v0.0.4

func HealthyCondition(notReadyIDs []string) metav1.Condition

HealthyCondition evaluates Healthy.

func ProjectVolumes

func ProjectVolumes(volumes []corev1.Volume, volumeMounts []corev1.VolumeMount) ([]corev1.Volume, []corev1.VolumeMount, error)

ProjectVolumes replaces volumes with the same mount path with a single projected volume.

func ReplicaStartupCondition added in v0.0.4

func ReplicaStartupCondition(errorIDs []string) metav1.Condition

ReplicaStartupCondition evaluates ReplicaStartupSucceeded.

func RunSteps added in v0.0.4

func RunSteps(ctx context.Context, log controllerutil.Logger, steps []ReconcileStep) (ctrl.Result, error)

RunSteps executes reconciliation steps sequentially with flow control. Blocked steps cause non-Always successors to be skipped. Returns the accumulated ctrl.Result (minimum RequeueAfter across all steps). On the first error, RunSteps returns immediately with that error.

func SetStatusCondition added in v0.0.4

func SetStatusCondition(conditions *[]metav1.Condition, newCondition metav1.Condition) bool

SetStatusCondition sets the given condition in conditions and returns true if the condition was changed. LastTransitionTime is updated only when Status changes, per Kubernetes conventions.

Types

type Controller added in v0.0.4

type Controller interface {
	GetClient() client.Client
	GetScheme() *runtime.Scheme
	GetRecorder() events.EventRecorder
}

Controller provides access to shared Kubernetes dependencies.

type EventSpec added in v0.0.4

type EventSpec struct {
	Type    string
	Reason  v1.EventReason
	Action  v1.EventAction
	Message string
}

EventSpec defines the specification for an event to be emitted when a condition transitions.

func GetUpgradeCondition added in v0.0.4

func GetUpgradeCondition(
	checker upgrade.Checker,
	probe VersionProbeResult,
	upgradeChannel string,
) (metav1.Condition, []EventSpec)

GetUpgradeCondition checks for available upgrades and returns the VersionUpgraded condition to set. Returns current condition and optional EventSpec that should be recorded if condition Status changed.

func GetVersionSyncCondition added in v0.0.4

func GetVersionSyncCondition(
	probe VersionProbeResult,
	replicaVersions map[string]string,
	isUpdating bool,
) (metav1.Condition, []EventSpec)

GetVersionSyncCondition evaluates the VersionInSync condition based on the probe result and replica versions. Returns current condition and optional EventSpec that should be recorded if condition Status changed.

type LoggerConfig

type LoggerConfig struct {
	Console    bool   `yaml:"console"`
	Level      string `yaml:"level"`
	Formatting struct {
		Type string `yaml:"type"`
	} `yaml:"formatting,omitempty"`
	// File logging settings
	Log      string `yaml:"log,omitempty"`
	ErrorLog string `yaml:"errorlog,omitempty"`
	Size     string `yaml:"size,omitempty"`
	Count    int64  `yaml:"count,omitempty"`
}

LoggerConfig represents the logger configuration in YAML format.

func GenerateLoggerConfig

func GenerateLoggerConfig(spec v1.LoggerConfig, basePath string, service string) LoggerConfig

GenerateLoggerConfig generates a LoggerConfig from the given LoggerConfig spec.

type OpenSSLConfig

type OpenSSLConfig struct {
	Server OpenSSLParams `yaml:"server,omitempty"`
	Client OpenSSLParams `yaml:"client,omitempty"`
}

OpenSSLConfig represents the server OpenSSL configuration in YAML format.

type OpenSSLParams

type OpenSSLParams struct {
	CertificateFile     string `yaml:"certificateFile"`
	PrivateKeyFile      string `yaml:"privateKeyFile"`
	CAConfig            string `yaml:"caConfig"`
	VerificationMode    string `yaml:"verificationMode"`
	DisableProtocols    string `yaml:"disableProtocols"`
	PreferServerCiphers bool   `yaml:"preferServerCiphers"`
}

OpenSSLParams represents OpenSSL parameters in YAML format.

type PrometheusConfig

type PrometheusConfig struct {
	Endpoint            string `yaml:"endpoint"`
	Port                uint16 `yaml:"port"`
	Metrics             bool   `yaml:"metrics"`
	Events              bool   `yaml:"events"`
	AsynchronousMetrics bool   `yaml:"asynchronous_metrics"`
}

PrometheusConfig represents the Prometheus configuration in YAML format.

func DefaultPrometheusConfig

func DefaultPrometheusConfig(port uint16) PrometheusConfig

DefaultPrometheusConfig returns the default Prometheus configuration for the given port.

type ReconcileStep added in v0.0.4

type ReconcileStep struct {
	// Name is used for logging.
	Name string
	// Fn is the step function.
	Fn func(context.Context, controllerutil.Logger) (StepResult, error)
	// Always makes the step run even when the pipeline is blocked by a prior step.
	Always bool
}

ReconcileStep defines a single step in the reconciliation pipeline.

type ReplicaUpdateInput added in v0.0.3

type ReplicaUpdateInput struct {
	Revisions RevisionState

	DesiredConfigMap *corev1.ConfigMap

	ExistingSTS        *appsv1.StatefulSet
	DesiredSTS         *appsv1.StatefulSet
	HasError           bool
	BreakingSTSVersion semver.Version

	ExistingPVC    *corev1.PersistentVolumeClaim
	DesiredPVCSpec *corev1.PersistentVolumeClaimSpec
}

ReplicaUpdateInput contains the parameters needed to reconcile a StatefulSet for a replica.

type ReplicaUpdateStage

type ReplicaUpdateStage int

ReplicaUpdateStage represents the stage of updating a ClickHouse replica. Used in reconciliation process.

const (
	StageUpToDate ReplicaUpdateStage = iota
	StageHasDiff
	StageNotReadyUpToDate
	StageUpdating
	StageError
	StageNotExists
)

func (ReplicaUpdateStage) String

func (s ReplicaUpdateStage) String() string

type ResourceManager added in v0.0.4

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

ResourceManager provides Kubernetes resource modification helpers.

func NewResourceManager added in v0.0.4

func NewResourceManager(
	ctrl Controller,
	owner interface {
		client.Object
		SpecificName() string
	},
) ResourceManager

NewResourceManager creates a new ResourceManager instance.

func (*ResourceManager) Create added in v0.0.4

func (rm *ResourceManager) Create(ctx context.Context, resource client.Object, action v1.EventAction) error

Create creates the given Kubernetes resource and emits events on failure.

func (*ResourceManager) Delete added in v0.0.4

func (rm *ResourceManager) Delete(ctx context.Context, resource client.Object, action v1.EventAction, opts ...client.DeleteOption) error

Delete deletes the given Kubernetes resource and emits events on failure.

func (*ResourceManager) GetPVCByStatefulSet added in v0.0.4

func (rm *ResourceManager) GetPVCByStatefulSet(
	ctx context.Context,
	log util.Logger,
	sts *appsv1.StatefulSet,
) (*corev1.PersistentVolumeClaim, error)

GetPVCByStatefulSet returns the PersistentVolumeClaim created by given StatefulSet.

func (*ResourceManager) ReconcileConfigMap added in v0.0.4

func (rm *ResourceManager) ReconcileConfigMap(
	ctx context.Context,
	log util.Logger,
	configMap *corev1.ConfigMap,
	action v1.EventAction,
) (bool, error)

ReconcileConfigMap reconciles a Kubernetes ConfigMap resource.

func (*ResourceManager) ReconcilePodDisruptionBudget added in v0.0.4

func (rm *ResourceManager) ReconcilePodDisruptionBudget(
	ctx context.Context,
	log util.Logger,
	pdb *policyv1.PodDisruptionBudget,
	action v1.EventAction,
) (bool, error)

ReconcilePodDisruptionBudget reconciles a Kubernetes PodDisruptionBudget resource.

func (*ResourceManager) ReconcileReplicaResources added in v0.0.4

func (rm *ResourceManager) ReconcileReplicaResources(
	ctx context.Context,
	log util.Logger,
	input ReplicaUpdateInput,
) (*ctrlruntime.Result, error)

ReconcileReplicaResources reconciles a replica's ConfigMap, StatefulSet and PVC. Handling Pod restarts on config changes.

func (*ResourceManager) ReconcileResource added in v0.0.4

func (rm *ResourceManager) ReconcileResource(
	ctx context.Context,
	log util.Logger,
	resource client.Object,
	specFields []string,
	action v1.EventAction,
) (bool, error)

ReconcileResource reconciles a Kubernetes resource by comparing spec hashes.

func (*ResourceManager) ReconcileService added in v0.0.4

func (rm *ResourceManager) ReconcileService(
	ctx context.Context,
	log util.Logger,
	service *corev1.Service,
	action v1.EventAction,
) (bool, error)

ReconcileService reconciles a Kubernetes Service resource.

func (*ResourceManager) Update added in v0.0.4

func (rm *ResourceManager) Update(ctx context.Context, resource client.Object, action v1.EventAction) error

Update updates the given Kubernetes resource and emits events on failure.

func (*ResourceManager) UpdatePVC added in v0.0.4

func (rm *ResourceManager) UpdatePVC(ctx context.Context, log util.Logger, input ReplicaUpdateInput) error

UpdatePVC updates the PersistentVolumeClaim for the given replica ID if it exists and differs from the provided spec.

func (*ResourceManager) VersionProbe added in v0.0.4

VersionProbe manages a one-time Job to detect the version from a container image. Returns the version string when available, or empty string if the Job is pending/running.

type RevisionState added in v0.0.4

type RevisionState struct {
	StatefulSetRevision   string
	ConfigurationRevision string
	PVCRevision           string
	HasPVCSpec            bool
}

RevisionState holds the target revision hashes for comparing replica state against desired state. Constructed by the reconciler from cached revision fields and passed to replicaState methods.

func (RevisionState) ReplicaHasDiff added in v0.0.4

func (rev RevisionState) ReplicaHasDiff(sts *appsv1.StatefulSet, pvc *corev1.PersistentVolumeClaim) bool

ReplicaHasDiff checks whether a StatefulSet and optional PVC match the target revisions.

type StatusManager added in v0.0.4

type StatusManager[S any, SP clusterStatus[S], C clusterObject[S, SP]] struct {
	// contains filtered or unexported fields
}

StatusManager provides generic status/condition management for cluster reconcilers. S is the concrete status struct (e.g., ClickHouseClusterStatus). SP is the pointer-to-status type satisfying clusterStatus[S].

func NewStatusManager added in v0.0.4

func NewStatusManager[S any, SP clusterStatus[S], C clusterObject[S, SP]](
	ctrl Controller,
	cluster C,
) StatusManager[S, SP, C]

NewStatusManager creates a new StatusManager instance.

func (*StatusManager[S, SP, C]) SetCondition added in v0.0.4

func (r *StatusManager[S, SP, C]) SetCondition(cond metav1.Condition, event ...EventSpec)

SetCondition sets a single condition in the CRD status conditions. If event is set it is emitted during UpsertStatus only if the condition actually transitions.

func (*StatusManager[S, SP, C]) SetConditions added in v0.0.4

func (r *StatusManager[S, SP, C]) SetConditions(conditions []metav1.Condition)

SetConditions sets the given conditions in the CRD status conditions. ObservedGeneration is filled automatically from the cluster object.

func (*StatusManager[S, SP, C]) SetUnknownConditions added in v0.0.4

func (r *StatusManager[S, SP, C]) SetUnknownConditions(cr v1.ConditionReason, m string, cts []v1.ConditionType)

SetUnknownConditions sets the given condition types to Unknown.

func (*StatusManager[S, SP, C]) UpsertStatus added in v0.0.4

func (r *StatusManager[S, SP, C]) UpsertStatus(ctx context.Context, log util.Logger) error

UpsertStatus upserts the current status of the cluster into the CRD status. Emits scheduled events of changed conditions.

type StepResult added in v0.0.4

type StepResult struct {
	// RequeueAfter requests the reconciler to requeue after the given duration.
	RequeueAfter time.Duration
	// Blocked prevents subsequent sequential steps from running in this reconciliation.
	Blocked bool
}

StepResult controls reconciliation flow after a step completes without error.

func StepBlocked added in v0.0.4

func StepBlocked(d time.Duration) StepResult

StepBlocked indicates the step is waiting for an external dependency. Subsequent sequential steps will be skipped; steps marked Always still run.

func StepContinue added in v0.0.4

func StepContinue() StepResult

StepContinue indicates the step completed successfully with no further action.

func StepRequeue added in v0.0.4

func StepRequeue(d time.Duration) StepResult

StepRequeue indicates the step completed but the cluster needs more work on the next reconcile.

func (StepResult) IsZero added in v0.0.4

func (s StepResult) IsZero() bool

IsZero returns true if the step result requires no requeue and is not blocked.

type VersionProbeConfig added in v0.0.3

type VersionProbeConfig struct {
	// Name of the binary to run.
	Binary string
	// Labels to apply to the Job, inherited from the cluster spec.
	Labels map[string]string
	// Annotations to apply to the Job, inherited from the cluster spec.
	Annotations map[string]string
	// PodTemplate to apply to the Job, inherited from the cluster spec.
	PodTemplate v1.PodTemplateSpec
	// ContainerTemplate to apply to the Job, inherited from the cluster spec.
	ContainerTemplate v1.ContainerTemplateSpec
	// VersionProbe is the user-provided override for the version probe Job.
	VersionProbe *v1.VersionProbeTemplate
}

VersionProbeConfig holds parameters for the version probe Job.

type VersionProbeResult added in v0.0.3

type VersionProbeResult struct {
	// Version is the detected version string, empty if not yet available.
	Version string
	// Pending is true when the Job is still running or being created.
	Pending bool
	// Err if version probe failed it contains the error.
	Err error
}

VersionProbeResult holds the outcome of a version probe reconciliation.

func (*VersionProbeResult) Completed added in v0.0.4

func (r *VersionProbeResult) Completed() bool

Completed returns true if probe completed successfully with a detected version, false otherwise.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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