-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathzip_test.go
1456 lines (1260 loc) · 42.1 KB
/
zip_test.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
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package cli
import (
"archive/zip"
"bytes"
"context"
enc_hex "encoding/hex"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync/atomic"
"testing"
"time"
_ "github.com/cockroachdb/cockroach/pkg/backup"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/jobs/jobstest"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/datapathutils"
"github.com/cockroachdb/cockroach/pkg/testutils/jobutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestZipContainsAllInternalTables verifies that we don't add new internal tables
// without also taking them into account in a `debug zip`. If this test fails,
// add your table to either of the []string slices referenced in the test (which
// are used by `debug zip`) or add it as an exception after having verified that
// it indeed should not be collected (this is rare).
// NB: if you're adding a new one, you'll also have to update TestZip.
func TestZipContainsAllInternalTables(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, db, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(context.Background())
rows, err := db.Query(`
SELECT concat('crdb_internal.', table_name) as name
FROM [ SELECT table_name FROM [ SHOW TABLES FROM crdb_internal ] ]
WHERE
table_name NOT IN (
-- allowlisted tables that don't need to be in debug zip
'backward_dependencies',
'builtin_functions',
'cluster_contended_keys',
'cluster_contended_indexes',
'cluster_contended_tables',
'cluster_execution_insights',
'cluster_inflight_traces',
'cluster_txn_execution_insights',
'cross_db_references',
'databases',
'forward_dependencies',
'gossip_network',
'index_columns',
'index_spans',
'kv_builtin_function_comments',
'kv_catalog_comments',
'kv_catalog_descriptor',
'kv_catalog_namespace',
'kv_catalog_zones',
'kv_repairable_catalog_corruptions',
'kv_dropped_relations',
'kv_inherited_role_members',
'kv_flow_control_handles',
'kv_flow_control_handles_v2',
'kv_flow_controller',
'kv_flow_controller_v2',
'kv_flow_token_deductions',
'kv_flow_token_deductions_v2',
'lost_descriptors_with_data',
'table_columns',
'table_row_statistics',
'ranges',
'ranges_no_leases',
'predefined_comments',
'session_trace',
'session_variables',
'table_spans',
'tables',
'cluster_statement_statistics',
'statement_activity',
'statement_statistics_persisted',
'statement_statistics_persisted_v22_2',
'store_liveness_support_for',
'store_liveness_support_from',
'cluster_transaction_statistics',
'statement_statistics',
'transaction_activity',
'transaction_statistics_persisted',
'transaction_statistics_persisted_v22_2',
'transaction_statistics',
'tenant_usage_details',
'pg_catalog_table_is_implemented',
'fully_qualified_names'
)
ORDER BY name ASC`)
assert.NoError(t, err)
var tables []string
for rows.Next() {
var table string
assert.NoError(t, rows.Scan(&table))
tables = append(tables, table)
}
tables = append(tables, "crdb_internal.probe_ranges_1s_read_limit_100")
sort.Strings(tables)
var exp []string
exp = append(exp, zipInternalTablesPerNode.GetTables()...)
for _, t := range zipInternalTablesPerCluster.GetTables() {
t = strings.TrimPrefix(t, `"".`)
exp = append(exp, t)
}
sort.Strings(exp)
assert.Equal(t, exp, tables)
}
// This tests the operation of zip over secure clusters.
func TestZip(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "test too slow under race")
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
c := NewCLITest(TestCLIParams{
StoreSpecs: []base.StoreSpec{{
Path: dir,
}},
})
defer c.Cleanup()
out, err := c.RunWithCapture("debug zip --concurrency=1 --cpu-profile-duration=1s " + os.DevNull)
if err != nil {
t.Fatal(err)
}
// Strip any non-deterministic messages.
out = eraseNonDeterministicZipOutput(out)
// We use datadriven simply to read the golden output file; we don't actually
// run any commands. Using datadriven allows TESTFLAGS=-rewrite.
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "testzip"), func(t *testing.T, td *datadriven.TestData) string {
return out
})
}
// This tests the operation of zip over secure clusters.
func TestZipQueryFallback(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "test too slow under race")
existing := zipInternalTablesPerCluster["crdb_internal.transaction_contention_events"]
// Avoid leaking configuration changes after the tests end.
defer func() {
zipInternalTablesPerCluster["crdb_internal.transaction_contention_events"] = existing
}()
zipInternalTablesPerCluster["crdb_internal.transaction_contention_events"] = TableRegistryConfig{
nonSensitiveCols: existing.nonSensitiveCols,
// We want this to fail to trigger the fallback.
customQueryUnredacted: "SELECT FAIL;",
customQueryUnredactedFallback: existing.customQueryUnredactedFallback,
}
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
c := NewCLITest(TestCLIParams{
StoreSpecs: []base.StoreSpec{{
Path: dir,
}},
})
defer c.Cleanup()
out, err := c.RunWithCapture("debug zip --concurrency=1 --cpu-profile-duration=1s " + os.DevNull)
if err != nil {
t.Fatal(err)
}
// Strip any non-deterministic messages.
out = eraseNonDeterministicZipOutput(out)
// We use datadriven simply to read the golden output file; we don't actually
// run any commands. Using datadriven allows TESTFLAGS=-rewrite.
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "testzip_fallback"), func(t *testing.T, td *datadriven.TestData) string {
return out
})
}
// This tests the operation of redacted zip over secure clusters.
func TestZipRedacted(t *testing.T) {
defer leaktest.AfterTest(t)()
skip.UnderRace(t, "test too slow under race")
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
c := NewCLITest(TestCLIParams{
StoreSpecs: []base.StoreSpec{{
Path: dir,
}},
})
defer c.Cleanup()
out, err := c.RunWithCapture("debug zip --concurrency=1 --cpu-profile-duration=1s --redact " + os.DevNull)
if err != nil {
t.Fatal(err)
}
// Strip any non-deterministic messages.
out = eraseNonDeterministicZipOutput(out)
// We use datadriven simply to read the golden output file; we don't actually
// run any commands. Using datadriven allows TESTFLAGS=-rewrite.
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "testzip_redacted"), func(t *testing.T, td *datadriven.TestData) string {
return out
})
}
// This tests the operation of zip using --include-goroutine-stacks.
func TestZipIncludeGoroutineStacks(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "test too slow under race")
tests := []struct {
name string
includeStacks bool
outputFileName string
}{
{
name: "includes goroutine stacks",
includeStacks: true,
outputFileName: "testzip_include_goroutine_stacks",
},
{
name: "excludes goroutine stacks",
includeStacks: false,
outputFileName: "testzip_exclude_goroutine_stacks",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
c := NewCLITest(TestCLIParams{
StoreSpecs: []base.StoreSpec{{
Path: dir,
}},
})
defer c.Cleanup()
cmd := "debug zip --concurrency=1 --cpu-profile-duration=1s "
if !tc.includeStacks {
cmd = cmd + "--include-goroutine-stacks=false "
}
out, err := c.RunWithCapture(cmd + os.DevNull)
if err != nil {
t.Fatal(err)
}
// Strip any non-deterministic messages.
out = eraseNonDeterministicZipOutput(out)
// We use datadriven simply to read the golden output file; we don't actually
// run any commands. Using datadriven allows TESTFLAGS=-rewrite.
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", tc.outputFileName),
func(t *testing.T, td *datadriven.TestData) string {
return out
},
)
})
}
}
// This tests the operation of zip using --include-range-info.
func TestZipIncludeRangeInfo(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "test too slow under race")
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
c := NewCLITest(TestCLIParams{
StoreSpecs: []base.StoreSpec{{
Path: dir,
}},
})
defer c.Cleanup()
out, err := c.RunWithCapture("debug zip --concurrency=1 --cpu-profile-duration=1s --include-range-info " + os.DevNull)
if err != nil {
t.Fatal(err)
}
// Strip any non-deterministic messages.
out = eraseNonDeterministicZipOutput(out)
// We use datadriven simply to read the golden output file; we don't actually
// run any commands. Using datadriven allows TESTFLAGS=-rewrite.
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "testzip_include_range_info"),
func(t *testing.T, td *datadriven.TestData) string {
return out
},
)
}
// This tests the operation of zip using --include-range-info=false.
func TestZipExcludeRangeInfo(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "test too slow under race")
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
c := NewCLITest(TestCLIParams{
StoreSpecs: []base.StoreSpec{{
Path: dir,
}},
})
defer c.Cleanup()
out, err := c.RunWithCapture(
"debug zip --concurrency=1 --cpu-profile-duration=1s --include-range-info=false " + os.DevNull)
if err != nil {
t.Fatal(err)
}
// Strip any non-deterministic messages.
out = eraseNonDeterministicZipOutput(out)
// We use datadriven simply to read the golden output file; we don't actually
// run any commands. Using datadriven allows TESTFLAGS=-rewrite.
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "testzip_exclude_range_info"),
func(t *testing.T, td *datadriven.TestData) string {
return out
},
)
}
// This tests the operation of zip running concurrently.
func TestConcurrentZip(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// We want a low timeout so that the test doesn't take forever;
// however low timeouts make race runs flaky with false positives.
skip.UnderShort(t)
skip.UnderRace(t)
sc := log.ScopeWithoutShowLogs(t)
defer sc.Close(t)
// Reduce the number of output log files to just what's expected.
defer sc.SetupSingleFileLogging()()
ctx := context.Background()
// Three nodes. We want to see what `zip` thinks when one of the nodes is down.
tc := testcluster.StartTestCluster(t, 3, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
DefaultTestTenant: base.TestIsSpecificToStorageLayerAndNeedsASystemTenant,
Insecure: true,
},
})
defer tc.Stopper().Stop(ctx)
// Zip it. We fake a CLI test context for this.
c := TestCLI{
t: t,
Server: tc.Server(0),
Insecure: true,
}
defer func(prevStderr *os.File) { stderr = prevStderr }(stderr)
stderr = os.Stdout
out, err := c.RunWithCapture("debug zip --timeout=30s --cpu-profile-duration=0s " + os.DevNull)
if err != nil {
t.Fatal(err)
}
// Strip any non-deterministic messages.
out = eraseNonDeterministicZipOutput(out)
// Sort the lines to remove non-determinism in the concurrent execution.
lines := strings.Split(out, "\n")
sort.Strings(lines)
out = strings.TrimSpace(strings.Join(lines, "\n"))
// Remove all "dumping SQL tables" messages since non-deterministic order in
// which the original messages interleve with other messages mean the number
// of them after each series is collapsed is also non-derministic.
out = regexp.MustCompile(`<dumping SQL tables>\n`).ReplaceAllString(out, "")
// We use datadriven simply to read the golden output file; we don't actually
// run any commands. Using datadriven allows TESTFLAGS=-rewrite.
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "testzip_concurrent"), func(t *testing.T, td *datadriven.TestData) string {
return out
})
}
func TestZipSpecialNames(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderShort(t)
skip.UnderRace(t)
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
c := NewCLITest(TestCLIParams{
StoreSpecs: []base.StoreSpec{{
Path: dir,
}},
})
defer c.Cleanup()
c.RunWithArgs([]string{"sql", "-e", `
create database "a:b";
create database "a-b";
create database "a-b-1";
create database "SYSTEM";
create table "SYSTEM.JOBS"(x int);
create database "../system";
create table defaultdb."a:b"(x int);
create table defaultdb."a-b"(x int);
create table defaultdb."pg_catalog.pg_class"(x int);
create table defaultdb."../system"(x int);
`})
out, err := c.RunWithCapture("debug zip --concurrency=1 --cpu-profile-duration=0 " + os.DevNull)
if err != nil {
t.Fatal(err)
}
re := regexp.MustCompile(`(?m)^.*(table|database).*$`)
out = strings.Join(re.FindAllString(out, -1), "\n")
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "specialnames"),
func(t *testing.T, td *datadriven.TestData) string {
return out
})
}
// This tests the operation of zip over unavailable clusters.
//
// We cannot combine this test with TestZip above because TestPartialZip
// needs a TestCluster, the TestCluster hides its SSL certs, and we
// need the SSL certs dir to run a CLI test securely.
func TestUnavailableZip(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderShort(t)
// Race builds make the servers so slow that they report spurious
// unavailability.
skip.UnderRace(t)
sc := log.ScopeWithoutShowLogs(t)
defer sc.Close(t)
// Reduce the number of output log files to just what's expected.
defer sc.SetupSingleFileLogging()()
// unavailableCh is used by the replica command filter
// to conditionally block requests and simulate unavailability.
var unavailableCh atomic.Value
closedCh := make(chan struct{})
close(closedCh)
unavailableCh.Store(closedCh)
knobs := &kvserver.StoreTestingKnobs{
TestingRequestFilter: func(ctx context.Context,
br *kvpb.BatchRequest) *kvpb.Error {
if br.Header.GatewayNodeID == 2 {
// For node 2 connections, block all replica requests.
select {
case <-unavailableCh.Load().(chan struct{}):
case <-ctx.Done():
}
} else if br.Header.GatewayNodeID == 1 {
// For node 1 connections, only block requests to table data ranges.
if br.Requests[0].GetInner().Header().Key.Compare(keys.
TableDataMin) >= 0 {
select {
case <-unavailableCh.Load().(chan struct{}):
case <-ctx.Done():
}
}
}
return nil
},
}
// Make a 3-node cluster, with an option to block replica requests.
tc := testcluster.StartTestCluster(t, 3,
base.TestClusterArgs{ServerArgs: base.TestServerArgs{
DefaultTestTenant: base.TestIsSpecificToStorageLayerAndNeedsASystemTenant,
Insecure: true,
Knobs: base.TestingKnobs{Store: knobs},
}})
defer tc.Stopper().Stop(context.Background())
// Sanity test: check that a simple SQL operation works against node 1.
if _, err := tc.ServerConn(0).Exec("SELECT * FROM system.users"); err != nil {
t.Fatal(err)
}
// Block querying table data from node 1.
// Block all replica requests from node 2.
ch := make(chan struct{})
unavailableCh.Store(ch)
defer close(ch)
// Run debug zip against node 1.
debugZipCommand :=
"debug zip --concurrency=1 --cpu-profile-duration=0 " + os.
DevNull + " --timeout=.5s"
t.Run("server 1", func(t *testing.T) {
c := TestCLI{
Server: tc.Server(0),
Insecure: true,
}
out, err := c.RunWithCapture(debugZipCommand)
require.NoError(t, err)
// Assert debug zip output for cluster, node 1, node 2, node 3.
assert.NotEmpty(t, out)
clusterOut := []string{
"[cluster] requesting nodes... received response...",
"[cluster] requesting liveness... received response...",
}
expectedOut := clusterOut
for i := 1; i < tc.NumServers()+1; i++ {
nodeOut := baseZipOutput(i)
expectedOut = append(expectedOut, nodeOut...)
// If the request to nodes failed, we can't expect the remaining
// nodes to be present in the debug zip output.
if i == 1 && strings.Contains(out,
"[cluster] requesting nodes: last request failed") {
break
}
}
containsAssert(t, out, expectedOut)
})
t.Run("server 2", func(t *testing.T) {
// Run debug zip against node 2.
c := TestCLI{
Server: tc.Server(1),
Insecure: true,
}
out, err := c.RunWithCapture(debugZipCommand)
require.NoError(t, err)
// Assert debug zip output for cluster, node 2.
assert.NotEmpty(t, out)
assert.NotContains(t, out, "[node 1]")
assert.NotContains(t, out, "[node 3]")
clusterOut := []string{
"[cluster] requesting nodes... received response...",
"[cluster] requesting liveness... received response...",
}
nodeOut := baseZipOutput(2)
expectedOut := append(clusterOut, nodeOut...)
containsAssert(t, out, expectedOut)
})
}
func containsAssert(t *testing.T, actual string, expected []string) {
var logOut bool
for _, line := range expected {
if !strings.Contains(actual, line) {
assertFail := fmt.Sprintf("output does not contain %#v", line)
if !logOut {
assertFail = fmt.Sprintf(
"the following output does not contain expected lines:\n%#v\n",
actual) + assertFail
logOut = true
}
assert.Fail(t, assertFail)
}
}
}
func baseZipOutput(nodeId int) []string {
output := []string{
fmt.Sprintf("[node %d] using SQL connection URL", nodeId),
fmt.Sprintf("[node %d] requesting stacks... received response...", nodeId),
fmt.Sprintf("[node %d] requesting stacks with labels... received response...", nodeId),
fmt.Sprintf("[node %d] requesting heap profile list... received response...", nodeId),
fmt.Sprintf("[node %d] requesting goroutine dump list... received response...", nodeId),
fmt.Sprintf("[node %d] requesting cpu profile list... received response...", nodeId),
fmt.Sprintf("[node %d] requesting log files list... received response...", nodeId),
fmt.Sprintf("[node %d] requesting ranges... received response...", nodeId),
}
return output
}
func eraseNonDeterministicZipOutput(out string) string {
re := regexp.MustCompile(`(?m)postgresql://.*$`)
out = re.ReplaceAllString(out, `postgresql://...`)
re = regexp.MustCompile(`(?m)SQL address: .*$`)
out = re.ReplaceAllString(out, `SQL address: ...`)
re = regexp.MustCompile(`(?m)^\[node \d+\] \[log file:.*$` + "\n")
out = re.ReplaceAllString(out, ``)
re = regexp.MustCompile(`(?m)RPC connection to .*$`)
out = re.ReplaceAllString(out, `RPC connection to ...`)
re = regexp.MustCompile(`(?m)dial tcp .*$`)
out = re.ReplaceAllString(out, `dial tcp ...`)
re = regexp.MustCompile(`(?m)rpc error: .*$`)
out = re.ReplaceAllString(out, `rpc error: ...`)
re = regexp.MustCompile(`(?m)timed out after.*$`)
out = re.ReplaceAllString(out, `timed out after...`)
re = regexp.MustCompile(`(?m)failed to connect to .*$`)
out = re.ReplaceAllString(out, `failed to connect to ...`)
// The number of memory profiles previously collected is not deterministic.
re = regexp.MustCompile(`(?m)^\[node \d+\] \d+ heap profiles found$`)
out = re.ReplaceAllString(out, `[node ?] ? heap profiles found`)
re = regexp.MustCompile(`(?m)^\[node \d+\] \d+ goroutine dumps found$`)
out = re.ReplaceAllString(out, `[node ?] ? goroutine dumps found`)
re = regexp.MustCompile(`(?m)^\[node \d+\] \d+ cpu profiles found$`)
out = re.ReplaceAllString(out, `[node ?] ? cpu profiles found`)
re = regexp.MustCompile(`(?m)^\[node \d+\] retrieving cpuprof.*$` + "\n")
out = re.ReplaceAllString(out, ``)
re = regexp.MustCompile(`(?m)^\[node \d+\] \d+ log files found$`)
out = re.ReplaceAllString(out, `[node ?] ? log files found`)
re = regexp.MustCompile(`(?m)^\[node \d+\] retrieving (memprof|memstats|memmonitoring).*$` + "\n")
out = re.ReplaceAllString(out, ``)
re = regexp.MustCompile(`(?m)^\[node \d+\] writing profile.*$` + "\n")
out = re.ReplaceAllString(out, ``)
re = regexp.MustCompile(`(?m)^\[node \d+\] writing dump.*$` + "\n")
out = re.ReplaceAllString(out, ``)
re = regexp.MustCompile(`(?m)^\[node \d+\] retrieving goroutine_dump.*$` + "\n")
out = re.ReplaceAllString(out, ``)
return out
}
// This tests the operation of zip over partial clusters.
//
// We cannot combine this test with TestZip above because TestPartialZip
// needs a TestCluster, the TestCluster hides its SSL certs, and we
// need the SSL certs dir to run a CLI test securely.
func TestPartialZip(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// We want a low timeout so that the test doesn't take forever;
// however low timeouts make race runs flaky with false positives.
skip.UnderShort(t)
skip.UnderRace(t)
sc := log.ScopeWithoutShowLogs(t)
defer sc.Close(t)
// Reduce the number of output log files to just what's expected.
defer sc.SetupSingleFileLogging()()
ctx := context.Background()
// Three nodes. We want to see what `zip` thinks when one of the nodes is down.
tc := testcluster.StartTestCluster(t, 3, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
DefaultTestTenant: base.TestIsSpecificToStorageLayerAndNeedsASystemTenant,
Insecure: true,
},
})
defer tc.Stopper().Stop(ctx)
// Switch off the second node.
tc.StopServer(1)
// Zip it. We fake a CLI test context for this.
c := TestCLI{
t: t,
Server: tc.Server(0),
Insecure: true,
}
defer func(prevStderr *os.File) { stderr = prevStderr }(stderr)
stderr = os.Stdout
out, err := c.RunWithCapture("debug zip --concurrency=1 --cpu-profile-duration=0s " + os.DevNull)
if err != nil {
t.Fatal(err)
}
// Strip any non-deterministic messages.
t.Log(out)
out = eraseNonDeterministicZipOutput(out)
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "partial1"),
func(t *testing.T, td *datadriven.TestData) string {
return out
})
// Now do it again and exclude the down node explicitly.
out, err = c.RunWithCapture("debug zip " + os.DevNull + " --concurrency=1 --exclude-nodes=2 --cpu-profile-duration=0")
if err != nil {
t.Fatal(err)
}
out = eraseNonDeterministicZipOutput(out)
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "partial1_excluded"),
func(t *testing.T, td *datadriven.TestData) string {
return out
})
// Now mark the stopped node as decommissioned, and check that zip
// skips over it automatically. We specifically use --wait=none because
// we're decommissioning a node in a 3-node cluster, so there's no node to
// up-replicate the under-replicated ranges to.
{
_, err := c.RunWithCapture(fmt.Sprintf("node decommission --checks=skip --wait=none %d", 2))
if err != nil {
t.Fatal(err)
}
}
// We use .Override() here instead of SET CLUSTER SETTING in SQL to
// override the 1m15s minimum placed on the cluster setting. There
// is no risk to see the override bumped due to a gossip update
// because this setting is not otherwise set in the test cluster.
s := tc.Server(0)
liveness.TimeUntilNodeDead.Override(ctx, &s.ClusterSettings().SV, liveness.TestTimeUntilNodeDead)
// This last case may take a little while to converge. To make this work with datadriven and at the same
// time retain the ability to use the `-rewrite` flag, we use a retry loop within that already checks the
// output ahead of time and retries for some time if necessary.
datadriven.RunTest(t, datapathutils.TestDataPath(t, "zip", "partial2"),
func(t *testing.T, td *datadriven.TestData) string {
f := func() string {
out, err := c.RunWithCapture("debug zip --concurrency=1 --cpu-profile-duration=0 " + os.DevNull)
if err != nil {
t.Fatal(err)
}
// Strip any non-deterministic messages.
return eraseNonDeterministicZipOutput(out)
}
var out string
_ = testutils.SucceedsSoonError(func() error {
out = f()
if out != td.Expected {
return errors.New("output did not match (yet)")
}
return nil
})
return out
})
}
// This checks that SQL retry errors are properly handled.
func TestZipRetries(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := serverutils.StartServerOnly(t, base.TestServerArgs{Insecure: true})
defer s.Stopper().Stop(context.Background())
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
zipName := filepath.Join(dir, "test.zip")
func() {
out, err := os.Create(zipName)
if err != nil {
t.Fatal(err)
}
z := newZipper(out)
defer func() {
if err := z.close(); err != nil {
t.Fatal(err)
}
}()
// Lower the buffer size so that an error is returned when running the
// generate_series query.
sqlURL := url.URL{
Scheme: "postgres",
User: url.User(username.RootUser),
Host: s.AdvSQLAddr(),
RawQuery: "sslmode=disable&results_buffer_size=16KiB",
}
sqlConn := sqlConnCtx.MakeSQLConn(io.Discard, io.Discard, sqlURL.String())
defer func() {
if err := sqlConn.Close(); err != nil {
t.Fatal(err)
}
}()
zr := zipCtx.newZipReporter("test")
zr.sqlOutputFilenameExtension = "json"
zc := debugZipContext{
z: z,
clusterPrinter: zr,
timeout: 3 * time.Second,
}
if err := zc.dumpTableDataForZip(
zr,
sqlConn,
"test",
`generate_series(1,15000) as t(x)`,
TableQuery{query: `select if(x<11000,x,crdb_internal.force_retry('1h')) from generate_series(1,15000) as t(x)`},
); err != nil {
t.Fatal(err)
}
}()
r, err := zip.OpenReader(zipName)
if err != nil {
t.Fatal(err)
}
defer func() { _ = r.Close() }()
var fileList bytes.Buffer
for _, f := range r.File {
fmt.Fprintln(&fileList, f.Name)
}
const expected = `test/generate_series(1,15000) as t(x).json
test/generate_series(1,15000) as t(x).json.err.txt
test/generate_series(1,15000) as t(x).1.json
test/generate_series(1,15000) as t(x).1.json.err.txt
test/generate_series(1,15000) as t(x).2.json
test/generate_series(1,15000) as t(x).2.json.err.txt
test/generate_series(1,15000) as t(x).3.json
test/generate_series(1,15000) as t(x).3.json.err.txt
test/generate_series(1,15000) as t(x).4.json
test/generate_series(1,15000) as t(x).4.json.err.txt
`
assert.Equal(t, expected, fileList.String())
}
// This checks that SQL retry errors are properly handled.
func TestZipFallback(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := serverutils.StartServerOnly(t, base.TestServerArgs{Insecure: true})
defer s.Stopper().Stop(context.Background())
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
zipName := filepath.Join(dir, "test.zip")
func() {
out, err := os.Create(zipName)
if err != nil {
t.Fatal(err)
}
z := newZipper(out)
defer func() {
if err := z.close(); err != nil {
t.Fatal(err)
}
}()
// Lower the buffer size so that an error is returned when running the
// generate_series query.
sqlURL := url.URL{
Scheme: "postgres",
User: url.User(username.RootUser),
Host: s.AdvSQLAddr(),
}
sqlConn := sqlConnCtx.MakeSQLConn(io.Discard, io.Discard, sqlURL.String())
defer func() {
if err := sqlConn.Close(); err != nil {
t.Fatal(err)
}
}()
zr := zipCtx.newZipReporter("test")
zr.sqlOutputFilenameExtension = "json"
zc := debugZipContext{
z: z,
clusterPrinter: zr,
timeout: 3 * time.Second,
}
if err := zc.dumpTableDataForZip(
zr,
sqlConn,
"test",
`test_table_fail`,
TableQuery{
query: `SELECT blah`,
},
); err != nil {
t.Fatal(err)
}
if err := zc.dumpTableDataForZip(
zr,
sqlConn,
"test",
`test_table_succeed`,
TableQuery{
query: `SELECT blah`,
fallback: `SELECT 1`,
},
); err != nil {
t.Fatal(err)
}
}()
r, err := zip.OpenReader(zipName)
if err != nil {
t.Fatal(err)
}
defer func() { _ = r.Close() }()
var fileList bytes.Buffer
for _, f := range r.File {
fmt.Fprintln(&fileList, f.Name)
}
const expected = `test/test_table_fail.json
test/test_table_fail.json.err.txt
test/test_table_succeed.json
test/test_table_succeed.json.err.txt
test/test_table_succeed.fallback.json
`
assert.Equal(t, expected, fileList.String())
}
// This test the operation of zip over secure clusters.
func TestToHex(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
c := NewCLITest(TestCLIParams{
StoreSpecs: []base.StoreSpec{{
Path: dir,
}},
})
defer c.Cleanup()
// Create a job to have non-empty system.jobs table.
c.RunWithArgs([]string{"sql", "-e", "CREATE STATISTICS foo FROM system.namespace"})
_, err := c.RunWithCapture("debug zip --concurrency=1 --cpu-profile-duration=0 " + dir + "/debug.zip")
if err != nil {
t.Fatal(err)
}
r, err := zip.OpenReader(dir + "/debug.zip")
if err != nil {