From 3b48c09dd8217af589306222afc42d372a998b19 Mon Sep 17 00:00:00 2001 From: Pervakov Grigorii Date: Tue, 1 Dec 2026 15:57:59 +0000 Subject: [PATCH] feat: drop and restore replica keeper metadata during horizontal scaling --- api/v1alpha1/conditions.go | 8 +- docs/guides/configuration.mdx | 2 +- docs/guides/scaling.mdx | 8 +- go.mod | 2 +- internal/controller/clickhouse/commands.go | 480 +++++++++++++----- .../controller/clickhouse/commands_test.go | 205 +++++++- .../controller/clickhouse/conncache_test.go | 4 +- internal/controller/clickhouse/schemasync.go | 45 +- .../controller/clickhouse/schemasync_test.go | 25 +- internal/controller/clickhouse/sync.go | 12 +- test/e2e/clickhouse_e2e_test.go | 143 ++++++ 11 files changed, 777 insertions(+), 157 deletions(-) diff --git a/api/v1alpha1/conditions.go b/api/v1alpha1/conditions.go index ffdf70179..1daedf8f1 100644 --- a/api/v1alpha1/conditions.go +++ b/api/v1alpha1/conditions.go @@ -71,9 +71,10 @@ const ( // ClickHouseCluster specific condition types and reasons. const ( - // ClickHouseConditionTypeSchemaInSync indicates that databases were created on all new replicas and deleted - // replicas metadata was removed. This condition indicates that newly created replicas are ready to use or cluster - // should operate normally after scale down, but it does not mean that all replicas have the same schema. + // ClickHouseConditionTypeSchemaInSync indicates that joining replicas registered all replicated + // databases and tables and caught up on the replicated schema before being opened to client traffic, + // and that removed replicas were deregistered from Keeper. It does not mean that all replicas + // have the same schema or data: only Replicated databases are kept in sync. ClickHouseConditionTypeSchemaInSync ConditionType = "SchemaInSync" ClickHouseConditionSchemaSyncDisabled ConditionReason = "SchemaSyncDisabled" @@ -81,6 +82,7 @@ const ( ClickHouseConditionDatabasesNotCreated ConditionReason = "DatabasesNotCreated" ClickHouseConditionDefaultDatabaseNotReplicated ConditionReason = "DefaultDatabaseNotReplicated" ClickHouseConditionReplicasNotCleanedUp ConditionReason = "ReplicasNotCleanedUp" + ClickHouseConditionReplicaRestorePending ConditionReason = "ReplicaRestorePending" // ClickHouseConditionTypeExternalSecretValid indicates whether the externally managed Secret contains all required keys. // This condition is present only when spec.externalSecret is configured; it is removed when externalSecret is unset. diff --git a/docs/guides/configuration.mdx b/docs/guides/configuration.mdx index e3f64e5e1..f73f5b64f 100644 --- a/docs/guides/configuration.mdx +++ b/docs/guides/configuration.mdx @@ -978,7 +978,7 @@ spec: When enabled, the operator synchronizes Replicated and integration tables to new replicas. -Every replica Pod carries the `clickhouse.com/ReplicaInitialized` readiness gate, so a new replica is published through the public headless Service only after the operator completes its initialization: the `default` database is converted to the Replicated engine and the schema is synchronized. Until then, the operator and the other replicas reach it through its internal Service. With `enableDatabaseSync: false`, the operator marks replicas initialized immediately, so readiness follows the container probes alone. +Every replica Pod carries the `clickhouse.com/ReplicaInitialized` readiness gate, so a new replica is published through the public headless Service only after the operator completes its initialization: the `default` database is converted to the Replicated engine, a replica rejoining with its previous volume is re-registered in Keeper, and the schema is synchronized. Until then, the operator and the other replicas reach it through its internal Service. With `enableDatabaseSync: false`, the operator marks replicas initialized immediately, so readiness follows the container probes alone. The operator never drops a populated non-Replicated `default` database. Such a replica still starts serving client traffic after schema preparation, but the cluster reports `SchemaInSync=False` with reason `DefaultDatabaseNotReplicated` until you resolve that database yourself. diff --git a/docs/guides/scaling.mdx b/docs/guides/scaling.mdx index 947f3b2a0..6f1a1127e 100644 --- a/docs/guides/scaling.mdx +++ b/docs/guides/scaling.mdx @@ -29,7 +29,7 @@ spec: ``` On scale up the operator creates the new per-replica StatefulSets, synchronizes the schema to the new replicas (see [Automatic schema sync](#automatic-schema-sync)), and only then lets each new pod become ready for client traffic. -On scale down it removes the surplus StatefulSets and cleans up the stale replicated-database replica registrations the removed replicas left behind. +On scale down it removes the surplus StatefulSets and deletes the removed replicas' Keeper registrations — the `Replicated` database entries and the entries of the `ReplicatedMergeTree` tables in those databases — so a later scale up can reuse the same replica names. For a removed shard only the database entries are deleted. ## Scaling shards {#scaling-shards} @@ -50,7 +50,10 @@ When `spec.settings.enableDatabaseSync` is `true` (the default), the operator ke - **On scale up** — the operator replicates the database definitions of the replicas already serving client traffic to the newly created replicas, so a fresh replica joins with the same `Replicated` and integration databases as the rest of the cluster. Before any replica serves traffic, for example on cluster creation, the definitions of all reachable replicas are merged. Replicas that already serve traffic are never changed, so create databases with `ON CLUSTER` to have them on every replica. While replicas that served traffic exist but none of them is reachable, new replicas wait. -- **On scale down** — once a replica is gone, the operator drops its registration from each `Replicated` database with `SYSTEM DROP DATABASE REPLICA`, so the shrunk cluster does not wait on a `Replicated` database replica that no longer exists. +A joining replica is held out of client traffic until it has caught up on the replicated schema; table data keeps replicating afterwards. A replica that rejoins with its previous volume is re-registered through `SYSTEM RESTORE DATABASE REPLICA` and `SYSTEM RESTORE REPLICA`, reusing the data it already holds, unless the database or table was dropped from the cluster meanwhile. Such leftovers stay read-only on the replica, which still serves client traffic, and the operator logs a warning naming them; drop them there, since they fail the shard sync that precedes a scale down. +Its local parts that the other replicas no longer have, for example merged, deleted, or never replicated ones, stay in the table's `detached` directory. The operator never deletes them, since they may hold the only copy of rows that were never replicated; inspect them in `system.detached_parts` and remove them with `ALTER TABLE ... DROP DETACHED PART` once they are no longer needed. +- **On scale down** — once a replica is gone, the operator drops its registration from each `Replicated` database and from the `ReplicatedMergeTree` tables in it with `SYSTEM DROP DATABASE REPLICA ... WITH TABLES`, so the shrunk cluster does not wait on a replica that no longer exists and nothing stale blocks that name from registering again. +`ReplicatedMergeTree` tables in other databases, such as `Atomic` ones, keep the removed replica's Keeper entries; drop them with `SYSTEM DROP REPLICA` if needed. This covers `Replicated` databases and integration database engines. It does not move table data — row data lives in `ReplicatedMergeTree` tables and replicates through Keeper independently of this schema sync. With a single replica there is nothing to replicate. @@ -72,6 +75,7 @@ kubectl get clickhousecluster sample -o yaml | sed -n '/conditions:/,/^[^ ]/p' | `SchemaInSync` | `ReplicasInSync` | Databases exist on all replicas and stale metadata is cleaned up | | `SchemaInSync` | `DatabasesNotCreated` | The operator has not finished creating databases on the new replicas | | `SchemaInSync` | `ReplicasNotCleanedUp` | Stale replica metadata from a scale down is not yet removed | +| `SchemaInSync` | `ReplicaRestorePending` | A joining replica is being re-registered in Keeper or is catching up on the replicated schema | | `SchemaInSync` | `SchemaSyncDisabled` | `enableDatabaseSync` is `false` | | `Ready` | `AllShardsReady` | Every shard has a ready replica | | `Ready` | `SomeShardsNotReady` | At least one shard has no ready replica | diff --git a/go.mod b/go.mod index 6cc78568e..81ce2d375 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/ClickHouse/clickhouse-operator go 1.27.3 require ( + github.com/ClickHouse/ch-go v0.76.0 github.com/ClickHouse/clickhouse-go/v2 v2.51.0 github.com/blang/semver/v4 v4.0.0 github.com/cert-manager/cert-manager v1.21.3 @@ -37,7 +38,6 @@ require ( dario.cat/mergo v1.0.2 // indirect filippo.io/edwards25519 v1.2.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 // indirect - github.com/ClickHouse/ch-go v0.76.0 // indirect github.com/Masterminds/semver/v3 v3.5.0 // indirect github.com/Microsoft/go-winio v0.6.4 // indirect github.com/andybalholm/brotli v1.3.0 // indirect diff --git a/internal/controller/clickhouse/commands.go b/internal/controller/clickhouse/commands.go index 85fb12fa7..9f2c80f2a 100644 --- a/internal/controller/clickhouse/commands.go +++ b/internal/controller/clickhouse/commands.go @@ -6,8 +6,13 @@ import ( "errors" "fmt" "maps" + "path" "slices" + "strconv" + "strings" + "time" + chproto "github.com/ClickHouse/ch-go/proto" "github.com/ClickHouse/clickhouse-go/v2" "github.com/google/uuid" corev1 "k8s.io/api/core/v1" @@ -45,9 +50,13 @@ GROUP BY database, shard_id, replica_id SETTINGS skip_unavailable_shards=1` createDefaultDatabaseQuery = `CREATE DATABASE IF NOT EXISTS default UUID ? ENGINE=Replicated('/clickhouse/databases/default', '{shard}', '{replica}')` - - // codeReplicaAlreadyExists is the ClickHouse REPLICA_ALREADY_EXISTS error code. - codeReplicaAlreadyExists = 253 + databaseReplicasQuery = `SELECT database, '' AS table, 'default' AS zookeeper_name, replica_path FROM system.database_replicas` + // A table that lost its replica path is readonly. + readonlyTableReplicasQuery = `SELECT database, table, zookeeper_name, replica_path FROM system.replicas WHERE is_readonly` + // system.zookeeper reads a single Keeper per query. + zookeeperChildrenQuery = `SELECT path, name, ctime FROM system.zookeeper WHERE zookeeperName = ? AND path IN ?` + tableReplicasQuery = `SELECT database, table, zookeeper_name, zookeeper_path FROM system.replicas WHERE database IN ?` + localTablesQuery = `SELECT database, name FROM system.tables WHERE database IN ?` ) type databaseDescriptor struct { @@ -60,12 +69,37 @@ type databaseDescriptor struct { // replicaResolver returns the host:port address of the replica management endpoint. type replicaResolver func(id v1.ClickHouseReplicaID) (string, error) +// replicaPeerFilter reports whether a replica can resolve Keeper paths of its shard's tables for its peers. +type replicaPeerFilter func(id v1.ClickHouseReplicaID) bool + +type replicaRegistration struct { + Database string `ch:"database"` + Table string `ch:"table"` + ZookeeperName string `ch:"zookeeper_name"` + ReplicaPath string `ch:"replica_path"` +} + +// znode is a node of the default or an auxiliary Keeper. +type znode struct { + Keeper string `ch:"zookeeper_name"` + Path string `ch:"zookeeper_path"` +} + +func (r replicaRegistration) String() string { + if r.Table == "" { + return r.Database + } + + return r.Database + "." + r.Table +} + type commander struct { log controllerutil.Logger cluster *v1.ClickHouseCluster auth clickhouse.Auth dialer controllerutil.DialContextFunc resolver replicaResolver + peers replicaPeerFilter entry *connCacheEntry } @@ -92,7 +126,15 @@ func newObservingCommander(log controllerutil.Logger, cluster *v1.ClickHouseClus }, true } -func newCommander(log controllerutil.Logger, cluster *v1.ClickHouseCluster, secret *corev1.Secret, dialer controllerutil.DialContextFunc, resolver replicaResolver, cache *connCache) *commander { +func newCommander( + log controllerutil.Logger, + cluster *v1.ClickHouseCluster, + secret *corev1.Secret, + dialer controllerutil.DialContextFunc, + resolver replicaResolver, + peers replicaPeerFilter, + cache *connCache, +) *commander { log = log.Named("commander") credHash, _ := controllerutil.DeepHashObject(secret.Data[SecretKeyManagementPassword]) @@ -102,6 +144,7 @@ func newCommander(log controllerutil.Logger, cluster *v1.ClickHouseCluster, secr cluster: cluster, dialer: dialer, resolver: resolver, + peers: peers, auth: clickhouse.Auth{ Username: OperatorManagementUsername, Password: string(secret.Data[SecretKeyManagementPassword]), @@ -155,27 +198,16 @@ func (cmd *commander) Warnings(ctx context.Context, id v1.ClickHouseReplicaID) ( return nil, fmt.Errorf("failed to get connection for replica %s: %w", id, err) } - var warnings []string - - rows, err := conn.Query(ctx, "SELECT message FROM system.warnings") - if err != nil { - return nil, fmt.Errorf("failed to query system.warnings on replica %s: %w", id, err) + var rows []struct { + Message string `ch:"message"` } - defer func() { - _ = rows.Close() - }() - - for rows.Next() { - var raw string - if err := rows.Scan(&raw); err != nil { - return nil, fmt.Errorf("failed to get data from system.warnings: replica %s, %w", id, err) - } - - warnings = append(warnings, raw) + if err := conn.Select(ctx, &rows, "SELECT message FROM system.warnings"); err != nil { + return nil, fmt.Errorf("failed to query system.warnings on replica %s: %w", id, err) } - if err := rows.Err(); err != nil { - return nil, fmt.Errorf("failed to scan data from system.warnings %s: %w", id, err) + warnings := make([]string, 0, len(rows)) + for _, row := range rows { + warnings = append(warnings, row.Message) } return warnings, nil @@ -264,29 +296,16 @@ func (cmd *commander) Databases(ctx context.Context, id v1.ClickHouseReplicaID) return nil, fmt.Errorf("failed to get connection for replica %s: %w", id, err) } - rows, err := conn.Query(ctx, listDatabasesQuery) - if err != nil { + var rows []databaseDescriptor + if err := conn.Select(ctx, &rows, listDatabasesQuery); err != nil { return nil, fmt.Errorf("failed to query databases on replica %s: %w", id, err) } - defer func() { - _ = rows.Close() - }() - - databases := map[string]databaseDescriptor{} - for rows.Next() { - var db databaseDescriptor - if err := rows.ScanStruct(&db); err != nil { - return nil, fmt.Errorf("failed to scan database row on replica %s: %w", id, err) - } - + databases := make(map[string]databaseDescriptor, len(rows)) + for _, db := range rows { databases[db.Name] = db } - if err = rows.Err(); err != nil { - return nil, fmt.Errorf("failed to fetch all database rows on replica %s: %w", id, err) - } - return databases, nil } @@ -301,7 +320,7 @@ func (cmd *commander) CreateDatabases(ctx context.Context, log controllerutil.Lo log.Info("creating database", "replica_id", id, "database", name) - if err = cmd.createDatabase(ctx, log, conn, id, name, fmt.Sprintf( + if err = cmd.createDatabase(ctx, log, conn, id, name, desc.IsReplicated, fmt.Sprintf( "CREATE DATABASE IF NOT EXISTS {database:Identifier} UUID '%s' ENGINE = %s", desc.UUID, desc.EngineFull, )); err != nil { @@ -363,7 +382,7 @@ func (cmd *commander) EnsureReplicaDefaultDatabaseEngine(ctx context.Context, lo log.Info("creating replicated default database") defaultDatabaseUUID := uuid.NewSHA1(uuid.Nil, []byte(cmd.cluster.SpecificName())).String() - if err = cmd.createDatabase(ctx, log, conn, id, "default", createDefaultDatabaseQuery, defaultDatabaseUUID); err != nil { + if err = cmd.createDatabase(ctx, log, conn, id, "default", true, createDefaultDatabaseQuery, defaultDatabaseUUID); err != nil { return false, fmt.Errorf("create default replicated database %s: %w", id, err) } @@ -421,46 +440,21 @@ func (cmd *commander) SyncReplica(ctx context.Context, log controllerutil.Logger } } - type replicatedTable struct { - database string - name string + var replicatedTables []struct { + Database string `ch:"database"` + Name string `ch:"name"` } - - var replicatedTables []replicatedTable - - rows, err := conn.Query(ctx, `SELECT database, name FROM system.tables WHERE engine LIKE 'Replicated%'`) - if err != nil { + if err := conn.Select(ctx, &replicatedTables, `SELECT database, name FROM system.tables WHERE engine LIKE 'Replicated%'`); err != nil { errs = append(errs, fmt.Errorf("query replicated tables: %w", err)) return errs } - defer func() { - _ = rows.Close() - }() - - for rows.Next() { - var dbName, tableName string - if err := rows.Scan(&dbName, &tableName); err != nil { - errs = append(errs, fmt.Errorf("scan replicated table row: %w", err)) - continue - } - - replicatedTables = append(replicatedTables, replicatedTable{database: dbName, name: tableName}) - } - - if err = rows.Err(); err != nil { - errs = append(errs, fmt.Errorf("fetch replicated table rows: %w", err)) - } - for _, table := range replicatedTables { - log.Debug("syncing table replica", "database", table.database, "table", table.name) + log.Debug("syncing table replica", "database", table.Database, "table", table.Name) - syncCtx := clickhouse.Context(ctx, clickhouse.WithParameters(clickhouse.Parameters{ - "database": table.database, - "table": table.name, - })) + syncCtx := tableCtx(ctx, table.Database, table.Name) if err = conn.Exec(syncCtx, "SYSTEM SYNC REPLICA {database:Identifier}.{table:Identifier} LIGHTWEIGHT"); err != nil { - errs = append(errs, fmt.Errorf("sync replica %s.%s: %w", table.database, table.name, err)) + errs = append(errs, fmt.Errorf("sync replica %s.%s: %w", table.Database, table.Name, err)) } } @@ -480,46 +474,42 @@ func (cmd *commander) CleanupDatabaseReplicas( log = log.With("replica_id", id) - rows, err := conn.Query(ctx, listStaleDatabaseReplicasQuery, cmd.cluster.Shards(), cmd.cluster.Replicas()) - if err != nil { + var staleReplicas []struct { + Database string `ch:"database"` + ShardID int32 `ch:"shard_id"` + Index int32 `ch:"replica_id"` + IsActive bool `ch:"is_active"` + } + if err := conn.Select(ctx, &staleReplicas, listStaleDatabaseReplicasQuery, cmd.cluster.Shards(), cmd.cluster.Replicas()); err != nil { return fmt.Errorf("query stale database replicas %v: %w", id, err) } - defer func() { - _ = rows.Close() - }() - - total := 0 succeed := 0 - for rows.Next() { - var ( - database string - toDrop v1.ClickHouseReplicaID - isActive bool - ) - - total++ - - if err = rows.Scan(&database, &toDrop.ShardID, &toDrop.Index, &isActive); err != nil { - log.Warn("failed to scan stale database replica", "error", err) - continue - } + for _, stale := range staleReplicas { + database := stale.Database + toDrop := v1.ClickHouseReplicaID{ShardID: stale.ShardID, Index: stale.Index} if _, ok := running[toDrop]; ok { log.Debug("skipping stale database replica cleanup that is still running", "database", database, "replica_id", toDrop) continue } - if isActive { + if stale.IsActive { log.Debug("stale database replica is still active, skipping", "database", database, "replica_id", toDrop) continue } log.Info("deleting stale database replica", "database", database, "replica_id", toDrop) - // Both parameters don't support query parameters, and arg binding doesn't support identifiers - err = conn.Exec(ctx, fmt.Sprintf("SYSTEM DROP DATABASE REPLICA '%d|%d' FROM DATABASE `%s`", toDrop.ShardID, toDrop.Index, database)) + if toDrop.ShardID < cmd.cluster.Shards() { + err = cmd.dropStaleReplicaMetadata(ctx, toDrop, database) + } else { + // A removed shard has no surviving peer for table-level paths; its data is dropped by design. + // Both parameters don't support query parameters, and arg binding doesn't support identifiers + err = conn.Exec(ctx, fmt.Sprintf("SYSTEM DROP DATABASE REPLICA '%d|%d' FROM DATABASE %s", toDrop.ShardID, toDrop.Index, quoteIdentifier(database))) + } + if err != nil { log.Warn("failed to drop stale database replica", "replica_id", toDrop, "error", err) continue @@ -528,43 +518,77 @@ func (cmd *commander) CleanupDatabaseReplicas( succeed++ } - if err := rows.Err(); err != nil { - if succeed > 0 { - return fmt.Errorf("some stale replicas were cleaned up (%d/%d) but failed to fetch all stale database replica rows: %w", succeed, total, err) + if succeed != len(staleReplicas) { + return fmt.Errorf("some stale replicas are not cleaned up: %d/%d", succeed, len(staleReplicas)) + } + + return nil +} + +// RestoreReplica re-registers the replica's databases, then tables, that lost their Keeper registration, and syncs its databases. +func (cmd *commander) RestoreReplica(ctx context.Context, log controllerutil.Logger, id v1.ClickHouseReplicaID) error { + log = log.With("replica_id", id) + + conn, err := cmd.getConn(id) + if err != nil { + return fmt.Errorf("failed to get connection for replica %s: %w", id, err) + } + + databases, err := restoreRegistrations(ctx, log, conn, databaseReplicasQuery, "SYSTEM RESTORE DATABASE REPLICA {database:Identifier}") + if err != nil { + return fmt.Errorf("restore databases of replica %s: %w", id, err) + } + + // A previous incarnation's table registrations wedge the database recovery on a fresh volume. + if err := cmd.dropLeakedTableReplicas(ctx, log, conn, id, databases); err != nil { + return fmt.Errorf("drop leaked table registrations of replica %s: %w", id, err) + } + + // Lets the database recovery move or recreate its tables before they are restored. + for _, database := range databases { + if err := conn.Exec(dbCtx(ctx, database.Database), "SYSTEM SYNC DATABASE REPLICA {database:Identifier}"); err != nil { + return fmt.Errorf("sync database %s on replica %s: %w", database, id, err) } - return fmt.Errorf("failed to fetch all stale database replica rows : %w", err) } - if total != succeed { - return fmt.Errorf("some stale replicas are not cleaned up: %d/%d", succeed, total) + if _, err := restoreRegistrations(ctx, log, conn, readonlyTableReplicasQuery, "SYSTEM RESTORE REPLICA {database:Identifier}.{table:Identifier}"); err != nil { + return fmt.Errorf("restore tables of replica %s: %w", id, err) } return nil } -func isReplicaAlreadyExists(err error) bool { +func isErrorCode(err error, code chproto.Error) bool { var exc *clickhouse.Exception - return errors.As(err, &exc) && exc.Code == codeReplicaAlreadyExists + return errors.As(err, &exc) && chproto.Error(exc.Code) == code } -// createDatabase runs a CREATE DATABASE statement on replica id. REPLICA_ALREADY_EXISTS on a replica -// with no local copy of the database means its metadata in Keeper outlived the volume; the stale -// metadata is dropped from a shard peer and the statement is retried. +// createDatabase creates a database the replica has no local copy of, dropping a previous incarnation's leftovers first. func (cmd *commander) createDatabase( ctx context.Context, log controllerutil.Logger, conn clickhouse.Conn, id v1.ClickHouseReplicaID, - database, query string, + database string, + replicated bool, + query string, args ...any, ) error { + // Leaked table replicas wedge the database's DDL recovery, RestoreReplica retries if this fails. + if replicated && cmd.cluster.Replicas() > 1 { + if err := cmd.dropStaleTableReplicas(ctx, id, database); err != nil { + log.Debug("failed to drop stale table registrations of the replica", + "replica_id", id, "database", database, "error", err) + } + } + err := conn.Exec(ctx, query, args...) if err == nil { return nil } - if !isReplicaAlreadyExists(err) { + if !isErrorCode(err, chproto.ErrReplicaAlreadyExists) { return fmt.Errorf("create database %s: %w", database, err) } @@ -581,41 +605,199 @@ func (cmd *commander) createDatabase( return nil } -// dropStaleReplicaMetadata removes the replica's metadata for the database from Keeper: the database -// replica entry and the per-table replica entries. It runs on a peer of the same shard because -// SYSTEM DROP REPLICA resolves table paths from the tables local to the executing host; both -// statements refuse to drop an active replica. +// dropStaleReplicaMetadata drops the replica's table and database registrations through a same-shard peer. func (cmd *commander) dropStaleReplicaMetadata(ctx context.Context, id v1.ClickHouseReplicaID, database string) error { peer, conn, err := cmd.shardPeerConn(ctx, id) if err != nil { return err } - // Neither statement accepts query parameters for these positions. - for _, query := range []string{ - fmt.Sprintf("SYSTEM DROP DATABASE REPLICA '%d|%d' FROM DATABASE `%s`", id.ShardID, id.Index, database), - fmt.Sprintf("SYSTEM DROP REPLICA '%d' FROM DATABASE `%s`", id.Index, database), - } { - if err := conn.Exec(ctx, query); err != nil { - return fmt.Errorf("on peer %s: %w", peer, err) - } + // The statement does not accept query parameters for these positions. + if err := conn.Exec(ctx, fmt.Sprintf("SYSTEM DROP DATABASE REPLICA '%d' FROM SHARD '%d' FROM DATABASE %s WITH TABLES", + id.Index, id.ShardID, quoteIdentifier(database))); err != nil { + return fmt.Errorf("on peer %s: %w", peer, err) } return nil } -func (cmd *commander) shardPeerConn(ctx context.Context, exclude v1.ClickHouseReplicaID) (v1.ClickHouseReplicaID, clickhouse.Conn, error) { - for id := range cmd.cluster.ReplicaIDs() { - if id.ShardID != exclude.ShardID || id.Index == exclude.Index { +// dropStaleTableReplicas drops the replica's table registrations of the database through a same-shard peer. +func (cmd *commander) dropStaleTableReplicas(ctx context.Context, id v1.ClickHouseReplicaID, database string) error { + peer, conn, err := cmd.shardPeerConn(ctx, id) + if err != nil { + return err + } + + // The statement does not accept query parameters for these positions. + if err := conn.Exec(ctx, fmt.Sprintf("SYSTEM DROP REPLICA '%d' FROM DATABASE %s", id.Index, quoteIdentifier(database))); err != nil { + return fmt.Errorf("on peer %s: %w", peer, err) + } + + return nil +} + +// dropLeakedTableReplicas drops, through a same-shard peer, the replica's Keeper registrations of tables it does not have. +func (cmd *commander) dropLeakedTableReplicas( + ctx context.Context, + log controllerutil.Logger, + conn clickhouse.Conn, + id v1.ClickHouseReplicaID, + databases []replicaRegistration, +) error { + if len(databases) == 0 { + return nil + } + + peer, peerConn, err := cmd.shardPeerConn(ctx, id) + if err != nil { + log.Debug("no reachable shard peer to check table registrations", "error", err) + return nil + } + + names := make([]any, 0, len(databases)) + for _, database := range databases { + names = append(names, database.Database) + } + + type tableReplica struct { + znode + + Database string `ch:"database"` + Table string `ch:"table"` + } + + var peerTables []tableReplica + if err := peerConn.Select(ctx, &peerTables, tableReplicasQuery, clickhouse.GroupSet{Value: names}); err != nil { + return fmt.Errorf("query replicated tables on peer %s: %w", peer, err) + } + + type tableName struct { + Database string `ch:"database"` + Name string `ch:"name"` + } + + var localTables []tableName + if err := conn.Select(ctx, &localTables, localTablesQuery, clickhouse.GroupSet{Value: names}); err != nil { + return fmt.Errorf("query local tables: %w", err) + } + + var localReplicas []tableReplica + if err := conn.Select(ctx, &localReplicas, tableReplicasQuery, clickhouse.GroupSet{Value: names}); err != nil { + return fmt.Errorf("query local replicated tables: %w", err) + } + + localNames := map[tableName]bool{} + for _, table := range localTables { + localNames[table] = true + } + + localPaths := map[znode]bool{} + for _, table := range localReplicas { + localPaths[table.znode] = true + } + + // A table renamed meanwhile keeps its Keeper path, one still loading is only listed by name. + missing := slices.DeleteFunc(peerTables, func(table tableReplica) bool { + return localNames[tableName{table.Database, table.Table}] || localPaths[table.znode] + }) + + replicasNodes := make([]znode, 0, len(missing)) + for _, table := range missing { + replicasNodes = append(replicasNodes, znode{table.Keeper, path.Join(table.Path, "replicas")}) + } + + replicas, err := zookeeperChildren(ctx, peerConn, replicasNodes) + if err != nil { + return err + } + + var started time.Time + if err := conn.QueryRow(ctx, "SELECT now() - uptime()").Scan(&started); err != nil { + return fmt.Errorf("query server start time: %w", err) + } + + var errs []error + + for _, table := range missing { + // A registration created since the server start belongs to a table the database recovery is creating. + created, ok := replicas[znode{table.Keeper, path.Join(table.Path, "replicas")}][strconv.Itoa(int(id.Index))] + if !ok || !created.Before(started) { continue } - conn, err := cmd.getConn(id) - if err != nil || conn.Ping(ctx) != nil { + log.Info("dropping leaked table registration", "database", table.Database, "table", table.Table) + + query := fmt.Sprintf("SYSTEM DROP REPLICA '%d' FROM TABLE {database:Identifier}.{table:Identifier}", id.Index) + if err := peerConn.Exec(tableCtx(ctx, table.Database, table.Table), query); err != nil { + errs = append(errs, fmt.Errorf("drop replica of %s.%s on peer %s: %w", table.Database, table.Table, peer, err)) + } + } + + return errors.Join(errs...) +} + +// restoreRegistrations restores the listed objects whose replica path is gone and returns those not dropped from the cluster. +func restoreRegistrations(ctx context.Context, log controllerutil.Logger, conn clickhouse.Conn, query, restore string) ([]replicaRegistration, error) { + var registrations []replicaRegistration + if err := conn.Select(ctx, ®istrations, query); err != nil { + return nil, fmt.Errorf("query replica registrations: %w", err) + } + + replicasNodes := make([]znode, 0, len(registrations)) + for _, registration := range registrations { + replicasNodes = append(replicasNodes, znode{registration.ZookeeperName, path.Dir(registration.ReplicaPath)}) + } + + replicas, err := zookeeperChildren(ctx, conn, replicasNodes) + if err != nil { + return nil, err + } + + var ( + alive []replicaRegistration + errs []error + ) + + for _, registration := range registrations { + siblings := replicas[znode{registration.ZookeeperName, path.Dir(registration.ReplicaPath)}] + + // The last replica dropping an object removes its whole path; restoring it then would resurrect the object. + if len(siblings) == 0 { + log.Warn("dropped from the cluster while the replica was away, drop it on the replica", + "database", registration.Database, "table", registration.Table) continue } - return id, conn, nil + if _, registered := siblings[path.Base(registration.ReplicaPath)]; !registered { + log.Info("restoring replica registration", "database", registration.Database, "table", registration.Table) + + if err := conn.Exec(tableCtx(ctx, registration.Database, registration.Table), restore); err != nil { + errs = append(errs, fmt.Errorf("restore replica of %s: %w", registration, err)) + continue + } + } + + alive = append(alive, registration) + } + + return alive, errors.Join(errs...) +} + +// shardPeerConn returns a reachable shard peer, preferring the ones the peer filter accepts. +func (cmd *commander) shardPeerConn(ctx context.Context, exclude v1.ClickHouseReplicaID) (v1.ClickHouseReplicaID, clickhouse.Conn, error) { + for _, preferred := range []bool{true, false} { + for id := range cmd.cluster.ReplicaIDs() { + if id.ShardID != exclude.ShardID || id.Index == exclude.Index || (cmd.peers != nil && cmd.peers(id)) != preferred { + continue + } + + conn, err := cmd.getConn(id) + if err != nil || conn.Ping(ctx) != nil { + continue + } + + return id, conn, nil + } } return v1.ClickHouseReplicaID{}, nil, fmt.Errorf("no reachable peer in shard %d for replica %s", exclude.ShardID, exclude) @@ -648,8 +830,52 @@ func (cmd *commander) getAnyConn(ctx context.Context) (v1.ClickHouseReplicaID, c return cmd.entry.AnyConn(ctx) } +// zookeeperChildren lists the children of the given Keeper nodes with their creation time; a missing node has none. +func zookeeperChildren(ctx context.Context, conn clickhouse.Conn, nodes []znode) (map[znode]map[string]time.Time, error) { + paths := map[string][]any{} + for _, node := range nodes { + paths[node.Keeper] = append(paths[node.Keeper], node.Path) + } + + children := map[znode]map[string]time.Time{} + + for keeper, keeperPaths := range paths { + var rows []struct { + Path string `ch:"path"` + Name string `ch:"name"` + Ctime time.Time `ch:"ctime"` + } + if err := conn.Select(ctx, &rows, zookeeperChildrenQuery, keeper, clickhouse.GroupSet{Value: keeperPaths}); err != nil { + return nil, fmt.Errorf("query children of %s Keeper nodes: %w", keeper, err) + } + + for _, row := range rows { + node := znode{keeper, row.Path} + if children[node] == nil { + children[node] = map[string]time.Time{} + } + + children[node][row.Name] = row.Ctime + } + } + + return children, nil +} + +// quoteIdentifier back-quotes a name for the statement positions that do not accept query parameters. +func quoteIdentifier(name string) string { + return "`" + strings.NewReplacer(`\`, `\\`, "`", "\\`").Replace(name) + "`" +} + func dbCtx(ctx context.Context, db string) context.Context { return clickhouse.Context(ctx, clickhouse.WithParameters(clickhouse.Parameters{ "database": db, })) } + +func tableCtx(ctx context.Context, db, table string) context.Context { + return clickhouse.Context(ctx, clickhouse.WithParameters(clickhouse.Parameters{ + "database": db, + "table": table, + })) +} diff --git a/internal/controller/clickhouse/commands_test.go b/internal/controller/clickhouse/commands_test.go index 44da79f1c..469d9bb40 100644 --- a/internal/controller/clickhouse/commands_test.go +++ b/internal/controller/clickhouse/commands_test.go @@ -71,6 +71,11 @@ zookeeper: node: host: %s port: %d +auxiliary_zookeepers: + aux: + node: + host: %s + port: %d remote_servers: default: shard: @@ -80,7 +85,7 @@ named_collections: config_revision: %s display_secrets_in_show_and_select: true custom_settings_prefixes: custom_ -`, replica, keeperHostname, keeper.PortNative, strings.Join(replicas, ","), testConfigRevision)) +`, replica, keeperHostname, keeper.PortNative, keeperHostname, keeper.PortNative, strings.Join(replicas, ","), testConfigRevision)) } func generateUsersConfig() *strings.Reader { @@ -102,11 +107,12 @@ profiles: var _ = Describe("commander", Ordered, Label("integration"), func() { var ( - chContainers []testcontainers.Container - testNetwork *testcontainers.DockerNetwork - cmd *commander - cache *connCache - startCHNode func(ctx context.Context, i int32) testcontainers.Container + chContainers []testcontainers.Container + testNetwork *testcontainers.DockerNetwork + cmd *commander + cache *connCache + startCHNode func(ctx context.Context, i int32) testcontainers.Container + refreshCHTarget func(ctx context.Context, ctr testcontainers.Container, i int32) ) BeforeAll(func(ctx context.Context) { @@ -164,6 +170,16 @@ var _ = Describe("commander", Ordered, Label("integration"), func() { }, } + // A stopped container keeps its disk but is remapped to a new host port on start. + refreshCHTarget = func(ctx context.Context, ctr testcontainers.Container, i int32) { + host, err := ctr.Host(ctx) + Expect(err).NotTo(HaveOccurred()) + port, err := ctr.MappedPort(ctx, chPort) + Expect(err).NotTo(HaveOccurred()) + + addrs[v1.ClickHouseReplicaID{Index: i}] = net.JoinHostPort(host, port.Port()) + } + startCHNode = func(ctx context.Context, i int32) testcontainers.Container { By(fmt.Sprintf("starting ClickHouse node %d", i)) hostname := fmt.Sprintf(clickhouseHostnameFormat, i) @@ -191,12 +207,7 @@ var _ = Describe("commander", Ordered, Label("integration"), func() { }) Expect(err).NotTo(HaveOccurred()) - host, err := ctr.Host(ctx) - Expect(err).NotTo(HaveOccurred()) - port, err := ctr.MappedPort(ctx, chPort) - Expect(err).NotTo(HaveOccurred()) - - addrs[v1.ClickHouseReplicaID{Index: i}] = net.JoinHostPort(host, port.Port()) + refreshCHTarget(ctx, ctr, i) return ctr } @@ -229,7 +240,7 @@ var _ = Describe("commander", Ordered, Label("integration"), func() { secret := &corev1.Secret{Data: map[string][]byte{SecretKeyManagementPassword: []byte(testPassword)}} cache = newConnCache() - cmd = newCommander(logger, &cluster, secret, nil, resolver, cache) + cmd = newCommander(logger, &cluster, secret, nil, resolver, nil, cache) DeferCleanup(func() { cache.Close(logger) @@ -446,6 +457,11 @@ var _ = Describe("commander", Ordered, Label("integration"), func() { Expect(conn.Exec(ctx, `CREATE TABLE testdb.test (id UInt64) ENGINE=ReplicatedMergeTree ORDER BY id`)).To(Succeed()) Expect(conn.Exec(ctx, `INSERT INTO testdb.test SELECT number FROM numbers(10)`)).To(Succeed()) + auxCtx := clickhouse.Context(ctx, clickhouse.WithSettings(clickhouse.Settings{"database_replicated_allow_replicated_engine_arguments": 3})) + Expect(conn.Exec(auxCtx, `CREATE TABLE testdb.aux (id UInt64) + ENGINE=ReplicatedMergeTree('aux:/clickhouse/tables/{uuid}/{shard}', '{replica}') ORDER BY id`)).To(Succeed()) + Expect(conn.Exec(ctx, `INSERT INTO testdb.aux SELECT number FROM numbers(10)`)).To(Succeed()) + By("syncing shard") Eventually(func() error { err := cmd.SyncShard(ctx, cmd.log, 0) @@ -540,6 +556,169 @@ var _ = Describe("commander", Ordered, Label("integration"), func() { var count uint32 Expect(row.Scan(&count)).To(Succeed()) Expect(count).To(Equal(uint32(testReplicas - 1))) + + By("verifying the table-level replica registration is dropped together with the database-level one") + + row = conn.QueryRow(ctx, `SELECT toUInt32(MAX(total_replicas)) FROM system.replicas`) + Expect(row.Err()).ToNot(HaveOccurred()) + Expect(row.Scan(&count)).To(Succeed()) + Expect(count).To(Equal(uint32(testReplicas - 1))) + }) + }) + + Describe("replica rejoin after deregistration", Ordered, func() { + var victim v1.ClickHouseReplicaID + + BeforeEach(func() { + victim = v1.ClickHouseReplicaID{ShardID: 0, Index: testReplicas - 1} + }) + + It("restores a deregistered replica that kept its volume", func(ctx context.Context) { + By("inserting rows on the survivors while the replica is deregistered and down") + + conn0, err := cmd.getConn(v1.ClickHouseReplicaID{ShardID: 0, Index: 0}) + Expect(err).NotTo(HaveOccurred()) + Expect(conn0.Exec(ctx, `INSERT INTO testdb.test SELECT number + 10 FROM numbers(10)`)).To(Succeed()) + + By("scaling back up and restarting the replica with its retained disk") + + *cmd.cluster.Spec.Replicas = testReplicas + + Expect(chContainers[victim.Index].Start(ctx)).To(Succeed()) + refreshCHTarget(ctx, chContainers[victim.Index], victim.Index) + cache.EvictReplica(cmd.cluster.NamespacedName(), victim, cmd.log) + + Eventually(func() (replicaProbe, error) { + return cmd.Probe(ctx, victim) + }, "2m", "2s").ShouldNot(BeZero()) + + By("restoring the database and table registrations") + + Eventually(func(g Gomega) { + g.Expect(cmd.RestoreReplica(ctx, cmd.log, victim)).To(Succeed()) + + var databaseReplicas, tableReplicas uint32 + g.Expect(conn0.QueryRow(ctx, `SELECT toUInt32(count()) FROM system.clusters WHERE cluster = 'testdb'`).Scan(&databaseReplicas)).To(Succeed()) + g.Expect(databaseReplicas).To(Equal(uint32(testReplicas))) + g.Expect(conn0.QueryRow(ctx, `SELECT toUInt32(MIN(total_replicas)) FROM system.replicas`).Scan(&tableReplicas)).To(Succeed()) + g.Expect(tableReplicas).To(Equal(uint32(testReplicas))) + }, "2m", "2s").Should(Succeed()) + + By("verifying the replica reuses its local data and serves every row exactly once") + + connV, err := cmd.getConn(victim) + Expect(err).NotTo(HaveOccurred()) + + Eventually(func(g Gomega) { + g.Expect(cmd.SyncReplica(ctx, cmd.log, victim)).To(BeEmpty()) + + var n uint64 + g.Expect(connV.QueryRow(ctx, `SELECT count() FROM testdb.test`).Scan(&n)).To(Succeed()) + g.Expect(n).To(Equal(uint64(20))) + g.Expect(connV.QueryRow(ctx, `SELECT count() FROM testdb.probe`).Scan(&n)).To(Succeed()) + g.Expect(n).To(Equal(uint64(100))) + }, "2m", "2s").Should(Succeed()) + }) + + It("recovers a replica rebuilt from an empty volume after a half-done deregistration", func(ctx context.Context) { + conn0, err := cmd.getConn(v1.ClickHouseReplicaID{ShardID: 0, Index: 0}) + Expect(err).NotTo(HaveOccurred()) + + By("creating a second database whose table the replica holds, to be recreated through the database sync") + + for id := range cmd.cluster.ReplicaIDs() { + conn, err := cmd.getConn(id) + Expect(err).NotTo(HaveOccurred()) + Expect(conn.Exec(ctx, "CREATE DATABASE leakdb ENGINE=Replicated('/clickhouse/databases/leakdb', '{shard}', '{replica}')")).To(Succeed()) + } + + Expect(conn0.Exec(ctx, "CREATE TABLE leakdb.t (id UInt64) ENGINE = ReplicatedMergeTree ORDER BY id")).To(Succeed()) + Expect(conn0.Exec(ctx, "INSERT INTO leakdb.t SELECT number FROM numbers(30)")).To(Succeed()) + Eventually(func() []error { + return cmd.SyncReplica(ctx, cmd.log, victim) + }, "1m", "2s").Should(BeEmpty()) + + By("stopping the replica and dropping only its database-level registration, leaking the table-level one") + + Expect(chContainers[victim.Index].Stop(ctx, new(time.Nanosecond))).To(Succeed()) + cache.EvictReplica(cmd.cluster.NamespacedName(), victim, cmd.log) + + for _, db := range []string{"default", "testdb", "leakdb"} { + Eventually(func() error { + return conn0.Exec(ctx, fmt.Sprintf("SYSTEM DROP DATABASE REPLICA '%d|%d' FROM DATABASE `%s`", victim.ShardID, victim.Index, db)) + }, "1m", "2s").Should(Succeed()) + } + + var leaked uint32 + + row := conn0.QueryRow(ctx, `SELECT toUInt32(MAX(total_replicas)) FROM system.replicas`) + Expect(row.Err()).NotTo(HaveOccurred()) + Expect(row.Scan(&leaked)).To(Succeed()) + Expect(leaked).To(Equal(uint32(testReplicas)), "table-level replica registration should be leaked") + + By("bringing the replica back with an empty volume") + + Expect(chContainers[victim.Index].Terminate(ctx)).To(Succeed()) + chContainers[victim.Index] = startCHNode(ctx, victim.Index) + + Eventually(func() (map[string]databaseDescriptor, error) { + return cmd.Databases(ctx, victim) + }, "2m", "2s").ShouldNot(HaveKey("testdb")) + + By("creating the database while the stale table registrations are still in Keeper, as when the proactive drop fails") + + Eventually(func() (bool, error) { + return cmd.EnsureReplicaDefaultDatabaseEngine(ctx, cmd.log, victim) + }, "2m", "5s").Should(BeTrue()) + + peerDatabases, err := cmd.Databases(ctx, v1.ClickHouseReplicaID{ShardID: 0, Index: 0}) + Expect(err).NotTo(HaveOccurred()) + Expect(peerDatabases).To(HaveKey("testdb")) + + connV, err := cmd.getConn(victim) + Expect(err).NotTo(HaveOccurred()) + Expect(connV.Exec(ctx, fmt.Sprintf("CREATE DATABASE testdb UUID '%s' ENGINE = %s", + peerDatabases["testdb"].UUID, peerDatabases["testdb"].EngineFull))).To(Succeed()) + + By("creating the second database through the database sync, which drops its stale table registrations first") + + sources := slices.DeleteFunc(slices.Collect(cmd.cluster.ReplicaIDs()), func(id v1.ClickHouseReplicaID) bool { return id == victim }) + Expect(cmd.SyncDatabases(ctx, cmd.log, sources, []v1.ClickHouseReplicaID{victim})).To(HaveKeyWithValue(victim, true)) + + Eventually(func(g Gomega) { + var n uint64 + g.Expect(connV.QueryRow(ctx, `SELECT count() FROM leakdb.t`).Scan(&n)).To(Succeed()) + g.Expect(n).To(Equal(uint64(30))) + }, "2m", "2s").Should(Succeed()) + + By("restoring the joining replica as the reconcile does") + + Eventually(func() error { + return cmd.RestoreReplica(ctx, cmd.log, victim) + }, "3m", "5s").Should(Succeed()) + + By("verifying the previously wedged tables replicate to the fresh replica") + + Eventually(func(g Gomega) { + g.Expect(cmd.SyncReplica(ctx, cmd.log, victim)).To(BeEmpty()) + + var n uint64 + g.Expect(connV.QueryRow(ctx, `SELECT count() FROM testdb.test`).Scan(&n)).To(Succeed()) + g.Expect(n).To(Equal(uint64(20))) + g.Expect(connV.QueryRow(ctx, `SELECT count() FROM testdb.probe`).Scan(&n)).To(Succeed()) + g.Expect(n).To(Equal(uint64(100))) + g.Expect(connV.QueryRow(ctx, `SELECT count() FROM testdb.aux`).Scan(&n)).To(Succeed()) + g.Expect(n).To(Equal(uint64(10))) + }, "2m", "2s").Should(Succeed()) + + By("verifying the replica re-registered at both levels") + + var registered uint32 + + row = conn0.QueryRow(ctx, `SELECT toUInt32(MIN(total_replicas)) FROM system.replicas`) + Expect(row.Err()).NotTo(HaveOccurred()) + Expect(row.Scan(®istered)).To(Succeed()) + Expect(registered).To(Equal(uint32(testReplicas))) }) }) }) diff --git a/internal/controller/clickhouse/conncache_test.go b/internal/controller/clickhouse/conncache_test.go index ce094f11b..e4a0f3c7a 100644 --- a/internal/controller/clickhouse/conncache_test.go +++ b/internal/controller/clickhouse/conncache_test.go @@ -73,7 +73,7 @@ var _ = Describe("replica connections", func() { return "", errors.New("replica pod has no IP") } - cmd := newCommander(logger, &cluster, &corev1.Secret{}, dialer, resolver, nil) + cmd := newCommander(logger, &cluster, &corev1.Secret{}, dialer, resolver, nil, nil) _, err := cmd.Probe(ctx, id) Expect(err).To(MatchError(ContainSubstring("replica pod has no IP"))) @@ -86,7 +86,7 @@ var _ = Describe("replica connections", func() { } cache := newConnCache() secret := &corev1.Secret{} - newCommander(logger, &cluster, secret, dialer, nil, cache) + newCommander(logger, &cluster, secret, dialer, nil, nil, cache) cmd, ok := newObservingCommander(logger, &cluster, secret, dialer, cache) Expect(ok).To(BeTrue()) diff --git a/internal/controller/clickhouse/schemasync.go b/internal/controller/clickhouse/schemasync.go index 587c30ef9..7a15a2b0a 100644 --- a/internal/controller/clickhouse/schemasync.go +++ b/internal/controller/clickhouse/schemasync.go @@ -20,6 +20,7 @@ import ( type schemaSyncResult struct { defaultDBReplicated map[v1.ClickHouseReplicaID]bool databasesSynced map[v1.ClickHouseReplicaID]bool + restored map[v1.ClickHouseReplicaID]bool admissionFailed bool @@ -93,9 +94,32 @@ func (r *clickhouseReconciler) reconcileSchemaSync(ctx context.Context, log ctrl r.schemaSync.databasesSynced = r.commander.SyncDatabases(syncCtx, log, sources, targets, ctrlutil.WithParallelism(ctrlutil.DefaultParallelism)) + r.restoreReplicas(syncCtx, log, targets) + return chctrl.StepContinue(), nil } +// restoreReplicas re-registers joining replicas whose retained volume outlived their Keeper registration. +func (r *clickhouseReconciler) restoreReplicas(ctx context.Context, log ctrlutil.Logger, targets []v1.ClickHouseReplicaID) { + synced := slices.DeleteFunc(slices.Clone(targets), func(id v1.ClickHouseReplicaID) bool { + return !r.schemaSync.databasesSynced[id] + }) + + res := ctrlutil.ExecuteParallel(ctx, synced, func(ctx context.Context, id v1.ClickHouseReplicaID) (struct{}, error) { + return struct{}{}, r.commander.RestoreReplica(ctx, log, id) + }) + + r.schemaSync.restored = map[v1.ClickHouseReplicaID]bool{} + for id, result := range res { + if result.Err != nil { + log.Warn("failed to restore replica registration", "replica_id", id, "error", result.Err) + continue + } + + r.schemaSync.restored[id] = true + } +} + // reconcileReplicaReadiness opens client traffic for ready replicas and withdraws it from replicas scheduled for deletion. func (r *clickhouseReconciler) reconcileReplicaReadiness(ctx context.Context, log ctrlutil.Logger) (chctrl.StepResult, error) { if r.Cluster.Spec.Settings.DatabaseSyncEnabled() && r.commander == nil { @@ -255,7 +279,7 @@ func (r *clickhouseReconciler) reconcileSyncCondition(_ context.Context, _ ctrlu return chctrl.StepContinue(), nil } - var nonReplicatedDefaultDatabaseIDs []string + var nonReplicatedDefaultDatabaseIDs, restorePendingIDs []string for id, replicated := range r.schemaSync.defaultDBReplicated { if !replicated { @@ -263,6 +287,12 @@ func (r *clickhouseReconciler) reconcileSyncCondition(_ context.Context, _ ctrlu } } + for id, synced := range r.schemaSync.databasesSynced { + if synced && !r.schemaSync.restored[id] { + restorePendingIDs = append(restorePendingIDs, id.String()) + } + } + allReplicasReachable := len(r.reachableReplicas) == len(r.ReplicaState) allReplicasInitialized := allReplicasReachable && !r.schemaSync.admissionFailed allDatabasesSynced := allReplicasReachable @@ -289,6 +319,17 @@ func (r *clickhouseReconciler) reconcileSyncCondition(_ context.Context, _ ctrlu return chctrl.StepRequeue(chctrl.RequeueProbePoll), nil + case len(restorePendingIDs) > 0: + slices.Sort(restorePendingIDs) + r.SetCondition(metav1.Condition{ + Type: v1.ClickHouseConditionTypeSchemaInSync, + Status: metav1.ConditionFalse, + Reason: v1.ClickHouseConditionReplicaRestorePending, + Message: "Joining replicas are restoring Keeper registration or catching up on the replicated schema: " + strings.Join(restorePendingIDs, ", "), + }) + + return chctrl.StepRequeue(chctrl.RequeueProbePoll), nil + case !allReplicasInitialized || !allDatabasesSynced: r.SetCondition(metav1.Condition{ Type: v1.ClickHouseConditionTypeSchemaInSync, @@ -339,7 +380,7 @@ func (r *clickhouseReconciler) trafficAdmission() map[v1.ClickHouseReplicaID]boo default: // Presence, not the value: a populated non-Replicated default database is preserved and still admitted. _, prepared := r.schemaSync.defaultDBReplicated[id] - trafficAdmitted[id] = prepared && r.schemaSync.databasesSynced[id] + trafficAdmitted[id] = prepared && r.schemaSync.restored[id] } } diff --git a/internal/controller/clickhouse/schemasync_test.go b/internal/controller/clickhouse/schemasync_test.go index 0f5b7dacf..cfa0a3513 100644 --- a/internal/controller/clickhouse/schemasync_test.go +++ b/internal/controller/clickhouse/schemasync_test.go @@ -58,6 +58,7 @@ var _ = Describe("schema sync steps", func() { initialized bool defaultDBReplicated *bool // nil: the default database step failed databasesSynced bool + restored bool admitted bool } @@ -71,6 +72,7 @@ var _ = Describe("schema sync steps", func() { sync := schemaSyncResult{ defaultDBReplicated: map[v1.ClickHouseReplicaID]bool{}, databasesSynced: map[v1.ClickHouseReplicaID]bool{id: c.databasesSynced}, + restored: map[v1.ClickHouseReplicaID]bool{id: c.restored}, } if c.defaultDBReplicated != nil { sync.defaultDBReplicated[id] = *c.defaultDBReplicated @@ -86,11 +88,13 @@ var _ = Describe("schema sync steps", func() { Entry("admits every desired replica when sync is disabled", admissionCase{syncDisabled: true, admitted: true}), Entry("admits a replica whose populated default database stays non-Replicated", - admissionCase{defaultDBReplicated: new(false), databasesSynced: true, admitted: true}), + admissionCase{defaultDBReplicated: new(false), databasesSynced: true, restored: true, admitted: true}), Entry("holds a replica whose default database step failed", - admissionCase{databasesSynced: true}), + admissionCase{databasesSynced: true, restored: true}), Entry("holds a replica whose databases are not synced", admissionCase{defaultDBReplicated: new(true)}), + Entry("holds a replica whose Keeper registration is not restored", + admissionCase{defaultDBReplicated: new(true), databasesSynced: true}), ) It("reports SchemaSyncDisabled even when the schema sync steps did not run", func(ctx context.Context) { @@ -121,4 +125,21 @@ var _ = Describe("schema sync steps", func() { Expect(cond).NotTo(BeNil()) Expect(cond.Reason).To(Equal(v1.ClickHouseConditionReplicasInSync)) }) + + It("reports ReplicaRestorePending while a joining replica's Keeper registration is not restored", func(ctx context.Context) { + joining := v1.ClickHouseReplicaID{ShardID: 0, Index: 1} + r := reconciler(true, map[v1.ClickHouseReplicaID]replicaState{joining: replica(false)}, schemaSyncResult{ + defaultDBReplicated: map[v1.ClickHouseReplicaID]bool{joining: true}, + databasesSynced: map[v1.ClickHouseReplicaID]bool{joining: true}, + staleReplicasCleanedUp: true, + }) + r.reachableReplicas = []v1.ClickHouseReplicaID{joining} + + _, err := r.reconcileSyncCondition(ctx, log) + Expect(err).NotTo(HaveOccurred()) + + cond := meta.FindStatusCondition(r.Cluster.Status.Conditions, v1.ClickHouseConditionTypeSchemaInSync) + Expect(cond).NotTo(BeNil()) + Expect(cond.Reason).To(Equal(v1.ClickHouseConditionReplicaRestorePending)) + }) }) diff --git a/internal/controller/clickhouse/sync.go b/internal/controller/clickhouse/sync.go index 4ac180818..5da52960f 100644 --- a/internal/controller/clickhouse/sync.go +++ b/internal/controller/clickhouse/sync.go @@ -303,7 +303,7 @@ func (r *clickhouseReconciler) reconcileClusterSecret(ctx context.Context, log c secretExists = false } else { - r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.connCache) + r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.replicaInitialized, r.connCache) } if !r.versionProbe.Completed() { @@ -335,7 +335,7 @@ func (r *clickhouseReconciler) reconcileClusterSecret(ctx context.Context, log c } // Create or recreate commander with new credentials - r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.connCache) + r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.replicaInitialized, r.connCache) if !secretExists { log.Info("cluster secret not found, creating", "secret", r.Cluster.SecretName()) @@ -396,7 +396,7 @@ func (r *clickhouseReconciler) reconcileExternalSecret(ctx context.Context, log r.secret.Data = make(map[string][]byte) } - r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.connCache) + r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.replicaInitialized, r.connCache) if !r.versionProbe.Completed() { log.Info("version probe is not completed yet, skipping external secret validation") @@ -449,7 +449,7 @@ func (r *clickhouseReconciler) reconcileExternalSecret(ctx context.Context, log return chctrl.StepResult{}, fmt.Errorf("fill external secret %q: %w", r.Cluster.SecretName(), err) } - r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.connCache) + r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.replicaInitialized, r.connCache) r.SetCondition(metav1.Condition{ Type: v1.ClickHouseConditionTypeExternalSecretValid, @@ -926,6 +926,10 @@ func (r *clickhouseReconciler) reconcileNetworkPolicy(ctx context.Context, log c return chctrl.StepContinue(), nil } +func (r *clickhouseReconciler) replicaInitialized(id v1.ClickHouseReplicaID) bool { + return r.ReplicaState[id].Initialized() +} + // replicaAddress resolves replicas by Pod IP: cluster DNS serves stale records for a while after a Pod restart. func (r *clickhouseReconciler) replicaAddress(id v1.ClickHouseReplicaID) (string, error) { pod := r.ReplicaState[id].Pod diff --git a/test/e2e/clickhouse_e2e_test.go b/test/e2e/clickhouse_e2e_test.go index 88d0c1c6b..96ab878f9 100644 --- a/test/e2e/clickhouse_e2e_test.go +++ b/test/e2e/clickhouse_e2e_test.go @@ -1097,6 +1097,149 @@ var _ = Describe("ClickHouse controller", Label("clickhouse"), func() { }) }) + DescribeTable("should rejoin replica after scale-down", func(ctx context.Context, keepDisk bool) { + cr := testutil.NewClickHouseCluster(ns, "rejoin-empty"). + WithStorage(defaultStorage). + WithReplicas(3). + WithKeeper(keeper.Name). + Cluster() + + By("creating cluster CR", func() { + Expect(k8sClient.Create(ctx, &cr)).To(Succeed()) + DeferCleanup(func(ctx context.Context) { + Expect(k8sClient.Delete(ctx, &cr)).To(Succeed()) + }) + env.WaitClickHouseUpdatedAndReady(ctx, &cr, 3*time.Minute) + }) + + rejoined := v1.ClickHouseReplicaID{Index: 2} + + By("creating a replicated table with rows", func() { + chClient, err := testutil.NewClickHouseClient(ctx, podDialer, &cr) + Expect(err).NotTo(HaveOccurred()) + + defer chClient.Close() + + Expect(chClient.Exec(ctx, + "CREATE TABLE default.scale_test (id UInt64) Engine=ReplicatedMergeTree ORDER BY id")).To(Succeed()) + Expect(chClient.Exec(ctx, "INSERT INTO default.scale_test SELECT number FROM numbers(1000)")).To(Succeed()) + Expect(chClient.Exec(ctx, + "CREATE TABLE default.dropped_table (id UInt64) Engine=ReplicatedMergeTree ORDER BY id")).To(Succeed()) + Expect(chClient.Exec(ctx, "INSERT INTO default.dropped_table SELECT number FROM numbers(100)")).To(Succeed()) + Expect(chClient.Exec(ctx, "CREATE DATABASE dropped_db ON CLUSTER 'default' "+ + "ENGINE = Replicated('/clickhouse/databases/dropped_db')")).To(Succeed()) + }) + + By("scaling down to deregister the replica", func() { + Expect(k8sClient.Get(ctx, cr.NamespacedName(), &cr)).To(Succeed()) + *cr.Spec.Replicas = 2 + Expect(k8sClient.Update(ctx, &cr)).To(Succeed()) + env.WaitClickHouseUpdatedAndReady(ctx, &cr, 3*time.Minute) + }) + + By("verifying the removed replica is deregistered from the database and its tables", func() { + chClient, err := testutil.NewClickHouseClient(ctx, podDialer, &cr) + Expect(err).NotTo(HaveOccurred()) + + defer chClient.Close() + + Eventually(func(g Gomega) { + for _, query := range []string{ + "SELECT toUInt64(total_replicas) FROM system.database_replicas WHERE database = 'default'", + "SELECT toUInt64(total_replicas) FROM system.replicas WHERE database = 'default' AND table = 'scale_test'", + } { + var replicas uint64 + g.Expect(chClient.QueryRowReplica(ctx, v1.ClickHouseReplicaID{Index: 0}, query, &replicas)).To(Succeed()) + g.Expect(replicas).To(Equal(uint64(2)), query) + } + }, time.Minute).WithPolling(pollingInterval).Should(Succeed()) + }) + + if !keepDisk { + By("discarding the removed replica's retained volume", func() { + pvcName := internal.PersistentVolumeName + "-" + cr.StatefulSetNameByReplicaID(rejoined) + "-0" + + var pvc corev1.PersistentVolumeClaim + Expect(k8sClient.Get(ctx, types.NamespacedName{Namespace: ns, Name: pvcName}, &pvc)).To(Succeed()) + Expect(k8sClient.Delete(ctx, &pvc)).To(Succeed()) + + Eventually(func(g Gomega) { + err := k8sClient.Get(ctx, types.NamespacedName{Namespace: ns, Name: pvcName}, &corev1.PersistentVolumeClaim{}) + g.Expect(k8serrors.IsNotFound(err)).To(BeTrue(), "retained PVC should be gone") + }, time.Minute).WithPolling(pollingInterval).Should(Succeed()) + }) + } + + By("changing data and dropping objects the removed replica still has", func() { + chClient, err := testutil.NewClickHouseClient(ctx, podDialer, &cr) + Expect(err).NotTo(HaveOccurred()) + + defer chClient.Close() + + Expect(chClient.Exec(ctx, + "INSERT INTO default.scale_test SELECT number + 1000 FROM numbers(500)")).To(Succeed()) + + Expect(chClient.Exec(ctx, "DROP TABLE default.dropped_table SYNC")).To(Succeed()) + + for _, id := range []v1.ClickHouseReplicaID{{Index: 0}, {Index: 1}} { + Expect(chClient.ExecReplica(ctx, id, "DROP DATABASE dropped_db SYNC")).To(Succeed()) + } + }) + + By("recreating replica", func() { + Expect(k8sClient.Get(ctx, cr.NamespacedName(), &cr)).To(Succeed()) + *cr.Spec.Replicas = 3 + Expect(k8sClient.Update(ctx, &cr)).To(Succeed()) + }) + + By("waiting for the operator to initialize the rejoined replica", func() { + podKey := types.NamespacedName{Namespace: ns, Name: cr.StatefulSetNameByReplicaID(rejoined) + "-0"} + Eventually(func(g Gomega) { + var pod corev1.Pod + g.Expect(k8sClient.Get(ctx, podKey, &pod)).To(Succeed()) + g.Expect(ctrl.PodConditionTrue(&pod, v1.ReplicaInitializedCondition)).To(BeTrue()) + }, 5*time.Minute).WithPolling(pollingInterval).Should(Succeed()) + }) + + env.WaitClickHouseUpdatedAndReady(ctx, &cr, 3*time.Minute) + + By("verifying the rejoined replica content", func() { + chClient, err := testutil.NewClickHouseClient(ctx, podDialer, &cr) + Expect(err).NotTo(HaveOccurred()) + + defer chClient.Close() + + Expect(chClient.ExecReplica(ctx, rejoined, "SYSTEM SYNC REPLICA default.scale_test")).To(Succeed()) + + var rows uint64 + Expect(chClient.QueryRowReplica(ctx, rejoined, "SELECT count() FROM default.scale_test", &rows)).To(Succeed()) + Expect(rows).To(Equal(uint64(1500))) + + // The rejoined replica still holds dropped_db locally; it must not be restored or copied back. + Consistently(func(g Gomega) { + for id := range cr.ReplicaIDs() { + var tables, dbs uint64 + + query := "SELECT count() FROM system.tables WHERE database = 'default' AND name = 'dropped_table'" + g.Expect(chClient.QueryRowReplica(ctx, id, query, &tables)).To(Succeed()) + g.Expect(tables).To(BeZero(), "replica %s", id) + + query = "SELECT count() FROM system.databases WHERE name = 'dropped_db'" + g.Expect(chClient.QueryRowReplica(ctx, id, query, &dbs)).To(Succeed()) + + if !keepDisk || id != rejoined { + g.Expect(dbs).To(BeZero(), "replica %s", id) + } else { + g.Expect(dbs).ToNot(BeZero(), "replica %s", id) + } + } + }).WithTimeout(20 * time.Second).WithPolling(pollingInterval).Should(Succeed()) + }) + }, + Entry("without data on disk", false), + Entry("with data on disk", true), + ) + It("should support named collections in Keeper with encryption", func(ctx context.Context) { cr := v1.ClickHouseCluster{ ObjectMeta: metav1.ObjectMeta{