controller

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RequeueOnRefreshTimeout       = time.Second
	RequeueProbePoll              = 5 * time.Second
	LoadReplicaStateTimeout       = 10 * time.Second
	WarningsPollInterval          = 30 * time.Second
	TLSFileMode             int32 = 0444
	DefaultUser             int64 = 101
)
View Source
const (
	DefaultProbeCPULimit      = "1"
	DefaultProbeCPURequest    = "250m"
	DefaultProbeMemoryLimit   = "256Mi"
	DefaultProbeMemoryRequest = "256Mi"
)
View Source
const KeeperClusterReferenceField = "clickhouse.com/keeperClusterReference"

KeeperClusterReferenceField indexes ClickHouseClusters by their referenced KeeperCluster "namespace/name". Registered by the ClickHouse controller setup; the Keeper controller requires it on the same manager.

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 readiness 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 ContainerTemplateSpec onto an operator-generated Container via SMP. Inputs are treated as read-only.

VolumeMounts are appended; same-path merging is handled by ProjectVolumes. SecurityContext and probes are pre-cleared on base before SMP so a non-nil user value fully replaces the operator default — deep-merging Capabilities would otherwise leave operator-defaulted Add survivors under user Drop:[ALL], breaking `restricted` PodSecurity.

func ApplyPodTemplateOverrides added in v0.0.4

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

ApplyPodTemplateOverrides merges PodTemplateSpec onto an operator-generated PodSpec via SMP. Inputs are treated as read-only.

Volumes (replaced by name) and Affinity (term lists concatenated) are merged manually and excluded from the patch. A non-nil SecurityContext fully replaces the default, see ApplyContainerTemplateOverrides for the rationale.

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(reloadErr, notUpdated, notReloaded []string) metav1.Condition

ConfigSyncCondition evaluates ConfigurationInSync.

func ContainerRunning added in v0.0.8

func ContainerRunning(pod *corev1.Pod, name string) bool

ContainerRunning reports whether the named container is currently running, regardless of readiness.

func DefaultContainerSecurityContext added in v0.0.5

func DefaultContainerSecurityContext() *corev1.SecurityContext

DefaultContainerSecurityContext returns the operator's default container-level SecurityContext.

func DefaultPodSecurityContext added in v0.0.5

func DefaultPodSecurityContext() *corev1.PodSecurityContext

DefaultPodSecurityContext returns the operator's default PodSecurityContext. It generates different defaults for OpenShift installations, so default settings conform restricted-v2.

func DesiredPVCs added in v0.0.6

func DesiredPVCs(dataVolumeClaimSpec *corev1.PersistentVolumeClaimSpec, additional []v1.PersistentVolumeClaimTemplate) map[string]*corev1.PersistentVolumeClaim

DesiredPVCs returns the desired PVCs (spec only) keyed by volumeClaimTemplate name.

func GetReplicaPod added in v0.0.8

func GetReplicaPod(ctx context.Context, log util.Logger, client client.Client, sts *appsv1.StatefulSet) (*corev1.Pod, error)

GetReplicaPod loads the Pod of the given StatefulSet.

func HealthyCondition added in v0.0.4

func HealthyCondition(notReadyIDs []string) metav1.Condition

HealthyCondition evaluates Healthy.

func ListReplicaResources added in v0.0.6

func ListReplicaResources[
	ID comparable,
	Res client.Object,
	RList client.ObjectList,
](ctx context.Context, rm *ResourceManager, labelToID func(map[string]string) (ID, error)) (map[ID]Res, error)

ListReplicaResources lists the resources for replicas and maps them to replica IDs using the provided labelToID function.

func PVCRevisions added in v0.0.6

func PVCRevisions(pvcs map[string]*corev1.PersistentVolumeClaim) (map[string]string, error)

PVCRevisions computes the desired spec revision for each PVC, keyed by name.

func PodConditionTrue added in v0.0.8

func PodConditionTrue(pod *corev1.Pod, conditionType corev1.PodConditionType) bool

PodConditionTrue reports whether the Pod condition is true.

func PodStartupError added in v0.0.8

