-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
test_runner.go
2193 lines (1985 loc) · 75.6 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 CockroachDB Software License
// included in the /LICENSE file.
package main
import (
"context"
"encoding/json"
"fmt"
"html"
"io"
"math/rand"
"net"
"net/http"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/DataExMachina-dev/side-eye-go/sideeyeclient"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/cli/exit"
"github.com/cockroachdb/cockroach/pkg/cmd/roachprod/grafana"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/cluster"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/option"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/registry"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/roachtestflags"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/roachtestutil"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/roachtestutil/task"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/spec"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/test"
"github.com/cockroachdb/cockroach/pkg/roachprod/logger"
"github.com/cockroachdb/cockroach/pkg/roachprod/vm"
"github.com/cockroachdb/cockroach/pkg/util/allstacks"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"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/petermattis/goid"
)
func init() {
pollPreemptionInterval.Lock()
defer pollPreemptionInterval.Unlock()
pollPreemptionInterval.interval = 5 * time.Minute
}
var (
errTestsFailed = fmt.Errorf("some tests failed")
// reference error used by main.go at the end of a run of tests
errSomeClusterProvisioningFailed = fmt.Errorf("some clusters could not be created")
prometheusNameSpace = "roachtest"
// prometheusScrapeInterval should be consistent with the scrape interval defined in
// https://grafana.testeng.crdb.io/prometheus/config
prometheusScrapeInterval = time.Second * 15
// errClusterProvisioningFailed wraps the error given in an error
// that is properly sent to Test Eng and marked as an infra flake.
errClusterProvisioningFailed = func(err error) error {
return registry.ErrorWithOwner(
registry.OwnerTestEng, err,
registry.WithTitleOverride("cluster_creation"),
registry.InfraFlake,
)
}
// vmPreemptionError is the error that indicates that a test failed
// *and* VMs were preempted. These errors are directed to Test Eng
// instead of owning teams.
vmPreemptionError = func(preemptedVMs string) error {
infraFlakeErr := registry.ErrorWithOwner(
registry.OwnerTestEng, fmt.Errorf("preempted VMs: %s", preemptedVMs),
registry.WithTitleOverride("vm_preemption"),
registry.InfraFlake,
)
// The returned error is marked as non-reportable to avoid the
// noise, as we get dozens of preemptions on each nightly run. We
// have dashboards that can be used to check how often we get
// preemptions in test runs.
return registry.NonReportable(infraFlakeErr)
}
// vmHostError is the error that indicates that a test failed
// a result of VM host error. These errors are directed to Test Eng
// instead of owning teams.
vmHostError = func(hostErrorVMs string) error {
return registry.ErrorWithOwner(
registry.OwnerTestEng, fmt.Errorf("hostError VMs: %s", hostErrorVMs),
registry.WithTitleOverride("vm_host_error"),
registry.InfraFlake,
)
}
prng, _ = randutil.NewLockedPseudoRand()
runID string
)
// VmLabelTestName is the label used to identify the test name in the VM metadata
const VmLabelTestName string = "test_name"
// VmLabelTestRunID is the label used to identify the test run id in the VM metadata
const VmLabelTestRunID string = "test_run_id"
// VmLabelTestOwner is the label used to identify the test owner in the VM metadata
const VmLabelTestOwner string = "test_owner"
// testRunner runs tests.
type testRunner struct {
stopper *stop.Stopper
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
// overrideShutdownPromScrapeInterval overrides the default time a test runner waits to
// shut down, normally used to ensure a remote prometheus server has scraped the roachtest
// endpoint.
overrideShutdownPromScrapeInterval time.Duration
}
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
// sideEyeClient, if set, is the client used to communicate with the Side-Eye
// debugging service.
sideEyeClient *sideeyeclient.SideEyeClient
}
// 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.
func newTestRunner(cr *clusterRegistry, stopper *stop.Stopper) *testRunner {
r := &testRunner{
stopper: stopper,
cr: cr,
}
r.config.skipClusterWipeOnAttach = !roachtestflags.ClusterWipe
r.config.disableIssue = roachtestflags.DisableIssue
r.workersMu.workers = make(map[string]*workerStatus)
return r
}
func newUnitTestRunner(cr *clusterRegistry, stopper *stop.Stopper) *testRunner {
r := newTestRunner(cr, stopper)
// To speed up unit tests, reduce test runner shutdown time.
r.config.overrideShutdownPromScrapeInterval = time.Millisecond
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
// Controls whether the cluster is cleaned up at the end of the test.
debugMode debugMode
// sideEyeToken, if not empty, is the token used to authenticate with the
// Side-Eye. If set, each node in the cluster will run the Side-Eye agent.
sideEyeToken string
// preAllocateClusterFn is a function called right before allocating a
// cluster. It allows the caller to e.g. inject errors for testing.
preAllocateClusterFn func(
ctx context.Context,
t registry.TestSpec,
arch vm.CPUArch,
) error
}
type debugMode int
const (
// NoDebug does not enable any debug behaviour. Clusters will
// be destroyed regardless of the test result.
NoDebug debugMode = iota
// DebugKeepOnFailure does not wipe or destroy a cluster when
// a test using the respective cluster fails. These clusters
// will linger around and they'll continue counting towards
// the cpuQuota.
DebugKeepOnFailure
// DebugKeepAlways never wipes or destroys a cluster.
DebugKeepAlways
)
func (p debugMode) IsDebug() bool {
return p == DebugKeepOnFailure || p == DebugKeepAlways
}
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
skipInit bool
goCoverEnabled bool
exportOpenMetrics bool
}
// 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,
) error {
// Validate options.
if len(tests) == 0 {
return fmt.Errorf("no test matched filters")
}
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,
)
}
}
}
clusterFactory := newClusterFactory(
clustersOpt.user, clustersOpt.clusterID, lopt.artifactsDir,
r.cr, numConcurrentClusterCreations(), r.sideEyeClient,
)
n := len(tests)
if n*count < parallelism {
// Don't spin up more workers than necessary.
parallelism = n * count
}
if roachtestflags.UseSpotVM == roachtestflags.AlwaysUseSpot || roachtestflags.UseSpotVM == roachtestflags.AutoUseSpot {
for i := range tests {
if roachtestflags.UseSpotVM == roachtestflags.AlwaysUseSpot {
tests[i].Cluster.UseSpotVMs = true
continue
}
// TODO(bhaskar): remove this once we have more usage details
// and more convinced about using spot VMs for all the runs.
if (roachtestflags.Cloud == spec.GCE || (roachtestflags.Cloud == spec.AWS &&
tests[i].Benchmark)) &&
!tests[i].Suites.Contains(registry.Weekly) &&
!tests[i].IsLastFailurePreempt() &&
rand.Float64() <= 0.75 {
lopt.l.PrintfCtx(ctx, "using spot VMs to run test %s", tests[i].Name)
tests[i].Cluster.UseSpotVMs = true
}
}
}
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
runID = generateRunID(clustersOpt)
shout(ctx, l, lopt.stdout, "%s: %s", VmLabelTestRunID, runID)
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()
name := fmt.Sprintf("w%d", i)
formattedPrefix := fmt.Sprintf("[%s] ", name)
childLogger, err := l.ChildLogger(name, logger.LogPrefix(formattedPrefix))
if err != nil {
l.ErrorfCtx(ctx, "unable to create logger %s: %s", name, err)
childLogger = l
}
err = r.runWorker(
ctx, name, r.work, qp,
r.stopper.ShouldQuiesce(),
clusterFactory,
clustersOpt,
lopt,
topt,
childLogger,
n*count,
)
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, childLogger, 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()
shutdownStart := timeutil.Now()
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 errSomeClusterProvisioningFailed
}
if len(r.status.fail) > 0 {
return errTestsFailed
}
// To ensure all prometheus metrics have been scraped, ensure shutdown takes
// at least one scrapeInterval, unless the roachtest fails or gets cancelled.
requiredShutDownTime := prometheusScrapeInterval
if r.config.overrideShutdownPromScrapeInterval > 0 {
requiredShutDownTime = r.config.overrideShutdownPromScrapeInterval
}
if shutdownSleep := requiredShutDownTime - timeutil.Since(shutdownStart); shutdownSleep > 0 {
select {
case <-r.stopper.ShouldQuiesce():
case <-time.After(shutdownSleep):
}
}
return nil
}
// N.B. currently this value is hardcoded per cloud provider.
func numConcurrentClusterCreations() int {
var res int
if roachtestflags.Cloud == spec.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
}
// This will be added as a label to all cluster nodes when the
// cluster is registered. `clusterOpt.clusterID` is conveniently
// set to the TC Build ID when running on TeamCity.
func generateRunID(cOpts clustersOpt) string {
if cOpts.clusterID == "" {
return fmt.Sprintf("%s-%d", cOpts.user, timeutil.Now().Unix())
}
return fmt.Sprintf("%s-%s", cOpts.user, cOpts.clusterID)
}
func (r *testRunner) allocateCluster(
ctx context.Context,
clusterFactory *clusterFactory,
clustersOpt clustersOpt,
lopt loggingOpt,
t registry.TestSpec,
arch vm.CPUArch,
wStatus *workerStatus,
) (*clusterImpl, *vm.CreateOpts, error) {
wStatus.SetStatus(fmt.Sprintf("creating cluster (arch=%q)", arch))
defer wStatus.SetStatus("")
if clustersOpt.preAllocateClusterFn != nil {
if err := clustersOpt.preAllocateClusterFn(ctx, t, arch); err != nil {
return nil, nil, err
}
}
existingClusterName := clustersOpt.clusterName
if existingClusterName != "" {
// Logs for attaching to a cluster go to a dedicated log file.
logPath := filepath.Join(lopt.artifactsDir, runnerLogsDir, "cluster-create", existingClusterName+".log")
clusterL, err := logger.RootLogger(logPath, lopt.tee)
if err != nil {
return nil, nil, err
}
defer clusterL.Close()
opt := attachOpt{
skipValidation: r.config.skipClusterValidationOnAttach,
skipStop: r.config.skipClusterStopOnAttach,
skipWipe: r.config.skipClusterWipeOnAttach,
}
// TODO(srosenberg): we need to think about validation here. Attaching to an incompatible cluster, e.g.,
// using arm64 AMI with amd64 binary, would result in obscure errors. The test runner ensures compatibility
// during cluster reuse, whereas attachment via CLI (e.g., via roachprod) does not.
lopt.l.PrintfCtx(ctx, "Attaching to existing cluster %s for test %s", existingClusterName, t.Name)
c, err := attachToExistingCluster(ctx, existingClusterName, clusterL, t.Cluster, opt, r.cr)
if err == nil {
// Pretend pre-existing's cluster architecture matches the desired one; see the above TODO wrt validation.
c.arch = arch
return c, nil, nil
}
if !errors.Is(err, errClusterNotFound) {
return nil, nil, err
}
// Fall through to create new cluster with name override.
lopt.l.PrintfCtx(
ctx, "Creating new cluster with custom name %q for test %s: %s (arch=%q)",
clustersOpt.clusterName, t.Name, t.Cluster, arch,
)
} else {
lopt.l.PrintfCtx(ctx, "Creating new cluster for test %s: %s (arch=%q)", t.Name, t.Cluster, arch)
}
cfg := clusterConfig{
nameOverride: clustersOpt.clusterName, // only set if we hit errClusterFound above
spec: t.Cluster,
artifactsDir: lopt.artifactsDir,
username: clustersOpt.user,
localCluster: clustersOpt.typ == localCluster,
arch: arch,
sideEyeToken: clustersOpt.sideEyeToken,
}
return clusterFactory.newCluster(ctx, cfg, wStatus.SetStatus, lopt.tee)
}
// 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.
//
// The worker's name will be used as a prefix for log messages.
//
// Each test's logs are going to be under a <test-name>/run_<n> dir inside
// lotp.artifactsDir. If empty, test log files will not be created.
func (r *testRunner) runWorker(
ctx context.Context,
name string,
work *workPool,
qp *quotapool.IntPool,
interrupt <-chan struct{},
clusterFactory *clusterFactory,
clustersOpt clustersOpt,
lopt loggingOpt,
topt testOpts,
l *logger.Logger,
maxTotalFailures int,
) error {
stdout := lopt.stdout
wStatus := r.addWorker(ctx, l, 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() {
// TODO (miral): Consider removing the test_run_id label here, as
// currently, is only removed when a cluster is unregistered, via c.Destroy()
// but not when the cluster is preserved via a debug mode.
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.")
}
}()
var alloc *quotapool.IntAlloc
defer func() {
// Release any quota, in case we exit from the loop from an error path.
if alloc != nil {
if alloc.Acquired() > 0 {
l.PrintfCtx(ctx, "Releasing quota for %s CPUs", alloc.String())
}
qp.Release(alloc)
}
}()
clusterDestroyWg := &sync.WaitGroup{}
// cluster destroy can be done concurrently. The WaitGroup just ensures that all pending Destroy calls have completed.
defer clusterDestroyWg.Wait() // wait for the clusters to be destroyed
// 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")
}
}
// stop the tests if the failure rate has been exceeded
r.status.Lock()
failureRate := float64(len(r.status.fail)) / float64(maxTotalFailures)
r.status.Unlock()
if failureRate > roachtestflags.AutoKillThreshold {
return errors.Errorf("failure rate %.2f exceeds limit %.2f", failureRate, roachtestflags.AutoKillThreshold)
}
wStatus.SetTest(nil /* test */, testToRunRes{})
testToRun := testToRunRes{noWork: true}
if c != nil {
// Try to reuse cluster.
testToRun = work.selectTestForCluster(ctx, l, c.spec, r.cr, roachtestflags.Cloud)
if !testToRun.noWork {
// We found a test to run on this cluster. Wipe the cluster.
if err := c.WipeForReuse(ctx, l, testToRun.spec.Cluster); err != nil {
// We do not count reuse attempt error toward clusterCreateErr. If
// either the Wipe or Extend failed, then destroy the cluster and attempt
// to create a fresh cluster for the selected test.
shout(ctx, l, stdout, "Unable to reuse cluster: %s due to: %s. Will attempt to create a fresh one",
c.Name(), err)
// We don't release the quota allocation - the new cluster will be
// identical.
testToRun.canReuseCluster = false
// We use a context that can't be canceled for the Destroy().
c.Destroy(context.Background(), closeLogger, l)
wStatus.SetCluster(nil)
c = nil
}
}
}
// We could not find a test that can reuse the cluster. Destroy the cluster
// and search for a new test.
if testToRun.noWork {
if c != nil {
wStatus.SetStatus("destroying cluster")
// We failed to find a test that can take advantage of this cluster. So
// we're going to release it, which will deallocate its resources.
l.PrintfCtx(ctx, "No tests that can reuse cluster %s found. Destroying.", c)
r.destroyClusterAsync(clusterDestroyWg, c, l)
wStatus.SetCluster(nil)
c = nil
}
// At this point, any previous cluster was destroyed; release any
// associated quota allocation.
if alloc != nil {
if alloc.Acquired() > 0 {
l.PrintfCtx(ctx, "Releasing quota for %s CPUs", alloc.String())
}
qp.Release(alloc)
alloc = nil
}
var err error
testToRun, alloc, err = work.selectTest(ctx, qp, l)
if err != nil {
return err
}
if testToRun.noWork {
shout(ctx, l, stdout, "No work remaining; runWorker is bailing out...")
return nil
}
}
// From this point onward, c != nil iff we are reusing the cluster.
var arch vm.CPUArch
if c != nil && !c.IsLocal() {
// We are reusing a non-local cluster. We have already determined that its
// architecture is acceptable for the test (from the fact that the
// previous cluster spec had the same arch).
//
// Note that we treat local clusters differently because (in the case of
// Apple M1/M2) it can run multiple architectures.
// TODO(radu): this is not true of Intel and/or linux hosts, we should
// somehow determine the capabilities at runtime.
arch = c.arch
} else {
arch = archForTest(ctx, l, testToRun.spec)
if c != nil {
// Switch architecture of local cluster (see above).
c.arch = arch
}
}
// Verify that required native libraries are available.
//
// TODO(radu): the arch is not guaranteed and another arch can be selected
// (in RoachprodOpts). All the code below using arch is incorrect in this
// case.
if err := VerifyLibraries(testToRun.spec.NativeLibs, arch); err != nil {
shout(ctx, l, stdout, "Library verification failed: %s", err)
return err
}
// Verify that the deprecated workload is available if needed.
if testToRun.spec.RequiresDeprecatedWorkload && workload[arch] == "" {
return errors.Errorf("%s requires deprecated workload binary but one was not found", testToRun.spec.Name)
}
var clusterCreateErr error
var vmCreateOpts *vm.CreateOpts
if c == nil {
// 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)
c, vmCreateOpts, clusterCreateErr = r.allocateCluster(
ctx, clusterFactory, clustersOpt, lopt,
testToRun.spec, arch, 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)
} else {
if c.arch != arch {
// N.B. this can happen if requested machine type is not feasible/available.
l.PrintfCtx(ctx, "WARN: cluster arch for test differs %s: %s (cluster arch=%q, specified arch=%q)",
testToRun.spec.Name, c.Name(), c.arch, arch)
arch = c.arch
}
l.PrintfCtx(ctx, "Created new cluster for test %s: %s (arch=%q)", testToRun.spec.Name, c.Name(), arch)
}
}
// If DebugKeepAlways is set, mark it as a saved cluster, so it isn't
// cleaned up. Do it now instead of at the end as the test may be interrupted
// with ctrl c before we get there.
if c != nil && clustersOpt.debugMode == DebugKeepAlways {
c.Save(ctx, "cluster saved since --debug-always set", l)
}
wStatus.SetCluster(c)
// If the Side-Eye integration is active, update the cluster's Side-Eye
// environment name to match the current test; this makes it easier to
// identify this cluster on app.side-eye.io.
if c != nil && r.sideEyeClient != nil {
testSuffix := ""
if testToRun.runCount > 1 {
testSuffix = fmt.Sprintf("#%d", testToRun.runNum)
}
envName := fmt.Sprintf("%s-%s%s", runID, testToRun.spec.Name, testSuffix)
err := c.UpdateSideEyeEnvironmentName(ctx, l, envName)
if err != nil {
l.ErrorfCtx(ctx, "failed to update Side-Eye environment name: %s", err)
}
}
// Prepare the test's logger. Always set this up with real files, using a
// temp dir if necessary. This simplifies testing.
artifactsRootDir := lopt.artifactsDir
if artifactsRootDir == "" {
artifactsRootDir, _ = os.MkdirTemp("", "roachtest-logger")
}
testName := testToRun.spec.Name
// N.B. c may be nil owing to clusterCreateErr
if c != nil && c.arch != vm.ArchAMD64 {
// N.B. For non-default cpu architecture, encode it in the test name. This helps to differentiate test
// artifacts/results by cpu architecture.
testName = fmt.Sprintf("%s/cpu_arch=%s", testName, c.arch)
}
escapedTestName := teamCityNameEscape(testName)
runSuffix := "run_" + strconv.Itoa(testToRun.runNum)
testArtifactsDir := filepath.Join(filepath.Join(artifactsRootDir, escapedTestName), runSuffix)
logPath := filepath.Join(testArtifactsDir, "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(lopt.literalArtifactsDir, escapedTestName), runSuffix, escapedTestName, runSuffix)
testL, err := logger.RootLogger(logPath, lopt.tee)
if err != nil {
return err
}
binaryVersion, err := version.Parse(build.BinaryVersion())
if err != nil {
return err
}
t := &testImpl{
spec: &testToRun.spec,
cockroach: cockroach[arch],
cockroachEA: cockroachEA[arch],
deprecatedWorkload: workload[arch],
buildVersion: binaryVersion,
artifactsDir: testArtifactsDir,
artifactsSpec: artifactsSpec,
l: testL,
versionsBinaryOverride: topt.versionsBinaryOverride,
skipInit: topt.skipInit,
debug: clustersOpt.debugMode.IsDebug(),
goCoverEnabled: topt.goCoverEnabled,
exportOpenmetrics: topt.exportOpenMetrics,
runID: generateRunID(clustersOpt),
}
github := newGithubIssues(r.config.disableIssue, c, vmCreateOpts)
// handleClusterCreationFailure can be called when the `err` given
// occurred for reasons related to creating or setting up a
// cluster for a test.
handleClusterCreationFailure := func(err error) {
t.Error(errClusterProvisioningFailed(err))
params := getTestParameters(t, github.cluster, github.vmCreateOpts)
logTestParameters(l, params)
if _, err := github.MaybePost(t, l, t.failureMsg(), "" /* sideEyeTimeoutSnapshotURL */, params); err != nil {
shout(ctx, l, stdout, "failed to post issue: %s", err)
}
}
if clusterCreateErr != nil {
// N.B. cluster creation failed. We mark the test as failed and
// continue with the next test.
handleClusterCreationFailure(clusterCreateErr)
} else {
// Now run the test.
l.PrintfCtx(ctx, "Starting test: %s:%d on cluster=%s (arch=%q)", testToRun.spec.Name, testToRun.runNum, c.Name(), arch)
c.setTest(t)
var setupErr error
if c.spec.NodeCount > 0 { // skip during tests
setupErr = c.PutCockroach(ctx, l, t)
}
if setupErr == nil {
setupErr = c.PutLibraries(ctx, "./lib", t.spec.NativeLibs)
}
if setupErr == nil {
setupErr = c.PutDeprecatedWorkload(ctx, l, t)
}
if setupErr != nil {
// If there was an error setting up the cluster (uploading
// initial files), we treat the error just like a cluster
// creation failure: the error is reported as an
// infrastructure flake, and we continue with the next test.
handleClusterCreationFailure(setupErr)
} else {
// Tell the cluster that, from now on, it will be run "on behalf of this
// test".
c.status("running test")
testSpec := t.Spec().(*registry.TestSpec)
switch 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() < roachtestflags.EncryptionProbability
}
// Set initial cluster settings for this test.
c.clusterSettings = map[string]string{}
c.virtualClusterSettings = map[string]string{}
leases := testSpec.Leases
if leases == registry.MetamorphicLeases {
// 50% change of using the default lease type, 50% change of choosing
// a random, specific lease type.
if prng.Intn(2) == 0 {
leases = registry.DefaultLeases
} else {
leases = registry.LeaseTypes[prng.Intn(len(registry.LeaseTypes))]
}
c.status(fmt.Sprintf("metamorphically using %s leases", leases))
t.AddParam("metamorphicLeases", leases.String())
}
switch leases {
case registry.DefaultLeases:
case registry.EpochLeases:
c.clusterSettings["kv.expiration_leases_only.enabled"] = "false"
c.clusterSettings["kv.raft.leader_fortification.fraction_enabled"] = "0.0"
case registry.ExpirationLeases:
c.clusterSettings["kv.expiration_leases_only.enabled"] = "true"
case registry.LeaderLeases:
c.clusterSettings["kv.expiration_leases_only.enabled"] = "false"
c.clusterSettings["kv.raft.leader_fortification.fraction_enabled"] = "1.0"
case registry.MetamorphicLeases:
t.Fatalf("metamorphic leases handled above")
default:
t.Fatalf("unknown lease type %s", leases)
}
c.goCoverDir = t.GoCoverArtifactsDir()
wStatus.SetTest(t, testToRun)
wStatus.SetStatus("running test")
r.runTest(ctx, t, testToRun.runNum, testToRun.runCount, c, stdout, testL, github)
}
}
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 t.Failed() {
failureMsg := fmt.Sprintf("%s (%d) - %s", testToRun.spec.Name, testToRun.runNum, t.failureMsg())
if c != nil {
switch clustersOpt.debugMode {
case DebugKeepAlways, DebugKeepOnFailure:
// Save the cluster for future debugging.
// We already marked the cluster as a saved cluster above in the case
// of DebugKeepAlways, but update it with the failureMsg.
c.Save(ctx, failureMsg, l)
// Continue with a fresh cluster.
c = nil
case NoDebug:
// 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
}
}
} else {
// Upon success fetch the perf artifacts from the remote hosts.
if t.spec.Benchmark {
getPerfArtifacts(ctx, c, t)
}
if clustersOpt.debugMode == DebugKeepAlways {
// We already marked the cluster as a saved cluster above.
alloc.Freeze()
alloc = nil
c = nil
}
}
}
}
// destroyClusterAsync runs cluster destroy in a goroutine and adds 1 to the wait group.
// if the cluster is local, the cluster destroy is sequential.
func (r *testRunner) destroyClusterAsync(
clusterDestroyWg *sync.WaitGroup, c *clusterImpl, l *logger.Logger,
) {
if c.IsLocal() {
// N.B. multiple local clusters aren't supported, hence we must use a blocking call.
c.Destroy(context.Background(), closeLogger, l)
return
}
clusterDestroyWg.Add(1)
go func(ci *clusterImpl) {
defer clusterDestroyWg.Done()
// We use a context that can't be canceled for the Destroy().
ci.Destroy(context.Background(), closeLogger, l)
}(c)
}