operator

package
v0.2.12 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 39 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package operator adapts the Altinity clickhouse-operator configuration generators, schema managers, and SQL client to chinit's domain ports.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoUsersSection = fmt.Errorf("spec has no users section")

ErrNoUsersSection reports that the spec declares no users section at all. Callers composing the users render with other renders (render -node) treat it as a benign skip — the generator's own users-group files already cover a spec without a users section.

Functions

func ExpectedTablesFromCR

func ExpectedTablesFromCR(cr any) []domain.TableRef

ExpectedTablesFromCR derives the tables the spec declares from the normalized CR's files section: every files entry ending in .sql is schema DDL (the operator's own initdb pattern — SQL files mounted into /docker-entrypoint-initdb.d), and every table/view/dictionary object created there is a table the cluster is expected to hold after schema sync.

Why the files section: the CHI CR has no dedicated table/DDL declaration — specs that create schema carry .sql files (the same pattern docs/chi-examples/20-engines-01 uses), and the stack's chctl-based bootstrap relies on schema sync from peers; the check verifies the RESULT matches what the spec intends.

Types

type ConfigRenderer

type ConfigRenderer struct{}

ConfigRenderer implements port.ConfigRenderer over the operator's config file generators — the same code that produces ConfigMaps on Kubernetes.

func NewConfigRenderer

func NewConfigRenderer() *ConfigRenderer

NewConfigRenderer builds the operator-backed renderer.

func (*ConfigRenderer) RenderCHI

func (r *ConfigRenderer) RenderCHI(ctx context.Context, request port.RenderCHIRequest) ([]port.RenderedFile, error)

RenderCHI writes the common, users and (when a host is selected) host config files for a normalized CHI.

Why the generator (not hand-written templates): the operator's normalizer defaults, section naming, and user hardening apply identically off-cluster, and any generator improvement is inherited automatically.

Without it: every deployment hand-maintains its own XML templates, which drift from ClickHouse LTS behavior and from each other.

func (*ConfigRenderer) RenderCHK

func (r *ConfigRenderer) RenderCHK(ctx context.Context, request port.RenderCHKRequest) ([]port.RenderedFile, error)

RenderCHK writes the common and host config files for a normalized CHK.

Why: keeper nodes need identical config discipline (raft, TLS, prometheus endpoint); reusing the keeper generator keeps keeper configs on the same single-source footing.

Single-file mode: when request.SingleFilePath is set, no per-group files are written to OutputDir — instead the common and host sections merge into ONE complete <clickhouse>-rooted document at the given path. Cloud stacks run clickhouse-keeper with an explicit --config=keeper_config.xml, which disables the config.d auto-include; those nodes need the whole configuration in a single file.

type HealthProbe

type HealthProbe struct{}

HealthProbe implements port.ClusterHealthProbe over the operator's clickhouse cluster client — the same connection machinery the schemer paths use (ClusterConnectionParams over the cloud inventory address, QueryAny against one host). All SQL lives here; the service layer only sees rows and errors.

func NewHealthProbe

func NewHealthProbe() *HealthProbe

NewHealthProbe builds the operator-backed cluster health probe.

func (*HealthProbe) PingHost