func PodStartupError(pod *corev1.Pod) *string

PodStartupError reports a non-empty description if Pod experiences startup errors.

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(startupErrors map[string]string) metav1.Condition

ReplicaStartupCondition evaluates ReplicaStartupSucceeded.

func RolePeer added in v0.0.8

func RolePeer(role string) networkingv1.NetworkPolicyPeer

RolePeer matches pods carrying the given clickhouse.com/role label in any namespace.

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.

func TCPPorts added in v0.0.8

func TCPPorts(ports ...int32) []networkingv1.NetworkPolicyPort

TCPPorts builds NetworkPolicy port entries for the given TCP ports.

func UserMountsAt added in v0.0.6

func UserMountsAt(mounts []corev1.VolumeMount, path string) bool

UserMountsAt reports whether any of the given mounts targets path.

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 Dependencies added in v0.0.8

type Dependencies struct {
	Logger  controllerutil.Logger
	Checker *upgrade.Checker
	Dialer  controllerutil.DialContextFunc
}

Dependencies holds the runtime objects shared by the controllers, replaceable in tests.

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,
	version string,
	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(
	version string,
	replicaVersions map[string]string,
	isUpdating bool,
) (metav1.Condition, []EventSpec)

GetVersionSyncCondition evaluates the VersionInSync condition by comparing the known cluster version against the versions reported by replicas. The version must be known; the "version unavailable" states are reported by the caller.

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,omitempty"`
	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 ReplicaResources added in v0.0.8

type ReplicaResources struct {
	STS  *appsv1.StatefulSet
	CFG  *corev1.ConfigMap
	PVCs map[string]*corev1.PersistentVolumeClaim
}

ReplicaResources holds resources owned by a single replica.

func (ReplicaResources) StatefulSetUpdated added in v0.0.8

func (s ReplicaResources) StatefulSetUpdated() bool

StatefulSetUpdated checks whether StatefulSet controller applied updates.

type ReplicaState added in v0.0.6

type ReplicaState struct {
	ReplicaResources

	Pod          *corev1.Pod
	StartupError *string
}

ReplicaState holds the observed state of a single replica.

type ReplicaUpdateInput added in v0.0.3

type ReplicaUpdateInput struct {
	Revisions RevisionState
	Existing  ReplicaState
	Desired   ReplicaResources
}

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 clusterOwner) 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) GetReplicaPVCs added in v0.0.6

GetReplicaPVCs returns the StatefulSet's PVCs keyed by disk name, matched by disk label.

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) UpdatePodCondition added in v0.0.8

func (rm *ResourceManager) UpdatePodCondition(ctx context.Context, pod *corev1.Pod, cond corev1.PodCondition) error

UpdatePodCondition patches a condition in the Pod status.

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. When CachedRevision matches the current image hash and CachedVersion is non-empty, returns the cached version immediately without creating or reading a Job.

type RevisionState added in v0.0.4

type RevisionState struct {
	StatefulSetRevision string

	ConfigurationRevision string
	// RestartConfigRevision is a partial revision of config that requires server restart.
	RestartConfigRevision string
	// ReloadConfigRevision is a partial revision of config that can be reloaded in runtime.
	ReloadConfigRevision string

	PVCRevisions map[string]string
}

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

func (RevisionState) ReplicaHasDiff added in v0.0.4

func (rev RevisionState) ReplicaHasDiff(state ReplicaResources) bool

ReplicaHasDiff checks whether any replica resources should be updated.

type Settings added in v0.0.8

type Settings struct {
	EnablePDB               bool
	EnableNetworkPolicy     bool
	ResyncPeriod            time.Duration
	MaxConcurrentReconciles int
}

Settings holds the reconciliation behavior knobs shared by the controllers.

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 {
	// 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
	// CachedVersion is the previously detected version stored in CR Status.
	CachedVersion string
	// CachedRevision is the image hash that produced CachedVersion.
	CachedRevision string
}

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
	// RetryAfter is the remaining cooldown before a failed probe Job is recreated.
	RetryAfter time.Duration
	// Revision is the image hash of the probe, set on successful completion.
	Revision string
}

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