-
Notifications
You must be signed in to change notification settings - Fork 209
/
clickhouse.go
1337 lines (1255 loc) · 47.4 KB
/
clickhouse.go
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"
"crypto/tls"
"crypto/x509"
"database/sql"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"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/ClickHouse/clickhouse-go/v2"
"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
"github.com/antchfx/xmlquery"
apexLog "github.com/apex/log"
"github.com/ricochet2200/go-disk-usage/du"
)
// ClickHouse - provide
type ClickHouse struct {
Config *config.ClickHouseConfig
Log *apexLog.Entry
conn driver.Conn
version int
isPartsColumnPresent int8
IsOpen bool
}
// Connect - establish connection to ClickHouse
func (ch *ClickHouse) Connect() error {
if ch.IsOpen {
if err := ch.conn.Close(); err != nil {
ch.Log.Errorf("close previous connection error: %v", err)
}
}
ch.IsOpen = false
timeout, err := time.ParseDuration(ch.Config.Timeout)
if err != nil {
return err
}
//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()),
},
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: 1,
DialTimeout: timeout,
ReadTimeout: timeout,
}
if ch.Config.Debug {
opt.Debug = true
}
if ch.Config.Secure {
tlsConfig := &tls.Config{
InsecureSkipVerify: ch.Config.SkipVerify,
}
if ch.Config.TLSKey != "" || ch.Config.TLSCert != "" || ch.Config.TLSCa != "" {
if ch.Config.TLSCert != "" || ch.Config.TLSKey != "" {
cert, err := tls.LoadX509KeyPair(ch.Config.TLSCert, ch.Config.TLSKey)
if err != nil {
ch.Log.Errorf("tls.LoadX509KeyPair error: %v", err)
return err
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
if ch.Config.TLSCa != "" {
caCert, err := os.ReadFile(ch.Config.TLSCa)
if err != nil {
ch.Log.Errorf("read `tls_ca` file %s return error: %v ", ch.Config.TLSCa, err)
return err
}
caCertPool := x509.NewCertPool()
if caCertPool.AppendCertsFromPEM(caCert) != true {
ch.Log.Errorf("AppendCertsFromPEM %s return false", ch.Config.TLSCa)
return fmt.Errorf("AppendCertsFromPEM %s return false", ch.Config.TLSCa)
}
tlsConfig.RootCAs = caCertPool
}
}
opt.TLS = tlsConfig
}
if !ch.Config.LogSQLQueries {
opt.Settings["log_queries"] = 0
}
if ch.conn, err = clickhouse.Open(opt); err != nil {
ch.Log.Errorf("clickhouse connection: %s, sql.Open return error: %v", fmt.Sprintf("tcp://%v:%v", ch.Config.Host, ch.Config.Port), err)
return err
}
logFunc := ch.Log.Infof
if !ch.Config.LogSQLQueries {
logFunc = ch.Log.Debugf
}
logFunc("clickhouse connection prepared: %s run ping", fmt.Sprintf("tcp://%v:%v", ch.Config.Host, ch.Config.Port))
err = ch.conn.Ping(context.Background())
if err != nil {
ch.Log.Errorf("clickhouse connection ping: %s return error: %v", fmt.Sprintf("tcp://%v:%v", ch.Config.Host, ch.Config.Port), err)
return err
} else {
ch.IsOpen = true
}
logFunc("clickhouse connection open: %s", fmt.Sprintf("tcp://%v:%v", ch.Config.Host, ch.Config.Port))
return err
}
// 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, err
}
var disks []Disk
if version < 19015000 {
disks, err = ch.getDisksFromSystemSettings(ctx)
} else {
disks, err = ch.getDisksFromSystemDisks(ctx)
}
if err != nil {
return nil, err
}
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 {
return "", nil
}
if ch.Config.EmbeddedBackupDisk == "" {
return "", fmt.Errorf("please setup `clickhouse->embedded_backup_disk` in config or CLICKHOUSE_EMBEDDED_BACKUP_DISK environment variable")
}
for _, d := range disks {
if d.Name == ch.Config.EmbeddedBackupDisk {
return d.Path, nil
}
}
return "", fmt.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, err
}
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;"
if err := ch.SelectContext(ctx, &result, query); err != nil {
return "", err
}
if len(result) == 0 {
return "", fmt.Errorf("can't get metadata_path from system.tables")
}
metadataPath := strings.Split(result[0].MetadataPath, "/")
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"`
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='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, err
}
diskTypeSQL := "'local'"
if len(diskFields) > 0 && diskFields[0].DiskTypePresent > 0 {
diskTypeSQL = "any(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)"
joinStoragePoliciesSQL = " INNER JOIN "
if ch.Config.UseEmbeddedBackupRestore {
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, 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,
)
err := ch.SelectContext(ctx, &result, query)
return result, err
}
}
// Close - closing connection to ClickHouse
func (ch *ClickHouse) Close() {
if ch.IsOpen {
if err := ch.conn.Close(); err != nil {
ch.Log.Warnf("can't close clickhouse connection: %v", err)
}
}
if ch.Config.LogSQLQueries {
ch.Log.Info("clickhouse connection closed")
} else {
ch.Log.Debug("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, err
}
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, err
}
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, err
}
allTablesSQL := ch.prepareGetTablesSQL(tablePattern, skipDatabaseNames, ch.Config.SkipTableEngines, settings, isSystemTablesFieldPresent)
if err != nil {
return nil, err
}
tables := make([]Table, 0)
if err = ch.SelectContext(ctx, &tables, allTablesSQL); err != nil {
return nil, err
}
metadataPath, err := ch.getMetadataPath(ctx)
if err != nil {
return nil, err
}
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
}
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, err
}
}
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, err
}
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 != "" {
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 engine NOT IN ('%s')", 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, ",")...)
}
for _, pattern := range skipTablesPatterns {
pattern = strings.Trim(pattern, " \r\t\n")
if strings.HasSuffix(pattern, ".*") {
skipDatabases = common.AddStringToSliceIfNotExists(skipDatabases, strings.Trim(strings.TrimSuffix(pattern, ".*"), "\"` "))
} else {
skipDatabases = common.AddStringToSliceIfNotExists(skipDatabases, strings.Trim(tableNameSuffixRE.ReplaceAllString(pattern, ""), "\"` "))
}
}
for _, pattern := range bypassTablesPatterns {
pattern = strings.Trim(pattern, " \r\t\n")
if strings.HasSuffix(pattern, ".*") {
bypassDatabases = common.AddStringToSliceIfNotExists(bypassDatabases, strings.Trim(strings.TrimSuffix(pattern, ".*"), "\"` "))
} else {
bypassDatabases = common.AddStringToSliceIfNotExists(bypassDatabases, strings.Trim(tableNameSuffixRE.ReplaceAllString(pattern, ""), "\"` "))
}
}
metadataPath, err := ch.getMetadataPath(ctx)
if err != nil {
return nil, err
}
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, err
}
} 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, err
}
}
}
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 {
ch.Log.Warnf("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]'") {
if attachSQL, err := os.ReadFile(path.Join(metadataPath, common.TablePathEncode(db.Name)+".sql")); err != nil {
return nil, err
} else {
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 {
ch.Log.Warnf("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 {
ch.Log.Warnf("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 {
ch.Log.Warnf("can't get ClickHouse version: %v", err)
return 0, nil
}
ch.version, err = strconv.Atoi(result)
return ch.version, err
}
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
}
// FreezeTableOldWay - freeze all partitions in table one by one
// This way using for ClickHouse below v19.1
func (ch *ClickHouse) FreezeTableOldWay(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 fmt.Errorf("can't get partitions for '%s.%s': %w", table.Database, table.Name, err)
}
withNameQuery := ""
if name != "" {
withNameQuery = fmt.Sprintf("WITH NAME '%s'", name)
}
for _, item := range partitions {
ch.Log.Debugf(" 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 {
ch.Log.Warnf("can't freeze partition: %v", err)
} else {
return fmt.Errorf("can't freeze partition '%s': %w", item.PartitionID, err)
}
}
}
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 err
}
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 {
ch.Log.Warnf("can't sync replica: %v", err)
} else {
ch.Log.WithField("table", fmt.Sprintf("%s.%s", table.Database, table.Name)).Debugf("replica synced")
}
}
if version < 19001005 || ch.Config.FreezeByPart {
return ch.FreezeTableOldWay(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 {
ch.Log.Warnf("can't freeze table: %v", err)
return nil
}
return fmt.Errorf("can't freeze table: %v", err)
}
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
}
canContinue, err := ch.CheckReplicationInProgress(table)
if err != nil {
return err
}
if !canContinue {
return nil
}
for disk := range table.Parts {
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 err
}
ch.Log.WithField("table", fmt.Sprintf("%s.%s", table.Database, table.Table)).WithField("disk", disk).WithField("part", part.Name).Debug("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 {
apexLog.Warnf("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
}
canContinue, err := ch.CheckReplicationInProgress(table)
if err != nil {
return err
}
if !canContinue {
return nil
}
if ch.version <= 21003000 {
return fmt.Errorf("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`", table.Database, table.Table)
if err := ch.Query(query); err != nil {
return err
}
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 err
}
replicaName, err = ch.ApplyMacros(ctx, replicaName)
if err != nil {
return err
}
query = fmt.Sprintf("SYSTEM DROP REPLICA '%s' FROM ZKPATH '%s'", replicaName, zkPath)
if err := ch.Query(query); err != nil {
return err
}
}
query = fmt.Sprintf("ATTACH TABLE `%s`.`%s`", table.Database, table.Table)
if err := ch.Query(query); err != nil {
return err
}
if len(replicatedMatches) > 0 {
query = fmt.Sprintf("SYSTEM RESTORE REPLICA `%s`.`%s`", table.Database, table.Table)
if err := ch.Query(query); err != nil {
return err
}
}
ch.Log.WithField("table", fmt.Sprintf("%s.%s", table.Database, table.Table)).Debug("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)
}
return ch.Query(query)
}
func (ch *ClickHouse) CreateDatabaseWithEngine(database, engine, cluster string) error {
query := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` ENGINE=%s", database, engine)
query = ch.addOnClusterToCreateDatabase(cluster, query)
return ch.Query(query)
}
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)
return ch.QueryContext(ctx, query, args)
}
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
}
// DropTable - drop ClickHouse table
func (ch *ClickHouse) DropTable(table Table, query string, onCluster string, ignoreDependencies bool, version int, defaultDataPath string) error {
var isAtomic bool
var err error
if isAtomic, err = ch.IsAtomic(table.Database); err != nil {
return err
}
kind := "TABLE"
if strings.HasPrefix(query, "CREATE DICTIONARY") {
kind = "DICTIONARY"
}
dropQuery := fmt.Sprintf("DROP %s IF EXISTS `%s`.`%s`", kind, table.Database, table.Name)
if version > 19000000 && onCluster != "" {
dropQuery += " ON CLUSTER '" + onCluster + "' "
}
if isAtomic {
dropQuery += " NO DELAY"
}
if ignoreDependencies {
dropQuery += " SETTINGS check_table_dependencies=0"
}
if defaultDataPath != "" {
if _, err = os.Create(path.Join(defaultDataPath, "/flags/force_drop_table")); err != nil {
return err
}
}
if err = ch.Query(dropQuery); err != nil {
return err
}
return nil
}
var createViewToClauseRe = regexp.MustCompile(`(?im)^(CREATE[\s\w]+VIEW[^(]+)(\s+TO\s+.+)`)
var createViewSelectRe = regexp.MustCompile(`(?im)^(CREATE[\s\w]+VIEW[^(]+)(\s+AS\s+SELECT.+)`)
var attachViewToClauseRe = regexp.MustCompile(`(?im)^(ATTACH[\s\w]+VIEW[^(]+)(\s+TO\s+.+)`)
var attachViewSelectRe = regexp.MustCompile(`(?im)^(ATTACH[\s\w]+VIEW[^(]+)(\s+AS\s+SELECT.+)`)
var createObjRe = regexp.MustCompile(`(?is)^(CREATE [^(]+)(\(.+)`)
var onClusterRe = regexp.MustCompile(`(?im)\s+ON\s+CLUSTER\s+`)
var distributedRE = regexp.MustCompile(`(Distributed)\(([^,]+),([^)]+)\)`)
// CreateTable - create ClickHouse table
func (ch *ClickHouse) CreateTable(table Table, query string, dropTable, ignoreDependencies bool, onCluster string, version int, defaultDataPath string) error {
var err error
if dropTable {
if err = ch.DropTable(table, query, onCluster, ignoreDependencies, version, defaultDataPath); err != nil {
return err
}
}
if version > 19000000 && onCluster != "" && !onClusterRe.MatchString(query) {
tryMatchReList := []*regexp.Regexp{attachViewToClauseRe, attachViewSelectRe, createViewToClauseRe, createViewSelectRe, createObjRe}
for _, tryMatchRe := range tryMatchReList {
if tryMatchRe.MatchString(query) {
query = tryMatchRe.ReplaceAllString(query, "$1 ON CLUSTER '"+onCluster+"' $2")
break
}
}
}
if !strings.Contains(query, table.Name) {
return errors.New(fmt.Sprintf("schema query ```%s``` doesn't contains table name `%s`", query, table.Name))
}
// fix restore schema for legacy backup
// see https://github.com/Altinity/clickhouse-backup/issues/268
// https://github.com/Altinity/clickhouse-backup/issues/297
// https://github.com/Altinity/clickhouse-backup/issues/331
isOnlyTableWithQuotesPresent, err := regexp.Match(fmt.Sprintf("^CREATE [^(\\.]+ `%s`", table.Name), []byte(query))
if err != nil {
return err
}
isOnlyTableWithQuotesPresent = isOnlyTableWithQuotesPresent && !strings.Contains(query, fmt.Sprintf("`%s`.`%s`", table.Database, table.Name))
isOnlyTablePresent, err := regexp.Match(fmt.Sprintf("^CREATE [^(\\.]+ %s", table.Name), []byte(query))
if err != nil {
return err
}
isOnlyTablePresent = isOnlyTablePresent && !strings.Contains(query, fmt.Sprintf("%s.%s", table.Database, table.Name))
if isOnlyTableWithQuotesPresent && table.Database != "" {
query = strings.Replace(query, fmt.Sprintf("`%s`", table.Name), fmt.Sprintf("`%s`.`%s`", table.Database, table.Name), 1)
} else if isOnlyTablePresent && table.Database != "" {
query = strings.Replace(query, fmt.Sprintf("%s", table.Name), fmt.Sprintf("%s.%s", table.Database, table.Name), 1)
}
// https://github.com/Altinity/clickhouse-backup/issues/574, replace ENGINE=Distributed to new cluster name
if onCluster != "" && distributedRE.MatchString(query) {
matches := distributedRE.FindAllStringSubmatch(query, -1)
if onCluster != strings.Trim(matches[0][2], "'\" ") {
apexLog.Warnf("Will replace cluster ENGINE=Distributed %s -> %s", matches[0][2], onCluster)
query = distributedRE.ReplaceAllString(query, fmt.Sprintf("${1}(%s,${3})", onCluster))
}
}
if err := ch.Query(query); err != nil {
return err
}
return nil
}
// GetConn - return current connection
func (ch *ClickHouse) GetConn() driver.Conn {
return ch.conn
}
func (ch *ClickHouse) IsClickhouseShadow(path string) bool {
d, err := os.Open(path)
if err != nil {
return false
}
defer func() {
if err := d.Close(); err != nil {
ch.Log.Warnf("can't close directory %v", err)
}
}()
names, err := d.Readdirnames(-1)
if err != nil {
return false
}
for _, name := range names {
if name == "increment.txt" {
continue
}
if _, err := strconv.Atoi(name); err != nil {
return false
}
}
return true
}
func (ch *ClickHouse) StructSelect(dest interface{}, query string, args ...interface{}) error {
return ch.SelectContext(context.Background(), dest, query, args...)
}