-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathclickhouse.go
More file actions
1676 lines (1566 loc) · 64.2 KB
/
clickhouse.go
File metadata and controls
1676 lines (1566 loc) · 64.2 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package clickhouse
import (
"context"
"database/sql"
"fmt"
"log/slog"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/Altinity/clickhouse-backup/v2/pkg/common"
"github.com/Altinity/clickhouse-backup/v2/pkg/config"
"github.com/Altinity/clickhouse-backup/v2/pkg/metadata"
"github.com/Altinity/clickhouse-backup/v2/pkg/utils"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
"github.com/antchfx/xmlquery"
"github.com/eapache/go-resiliency/retrier"
"github.com/pkg/errors"
"github.com/ricochet2200/go-disk-usage/du"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// ClickHouse - provide
type ClickHouse struct {
Config *config.ClickHouseConfig
conn driver.Conn
ConnMutex *sync.Mutex
version int
IsOpen bool
BreakConnectOnError bool
}
// zerologSlogHandler adapts slog.Handler interface to write through zerolog.
// Used to bridge clickhouse-go v2 Logger (*slog.Logger) to zerolog.
type zerologSlogHandler struct {
attrs []slog.Attr
}
func (h *zerologSlogHandler) Enabled(_ context.Context, level slog.Level) bool {
return zerolog.GlobalLevel() <= slogToZerologLevel(level)
}
func (h *zerologSlogHandler) Handle(_ context.Context, record slog.Record) error {
event := log.WithLevel(slogToZerologLevel(record.Level))
for _, attr := range h.attrs {
event = event.Str(attr.Key, attr.Value.String())
}
record.Attrs(func(attr slog.Attr) bool {
event = event.Str(attr.Key, attr.Value.String())
return true
})
event.Msg(record.Message)
return nil
}
func (h *zerologSlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &zerologSlogHandler{attrs: append(h.attrs, attrs...)}
}
func (h *zerologSlogHandler) WithGroup(_ string) slog.Handler {
return h
}
func slogToZerologLevel(level slog.Level) zerolog.Level {
switch {
case level >= slog.LevelError:
return zerolog.ErrorLevel
case level >= slog.LevelWarn:
return zerolog.WarnLevel
case level >= slog.LevelInfo:
return zerolog.InfoLevel
default:
return zerolog.DebugLevel
}
}
func NewClickHouse(cfg *config.ClickHouseConfig) *ClickHouse {
return &ClickHouse{
Config: cfg,
ConnMutex: &sync.Mutex{},
}
}
// Connect - establish connection to ClickHouse
func (ch *ClickHouse) Connect() error {
ch.ConnMutex.Lock()
defer ch.ConnMutex.Unlock()
if ch.IsOpen {
if err := ch.conn.Close(); err != nil {
log.Error().Msgf("close previous connection error: %v", err)
}
}
ch.IsOpen = false
timeout, err := time.ParseDuration(ch.Config.Timeout)
if err != nil {
return errors.WithMessage(err, "Connect: parse timeout")
}
//timeoutSeconds := fmt.Sprintf("%d", int(timeout.Seconds()))
opt := &clickhouse.Options{
Addr: []string{fmt.Sprintf("%s:%d", ch.Config.Host, ch.Config.Port)},
Auth: clickhouse.Auth{
Username: ch.Config.Username,
Password: ch.Config.Password,
},
Settings: clickhouse.Settings{
"connect_timeout": int(timeout.Seconds()),
"receive_timeout": int(timeout.Seconds()),
"send_timeout": int(timeout.Seconds()),
"http_send_timeout": 300,
"http_receive_timeout": 300,
},
MaxOpenConns: ch.Config.MaxConnections,
ConnMaxLifetime: 0, // don't change it, it related to SYSTEM SHUTDOWN behavior for properly rebuild RBAC lists on 20.4-22.3
MaxIdleConns: 0,
DialTimeout: timeout,
ReadTimeout: timeout,
}
if ch.Config.Debug {
opt.Logger = slog.New(&zerologSlogHandler{})
}
if ch.Config.Secure {
tlsConfig, err := utils.NewTLSConfig(ch.Config.TLSCa, ch.Config.TLSCert, ch.Config.TLSKey, ch.Config.SkipVerify, true)
if err != nil {
return errors.WithMessage(err, "Connect: create TLS config")
}
opt.TLS = tlsConfig
}
if !ch.Config.LogSQLQueries {
opt.Settings["log_queries"] = 0
} else {
opt.Settings["log_queries"] = 1
}
logLevel := zerolog.InfoLevel
if !ch.Config.LogSQLQueries {
logLevel = zerolog.DebugLevel
}
// infinite reconnect until success, fix https://github.com/Altinity/clickhouse-backup/issues/857
for {
for {
ch.conn, err = clickhouse.Open(opt)
if err == nil {
break
}
if ch.BreakConnectOnError {
return errors.WithStack(err)
}
log.Warn().Msgf("clickhouse connection: %s, sql.Open return error: %v, will wait 5 second to reconnect", fmt.Sprintf("tcp://%v:%v", ch.Config.Host, ch.Config.Port), err)
time.Sleep(5 * time.Second)
}
err = ch.conn.Ping(context.Background())
if err == nil {
log.WithLevel(logLevel).Msgf("clickhouse connection success: %s", fmt.Sprintf("tcp://%v:%v", ch.Config.Host, ch.Config.Port))
ch.IsOpen = true
break
}
if ch.BreakConnectOnError {
return errors.WithStack(err)
}
log.Warn().Msgf("clickhouse connection ping: %s return error: %v, will wait 5 second to reconnect", fmt.Sprintf("tcp://%v:%v", ch.Config.Host, ch.Config.Port), err)
time.Sleep(5 * time.Second)
}
return nil
}
// GetDisks - return data from system.disks table
func (ch *ClickHouse) GetDisks(ctx context.Context, enrich bool) ([]Disk, error) {
version, err := ch.GetVersion(ctx)
if err != nil {
return nil, errors.WithMessage(err, "GetDisks: get version")
}
var disks []Disk
if version < 19015000 {
disks, err = ch.getDisksFromSystemSettings(ctx)
} else {
disks, err = ch.getDisksFromSystemDisks(ctx)
}
if err != nil {
return nil, errors.WithMessage(err, "GetDisks: query disks")
}
for i := range disks {
if disks[i].Name == ch.Config.EmbeddedBackupDisk {
disks[i].IsBackup = true
}
// s3_plain disk could contain relative remote disks path, need transform it to `/var/lib/clickhouse/disks/disk_name`
if disks[i].Path != "" && !strings.HasPrefix(disks[i].Path, "/") {
for _, d := range disks {
if d.Name == "default" {
disks[i].Path = path.Join(d.Path, "disks", disks[i].Name) + "/"
break
}
}
}
}
if len(ch.Config.DiskMapping) == 0 {
return disks, nil
}
dm := map[string]string{}
for k, v := range ch.Config.DiskMapping {
dm[k] = v
}
for i := range disks {
if p, ok := dm[disks[i].Name]; ok {
disks[i].Path = p
delete(dm, disks[i].Name)
}
}
// https://github.com/Altinity/clickhouse-backup/issues/676#issuecomment-1606547960
if enrich {
for k, v := range dm {
disks = append(disks, Disk{
Name: k,
Path: v,
Type: "local",
})
}
}
return disks, nil
}
func (ch *ClickHouse) GetEmbeddedBackupPath(disks []Disk) (string, error) {
if !ch.Config.UseEmbeddedBackupRestore || ch.Config.EmbeddedBackupDisk == "" {
return "", nil
}
for _, d := range disks {
if d.Name == ch.Config.EmbeddedBackupDisk {
return d.Path, nil
}
}
return "", errors.Errorf("%s not found in system.disks %v", ch.Config.EmbeddedBackupDisk, disks)
}
func (ch *ClickHouse) GetDefaultPath(disks []Disk) (string, error) {
defaultPath := "/var/lib/clickhouse"
for _, d := range disks {
if d.Name == "default" {
defaultPath = d.Path
break
}
}
return defaultPath, nil
}
func (ch *ClickHouse) getDisksFromSystemSettings(ctx context.Context) ([]Disk, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
metadataPath, err := ch.getMetadataPath(ctx)
if err != nil {
return nil, errors.WithMessage(err, "getDisksFromSystemSettings: get metadata path")
}
dataPathArray := strings.Split(metadataPath, "/")
clickhouseData := path.Join(dataPathArray[:len(dataPathArray)-1]...)
return []Disk{{
Name: "default",
Path: path.Join("/", clickhouseData),
Type: "local",
FreeSpace: du.NewDiskUsage(path.Join("/", clickhouseData)).Free(),
StoragePolicies: []string{"default"},
}}, nil
}
}
func (ch *ClickHouse) getMetadataPath(ctx context.Context) (string, error) {
var result []struct {
MetadataPath string `ch:"metadata_path"`
}
query := "SELECT metadata_path FROM system.tables WHERE database = 'system' AND metadata_path!='' LIMIT 1"
// https://github.com/ClickHouse/ClickHouse/issues/76546
if ch.version >= 25000000 {
query = "SELECT data_path AS metadata_path FROM system.databases WHERE name = 'system' LIMIT 1"
}
if err := ch.SelectContext(ctx, &result, query); err != nil {
return "", errors.WithMessage(err, "getMetadataPath: select metadata_path")
}
if len(result) == 0 {
return "", errors.New("can't get metadata_path from system.tables or system.databases")
}
metadataPath := strings.Split(result[0].MetadataPath, "/")
// https://github.com/ClickHouse/ClickHouse/issues/76546
if ch.version >= 25000000 && strings.HasSuffix(result[0].MetadataPath, "/store/") {
result[0].MetadataPath = path.Join(metadataPath[:len(metadataPath)-2]...)
result[0].MetadataPath = path.Join(result[0].MetadataPath, "metadata")
} else if strings.Contains(result[0].MetadataPath, "/store/") {
result[0].MetadataPath = path.Join(metadataPath[:len(metadataPath)-4]...)
result[0].MetadataPath = path.Join(result[0].MetadataPath, "metadata")
} else {
result[0].MetadataPath = path.Join(metadataPath[:len(metadataPath)-2]...)
}
return path.Join("/", result[0].MetadataPath), nil
}
func (ch *ClickHouse) getDisksFromSystemDisks(ctx context.Context) ([]Disk, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
type DiskFields struct {
DiskTypePresent uint64 `ch:"is_disk_type_present"`
ObjectStorageTypePresent uint64 `ch:"is_object_storage_type_present"`
FreeSpacePresent uint64 `ch:"is_free_space_present"`
StoragePolicyPresent uint64 `ch:"is_storage_policy_present"`
}
diskFields := make([]DiskFields, 0)
if err := ch.SelectContext(ctx, &diskFields,
"SELECT countIf(name='type') AS is_disk_type_present, "+
"countIf(name='object_storage_type') AS is_object_storage_type_present, "+
"countIf(name='free_space') AS is_free_space_present, "+
"countIf(name='disks') AS is_storage_policy_present "+
"FROM system.columns WHERE database='system' AND table IN ('disks','storage_policies') ",
); err != nil {
return nil, errors.WithMessage(err, "getDisksFromSystemDisks: query disk fields")
}
diskTypeSQL := "'local'"
if len(diskFields) > 0 && diskFields[0].DiskTypePresent > 0 {
diskTypeSQL = "any(d.type)"
}
if len(diskFields) > 0 && diskFields[0].ObjectStorageTypePresent > 0 {
diskTypeSQL = "any(lower(if(d.type='ObjectStorage',d.object_storage_type,d.type)))"
}
diskFreeSpaceSQL := "toUInt64(0)"
if len(diskFields) > 0 && diskFields[0].FreeSpacePresent > 0 {
diskFreeSpaceSQL = "min(d.free_space)"
}
storagePoliciesSQL := "['default']"
joinStoragePoliciesSQL := ""
if len(diskFields) > 0 && diskFields[0].StoragePolicyPresent > 0 {
storagePoliciesSQL = "groupUniqArray(s.policy_name)"
// LEFT JOIN to allow disks which not have policy, https://github.com/Altinity/clickhouse-backup/issues/845
joinStoragePoliciesSQL = " LEFT JOIN "
joinStoragePoliciesSQL += "(SELECT policy_name, arrayJoin(disks) AS disk FROM system.storage_policies) AS s ON s.disk = d.name"
}
var result []Disk
query := fmt.Sprintf(
"SELECT d.path AS path, any(d.name) AS name, %s AS type, %s AS free_space, %s AS storage_policies "+
"FROM system.disks AS d %s GROUP BY d.path",
diskTypeSQL, diskFreeSpaceSQL, storagePoliciesSQL, joinStoragePoliciesSQL,
)
if err := ch.SelectContext(ctx, &result, query); err != nil {
return nil, errors.WithMessage(err, "getDisksFromSystemDisks: select disks")
}
return result, nil
}
}
// Close - closing connection to ClickHouse
func (ch *ClickHouse) Close() {
if ch.IsOpen {
if err := ch.conn.Close(); err != nil {
log.Warn().Msgf("can't close clickhouse connection: %v", err)
}
}
if ch.Config.LogSQLQueries {
log.Info().Msg("clickhouse connection closed")
} else {
log.Debug().Msg("clickhouse connection closed")
}
ch.IsOpen = false
}
// GetTables - return slice of all tables suitable for backup, MySQL and PostgresSQL database engine shall be skipped
func (ch *ClickHouse) GetTables(ctx context.Context, tablePattern string) ([]Table, error) {
var err error
settings := map[string]bool{
"show_table_uuid_in_table_create_query_if_not_nil": false,
"display_secrets_in_show_and_select": false,
}
if settings, err = ch.CheckSettingsExists(ctx, settings); err != nil {
return nil, errors.WithMessage(err, "GetTables: check settings")
}
skipDatabases := make([]struct {
Name string `ch:"name"`
}, 0)
// MaterializedPostgreSQL doesn't support FREEZE look https://github.com/Altinity/clickhouse-backup/issues/550 and https://github.com/ClickHouse/ClickHouse/issues/32902
if err = ch.SelectContext(ctx, &skipDatabases, "SELECT name FROM system.databases WHERE engine IN ('MySQL','PostgreSQL','MaterializedPostgreSQL')"); err != nil {
return nil, errors.WithMessage(err, "GetTables: select skip databases")
}
skipDatabaseNames := make([]string, len(skipDatabases))
for i, s := range skipDatabases {
skipDatabaseNames[i] = s.Name
}
isSystemTablesFieldPresent := make([]IsSystemTablesFieldPresent, 0)
isFieldPresentSQL := `
SELECT
countIf(name='data_path') is_data_path_present,
countIf(name='data_paths') is_data_paths_present,
countIf(name='uuid') is_uuid_present,
countIf(name='create_table_query') is_create_table_query_present,
countIf(name='total_bytes') is_total_bytes_present
FROM system.columns WHERE database='system' AND table='tables'
`
if err = ch.SelectContext(ctx, &isSystemTablesFieldPresent, isFieldPresentSQL); err != nil {
return nil, errors.WithMessage(err, "GetTables: check system.tables fields")
}
allTablesSQL := ch.prepareGetTablesSQL(tablePattern, skipDatabaseNames, ch.Config.SkipTableEngines, settings, isSystemTablesFieldPresent)
tables := make([]Table, 0)
if err = ch.SelectContext(ctx, &tables, allTablesSQL); err != nil {
return nil, errors.WithMessage(err, "GetTables: select tables")
}
for i := range tables {
// https://github.com/Altinity/clickhouse-backup/issues/1091, https://github.com/Altinity/clickhouse-backup/issues/1151
escapeReplacer := strings.NewReplacer(`\`, `\\`)
escapeDb := escapeReplacer.Replace(tables[i].Database)
escapeTable := escapeReplacer.Replace(tables[i].Name)
tables[i].CreateTableQuery = strings.Replace(tables[i].CreateTableQuery, escapeDb, tables[i].Database, 1)
tables[i].CreateTableQuery = strings.Replace(tables[i].CreateTableQuery, escapeTable, tables[i].Name, 1)
}
metadataPath, err := ch.getMetadataPath(ctx)
if err != nil {
return nil, errors.WithMessage(err, "GetTables: get metadata path")
}
for i, t := range tables {
for _, filter := range ch.Config.SkipTables {
if matched, _ := filepath.Match(strings.Trim(filter, " \t\r\n"), fmt.Sprintf("%s.%s", t.Database, t.Name)); matched {
t.Skip = true
break
}
}
if ch.Config.UseEmbeddedBackupRestore && (strings.HasPrefix(t.Name, ".inner_id.") /*|| strings.HasPrefix(t.Name, ".inner.")*/) {
t.Skip = true
}
for _, engine := range ch.Config.SkipTableEngines {
if t.Engine == engine {
t.Skip = true
break
}
}
if t.Skip {
tables[i] = t
continue
}
tables[i] = ch.fixVariousVersions(ctx, t, metadataPath)
}
if len(tables) == 0 {
return tables, nil
}
for i, table := range tables {
if table.TotalBytes == 0 && !table.Skip && strings.HasSuffix(table.Engine, "Tree") {
tables[i].TotalBytes = ch.getTableSizeFromParts(ctx, tables[i])
}
}
// https://github.com/Altinity/clickhouse-backup/issues/613
if !ch.Config.UseEmbeddedBackupRestore {
if tables, err = ch.enrichTablesByInnerDependencies(ctx, tables, metadataPath, settings, isSystemTablesFieldPresent); err != nil {
return nil, errors.WithMessage(err, "GetTables: enrich inner dependencies")
}
}
return tables, nil
}
// https://github.com/Altinity/clickhouse-backup/issues/613
func (ch *ClickHouse) enrichTablesByInnerDependencies(ctx context.Context, tables []Table, metadataPath string, settings map[string]bool, isSystemTablesFieldPresent []IsSystemTablesFieldPresent) ([]Table, error) {
innerTablesMissed := make([]string, 0)
for _, t := range tables {
if !t.Skip && (strings.HasPrefix(t.CreateTableQuery, "ATTACH MATERIALIZED") || strings.HasPrefix(t.CreateTableQuery, "CREATE MATERIALIZED")) {
if strings.Contains(t.CreateTableQuery, " TO ") && !strings.Contains(t.CreateTableQuery, " TO INNER UUID") {
continue
}
found := false
for j := range tables {
if tables[j].Database == t.Database && (tables[j].Name == ".inner."+t.Name || tables[j].Name == ".inner_id."+t.UUID) {
found = true
break
}
}
if !found {
missedInnerTableName := ".inner." + t.Name
if t.UUID != "" {
missedInnerTableName = ".inner_id." + t.UUID
}
innerTablesMissed = append(innerTablesMissed, fmt.Sprintf("%s.%s", t.Database, missedInnerTableName))
}
}
}
if len(innerTablesMissed) == 0 {
return tables, nil
}
missedTablesSQL := ch.prepareGetTablesSQL(strings.Join(innerTablesMissed, ","), nil, nil, settings, isSystemTablesFieldPresent)
missedTables := make([]Table, 0)
var err error
if err = ch.SelectContext(ctx, &missedTables, missedTablesSQL); err != nil {
return nil, errors.WithMessage(err, "enrichTablesByInnerDependencies: select missed tables")
}
if len(missedTables) == 0 {
return tables, nil
}
for i, t := range missedTables {
missedTables[i] = ch.fixVariousVersions(ctx, t, metadataPath)
if t.TotalBytes == 0 && !t.Skip && strings.HasSuffix(t.Engine, "Tree") {
missedTables[i].TotalBytes = ch.getTableSizeFromParts(ctx, missedTables[i])
}
}
return append(missedTables, tables...), nil
}
func (ch *ClickHouse) prepareGetTablesSQL(tablePattern string, skipDatabases, skipTableEngines []string, settings map[string]bool, isSystemTablesFieldPresent []IsSystemTablesFieldPresent) string {
allTablesSQL := "SELECT database, name, engine "
if len(isSystemTablesFieldPresent) > 0 && isSystemTablesFieldPresent[0].IsDataPathPresent > 0 {
allTablesSQL += ", data_path "
}
if len(isSystemTablesFieldPresent) > 0 && isSystemTablesFieldPresent[0].IsDataPathsPresent > 0 {
allTablesSQL += ", data_paths "
}
if len(isSystemTablesFieldPresent) > 0 && isSystemTablesFieldPresent[0].IsUUIDPresent > 0 {
allTablesSQL += ", uuid "
}
if len(isSystemTablesFieldPresent) > 0 && isSystemTablesFieldPresent[0].IsCreateTableQueryPresent > 0 {
allTablesSQL += ", create_table_query "
}
if len(isSystemTablesFieldPresent) > 0 && isSystemTablesFieldPresent[0].IsTotalBytesPresent > 0 {
allTablesSQL += ", coalesce(total_bytes, 0) AS total_bytes "
}
allTablesSQL += " FROM system.tables WHERE is_temporary = 0"
if tablePattern != "" {
// https://github.com/Altinity/clickhouse-backup/issues/1091
replacer := strings.NewReplacer(`\`, `\\\`, ".", "\\.", "$", ".", ",", "$|^", "*", ".*", "?", ".", " ", "", "`", "", `"`, "", "-", "\\-")
allTablesSQL += fmt.Sprintf(" AND match(concat(database,'.',name),'^%s$') ", replacer.Replace(tablePattern))
}
if len(skipDatabases) > 0 {
allTablesSQL += fmt.Sprintf(" AND database NOT IN ('%s')", strings.Join(skipDatabases, "','"))
}
if len(skipTableEngines) > 0 {
allTablesSQL += fmt.Sprintf(" AND NOT has(arrayMap(x->lower(x), ['%s']), lower(engine))", strings.Join(skipTableEngines, "','"))
}
// try to upload big tables first
if len(isSystemTablesFieldPresent) > 0 && isSystemTablesFieldPresent[0].IsTotalBytesPresent > 0 {
allTablesSQL += " ORDER BY total_bytes DESC"
}
allTablesSQL = ch.addSettingsSQL(allTablesSQL, settings)
return allTablesSQL
}
func (ch *ClickHouse) addSettingsSQL(inputSQL string, settings map[string]bool) string {
maxI := 0
for _, v := range settings {
if v {
maxI += 1
}
}
i := 0
for k, v := range settings {
if v {
if i == 0 {
inputSQL += " SETTINGS "
}
inputSQL += k + "=1"
if i < maxI-1 {
inputSQL += ", "
}
i++
}
}
return inputSQL
}
var tableNameSuffixRE = regexp.MustCompile("\\.\"[^\"]+\"$|\\.`[^`]+`$|\\.[a-zA-Z0-9\\-_]+$")
// GetDatabases - return slice of all non system databases for backup
func (ch *ClickHouse) GetDatabases(ctx context.Context, cfg *config.Config, tablePattern string) ([]Database, error) {
allDatabases := make([]Database, 0)
skipDatabases := []string{"system", "INFORMATION_SCHEMA", "information_schema", "_temporary_and_external_tables"}
bypassDatabases := make([]string, 0)
skipTablesPatterns := make([]string, 0)
bypassTablesPatterns := make([]string, 0)
if len(cfg.ClickHouse.SkipTables) > 0 {
skipTablesPatterns = append(skipTablesPatterns, cfg.ClickHouse.SkipTables...)
}
if tablePattern != "" {
bypassTablesPatterns = append(bypassTablesPatterns, strings.Split(tablePattern, ",")...)
}
processDbPatterns := func(databases []string, patterns []string) []string {
for _, pattern := range patterns {
pattern = strings.Trim(pattern, " \r\t\n")
if strings.HasSuffix(pattern, ".*") {
databases = common.AddStringToSliceIfNotExists(databases, strings.Trim(strings.TrimSuffix(pattern, ".*"), "\"` "))
} else {
databases = common.AddStringToSliceIfNotExists(databases, strings.Trim(tableNameSuffixRE.ReplaceAllString(pattern, ""), "\"` "))
}
}
return databases
}
skipDatabases = processDbPatterns(skipDatabases, skipTablesPatterns)
bypassDatabases = processDbPatterns(bypassDatabases, bypassTablesPatterns)
metadataPath, err := ch.getMetadataPath(ctx)
if err != nil {
return nil, errors.WithMessage(err, "GetDatabases: get metadata path")
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
fileMatchToRE := strings.NewReplacer("*", ".*", "?", ".", "(", "\\(", ")", "\\)", "[", "\\[", "]", "\\]", "$", "\\$", "^", "\\^")
if len(bypassDatabases) > 0 {
allDatabasesSQL := fmt.Sprintf(
"SELECT name, engine FROM system.databases WHERE NOT match(name,'^(%s)$') AND match(name,'^(%s)$')",
fileMatchToRE.Replace(strings.Join(skipDatabases, "|")), fileMatchToRE.Replace(strings.Join(bypassDatabases, "|")),
)
if err := ch.StructSelect(&allDatabases, allDatabasesSQL); err != nil {
return nil, errors.WithMessage(err, "GetDatabases: select databases with bypass")
}
} else {
allDatabasesSQL := fmt.Sprintf(
"SELECT name, engine FROM system.databases WHERE NOT match(name,'^(%s)$')",
fileMatchToRE.Replace(strings.Join(skipDatabases, "|")),
)
if err := ch.StructSelect(&allDatabases, allDatabasesSQL); err != nil {
return nil, errors.WithMessage(err, "GetDatabases: select databases")
}
}
}
for i, db := range allDatabases {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
showDatabaseSQL := fmt.Sprintf("SHOW CREATE DATABASE `%s`", db.Name)
var result string
// 19.4 doesn't have /var/lib/clickhouse/metadata/default.sql
if err := ch.SelectSingleRow(ctx, &result, showDatabaseSQL); err != nil {
log.Warn().Msgf("can't get create database query: %v", err)
allDatabases[i].Query = fmt.Sprintf("CREATE DATABASE `%s` ENGINE = %s", db.Name, db.Engine)
} else {
// 23.3+ masked secrets https://github.com/Altinity/clickhouse-backup/issues/640
if strings.Contains(result, "'[HIDDEN]'") {
var attachSQL []byte
var readErr error
if attachSQL, readErr = os.ReadFile(path.Join(metadataPath, common.TablePathEncode(db.Name)+".sql")); readErr != nil {
return nil, errors.WithStack(readErr)
}
result = strings.Replace(string(attachSQL), "ATTACH", "CREATE", 1)
result = strings.Replace(result, " _ ", " `"+db.Name+"` ", 1)
}
allDatabases[i].Query = result
}
}
}
return allDatabases, nil
}
func (ch *ClickHouse) getTableSizeFromParts(ctx context.Context, table Table) uint64 {
var tablesSize []struct {
Size uint64 `ch:"size"`
}
query := fmt.Sprintf("SELECT sum(bytes_on_disk) as size FROM system.parts WHERE active AND database='%s' AND table='%s' GROUP BY database, table", table.Database, table.Name)
if err := ch.SelectContext(ctx, &tablesSize, query); err != nil {
log.Warn().Msgf("error parsing tablesSize: %v", err)
}
if len(tablesSize) > 0 {
return tablesSize[0].Size
}
return 0
}
func (ch *ClickHouse) fixVariousVersions(ctx context.Context, t Table, metadataPath string) Table {
// versions before 19.15 contain data_path in a different column
if t.DataPath != "" {
t.DataPaths = []string{t.DataPath}
}
// version 20.6.3.28 has zero UUID
if t.UUID == "00000000-0000-0000-0000-000000000000" {
t.UUID = ""
}
// version 1.1.54394 has no query column
if strings.TrimSpace(t.CreateTableQuery) == "" {
t.CreateTableQuery = ch.ShowCreateTable(ctx, t.Database, t.Name)
}
// materialized views should properly restore via attach
if t.Engine == "MaterializedView" {
t.CreateTableQuery = strings.Replace(
t.CreateTableQuery, "CREATE MATERIALIZED VIEW", "ATTACH MATERIALIZED VIEW", 1,
)
}
// 23.3+ masked secrets https://github.com/Altinity/clickhouse-backup/issues/640
if strings.Contains(t.CreateTableQuery, "'[HIDDEN]'") {
tableSQLPath := path.Join(metadataPath, common.TablePathEncode(t.Database), common.TablePathEncode(t.Name)+".sql")
if attachSQL, err := os.ReadFile(tableSQLPath); err != nil {
log.Warn().Msgf("can't read %s: %v", tableSQLPath, err)
} else {
t.CreateTableQuery = strings.Replace(string(attachSQL), "ATTACH", "CREATE", 1)
t.CreateTableQuery = strings.Replace(t.CreateTableQuery, " _ ", " `"+t.Database+"`.`"+t.Name+"` ", 1)
}
}
return t
}
// GetVersion - returned ClickHouse version in number format
// Example value: 19001005
func (ch *ClickHouse) GetVersion(ctx context.Context) (int, error) {
if ch.version != 0 {
return ch.version, nil
}
var result string
var err error
query := "SELECT value FROM `system`.`build_options` where name='VERSION_INTEGER'"
if err = ch.SelectSingleRow(ctx, &result, query); err != nil {
log.Warn().Msgf("can't get ClickHouse version: %v", err)
return 0, nil
}
ch.version, err = strconv.Atoi(result)
if err != nil {
return ch.version, errors.WithMessage(err, "GetVersion: parse version integer")
}
return ch.version, nil
}
func (ch *ClickHouse) GetVersionDescribe(ctx context.Context) string {
var result string
query := "SELECT value FROM `system`.`build_options` WHERE name='VERSION_DESCRIBE'"
if err := ch.SelectSingleRow(ctx, &result, query); err != nil {
return ""
}
return result
}
// FreezeTableByParts - freeze all partitions in table one by one
// also ally `freeze_by_part_where`
func (ch *ClickHouse) FreezeTableByParts(ctx context.Context, table *Table, name string) error {
var partitions []struct {
PartitionID string `ch:"partition_id"`
}
q := fmt.Sprintf("SELECT DISTINCT partition_id FROM `system`.`parts` WHERE database='%s' AND table='%s' %s", table.Database, table.Name, ch.Config.FreezeByPartWhere)
if err := ch.SelectContext(ctx, &partitions, q); err != nil {
return errors.Wrapf(err, "can't get partitions for '%s.%s'", table.Database, table.Name)
}
withNameQuery := ""
if name != "" {
withNameQuery = fmt.Sprintf("WITH NAME '%s'", name)
}
for _, item := range partitions {
log.Debug().Msgf(" partition '%v'", item.PartitionID)
query := fmt.Sprintf(
"ALTER TABLE `%v`.`%v` FREEZE PARTITION ID '%v' %s;",
table.Database,
table.Name,
item.PartitionID,
withNameQuery,
)
if item.PartitionID == "all" {
query = fmt.Sprintf(
"ALTER TABLE `%v`.`%v` FREEZE PARTITION tuple() %s;",
table.Database,
table.Name,
withNameQuery,
)
}
if err := ch.QueryContext(ctx, query); err != nil {
if (strings.Contains(err.Error(), "code: 60") || strings.Contains(err.Error(), "code: 81")) && ch.Config.IgnoreNotExistsErrorDuringFreeze {
log.Warn().Msgf("can't freeze partition: %v", err)
} else {
return errors.Wrapf(err, "can't freeze partition '%s'", item.PartitionID)
}
}
}
return nil
}
// FreezeTable - freeze all partitions for table
// This way available for ClickHouse since v19.1
func (ch *ClickHouse) FreezeTable(ctx context.Context, table *Table, name string) error {
version, err := ch.GetVersion(ctx)
if err != nil {
return errors.WithMessage(err, "FreezeTable: get version")
}
if strings.HasPrefix(table.Engine, "Replicated") && ch.Config.SyncReplicatedTables {
query := fmt.Sprintf("SYSTEM SYNC REPLICA `%s`.`%s`;", table.Database, table.Name)
if err := ch.QueryContext(ctx, query); err != nil {
log.Warn().Msgf("can't sync replica: %v", err)
} else {
log.Debug().Str("table", fmt.Sprintf("%s.%s", table.Database, table.Name)).Msg("replica synced")
}
}
if version < 19001005 || ch.Config.FreezeByPart {
return ch.FreezeTableByParts(ctx, table, name)
}
withNameQuery := ""
if name != "" {
withNameQuery = fmt.Sprintf("WITH NAME '%s'", name)
}
query := fmt.Sprintf("ALTER TABLE `%s`.`%s` FREEZE %s;", table.Database, table.Name, withNameQuery)
if err := ch.QueryContext(ctx, query); err != nil {
if (strings.Contains(err.Error(), "code: 60") || strings.Contains(err.Error(), "code: 81") || strings.Contains(err.Error(), "code: 218")) && ch.Config.IgnoreNotExistsErrorDuringFreeze {
log.Warn().Msgf("can't freeze table: %v", err)
return nil
}
return errors.Wrap(err, "can't freeze table")
}
return nil
}
// AttachDataParts - execute ALTER TABLE ... ATTACH PART command for specific table
func (ch *ClickHouse) AttachDataParts(table metadata.TableMetadata, dstTable Table) error {
if dstTable.Database != "" && dstTable.Database != table.Database {
table.Database = dstTable.Database
}
if dstTable.Name != "" && dstTable.Name != table.Table {
table.Table = dstTable.Name
}
canContinue, err := ch.CheckReplicationInProgress(table)
if err != nil {
return errors.WithMessage(err, "AttachDataParts: check replication")
}
if !canContinue {
return nil
}
for disk := range table.Parts {
// https://github.com/ClickHouse/ClickHouse/issues/71009
metadata.SortPartsByMinBlock(table.Parts[disk])
for _, part := range table.Parts[disk] {
if !strings.HasSuffix(part.Name, ".proj") {
query := fmt.Sprintf("ALTER TABLE `%s`.`%s` ATTACH PART '%s'", table.Database, table.Table, part.Name)
if err := ch.Query(query); err != nil {
return errors.WithMessage(err, "AttachDataParts: attach part")
}
log.Debug().Str("table", fmt.Sprintf("%s.%s", table.Database, table.Table)).Str("disk", disk).Str("part", part.Name).Msg("attached")
}
}
}
return nil
}
var replicatedMergeTreeRE = regexp.MustCompile(`Replicated[\w_]*MergeTree\s*\(((\s*'[^']+'\s*),(\s*'[^']+')(\s*,\s*|.*?)([^)]*)|)\)`)
var uuidRE = regexp.MustCompile(`UUID '([^']+)'`)
// AttachTable - execute ATTACH TABLE command for specific table
func (ch *ClickHouse) AttachTable(ctx context.Context, table metadata.TableMetadata, dstTable Table) error {
if len(table.Parts) == 0 {
log.Warn().Msgf("no data parts for restore for `%s`.`%s`", table.Database, table.Table)
return nil
}
if dstTable.Database != "" && dstTable.Database != table.Database {
table.Database = dstTable.Database
}
if dstTable.Name != "" && dstTable.Name != table.Table {
table.Table = dstTable.Name
}
canContinue, err := ch.CheckReplicationInProgress(table)
if err != nil {
return errors.Wrap(err, "ch.CheckReplicationInProgress error")
}
if !canContinue {
return nil
}
if ch.version <= 21003000 {
return errors.New("your clickhouse-server version doesn't support SYSTEM RESTORE REPLICA statement, use `restore_as_attach: false` in config")
}
query := fmt.Sprintf("DETACH TABLE `%s`.`%s` SYNC", table.Database, table.Table)
if err := ch.Query(query); err != nil {
return errors.Wrapf(err, "%s error", query)
}
replicatedMatches := replicatedMergeTreeRE.FindStringSubmatch(table.Query)
if len(replicatedMatches) > 0 {
zkPath := strings.Trim(replicatedMatches[2], "' \r\n\t")
replicaName := strings.Trim(replicatedMatches[3], "' \r\n\t")
if strings.Contains(zkPath, "{uuid}") {
if uuidMatches := uuidRE.FindStringSubmatch(table.Query); len(uuidMatches) > 0 {
zkPath = strings.Replace(zkPath, "{uuid}", uuidMatches[1], 1)
}
}
zkPath = strings.NewReplacer("{database}", table.Database, "{table}", table.Table).Replace(zkPath)
zkPath, err = ch.ApplyMacros(ctx, zkPath)
if err != nil {
return errors.Wrap(err, "ch.ApplyMacros(ctx, zkPath) error")
}
replicaName, err = ch.ApplyMacros(ctx, replicaName)
if err != nil {
return errors.Wrap(err, "ch.ApplyMacros(ctx, replicaName) error")
}
query = fmt.Sprintf("SYSTEM DROP REPLICA '%s' FROM ZKPATH '%s'", replicaName, zkPath)
if err := ch.Query(query); err != nil {
return errors.Wrapf(err, "%s error", query)
}
}
query = fmt.Sprintf("ATTACH TABLE `%s`.`%s`", table.Database, table.Table)
if err := ch.Query(query); err != nil {
return errors.Wrapf(err, "%s error", query)
}
if len(replicatedMatches) > 0 {
query = fmt.Sprintf("SYSTEM RESTORE REPLICA `%s`.`%s`", table.Database, table.Table)
if err := ch.Query(query); err != nil {
return errors.Wrapf(err, "%s error", query)
}
}
log.Debug().Str("table", fmt.Sprintf("%s.%s", table.Database, table.Table)).Msg("attached")
return nil
}
func (ch *ClickHouse) ShowCreateTable(ctx context.Context, database, name string) string {
var result []struct {
Statement string `ch:"statement"`
}
query := fmt.Sprintf("SHOW CREATE TABLE `%s`.`%s`;", database, name)
if err := ch.SelectContext(ctx, &result, query); err != nil {
return ""
}
return result[0].Statement
}
// CreateDatabase - create ClickHouse database
func (ch *ClickHouse) CreateDatabase(database string, cluster string) error {
query := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s`", database)
if cluster != "" {
query += fmt.Sprintf(" ON CLUSTER '%s'", cluster)
}
if err := ch.Query(query); err != nil {
return errors.WithMessage(err, "CreateDatabase")
}
return nil
}
func (ch *ClickHouse) CreateDatabaseWithEngine(database, engine, cluster string, version int) error {
if version <= 24004000 {
engine = strings.Replace(engine, "{database}", database, -1)
}
query := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` ENGINE=%s", database, engine)
query = ch.addOnClusterToCreateDatabase(cluster, query)
if err := ch.Query(query); err != nil {
return errors.WithMessage(err, "CreateDatabaseWithEngine")
}
return nil
}
func (ch *ClickHouse) CreateDatabaseFromQuery(ctx context.Context, query, cluster string, args ...interface{}) error {
if !strings.HasPrefix(query, "CREATE DATABASE IF NOT EXISTS") {
query = strings.Replace(query, "CREATE DATABASE", "CREATE DATABASE IF NOT EXISTS", 1)
}
query = ch.addOnClusterToCreateDatabase(cluster, query)
if err := ch.QueryContext(ctx, query, args); err != nil {
return errors.WithMessage(err, "CreateDatabaseFromQuery")
}
return nil
}
func (ch *ClickHouse) addOnClusterToCreateDatabase(cluster string, query string) string {
if cluster != "" && !strings.Contains(query, " ON CLUSTER ") {
if !strings.Contains(query, "ENGINE") {
query += fmt.Sprintf(" ON CLUSTER '%s'", cluster)
} else {
query = strings.Replace(query, "ENGINE", fmt.Sprintf(" ON CLUSTER '%s' ENGINE", cluster), 1)
}
}
return query
}
// DropOrDetachTable - drop ClickHouse table
func (ch *ClickHouse) DropOrDetachTable(table Table, query, onCluster string, ignoreDependencies bool, version int, defaultDataPath string, useDetach bool, databaseEngine string) error {
var isAtomicOrReplicated bool
var err error
if databaseEngine == "" {
if databaseEngine, err = ch.GetDatabaseEngine(table.Database); err != nil {
return errors.WithMessage(err, "DropOrDetachTable: get database engine")
}
}
isAtomicOrReplicated = strings.HasPrefix(databaseEngine, "Atomic") || strings.HasPrefix(databaseEngine, "Replicated")
kind := "TABLE"
if strings.HasPrefix(query, "CREATE DICTIONARY") {
kind = "DICTIONARY"
}
action := "DROP"
if useDetach {
action = "DETACH"
}
dropQuery := fmt.Sprintf("%s %s IF EXISTS `%s`.`%s`", action, kind, table.Database, table.Name)
if version > 19000000 && onCluster != "" {
// https://github.com/Altinity/clickhouse-backup/issues/1127
if !strings.HasPrefix(databaseEngine, "Replicated") {
dropQuery += " ON CLUSTER '" + onCluster + "' "
} else {
log.Warn().Msgf("can't drop or detach table `%s`.`%s` on cluster for database engine=Replicated, will drop only in current host", table.Database, table.Name)
}
}
if isAtomicOrReplicated {
dropQuery += " NO DELAY"
}
if ignoreDependencies {
dropQuery += " SETTINGS check_table_dependencies=0"
}
if defaultDataPath != "" && !useDetach {
var f *os.File