PingHost answers whether the host serves SQL (SELECT 1 over the driver's real connection path — the same probe the pool uses). PingHost implements port.ClusterHealthProbe.PingHost.

func (*HealthProbe) QueryReplicas

func (p *HealthProbe) QueryReplicas(ctx context.Context, request port.HealthReplicasRequest) ([]port.HealthReplicaRow, error)

QueryReplicas reads replication state across the cluster from the run-on host.

func (*HealthProbe) QueryTables

func (p *HealthProbe) QueryTables(ctx context.Context, request port.HealthTablesRequest) ([]domain.TableRef, error)

QueryTables reads existing table names on one host.

func (*HealthProbe) QueryVersion

func (p *HealthProbe) QueryVersion(ctx context.Context, request port.HealthPingRequest) (string, error)

QueryVersion implements port.ClusterHealthProbe.QueryVersion: the server binary version over the same connection machinery PingHost uses (the status publisher's input; a failed probe is the caller's degraded answer, never a guess).

type NodeRenderer

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

NodeRenderer implements port.NodeRenderer over the operator-backed ConfigRenderer + UsersRenderer, owning the full install discipline: render → validate → stage → install → own/permission → prune.

func NewNodeRenderer

func NewNodeRenderer(config *ConfigRenderer, users *UsersRenderer) *NodeRenderer

NewNodeRenderer builds the node renderer over the shared renderers.

func (*NodeRenderer) RenderNode

RenderNode renders one node's complete configuration set and installs it with correct ownership and permissions — composing what previously took a host-scoped render, an inventory render and a users render.

Discipline, in order:

- Render every section into memory (nothing on disk yet). - Validate every XML document parses; a malformed section fails the whole run with the section named and NOTHING installed (a bad files: entry used to leave a config.d the server parsed into a boot loop). - Install through a staging directory with atomic renames, chmod the exact mode AFTER write (umask can never soften it) and chown the service account — the chmod/chown the calling stack previously duplicated per site, one site forgetting them being root-owned-0640 crash class. - Prune files this command installed on a previous run but no longer renders (tracked in the manifest), so a renamed or removed spec section stops lingering on re-rendered nodes.

Check mode computes the drift against the installed tree and writes nothing; dry-run reports the plan and writes nothing.

type SchemaClientFactory

type SchemaClientFactory struct{}

SchemaClientFactory implements port.SchemaClientFactory building operator-backed runners.

func NewSchemaClientFactory

func NewSchemaClientFactory() *SchemaClientFactory

NewSchemaClientFactory builds the factory.

func (*SchemaClientFactory) NewClient

NewClient builds a SchemaRunner bound to a cluster's inventory.

Why the normalized CR: the operator's schemer names replicas by walking the CR's cluster/shard tree (GetShard dereferences the CR — hand-built Host values panic in its namer). The CR's normalized hosts carry the full runtime addressing; cloud addresses from the inventory override their FQDNs so connections go where the operator's pod-FQDNs cannot.

type SchemaRunner

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

SchemaRunner implements port.SchemaRunner over the operator's ClusterSchemer.

func (*SchemaRunner) CountRunningMerges

func (r *SchemaRunner) CountRunningMerges(ctx context.Context, request domain.QueueHealRequest) (int, error)

CountRunningMerges returns the node's in-flight merge count used by the queue-heal busy-skip gate.

func (*SchemaRunner) DropReplica

func (r *SchemaRunner) DropReplica(ctx context.Context, request domain.ReplicaDropRequest) error

DropReplica removes a dead replica's Keeper registration (HostDropReplica — SYSTEM DROP REPLICA).

Why not schemer.HostDropReplica directly: it runs the SQL via ExecHost, which resolves the run-on host through the operator's pod-FQDN pattern (chi-...svc.cluster.local) — unresolvable off-cluster.

Replica naming: SYSTEM DROP REPLICA takes the replica_path name that tables were CREATED with. On Kubernetes that is the operator's instance-hostname (chi-<chi>-<cluster>-<s>-<r>); on VM/EC2 stacks it is whatever the deployment's macros.xml declares — the host's cloud name (writer-0, reader-0) in the AWS stack. The inventory name IS the cloud name here, so it is used directly; no guessing between conventions. The DATABASE-replica shard index follows the operator's HostDropReplica (the run-on host's shard index).

func (*SchemaRunner) FindInitFailedReadonlyTables

func (r *SchemaRunner) FindInitFailedReadonlyTables(ctx context.Context, request domain.QueueHealRequest) ([]string, error)

FindInitFailedReadonlyTables returns read-only tables whose replication queue never initialized (last_queue_update at the epoch), which are recovered by setting the flags/force_restore_data znode and restarting the replica.

func (*SchemaRunner) FindOrphanMergeTables

func (r *SchemaRunner) FindOrphanMergeTables(ctx context.Context, request domain.QueueHealRequest) ([]string, error)

FindOrphanMergeTables returns every table with orphan-merge queue entries: a queued MERGE_PARTS whose source part no live replica holds (NO_REPLICA_HAS_PART, StorageReplicatedMergeTree.cpp:2865). The graceful path (fetch-merged-part-instead + enqueuePartForCheck, :2913) only runs when a sibling merge covers the missing part; the throw-path entries exponential-postpone (Queue.cpp:1667, capped at max_postpone_time_for_failed_replicated_merges_ms) and retry forever, each pass blocking merge assignment evaluation on the table. The heal is SYNC REPLICA — re-enqueue the part checks whose PartCheckThread resolves or deletes the lost-part entries (ReplicatedMergeTreePartCheckThread.cpp:180-199: "consider the part lost and delete the entry from the queue").

func (*SchemaRunner) FindReadonlyTables

func (r *SchemaRunner) FindReadonlyTables(ctx context.Context, request domain.QueueHealRequest) ([]string, error)

FindReadonlyTables returns every table on the node whose replica is in read-only mode (Keeper lost quorum or the node lost its Keeper session — writes to those tables fail; the fleet-wide read-only failure class). The restore itself runs via RestartReplica-shaped SYSTEM RESTORE REPLICA.

func (*SchemaRunner) FindStaleReplicas

func (r *SchemaRunner) FindStaleReplicas(ctx context.Context, request domain.ReplicaGcRequest) ([]string, error)

FindStaleReplicas returns host names registered in system.replicas on the run-on peer but absent from live cluster membership (the dead-replica GC detection step).

Without it: stale znodes accumulate after scale-in or spot reclaim and DDL/re-join reliability decays; detection lived in bash that had to be scheduled and parsed separately from the drop it feeds.

func (*SchemaRunner) FindStuckQueueTables

func (r *SchemaRunner) FindStuckQueueTables(ctx context.Context, request domain.QueueHealRequest) ([]string, error)

FindStuckQueueTables returns every table whose replication queue holds an entry past the retry threshold.

func (*SchemaRunner) ReplicaKeeperPathExists

func (r *SchemaRunner) ReplicaKeeperPathExists(ctx context.Context, request domain.QueueHealRequest) (bool, error)

ReplicaKeeperPathExists reports whether the table's replica is registered under its replicas/ path in Keeper. When present, the replica is recovered with SYSTEM RESTART REPLICA; when absent, SYSTEM RESTORE REPLICA re-creates the metadata.

func (*SchemaRunner) RestartReplica

func (r *SchemaRunner) RestartReplica(ctx context.Context, request domain.QueueHealRequest) error

RestartReplica re-initializes a table's replication queue from Keeper (SYSTEM RESTART REPLICA) — the stuck-queue heal. The restart drops the in-memory queue state and re-reads the log from Keeper; parts already written are untouched (the queue's block is the retry loop, not data).

Without it: a NO_REPLICA_HAS_PART entry blocks every merge behind it forever — parts climb to the insert cliff while merges sit idle, and the parts alarm pages a scale-out that cannot help (merge debt is not solved by more replicas).

func (*SchemaRunner) RestoreReplica

func (r *SchemaRunner) RestoreReplica(ctx context.Context, request domain.QueueHealRequest) error

RestoreReplica re-creates a read-only table's replica metadata in Keeper (SYSTEM RESTORE REPLICA — verified in the 26.8 source: restoreMetadataInZooKeeper). The readonly-heal: a table flipped read-only by a lost Keeper session stays read-only until the metadata znode is re-created; the operator's answer is pod recreation, the EC2 analog is this statement (the node keeps its data — the parts catalog re-attaches to the restored metadata).

func (*SchemaRunner) SyncReplica

func (r *SchemaRunner) SyncReplica(ctx context.Context, request domain.ReplicaSyncRequest) error

SyncReplica re-queues replication on a restarted or recovering node using SYSTEM SYNC REPLICA ... LIGHTWEIGHT so replication logs are pulled and data-visibility entries (GET_PART/ATTACH_PART/DROP_*) converge without blocking 300s on background MERGE_PARTS under heavy ingest.

func (*SchemaRunner) SyncSchema

func (r *SchemaRunner) SyncSchema(ctx context.Context, request domain.SchemaSyncRequest) error

SyncSchema creates all replicated and distributed objects on a host from cluster peers (HostCreateTables).

Without it: a scaled-in reader serves queries with missing tables.

type SpanLogStore added in v0.2.6

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

SpanLogStore implements port.SpanLogReader over clickhouse-operator's pooled EndpointConnectionParams / GetPooledDBConnection machinery (the same connection pool MetricsFetcher uses).

func NewSpanLogStore added in v0.2.6

func NewSpanLogStore(cfg SpanLogStoreConfig) *SpanLogStore

NewSpanLogStore constructs a SpanLogStore targeting cfg.Address (defaulting to 127.0.0.1:8123 when omitted).

func (*SpanLogStore) ReadSpans added in v0.2.6

func (s *SpanLogStore) ReadSpans(ctx context.Context, query port.SpanLogQuery) ([]model.RecordedSpan, error)

ReadSpans queries newly flushed spans strictly newer than query.AfterFinishMicros, returning an empty slice when the table has not been materialized yet (Code 60 UNKNOWN_TABLE).

type SpanLogStoreConfig added in v0.2.6

type SpanLogStoreConfig struct {
	Address     string
	HTTPPort    int
	Secure      bool
	Credentials domain.Credentials
}

SpanLogStoreConfig configures SpanLogStore's local ClickHouse endpoint.

type SpecLoader

type SpecLoader struct{}

SpecLoader implements port.SpecLoader over the operator's normalizer.

func NewSpecLoader

func NewSpecLoader() *SpecLoader

NewSpecLoader builds the operator-backed spec loader.

func (*SpecLoader) LoadCHI

func (l *SpecLoader) LoadCHI(ctx context.Context, request port.LoadCHIRequest) (any, error)

LoadCHI parses, defaults and runtime-wires a CHI spec document.

Why: rendering configs and running schemer operations require a *normalized* CR — the raw parsed spec has nil runtime addresses and panics inside the config generator's host-naming lookups.

Without it: every consumer would re-derive the normalizer bootstrap order and drift from the operator's on-cluster behavior.

func (*SpecLoader) LoadCHK

func (l *SpecLoader) LoadCHK(ctx context.Context, request port.LoadCHKRequest) (any, error)

LoadCHK parses, defaults and runtime-wires a CHK spec document.

type SpecRejectedError

type SpecRejectedError struct {
	// Errors are the normalizer's status errors.
	Errors []string
}

SpecRejectedError marks a spec the normalizer refused (e.g. the RemovedSecretRefSyntax hardening).

func (*SpecRejectedError) Error

func (e *SpecRejectedError) Error() string

Error implements error.

type UsersRenderer

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

UsersRenderer implements port.UsersRenderer: builds the users.d XML from the normalized CR's user settings, resolving password references via the SecretsResolver and hashing to password_sha256_hex.

Spec convention (cloud-agnostic): a user's password is declared as

passwordFrom: <secret-name>[/<field>]

(e.g. "example-admin-password" or "myapp/creds/admin"). The renderer resolves it through the injected resolver (AWS Secrets Manager, Key Vault, ...), SHA-256-hashes the value, and writes password_sha256_hex — plaintext never lands in spec, state, or XML.

Why not the operator's env-var substitution path: it wires Secret values into POD env vars (AppendAdditionalEnvVar) — meaningless off-cluster. The cloud-secret reference + SecretSource port is the off-cluster equivalent of the operator's secretKeyRef discipline.

func NewUsersRenderer

func NewUsersRenderer(secrets port.SecretsResolver) *UsersRenderer

NewUsersRenderer builds the renderer over a secrets resolver.

func (*UsersRenderer) RenderUsers

func (r *UsersRenderer) RenderUsers(ctx context.Context, request port.RenderUsersRequest) ([]port.RenderedFile, error)

RenderUsers writes the users.d XML for a normalized CHI.

Without it: user/password management stays hand-written bash XML (configure_users, 106 lines) with plaintext hashes assembled in shell.

Jump to

Keyboard shortcuts

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