8000 fix(schemer): fail table migration when the peer schema cannot be read by theluckystrike · Pull Request #2144 · Altinity/clickhouse-operator · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pkg/controller/chi/worker-migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,12 @@ func (w *worker) shouldMigrateTables(host *api.Host, opts ...*migrateTableOption
// Force migration requested
return true

case host.HasAncestor():
// Existing hosts already have a schema even when hostsWithTablesCreated is
// empty (initial installation skips migration). Only new hosts need it.
// ForceMigrate above still handles schema restoration after data loss.
return false

case host.HasData():
// This host is listed as having tables created already, no need to migrate again
return false
Expand Down
44 changes: 44 additions & 0 deletions pkg/controller/chi/worker-migrator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,50 @@ func TestShouldMigrateTablesSkipsHostThatHasData(t *testing.T) {
"a host with no tables recorded must remain eligible for migration retry")
}

// Initial CHI creation does not record hostsWithTablesCreated. During scale-up,
// the original host is already populated and must not query an unavailable new peer.
func TestShouldMigrateTablesSkipsAncestorWithoutMigrationMarker(t *testing.T) {
w := &worker{}
previousHost := &api.Host{Name: "0-0"}
previousHost.Runtime.Address.HostName = "0-0"
previous := &api.ClickHouseInstallation{}
previous.Spec.Configuration = &api.Configuration{
Clusters: []*api.Cluster{{
Name: "simple",
Layout: &api.ChiClusterLayout{
Shards: []*api.ChiShard{{
Name: "0",
Hosts: []*api.Host{previousHost},
}},
},
}},
}

makeHost := func(name string) *api.Host {
host := newTestHost()
host.Name = name
host.Runtime.Address.ClusterName = "simple"
host.Runtime.Address.ShardName = "0"
host.Runtime.Address.HostName = name
host.GetCR().(*api.ClickHouseInstallation).SetAncestor(previous)
return host
}

existingHost := makeHost("0-0")
require.True(t, existingHost.HasAncestor())
require.Empty(t, existingHost.GetCR().IEnsureStatus().GetHostsWithTablesCreated())
require.False(t, existingHost.HasData())
require.False(t, w.shouldMigrateTables(existingHost),
"an existing host must not read its schema from an unready new peer")

newHost := makeHost("0-1")
require.False(t, newHost.HasAncestor())
require.True(t, w.shouldMigrateTables(newHost),
"a newly added host must still migrate even when the marker list is empty")
require.True(t, w.shouldMigrateTables(existingHost, NewMigrateTableOptions().SetForceMigrate()),
"forced migration after data loss must override the ancestor guard")
}

