-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathtest_runner.go
1475 lines (1347 loc) · 46.3 KB
/
test_runner.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 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package main
import (
"archive/zip"
"context"
"fmt"
"html"
"io"
"math/rand"
"net"
"net/http"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/cmd/internal/issues"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/option"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/registry"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/spec"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/test"
"github.com/cockroachdb/cockroach/pkg/internal/team"
"github.com/cockroachdb/cockroach/pkg/roachprod/config"
"github.com/cockroachdb/cockroach/pkg/roachprod/logger"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/quotapool"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/version"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/petermattis/goid"
)
var errTestsFailed = fmt.Errorf("some tests failed")
var errClusterProvisioningFailed = fmt.Errorf("some clusters could not be created")
// testRunner runs tests.
type testRunner struct {
stopper *stop.Stopper
// buildVersion is the version of the Cockroach binary that tests will run against.
buildVersion version.Version
config struct {
// skipClusterValidationOnAttach skips validation on existing clusters that
// the registry uses for running tests.
skipClusterValidationOnAttach bool
// skipClusterStopOnAttach skips stopping existing clusters that
// the registry uses for running tests. It implies skipClusterWipeOnAttach.
skipClusterStopOnAttach bool
skipClusterWipeOnAttach bool
// disableIssue disables posting GitHub issues for test failures.
disableIssue bool
}
status struct {
syncutil.Mutex
running map[*testImpl]struct{}
pass map[*testImpl]struct{}
fail map[*testImpl]struct{}
skip map[*testImpl]struct{}
}
// cr keeps track of all live clusters.
cr *clusterRegistry
workersMu struct {
syncutil.Mutex
// workers is a map from worker name to information about each worker currently running tests.
workers map[string]*workerStatus
}
// work maintains the remaining tests to run.
work *workPool
completedTestsMu struct {
syncutil.Mutex
// completed maintains information on all completed test runs.
completed []completedTestInfo
}
// Counts cluster creation errors across all workers.
numClusterErrs int32
}
// newTestRunner constructs a testRunner.
//
// cr: The cluster registry with which all clusters will be registered. The
// caller provides this as the caller needs to be able to shut clusters down
// on Ctrl+C.
// buildVersion: The version of the Cockroach binary against which tests will run.
func newTestRunner(
cr *clusterRegistry, stopper *stop.Stopper, buildVersion version.Version,
) *testRunner {
r := &testRunner{
stopper: stopper,
cr: cr,
buildVersion: buildVersion,
}
r.config.skipClusterWipeOnAttach = !clusterWipe
r.config.disableIssue = disableIssue
r.workersMu.workers = make(map[string]*workerStatus)
return r
}
// clustersOpt groups options for the clusters to be used by the tests.
type clustersOpt struct {
// The type of cluster to use. If localCluster, then no other fields can be
// set.
typ clusterType
// If set, all the tests will run against this roachprod cluster.
clusterName string
// If set, all the clusters will use this ID as part of their name. When
// roachtests is invoked by TeamCity, this will be the build id.
clusterID string
// The name of the user running the tests. This will be part of cluster names.
user string
// cpuQuota specifies how many CPUs can be used concurrently by the roachprod
// clusters. While there's no quota available for creating a new cluster, the
// test runner will wait for other tests to finish and their cluster to be
// destroyed (or reused). Note that this limit is global, not per zone.
cpuQuota int
// If set, clusters will not be wiped or destroyed when a test using the
// respective cluster fails. These cluster will linger around and they'll
// continue counting towards the cpuQuota.
keepClustersOnTestFailure bool
}
func (c clustersOpt) validate() error {
if c.typ == localCluster {
if c.clusterName != "" {
return errors.New("clusterName cannot be set when typ=localCluster")
}
if c.clusterID != "" {
return errors.New("clusterID cannot be set when typ=localCluster")
}
}
return nil
}
type testOpts struct {
versionsBinaryOverride map[string]string
}
// Run runs tests.
//
// Args:
// tests: The tests to run.
// count: How many times to run each test selected by filter.
// parallelism: How many workers to use for running tests. Tests are run
// locally (although generally they run against remote roachprod clusters).
// parallelism bounds the maximum number of tests that run concurrently. Note
// that the concurrency is also affected by cpuQuota.
// clusterOpt: Options for the clusters to use by tests.
// lopt: Options for logging.
func (r *testRunner) Run(
ctx context.Context,
tests []registry.TestSpec,
count int,
parallelism int,
clustersOpt clustersOpt,
topt testOpts,
lopt loggingOpt,
clusterAllocator clusterAllocatorFn,
) error {
// Validate options.
if len(tests) == 0 {
return fmt.Errorf("no test matched filters")
}
hasDevLicense := config.CockroachDevLicense != ""
for _, t := range tests {
if t.RequiresLicense && !hasDevLicense {
return fmt.Errorf("test %q requires an enterprise license, set COCKROACH_DEV_LICENSE", t.Name)
}
}
if err := clustersOpt.validate(); err != nil {
return err
}
if parallelism != 1 {
if clustersOpt.clusterName != "" {
return fmt.Errorf("--cluster incompatible with --parallelism. Use --parallelism=1")
}
if clustersOpt.typ == localCluster {
return fmt.Errorf("--local incompatible with --parallelism. Use --parallelism=1")
}
}
if name := clustersOpt.clusterName; name != "" {
// Since we were given a cluster, check that all tests we have to run have compatible specs.
// We should also check against the spec of the cluster, but we don't
// currently have a way of doing that; we're relying on the fact that attaching to the cluster
// will fail if the cluster is incompatible.
spec := tests[0].Cluster
spec.Lifetime = 0
for i := 1; i < len(tests); i++ {
spec2 := tests[i].Cluster
spec2.Lifetime = 0
if spec != spec2 {
return errors.Errorf("cluster specified but found tests "+
"with incompatible specs: %s (%s) - %s (%s)",
tests[0].Name, spec, tests[i].Name, spec2,
)
}
}
}
if clusterAllocator == nil {
clusterAllocator = defaultClusterAllocator(r, clustersOpt, lopt)
}
// Seed the default rand source so that different runs get different cluster
// IDs.
rand.Seed(timeutil.Now().UnixNano())
n := len(tests)
if n*count < parallelism {
// Don't spin up more workers than necessary.
parallelism = n * count
}
r.status.running = make(map[*testImpl]struct{})
r.status.pass = make(map[*testImpl]struct{})
r.status.fail = make(map[*testImpl]struct{})
r.status.skip = make(map[*testImpl]struct{})
r.work = newWorkPool(tests, count)
errs := &workerErrors{}
qp := quotapool.NewIntPool("cloud cpu", uint64(clustersOpt.cpuQuota))
l := lopt.l
var wg sync.WaitGroup
for i := 0; i < parallelism; i++ {
i := i // Copy for closure.
wg.Add(1)
if err := r.stopper.RunAsyncTask(ctx, "worker", func(ctx context.Context) {
defer wg.Done()
err := r.runWorker(
ctx, fmt.Sprintf("w%d", i) /* name */, r.work, qp,
r.stopper.ShouldQuiesce(),
clustersOpt.keepClustersOnTestFailure,
lopt.artifactsDir, lopt.literalArtifactsDir, lopt.tee, lopt.stdout,
clusterAllocator,
topt,
l,
)
if err != nil {
// A worker returned an error. Let's shut down.
msg := fmt.Sprintf("Worker %d returned with error. Quiescing. Error: %v", i, err)
shout(ctx, l, lopt.stdout, msg)
errs.AddErr(err)
// Stop the stopper. This will cause all workers to not pick up more
// tests after finishing the currently running one. We add one to the
// WaitGroup so that wg.Wait() will also wait for the stopper.
wg.Add(1)
go func() {
defer wg.Done()
r.stopper.Stop(ctx)
}()
// Interrupt everybody waiting for resources.
if qp != nil {
qp.Close(msg)
}
}
}); err != nil {
wg.Done()
}
}
// Wait for all the workers to finish.
wg.Wait()
r.cr.destroyAllClusters(ctx, l)
if errs.Err() != nil {
shout(ctx, l, lopt.stdout, "FAIL (err: %s)", errs.Err())
return errs.Err()
}
passFailLine := r.generateReport()
shout(ctx, l, lopt.stdout, passFailLine)
if r.numClusterErrs > 0 {
shout(ctx, l, lopt.stdout, "%d clusters could not be created", r.numClusterErrs)
return errClusterProvisioningFailed
}
if len(r.status.fail) > 0 {
return errTestsFailed
}
return nil
}
// N.B. currently this value is hardcoded per cloud provider.
func numConcurrentClusterCreations() int {
var res int
if cloud == "aws" {
// AWS has ridiculous API calls limits, so we're going to create one cluster
// at a time. Internally, roachprod has throttling for the calls required to
// create a single cluster.
res = 1
} else {
res = 1000
}
return res
}
// defaultClusterAllocator is used by workers to create new clusters (or to attach
// to an existing one).
//
// N.B. the resulting clusterAllocatorFn reuses the same clusterFactory to allocate clusters.
func defaultClusterAllocator(
r *testRunner, clustersOpt clustersOpt, lopt loggingOpt,
) clusterAllocatorFn {
clusterFactory := newClusterFactory(
clustersOpt.user, clustersOpt.clusterID, lopt.artifactsDir, r.cr, numConcurrentClusterCreations())
allocateCluster := func(
ctx context.Context,
t registry.TestSpec,
alloc *quotapool.IntAlloc,
artifactsDir string,
wStatus *workerStatus,
) (*clusterImpl, error) {
wStatus.SetStatus("creating cluster")
defer wStatus.SetStatus("")
existingClusterName := clustersOpt.clusterName
if existingClusterName != "" {
// Logs for attaching to a cluster go to a dedicated log file.
logPath := filepath.Join(artifactsDir, runnerLogsDir, "cluster-create", existingClusterName+".log")
clusterL, err := logger.RootLogger(logPath, lopt.tee)
if err != nil {
return nil, err
}
defer clusterL.Close()
opt := attachOpt{
skipValidation: r.config.skipClusterValidationOnAttach,
skipStop: r.config.skipClusterStopOnAttach,
skipWipe: r.config.skipClusterWipeOnAttach,
}
lopt.l.PrintfCtx(ctx, "Attaching to existing cluster %s for test %s", existingClusterName, t.Name)
return attachToExistingCluster(ctx, existingClusterName, clusterL, t.Cluster, opt, r.cr)
}
lopt.l.PrintfCtx(ctx, "Creating new cluster for test %s: %s", t.Name, t.Cluster)
cfg := clusterConfig{
spec: t.Cluster,
artifactsDir: artifactsDir,
username: clustersOpt.user,
localCluster: clustersOpt.typ == localCluster,
alloc: alloc,
}
return clusterFactory.newCluster(ctx, cfg, wStatus.SetStatus, lopt.tee)
}
return allocateCluster
}
type clusterAllocatorFn func(
ctx context.Context,
t registry.TestSpec,
alloc *quotapool.IntAlloc,
artifactsDir string,
wStatus *workerStatus,
) (*clusterImpl, error)
// runWorker runs tests in a loop until work is exhausted.
//
// Errors are returned in exceptional circumstances, like when a cluster failed
// to be created or when a test timed out and failed to react to its
// cancellation. Upon return, an attempt is performed to destroy the cluster used
// by this worker. If an error is returned, we might have "leaked" cpu quota
// because the cluster destruction might have failed but we've still released
// the quota. Also, we might have "leaked" a test goroutine (in the test
// nonresponsive to timeout case) which might still be running and doing
// arbitrary things to the cluster it was using.
//
// If a cluster cannot be provisioned (owing to an infrastructure issue), the corresponding
// test is skipped; the provisioning error is posted to github; the count of cluster provisioning
// errors is incremented.
//
// runWorker returns either error (other than cluster provisioning) or the count of cluster provisioning errors.
//
// Args:
// name: The worker's name, to be used as a prefix for log messages.
// artifactsRootDir: The artifacts dir. Each test's logs are going to be under a
// run_<n> dir. If empty, test log files will not be created.
// literalArtifactsDir: The literal on-agent path where artifacts are stored.
// Only used for teamcity[publishArtifacts] messages.
// stdout: The Writer to use for messages that need to go to stdout (e.g. the
// "=== RUN" and "--- FAIL" lines).
// teeOpt: The teeing option for future test loggers.
// l: The logger to use for more verbose messages.
func (r *testRunner) runWorker(
ctx context.Context,
name string,
work *workPool,
qp *quotapool.IntPool,
interrupt <-chan struct{},
debug bool,
artifactsRootDir string,
literalArtifactsDir string,
teeOpt logger.TeeOptType,
stdout io.Writer,
allocateCluster clusterAllocatorFn,
topt testOpts,
l *logger.Logger,
) error {
ctx = logtags.AddTag(ctx, name, nil /* value */)
wStatus := r.addWorker(ctx, name)
defer func() {
r.removeWorker(ctx, name)
}()
var c *clusterImpl // The cluster currently being used.
// When this method returns we'll destroy the cluster we had at the time.
// Note that, if debug was set, c has been set to nil.
defer func() {
wStatus.SetTest(nil /* test */, testToRunRes{noWork: true})
wStatus.SetStatus("worker done")
wStatus.SetCluster(nil)
if c == nil {
l.PrintfCtx(ctx, "Worker exiting; no cluster to destroy.")
return
}
doDestroy := ctx.Err() == nil
if doDestroy {
l.PrintfCtx(ctx, "Worker exiting; destroying cluster.")
c.Destroy(context.Background(), closeLogger, l)
} else {
l.PrintfCtx(ctx, "Worker exiting with canceled ctx. Not destroying cluster.")
}
}()
prng, _ := randutil.NewPseudoRand()
// Loop until there's no more work in the pool, we get interrupted, or an
// error occurs.
for {
select {
case <-interrupt:
l.ErrorfCtx(ctx, "worker detected interruption")
return errors.Errorf("interrupted")
default:
if ctx.Err() != nil {
// The context has been canceled. No need to continue.
return errors.Wrap(ctx.Err(), "worker ctx done")
}
}
if c != nil {
if _, ok := c.spec.ReusePolicy.(spec.ReusePolicyNone); ok {
wStatus.SetStatus("destroying cluster")
// We use a context that can't be canceled for the Destroy().
c.Destroy(context.Background(), closeLogger, l)
c = nil
}
}
var testToRun testToRunRes
var err error
wStatus.SetTest(nil /* test */, testToRunRes{})
wStatus.SetStatus("getting work")
testToRun, err = r.getWork(
ctx, work, qp, c, interrupt, l,
getWorkCallbacks{
onDestroy: func() {
wStatus.SetCluster(nil)
},
})
if err != nil {
// Problem selecting a test, bail out.
return err
}
if testToRun.noWork {
shout(ctx, l, stdout, "no work remaining; runWorker is bailing out...")
return nil
}
// Attempt to reuse existing cluster.
if c != nil && testToRun.canReuseCluster {
err = func() error {
l.PrintfCtx(ctx, "Using existing cluster: %s. Wiping", c.name)
if err := c.WipeE(ctx, l); err != nil {
return err
}
if err := c.RunE(ctx, c.All(), "rm -rf "+perfArtifactsDir); err != nil {
return errors.Wrapf(err, "failed to remove perf artifacts dir")
}
if c.localCertsDir != "" {
if err := os.RemoveAll(c.localCertsDir); err != nil {
return errors.Wrapf(err,
"failed to remove local certs in %s", c.localCertsDir)
}
c.localCertsDir = ""
}
// Overwrite the spec of the cluster with the one coming from the test. In
// particular, this overwrites the reuse policy to reflect what the test
// intends to do with it.
c.spec = testToRun.spec.Cluster
return nil
}()
if err != nil {
// N.B. handle any error during reuse attempt as clusterCreateErr.
shout(ctx, l, stdout, "Unable to reuse cluster: %s due to: %s. Will attempt to create a fresh one",
c.Name(), err)
atomic.AddInt32(&r.numClusterErrs, 1)
// Let's attempt to create a fresh one.
testToRun.canReuseCluster = false
}
}
var clusterCreateErr error
if !testToRun.canReuseCluster {
// Create a new cluster if can't reuse or reuse attempt failed.
// N.B. non-reusable cluster would have been destroyed above.
wStatus.SetTest(nil /* test */, testToRun)
wStatus.SetStatus("creating cluster")
c, clusterCreateErr = allocateCluster(ctx, testToRun.spec, testToRun.alloc, artifactsRootDir, wStatus)
if clusterCreateErr != nil {
atomic.AddInt32(&r.numClusterErrs, 1)
shout(ctx, l, stdout, "Unable to create (or reuse) cluster for test %s due to: %s.",
testToRun.spec.Name, clusterCreateErr)
}
}
// Prepare the test's logger.
logPath := ""
var artifactsDir string
var artifactsSpec string
if artifactsRootDir != "" {
escapedTestName := teamCityNameEscape(testToRun.spec.Name)
runSuffix := "run_" + strconv.Itoa(testToRun.runNum)
artifactsDir = filepath.Join(filepath.Join(artifactsRootDir, escapedTestName), runSuffix)
logPath = filepath.Join(artifactsDir, "test.log")
// Map artifacts/TestFoo/run_?/** => TestFoo/run_?/**, i.e. collect the artifacts
// for this test exactly as they are laid out on disk (when the time
// comes).
artifactsSpec = fmt.Sprintf("%s/%s/** => %s/%s", filepath.Join(literalArtifactsDir, escapedTestName), runSuffix, escapedTestName, runSuffix)
}
testL, err := logger.RootLogger(logPath, teeOpt)
if err != nil {
return err
}
t := &testImpl{
spec: &testToRun.spec,
cockroach: cockroach,
deprecatedWorkload: workload,
buildVersion: r.buildVersion,
artifactsDir: artifactsDir,
artifactsSpec: artifactsSpec,
l: testL,
versionsBinaryOverride: topt.versionsBinaryOverride,
debug: debug,
}
// Now run the test.
l.PrintfCtx(ctx, "starting test: %s:%d", testToRun.spec.Name, testToRun.runNum)
if clusterCreateErr != nil {
// N.B. cluster creation must have failed...
// We don't want to prematurely abort the test suite since it's likely a transient issue.
// Instead, let's report an infrastructure issue, mark the test as failed and continue with the next test.
// Note, we fake the test name so that all cluster creation errors are posted to the same github issue.
oldName := t.spec.Name
oldOwner := t.spec.Owner
// Generate failure reason and mark the test failed to preclude fetching (cluster) artifacts.
t.printAndFail(0, clusterCreateErr)
issueOutput := "test %s was skipped due to %s"
issueOutput = fmt.Sprintf(issueOutput, oldName, t.FailureMsg())
// N.B. issue title is of the form "roachtest: ${t.spec.Name} failed" (see UnitTestFormatter).
t.spec.Name = "cluster_creation"
t.spec.Owner = registry.OwnerDevInf
r.maybePostGithubIssue(ctx, l, t, stdout, issueOutput)
// Restore test name and owner.
t.spec.Name = oldName
t.spec.Owner = oldOwner
} else {
// Tell the cluster that, from now on, it will be run "on behalf of this
// test".
c.status("running test")
c.setTest(t)
switch t.Spec().(*registry.TestSpec).EncryptionSupport {
case registry.EncryptionAlwaysEnabled:
c.encAtRest = true
case registry.EncryptionAlwaysDisabled:
c.encAtRest = false
case registry.EncryptionMetamorphic:
// when tests opted-in to metamorphic testing, encryption will
// be enabled according to the probability passed to
// --metamorphic-encryption-probability
c.encAtRest = prng.Float64() < encryptionProbability
}
wStatus.SetCluster(c)
wStatus.SetTest(t, testToRun)
wStatus.SetStatus("running test")
err = r.runTest(ctx, t, testToRun.runNum, testToRun.runCount, c, stdout, testL)
}
if err != nil {
shout(ctx, l, stdout, "test returned error: %s: %s", t.Name(), err)
// Mark the test as failed if it isn't already.
if !t.Failed() {
t.printAndFail(0 /* skip */, err)
}
} else {
msg := "test passed: %s (run %d)"
if t.Failed() {
msg = "test failed: %s (run %d)"
}
msg = fmt.Sprintf(msg, t.Name(), testToRun.runNum)
l.PrintfCtx(ctx, msg)
}
testL.Close()
if err != nil || t.Failed() {
failureMsg := fmt.Sprintf("%s (%d) - ", testToRun.spec.Name, testToRun.runNum)
if err != nil {
failureMsg += fmt.Sprintf("%+v", err)
} else {
failureMsg += t.FailureMsg()
}
if c != nil {
if debug {
// Save the cluster for future debugging.
c.Save(ctx, failureMsg, l)
// Continue with a fresh cluster.
c = nil
} else {
// On any test failure or error, we destroy the cluster. We could be
// more selective, but this sounds safer.
l.PrintfCtx(ctx, "destroying cluster %s because: %s", c, failureMsg)
c.Destroy(context.Background(), closeLogger, l)
c = nil
}
}
if err != nil {
// N.B. bail out iff runTest exits exceptionally.
return err
}
} else {
// Upon success fetch the perf artifacts from the remote hosts.
getPerfArtifacts(ctx, l, c, t)
}
}
}
// getPerfArtifacts retrieves the perf artifacts for the test.
// If there's an error, oh well, don't do anything rash like fail a test
// which already passed.
func getPerfArtifacts(ctx context.Context, l *logger.Logger, c *clusterImpl, t test.Test) {
g := ctxgroup.WithContext(ctx)
fetchNode := func(node int) func(context.Context) error {
return func(ctx context.Context) error {
testCmd := `'PERF_ARTIFACTS="` + perfArtifactsDir + `"
if [[ -d "${PERF_ARTIFACTS}" ]]; then
echo true
elif [[ -e "${PERF_ARTIFACTS}" ]]; then
ls -la "${PERF_ARTIFACTS}"
exit 1
else
echo false
fi'`
result, err := c.RunWithDetailsSingleNode(ctx, t.L(), c.Node(node), "bash", "-c", testCmd)
if err != nil {
return errors.Wrapf(err, "failed to check for perf artifacts")
}
out := strings.TrimSpace(result.Stdout)
switch out {
case "true":
dst := fmt.Sprintf("%s/%d.%s", t.ArtifactsDir(), node, perfArtifactsDir)
return c.Get(ctx, l, perfArtifactsDir, dst, c.Node(node))
case "false":
l.PrintfCtx(ctx, "no perf artifacts exist on node %v", c.Node(node))
return nil
default:
return errors.Errorf("unexpected output when checking for perf artifacts: %s", out)
}
}
}
for _, i := range c.All() {
g.GoCtx(fetchNode(i))
}
if err := g.Wait(); err != nil {
l.PrintfCtx(ctx, "failed to get perf artifacts: %v", err)
}
}
func allStacks() []byte {
// Collect up to 5mb worth of stacks.
b := make([]byte, 5*(1<<20))
return b[:runtime.Stack(b, true /* all */)]
}
// An error is returned if the test is still running (on another goroutine) when
// this returns. This happens when the test doesn't respond to cancellation.
//
// Args:
// c: The cluster on which the test will run. runTest() does not wipe or destroy
// the cluster.
func (r *testRunner) runTest(
ctx context.Context,
t *testImpl,
runNum int,
runCount int,
c *clusterImpl,
stdout io.Writer,
l *logger.Logger,
) error {
if t.Spec().(*registry.TestSpec).Skip != "" {
return fmt.Errorf("can't run skipped test: %s: %s", t.Name(), t.Spec().(*registry.TestSpec).Skip)
}
runID := t.Name()
if runCount > 1 {
runID += fmt.Sprintf("#%d", runNum)
}
if teamCity {
shout(ctx, l, stdout, "##teamcity[testStarted name='%s' flowId='%s']", t.Name(), runID)
} else {
shout(ctx, l, stdout, "=== RUN %s", runID)
}
r.status.Lock()
r.status.running[t] = struct{}{}
r.status.Unlock()
t.runner = callerName()
t.runnerID = goid.Get()
defer func() {
t.end = timeutil.Now()
// We only have to record panics if the panic'd value is not the sentinel
// produced by t.Fatal*().
//
// TODO(test-eng): we shouldn't be seeing errTestFatal here unless this
// goroutine accidentally ends up calling t.Fatal; the test runs in a
// different goroutine.
if err := recover(); err != nil && err != errTestFatal {
t.mu.Lock()
t.mu.failed = true
t.mu.output = append(t.mu.output, t.decorate(0 /* skip */, fmt.Sprint(err))...)
t.mu.Unlock()
}
t.mu.Lock()
t.mu.done = true
t.mu.Unlock()
durationStr := fmt.Sprintf("%.2fs", t.duration().Seconds())
if t.Failed() {
t.mu.Lock()
output := fmt.Sprintf("test artifacts and logs in: %s\n", t.ArtifactsDir()) + string(t.mu.output)
t.mu.Unlock()
if teamCity {
shout(ctx, l, stdout, "##teamcity[testFailed name='%s' details='%s' flowId='%s']",
t.Name(), teamCityEscape(output), runID)
}
shout(ctx, l, stdout, "--- FAIL: %s (%s)\n%s", runID, durationStr, output)
r.maybePostGithubIssue(ctx, l, t, stdout, output)
} else {
shout(ctx, l, stdout, "--- PASS: %s (%s)", runID, durationStr)
// If `##teamcity[testFailed ...]` is not present before `##teamCity[testFinished ...]`,
// TeamCity regards the test as successful.
}
if teamCity {
shout(ctx, l, stdout, "##teamcity[testFinished name='%s' flowId='%s']", t.Name(), runID)
// Zip the artifacts. This improves the TeamCity UX where we can navigate
// through zip files just fine, but we can't download subtrees of the
// artifacts storage. By zipping we get this capability as we can just
// download the zip file for the failing test instead.
if err := zipArtifacts(t.ArtifactsDir()); err != nil {
l.Printf("unable to zip artifacts: %s", err)
}
if t.artifactsSpec != "" {
// Tell TeamCity to collect this test's artifacts now. The TC job
// also collects the artifacts directory wholesale at the end, but
// here we make sure that the artifacts for any test that has already
// finished are available in the UI even before the job as a whole
// has completed. We're using the exact same destination to avoid
// duplication of any of the artifacts.
shout(ctx, l, stdout, "##teamcity[publishArtifacts '%s']", t.artifactsSpec)
}
}
r.recordTestFinish(completedTestInfo{
test: t.Name(),
run: runNum,
start: t.start,
end: t.end,
pass: !t.Failed(),
failure: t.FailureMsg(),
})
r.status.Lock()
delete(r.status.running, t)
// Only include tests with a Run function in the summary output.
if t.Spec().(*registry.TestSpec).Run != nil {
if t.Failed() {
r.status.fail[t] = struct{}{}
} else if t.Spec().(*registry.TestSpec).Skip == "" {
r.status.pass[t] = struct{}{}
} else {
r.status.skip[t] = struct{}{}
}
}
r.status.Unlock()
}()
t.start = timeutil.Now()
timeout := 10 * time.Hour
if d := t.Spec().(*registry.TestSpec).Timeout; d != 0 {
timeout = d
}
// Make sure the cluster has enough life left for the test plus enough headroom
// after the test finishes so that the next test can be selected. If it
// doesn't, extend it.
minExp := timeutil.Now().Add(timeout + time.Hour)
if c.expiration.Before(minExp) {
extend := minExp.Sub(c.expiration)
l.PrintfCtx(ctx, "cluster needs to survive until %s, but has expiration: %s. Extending.",
minExp, c.expiration)
if err := c.Extend(ctx, extend, l); err != nil {
return errors.Wrapf(err, "failed to extend cluster: %s", c.name)
}
}
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
t.mu.Lock()
// t.Fatal() will cancel this context.
t.mu.cancel = cancel
t.mu.Unlock()
// We run the actual test in a different goroutine because it might call
// t.Fatal() which kills the goroutine, and also because we want to enforce a
// timeout.
testReturnedCh := make(chan struct{})
go func() {
defer close(testReturnedCh) // closed only after we've grabbed the debug info below
defer func() {
// We only have to record panics if the panic'd value is not the sentinel
// produced by t.Fatal*().
if r := recover(); r != nil && r != errTestFatal {
// NB: we're careful to avoid t.Fatalf here, which re-panics.
t.Errorf("test panicked: %v", r)
}
}()
// This is the call to actually run the test.
t.Spec().(*registry.TestSpec).Run(runCtx, t, c)
}()
var timedOut bool
select {
case <-testReturnedCh:
s := "success"
if t.Failed() {
s = "failure"
}
t.L().Printf("tearing down after %s; see teardown.log", s)
case <-time.After(timeout):
// NB: we're intentionally not failing the test if it hasn't
// already. This will be done at the very end of this method,
// after we've collected artifacts.
t.L().Printf("test timed out after %s; check __stacks.log and CRDB logs for goroutine dumps", timeout)
timedOut = true
}
// From now on, all logging goes to teardown.log to give a clear
// separation between operations originating from the test vs the
// harness.
teardownL, err := c.l.ChildLogger("teardown", logger.QuietStderr, logger.QuietStdout)
if err != nil {
return err
}
l, c.l = teardownL, teardownL
t.ReplaceL(teardownL)
return r.teardownTest(ctx, t, c, timedOut)
}
func (r *testRunner) teardownTest(
ctx context.Context, t *testImpl, c *clusterImpl, timedOut bool,
) error {
// We still have to collect artifacts and run post-flight checks, and any of
// these might hang. So they go into a goroutine and the main goroutine
// abandons them after a timeout. We intentionally don't wait for the
// goroutines to return, as this too may hang if something doesn't respond to
// ctx cancellation.
artifactsCollectedCh := make(chan struct{})
_ = r.stopper.RunAsyncTask(ctx, "collect-artifacts", func(ctx context.Context) {
// TODO(tbg): make `t` and `logger` resilient to use-after-Close to avoid
// crashes here in cases where the goroutine leaks but later gets unstuck
// and tries to log something.
defer close(artifactsCollectedCh)
if timedOut {
// Timeouts are often opaque. Improve our changes by dumping the stack
// so that at least we can piece together what the test is trying to
// do at this very moment.
//
// We're careful here to not fail the test, i.e. we don't call t.Error
// here. We want to preserve as much state as possible in the artifacts,
// and calling t.{Error,Fatal}{,f} cancels the test's main context.
//
// We make sure to fail the test later when handling the timedOut variable.
const stacksFile = "__stacks"
if cl, err := t.L().ChildLogger(stacksFile, logger.QuietStderr, logger.QuietStdout); err == nil {
sl := allStacks()
if c.Spec().NodeCount == 0 {
sl = []byte("<elided during unit test>") // keep test outputs clutter-free
}
cl.PrintfCtx(ctx, "all stacks:\n\n%s\n", sl)
t.L().PrintfCtx(ctx, "dumped stacks to %s", stacksFile)
}
// Send SIGQUIT to ask all processes to dump stacks if requested (without shutting down).
// We need to do this before collectClusterArtifacts below, which will download the logs.
// Note that the debug.zip will hopefully also contain stacks, but we're just making sure
// there's something even if the debug.zip doesn't go through.
args := option.DefaultStopOpts()
args.RoachprodOpts.Sig = 3
err := c.StopE(ctx, t.L(), args, c.All())
t.L().PrintfCtx(ctx, "asked CRDB nodes to dump stacks; check their main (DEV) logs: %v", err)
// It takes a little moment for the stacks to get flushed to the logs.
// Against a real cluster they'll typically be there by the time we fetch
// logs but on local clusters this may not be true; either way better to
// not take any chances.
if c.Spec().NodeCount > 0 { // unit tests
time.Sleep(3 * time.Second)
}
}
// Detect dead nodes. This will call t.Error() when appropriate. Note that
// we do this even if t.Failed() since a down node is often the reason for
// the failure, and it's helpful to have the listing in the teardown logs
// as well (it is typically already in the main logs if the test used a
// monitor).
c.assertNoDeadNode(ctx, t)
// Detect replica divergence (i.e. ranges in which replicas have arrived
// at the same log position with different states).
//
// We avoid trying to do this when t.Failed() (and in particular when there
// are dead nodes) because for reasons @tbg does not understand this gets
// stuck occasionally, which really ruins the roachtest run. The method
// below already uses a ctx timeout and SQL statement_timeout, but it does
// not seem to be enough.
//
// TODO(testinfra): figure out why this can still get stuck despite the
// above.
c.FailOnReplicaDivergence(ctx, t)
if timedOut || t.Failed() {
r.collectClusterArtifacts(ctx, c, t)
}
})
const artifactsCollectionTimeout = time.Hour
select {
case <-artifactsCollectedCh:
case <-time.After(artifactsCollectionTimeout):
// Leak the artifacts collection goroutine. Note that the test may not be
// marked as failing here. We intentionally do not trigger it to fail here,