-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathvalidation.go
More file actions
325 lines (289 loc) · 11.1 KB
/
Copy pathvalidation.go
File metadata and controls
325 lines (289 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package clickhouse
import (
"context"
"database/sql"
"errors"
"fmt"
"log/slog"
"slices"
"strings"
"time"
chproto "github.com/ClickHouse/ch-go/proto"
clickhouse "github.com/ClickHouse/clickhouse-go/v2"
chvproto "github.com/ClickHouse/clickhouse-go/v2/lib/proto"
"go.temporal.io/sdk/log"
"github.com/PeerDB-io/peerdb/flow/pkg/common"
"github.com/PeerDB-io/peerdb/flow/pkg/objectstore"
)
func CheckNotSystemDatabase(database string) error {
switch database {
case "system", "information_schema", "INFORMATION_SCHEMA":
return fmt.Errorf("database %q is a system database and cannot be used as a destination", database)
}
return nil
}
var acceptableTableEngines = []string{
EngineReplacingMergeTree, EngineMergeTree, EngineReplicatedReplacingMergeTree, EngineReplicatedMergeTree,
EngineCoalescingMergeTree, EngineNull,
}
// supportedDatabaseEngines are the ClickHouse database engines that can be used
// as a replication destination. Foreign-database engines such as MySQL or
// PostgreSQL expose read-only proxied tables and cannot be written to.
var supportedDatabaseEngines = []string{"Atomic", "Replicated", "Shared"}
func validateDatabaseEngine(ctx context.Context, logger log.Logger, conn clickhouse.Conn) error {
var engine string
if err := QueryRow(ctx, logger, conn,
"SELECT engine FROM system.databases WHERE name = currentDatabase()",
).Scan(&engine); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil
}
return fmt.Errorf("failed to determine destination database engine: %w", err)
}
if !slices.Contains(supportedDatabaseEngines, engine) {
return fmt.Errorf("unsupported destination database engine %q; "+
"only Atomic, Replicated and Shared database engines are supported", engine)
}
return nil
}
func CheckIfClickHouseCloudHasSharedMergeTreeEnabled(ctx context.Context, logger log.Logger,
conn clickhouse.Conn,
) error {
// this is to indicate ClickHouse Cloud service is now creating tables with Shared* by default
var cloudModeEngine bool
if err := QueryRow(ctx, logger, conn,
"SELECT value='2' AND changed='1' AND readonly='1' FROM system.settings WHERE name = 'cloud_mode_engine'").
Scan(&cloudModeEngine); err != nil {
return fmt.Errorf("failed to validate cloud_mode_engine setting: %w", err)
}
if !cloudModeEngine {
return fmt.Errorf("ClickHouse service is not migrated to use SharedMergeTree tables, please contact support")
}
return nil
}
func CheckIfTablesEmptyAndEngine(ctx context.Context, logger log.Logger, conn clickhouse.Conn,
tables []string, initialSnapshotEnabled bool, checkForCloudSMT bool, allowNonEmpty bool,
) error {
queryTables := make([]string, 0, min(len(tables), 200))
for chunk := range slices.Chunk(tables, 200) {
if err := func() error {
queryTables = queryTables[:0]
for _, table := range chunk {
queryTables = append(queryTables, QuoteLiteral(table))
}
rows, err := Query(ctx, logger, conn,
fmt.Sprintf("SELECT name,engine,total_rows FROM system.tables WHERE database=currentDatabase() AND name IN (%s)",
strings.Join(queryTables, ",")))
if err != nil {
return fmt.Errorf("failed to get information for destination tables: %w", err)
}
defer rows.Close()
for rows.Next() {
var tableName, engine string
var totalRows uint64
if err := rows.Scan(&tableName, &engine, &totalRows); err != nil {
return fmt.Errorf("failed to scan information for tables: %w", err)
}
if !allowNonEmpty && totalRows != 0 && initialSnapshotEnabled {
return fmt.Errorf("table %s exists and is not empty", tableName)
}
if engine == "View" || engine == "MaterializedView" {
return fmt.Errorf("destination table can not be a view")
}
if !slices.Contains(acceptableTableEngines, strings.TrimPrefix(engine, "Shared")) {
logger.Warn("[clickhouse] table engine not explicitly supported",
slog.String("table", tableName), slog.String("engine", engine))
}
if checkForCloudSMT && !strings.HasPrefix(engine, "Shared") {
return fmt.Errorf("table %s exists and does not use SharedMergeTree engine", tableName)
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("failed to read rows: %w", err)
}
return nil
}(); err != nil {
return err
}
}
return nil
}
func ValidateClickHouseHost(ctx context.Context, chHost string, allowedDomainString string) error {
allowedDomains := strings.Split(allowedDomainString, ",")
if len(allowedDomains) == 0 {
return nil
}
// check if chHost ends with one of the allowed domains
for _, domain := range allowedDomains {
if strings.HasSuffix(chHost, domain) {
return nil
}
}
return fmt.Errorf("invalid ClickHouse host domain: %s. Allowed domains: %s",
chHost, strings.Join(allowedDomains, ","))
}
func ValidateClickHousePeer(
ctx context.Context,
logger log.Logger,
allowedDomains string,
serviceHost string,
conn clickhouse.Conn,
stagingValidator objectstore.StagingValidator,
) error {
// Hostname validation
if err := ValidateClickHouseHost(ctx, serviceHost, allowedDomains); err != nil {
return err
}
// Destination database engine validation
if err := validateDatabaseEngine(ctx, logger, conn); err != nil {
return err
}
// Target service validation
validateDummyTableName := "peerdb_validation_" + common.RandomString(4)
validateDummyTableNameRenamed := validateDummyTableName + "_renamed"
// create a table
if err := Exec(ctx, logger, conn,
fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (id UInt64) ENGINE = ReplacingMergeTree ORDER BY id;`, validateDummyTableName),
); err != nil {
return fmt.Errorf("failed to create validation table %s: %w", validateDummyTableName, err)
}
defer func() {
dropCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
for _, table := range []string{validateDummyTableName, validateDummyTableNameRenamed} {
for attempt := range 3 {
if attempt > 0 {
time.Sleep(time.Duration(attempt) * 2 * time.Second)
}
err := Exec(dropCtx, logger, conn, "DROP TABLE IF EXISTS "+table)
if err == nil {
break
}
var chException *clickhouse.Exception
if errors.As(err, &chException) && chproto.Error(chException.Code) == chproto.ErrUnfinished {
logger.Warn("validation drop table blocked by in-flight DDL, retrying",
slog.String("table", table), slog.Int("attempt", attempt+1))
continue
}
logger.Error("validation failed to drop table", slog.String("table", table), slog.Any("error", err))
break
}
}
}()
// add a column
if err := Exec(ctx, logger, conn,
fmt.Sprintf("ALTER TABLE %s ADD COLUMN updated_at DateTime64(9) DEFAULT now64()", validateDummyTableName),
); err != nil {
return fmt.Errorf("failed to add column to validation table %s: %w", validateDummyTableName, err)
}
// rename the table
if err := Exec(ctx, logger, conn,
fmt.Sprintf("RENAME TABLE %s TO %s", validateDummyTableName, validateDummyTableNameRenamed),
); err != nil {
return fmt.Errorf("failed to rename validation table %s: %w", validateDummyTableName, err)
}
// insert a row
if err := Exec(ctx, logger, conn, fmt.Sprintf("INSERT INTO %s VALUES (1, now64())", validateDummyTableNameRenamed)); err != nil {
return fmt.Errorf("failed to insert into validation table %s: %w", validateDummyTableNameRenamed, err)
}
// drop the table
if err := Exec(ctx, logger, conn, "DROP TABLE IF EXISTS "+validateDummyTableNameRenamed); err != nil {
return fmt.Errorf("failed to drop validation table %s: %w", validateDummyTableNameRenamed, err)
}
// Staging validation
// validate staging storage
if err := stagingValidator(ctx); err != nil {
return fmt.Errorf("failed to validate staging bucket: %w", err)
}
return nil
}
type ClickHouseColumn struct {
Name string
Type string
DefaultKind string
}
func GetTableColumnsMapping(ctx context.Context, logger log.Logger, conn clickhouse.Conn,
tables []string,
) (map[string][]ClickHouseColumn, error) {
tableColumnsMapping := make(map[string][]ClickHouseColumn, len(tables))
queryTables := make([]string, 0, min(len(tables), 200))
for chunk := range slices.Chunk(tables, 200) {
queryTables = queryTables[:0]
for _, table := range chunk {
queryTables = append(queryTables, QuoteLiteral(table))
}
if err := storeColumnInfoForTable(ctx, logger, conn, queryTables, tableColumnsMapping); err != nil {
return nil, fmt.Errorf("failed to get columns for destination tables in chunk: %w", err)
}
}
return tableColumnsMapping, nil
}
func storeColumnInfoForTable(ctx context.Context, logger log.Logger, conn clickhouse.Conn,
queryTables []string,
tableColumnsMapping map[string][]ClickHouseColumn,
) error {
rows, err := Query(ctx, logger, conn,
fmt.Sprintf("SELECT name,type,default_kind,table FROM system.columns WHERE database=currentDatabase() AND table IN (%s)",
strings.Join(queryTables, ",")))
if err != nil {
return fmt.Errorf("failed to get columns for destination tables: %w", err)
}
defer rows.Close()
for rows.Next() {
var tableName string
var clickhouseColumn ClickHouseColumn
if err := rows.Scan(&clickhouseColumn.Name, &clickhouseColumn.Type, &clickhouseColumn.DefaultKind, &tableName); err != nil {
return fmt.Errorf("failed to scan columns for tables: %w", err)
}
tableColumnsMapping[tableName] = append(tableColumnsMapping[tableName], clickhouseColumn)
}
if err := rows.Err(); err != nil {
return fmt.Errorf("failed to read rows: %w", err)
}
return nil
}
func ValidateOrderingKeys(ctx context.Context, logger log.Logger, conn clickhouse.Conn,
chVersion *chvproto.Version, sourceTable string,
hasPrimaryKeys bool, sortingKeys []string, engine string,
) error {
if hasPrimaryKeys || len(sortingKeys) > 0 {
return nil
}
if engine == EngineNull || engine == EngineMergeTree {
return nil
}
if chVersion == nil || !chvproto.CheckMinVersion(chvproto.Version{Major: 25, Minor: 12, Patch: 0}, *chVersion) {
return nil
}
var settingVal string
err := QueryRow(ctx, logger, conn, "SELECT value FROM system.settings WHERE name = 'allow_suspicious_primary_key'").Scan(&settingVal)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("failed to query ClickHouse settings: %w", err)
}
if settingVal == "1" {
return nil
}
return fmt.Errorf(
"cannot determine ORDER BY key from source table %s; empty sort key is not supported",
sourceTable,
)
}
// ValidateClusterShardingKey returns an error when the destination is a multi-shard cluster,
// the source table has no primary key and no custom ordering, and no explicit sharding_key is
// provided. In that configuration ClickHouse would reject writes to the Distributed table
// (error 55: "Method write is not supported by storage Distributed with more than one shard
// and no sharding key provided").
func ValidateClusterShardingKey(cluster, shardingKey, sourceTable string, hasPrimaryKeys bool, sortingKeys []string) error {
if cluster == "" {
return nil
}
if shardingKey != "" || hasPrimaryKeys || len(sortingKeys) > 0 {
return nil
}
return fmt.Errorf(
"table %q has no primary key and no custom ordering columns; "+
"an explicit sharding_key is required for cluster deployments "+
"(e.g. sharding_key: rand() for random distribution across shards)",
sourceTable,
)
}