// ForceMigrate outranks HasData, which is what lets the data-loss recovery path replay the schema
// onto a host that is already listed as tables-created.
func TestShouldMigrateTablesForceOutranksHasData(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/model/chi/schemer/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (c *Cluster) queryUnzipColumns(ctx context.Context, hosts []string, sql str
// Fetch data from any of specified hosts
query, err := c.SetHosts(hosts).QueryAny(ctx, sql)
if err != nil {
return nil
return err
}
if query == nil {
return nil
Expand Down
15 changes: 12 additions & 3 deletions pkg/model/chi/schemer/distributed.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,27 +56,36 @@ func (s *ClusterSchemer) getDistributedObjectsSQLs(ctx context.Context, host *ap
// Exclude self — see the matching comment in getReplicatedObjectsSQLs.
peers := s.Names(interfaces.NameFQDNs, host, api.Cluster{}, true)

databaseNames, createDatabaseSQLs := debugCreateSQLs(
databaseNames, createDatabaseSQLs, err := debugCreateSQLs(
s.QueryUnzip2Columns(
ctx,
peers,
s.sqlCreateDatabaseDistributed(host.Runtime.Address.ClusterName),
),
)
tableNames, createTableSQLs := debugCreateSQLs(
if err != nil {
return nil, nil, err
}
tableNames, createTableSQLs, err := debugCreateSQLs(
s.QueryUnzipAndApplyUUIDs(
ctx,
peers,
s.sqlCreateTableDistributed(host.Runtime.Address.ClusterName),
),
)
functionNames, createFunctionSQLs := debugCreateSQLs(
if err != nil {
return nil, nil, err
}
functionNames, createFunctionSQLs, err := debugCreateSQLs(
s.QueryUnzip2Columns(
ctx,
peers,
s.sqlCreateFunction(host.Runtime.Address.ClusterName),
),
)
if err != nil {
return nil, nil, err
}
return util.ConcatSlices([][]string{databaseNames, tableNames, functionNames}),
util.ConcatSlices([][]string{createDatabaseSQLs, createTableSQLs, createFunctionSQLs}),
nil
Expand Down
18 changes: 18 additions & 0 deletions pkg/model/chi/schemer/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright 2019 Altinity Ltd and/or its affiliates. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package schemer

// RetryPeerSchemaRead exposes retryPeerSchemaRead to the schemer_test package.
var RetryPeerSchemaRead = retryPeerSchemaRead
15 changes: 12 additions & 3 deletions pkg/model/chi/schemer/replicated.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,27 +71,36 @@ func (s *ClusterSchemer) getReplicatedObjectsSQLs(ctx context.Context, host *api
// schemer silently skips CREATE. Peers hold the truth.
peers := s.Names(interfaces.NameFQDNs, host, api.Cluster{}, true)

databaseNames, createDatabaseSQLs := debugCreateSQLs(
databaseNames, createDatabaseSQLs, err := debugCreateSQLs(
s.QueryUnzip2Columns(
ctx,
peers,
s.sqlCreateDatabaseReplicated(host.Runtime.Address.ClusterName),
),
)
tableNames, createTableSQLs := debugCreateSQLs(
if err != nil {
return nil, nil, err
}
tableNames, createTableSQLs, err := debugCreateSQLs(
s.QueryUnzipAndApplyUUIDs(
ctx,
peers,
s.sqlCreateTableReplicated(host.Runtime.Address.ClusterName),
),
)
functionNames, createFunctionSQLs := debugCreateSQLs(
if err != nil {
return nil, nil, err
}
functionNames, createFunctionSQLs, err := debugCreateSQLs(
s.QueryUnzip2Columns(
ctx,
peers,
s.sqlCreateFunction(host.Runtime.Address.ClusterName),
),
)
if err != nil {
return nil, nil, err
}
return util.ConcatSlices([][]string{databaseNames, tableNames, functionNames}),
util.ConcatSlices([][]string{createDatabaseSQLs, createTableSQLs, createFunctionSQLs}),
nil
Expand Down
43 changes: 33 additions & 10 deletions pkg/model/chi/schemer/schemer.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package schemer
import (
"context"
"errors"
"fmt"
"time"

log "github.com/altinity/clickhouse-operator/pkg/announcer"
Expand All @@ -26,6 +27,7 @@ import (
"github.com/altinity/clickhouse-operator/pkg/model/clickhouse"
"github.com/altinity/clickhouse-operator/pkg/model/managers"
"github.com/altinity/clickhouse-operator/pkg/util"
"github.com/altinity/clickhouse-operator/pkg/util/retry"
)

// ClusterSchemer specifies cluster schema manager
Expand Down Expand Up @@ -78,6 +80,16 @@ func (s *ClusterSchemer) HostDropReplica(ctx context.Context, hostToRunOn, hostT
clickhouse.NewQueryOptions().SetRetry(false).SetLogQueries(true))
}

// schemaReadRetryAttempts is the number of attempts to read the schema from peers.
// Three attempts (5s and 10s backoff) cover a users.d ConfigMap update that has not yet
// reached every peer, which shows up as a transient Code 516 authentication failure.
const schemaReadRetryAttempts = 3

// retryPeerSchemaRead runs read up to schemaReadRetryAttempts times and returns the last error
func retryPeerSchemaRead(ctx context.Context, read func() error) error {
return retry.Retry(ctx, schemaReadRetryAttempts, "Reading schema from peers", log.V(1), read)
}

// createTablesSQLs makes all SQL for migrating tables
func (s *ClusterSchemer) createTablesSQLs(
ctx context.Context,
Expand All @@ -87,14 +99,19 @@ func (s *ClusterSchemer) createTablesSQLs(
replicatedCreateSQLs []string,
distributedObjectNames []string,
distributedCreateSQLs []string,
err error,
) {
if names, sql, err := s.getReplicatedObjectsSQLs(ctx, host); err == nil {
replicatedObjectNames = names
replicatedCreateSQLs = sql
}
if names, sql, err := s.getDistributedObjectsSQLs(ctx, host); err == nil {
distributedObjectNames = names
distributedCreateSQLs = sql
// No DDL runs until both reads complete, so a failed attempt can safely repeat both.
err = retryPeerSchemaRead(ctx, func() error {
var readErr error
if replicatedObjectNames, replicatedCreateSQLs, readErr = s.getReplicatedObjectsSQLs(ctx, host); readErr != nil {
return readErr
}
distributedObjectNames, distributedCreateSQLs, readErr = s.getDistributedObjectsSQLs(ctx, host)
return readErr
})
if err != nil {
return nil, nil, nil, nil, err
}
return
}
Expand All @@ -112,7 +129,13 @@ func (s *ClusterSchemer) HostCreateTables(ctx context.Context, host *api.Host) e
replicatedObjectNames,
replicatedCreateSQLs,
distributedObjectNames,
distributedCreateSQLs := s.createTablesSQLs(ctx, host)
distributedCreateSQLs,
err := s.createTablesSQLs(ctx, host)
if err != nil {
// Without the peer schema there is nothing to create. Report it, so the host is not
// recorded as migrated and the migration is retried.
return fmt.Errorf("unable to read schema from peers of host %s: %w", host.Runtime.Address.HostName, err)
}

var err1 error
if len(replicatedCreateSQLs) > 0 {
Expand Down Expand Up @@ -216,7 +239,7 @@ func (s *ClusterSchemer) HostShutdown(ctx context.Context, host *api.Host) error
clickhouse.NewQueryOptions().SetRetry(false).SetLogQueries(true))
}

func debugCreateSQLs(names, sqls []string, err error) ([]string, []string) {
func debugCreateSQLs(names, sqls []string, err error) ([]string, []string, error) {
if err != nil {
log.V(1).Warning("got error: %v", err)
}
Expand All @@ -228,5 +251,5 @@ func debugCreateSQLs(names, sqls []string, err error) ([]string, []string) {
for _, v := range sqls {
log.V(2).Info("sql: %s", v)
}
return names, sqls
return names, sqls, err
}
Loading
Loading
0