-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
cluster.go
3144 lines (2835 loc) · 102 KB
/
cluster.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 (
"bytes"
"context"
gosql "database/sql"
"encoding/json"
"fmt"
"io"
"io/fs"
"math/rand"
"net"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"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/spec"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/test"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/tests"
"github.com/cockroachdb/cockroach/pkg/roachprod"
"github.com/cockroachdb/cockroach/pkg/roachprod/cloud"
"github.com/cockroachdb/cockroach/pkg/roachprod/config"
"github.com/cockroachdb/cockroach/pkg/roachprod/install"
"github.com/cockroachdb/cockroach/pkg/roachprod/logger"
"github.com/cockroachdb/cockroach/pkg/roachprod/prometheus"
"github.com/cockroachdb/cockroach/pkg/roachprod/vm"
"github.com/cockroachdb/cockroach/pkg/roachprod/vm/gce"
"github.com/cockroachdb/cockroach/pkg/util/httputil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
_ "github.com/lib/pq"
)
func init() {
_ = roachprod.InitProviders()
}
var (
// maps cpuArch to the corresponding crdb binary's absolute path
cockroach = make(map[vm.CPUArch]string)
// maps cpuArch to the corresponding crdb binary with runtime assertions enabled (EA)
cockroachEA = make(map[vm.CPUArch]string)
// maps cpuArch to the corresponding workload binary's absolute path
workload = make(map[vm.CPUArch]string)
// maps cpuArch to the corresponding dynamically-linked libraries' absolute paths
libraryFilePaths = make(map[vm.CPUArch][]string)
)
type errBinaryOrLibraryNotFound struct {
binary string
}
func (e errBinaryOrLibraryNotFound) Error() string {
return fmt.Sprintf("binary or library %q not found (or was not executable)", e.binary)
}
func validateBinaryFormat(path string, arch vm.CPUArch, checkEA bool) (string, error) {
abspath, err := filepath.Abs(path)
if err != nil {
return "", errors.WithStack(err)
}
// Check that the binary ELF format matches the expected architecture.
cmd := exec.Command("file", "-b", abspath)
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
return "", errors.Wrapf(err, "error executing 'file %s'", abspath)
}
fileFormat := strings.ToLower(out.String())
// N.B. 'arm64' is returned on macOS, while 'aarch64' is returned on Linux;
// "x86_64" string is returned on macOS, while "x86-64" is returned on Linux.
if arch == vm.ArchARM64 && !strings.Contains(fileFormat, "arm64") && !strings.Contains(fileFormat, "aarch64") {
return "", errors.Newf("%s has incompatible architecture; want: %q, got: %q", abspath, arch, fileFormat)
} else if arch == vm.ArchAMD64 && !strings.Contains(fileFormat, "x86-64") && !strings.Contains(fileFormat, "x86_64") {
// Otherwise, we expect a binary that was built for amd64.
return "", errors.Newf("%s has incompatible architecture; want: %q, got: %q", abspath, arch, fileFormat)
}
if arch == vm.ArchFIPS && strings.HasSuffix(abspath, "cockroach") {
// Check that the binary is patched to use OpenSSL FIPS.
// N.B. only the cockroach binary is patched, so we exclude this check for dynamically-linked libraries.
cmd = exec.Command("bash", "-c", fmt.Sprintf("nm %s | grep golang-fips |head -1", abspath))
if err := cmd.Run(); err != nil {
return "", errors.Newf("%s is not compiled with FIPS", abspath)
}
}
if checkEA {
// Check that the binary was compiled with assertions _enabled_.
cmd = exec.Command("bash", "-c", fmt.Sprintf("%s version |grep \"Enabled Assertions\" |grep true", abspath))
if err := cmd.Run(); err != nil {
return "", errors.Newf("%s is not compiled with assertions enabled", abspath)
}
}
return abspath, nil
}
func findBinary(
name string, osName string, arch vm.CPUArch, checkEA bool,
) (abspath string, err error) {
// Check to see if binary exists and is a regular file and executable.
if fi, err := os.Stat(name); err == nil && fi.Mode().IsRegular() && (fi.Mode()&0111) != 0 {
return validateBinaryFormat(name, arch, checkEA)
}
return findBinaryOrLibrary("bin", name, "", osName, arch, checkEA)
}
func findLibrary(libraryName string, os string, arch vm.CPUArch) (string, error) {
suffix := ".so"
if roachtestflags.Cloud == spec.Local {
switch runtime.GOOS {
case "linux":
case "freebsd":
case "openbsd":
case "dragonfly":
case "windows":
suffix = ".dll"
case "darwin":
suffix = ".dylib"
default:
return "", errors.Newf("failed to find suffix for runtime %s", runtime.GOOS)
}
}
return findBinaryOrLibrary("lib", libraryName, suffix, os, arch, false)
}
// findBinaryOrLibrary searches for a binary or library, _first_ in the $PATH, _then_ in the following hardcoded paths,
//
// $GOPATH/src/github.com/cockroachdb/cockroach/
// $GOPATH/src/github.com/cockroachdb/artifacts/
// $PWD/binOrLib
// $GOPATH/src/github.com/cockroachdb/cockroach/binOrLib
//
// in the above order, unless 'name' is an absolute path, in which case the hardcoded paths are skipped.
//
// binOrLib is either 'bin' or 'lib'; nameSuffix is either empty, '.so', '.dll', or '.dylib'.
// Both osName and arch are used to derive a fully qualified binary or library name by inserting the
// corresponding arch suffix (see install.ArchInfoForOS), e.g. '.linux-arm64' or '.darwin-amd64'.
//
// Each resulting path is searched for a file named 'name', 'name.nameSuffix.archSuffix', or 'name.nameSuffix', in
// the specified order.
//
// If no binary or library is found, an error is returned.
// Otherwise, if multiple binaries or libraries are located at the above paths, the first one found is returned.
// If the found binary or library happens to be of the wrong type, e.g., architecture is different from 'arch', or
// checkEA is true, and the binary was not compiled with runtime assertions enabled, an error is returned.
// While we could continue the search instead of returning an error, it is assumed the user can stage the binaries
// to avoid such ambiguity. Alternatively, the user can specify the absolute path to the binary or library,
// e.g., via --cockroach; in this case, only the absolute path is checked and validated.
func findBinaryOrLibrary(
binOrLib string, name string, nameSuffix string, osName string, arch vm.CPUArch, checkEA bool,
) (string, error) {
// Find the binary to run and translate it to an absolute path. First, look
// for the binary in PATH.
pathFromEnv, err := exec.LookPath(name)
if err == nil {
// Found it in PATH, validate and return absolute path.
return validateBinaryFormat(pathFromEnv, arch, checkEA)
}
if strings.HasPrefix(name, "/") {
// Specified name is an absolute path, but we couldn't find it; bail out.
return "", errors.WithStack(err)
}
// We're unable to find the name in PATH and "name" is a relative path:
// look in the cockroach repo.
gopath := os.Getenv("GOPATH")
if gopath == "" {
gopath = filepath.Join(os.Getenv("HOME"), "go")
}
dirs := []string{
filepath.Join(gopath, "/src/github.com/cockroachdb/cockroach/"),
filepath.Join(gopath, "/src/github.com/cockroachdb/cockroach/artifacts/"),
filepath.Join(os.ExpandEnv("$PWD"), binOrLib),
filepath.Join(gopath, "/src/github.com/cockroachdb/cockroach", binOrLib),
}
archInfo, err := install.ArchInfoForOS(osName, arch)
if err != nil {
return "", err
}
archSuffixes := []string{"." + archInfo.DebugArchitecture, "." + archInfo.ReleaseArchitecture}
for _, dir := range dirs {
var path string
for _, archSuffix := range archSuffixes {
if path, err = exec.LookPath(filepath.Join(dir, name+archSuffix+nameSuffix)); err == nil {
return validateBinaryFormat(path, arch, checkEA)
}
}
if path, err = exec.LookPath(filepath.Join(dir, name+nameSuffix)); err == nil {
return validateBinaryFormat(path, arch, checkEA)
}
}
return "", errBinaryOrLibraryNotFound{name}
}
// VerifyLibraries verifies that the required libraries, specified by name, are
// available for the target environment.
func VerifyLibraries(requiredLibs []string, arch vm.CPUArch) error {
foundLibraryPaths := libraryFilePaths[arch]
for _, requiredLib := range requiredLibs {
if !contains(foundLibraryPaths, libraryNameFromPath, requiredLib) {
return errors.Wrap(errors.Errorf("missing required library %s (arch=%q)", requiredLib, arch), "cluster.VerifyLibraries")
}
}
return nil
}
// libraryNameFromPath returns the name of a library without the extension(s), for a
// given path.
func libraryNameFromPath(path string) string {
filename := filepath.Base(path)
// N.B. filename may contain multiple extensions, e.g. "libgeos.linux-amd64.fips.so".
for ext := filepath.Ext(filename); ext != ""; ext = filepath.Ext(filename) {
filename = strings.TrimSuffix(filename, ext)
}
return filename
}
func contains(list []string, transformString func(s string) string, str string) bool {
if transformString == nil {
transformString = func(s string) string { return s }
}
for _, element := range list {
if transformString(element) == str {
return true
}
}
return false
}
func initBinariesAndLibraries() {
// TODO(srosenberg): enable metamorphic local clusters; currently, spec.Local means run all tests locally.
// This could be revisited after we have a way to specify which clouds a given test supports,
// see https://github.com/cockroachdb/cockroach/issues/104029.
defaultOSName := "linux"
defaultArch := vm.ArchAMD64
if roachtestflags.Cloud == spec.Local {
defaultOSName = runtime.GOOS
if roachtestflags.ARM64Probability == 1 {
// N.B. if arm64Probability != 1, then we're running a local cluster with both arm64 and amd64.
defaultArch = vm.ArchARM64
}
if string(defaultArch) != runtime.GOARCH {
fmt.Printf("WARN: local cluster's architecture (%q) differs from default (%q)\n", runtime.GOARCH, defaultArch)
}
}
fmt.Printf("Locating and verifying binaries for os=%q, arch=%q\n", defaultOSName, defaultArch)
// Finds and validates a binary.
resolveBinary := func(binName string, userSpecified string, arch vm.CPUArch, exitOnErr bool, checkEA bool) (string, error) {
path := binName
if userSpecified != "" {
path = userSpecified
}
abspath, err := findBinary(path, defaultOSName, arch, checkEA)
if err != nil {
if exitOnErr {
fmt.Fprintf(os.Stderr, "ERROR: unable to find required binary %q for %q: %v\n", binName, arch, err)
os.Exit(1)
}
return "", err
}
if userSpecified == "" {
// No user-specified path, so return the found absolute path.
return abspath, nil
}
// Bail out if a path other than the user-specified was found.
userPath, err := filepath.Abs(userSpecified)
if err != nil {
if exitOnErr {
fmt.Fprintf(os.Stderr, "ERROR: unable to find required binary %q for %q: %v\n", binName, arch, err)
os.Exit(1)
}
return "", err
}
if userPath != abspath {
err = errors.Errorf("found %q at: %q instead of the user-specified path: %q\n", binName, abspath, userSpecified)
if exitOnErr {
fmt.Fprintf(os.Stderr, "ERROR: unable to find required binary %q for %q: %v\n", binName, arch, err)
os.Exit(1)
}
return "", err
}
return abspath, nil
}
// We need to verify we have at least both the cockroach and the workload binaries.
var err error
cockroachPath := roachtestflags.CockroachPath
cockroachEAPath := roachtestflags.CockroachEAPath
workloadPath := roachtestflags.WorkloadPath
cockroach[defaultArch], _ = resolveBinary("cockroach", cockroachPath, defaultArch, true, false)
workload[defaultArch], _ = resolveBinary("workload", workloadPath, defaultArch, true, false)
cockroachEA[defaultArch], err = resolveBinary("cockroach-ea", cockroachEAPath, defaultArch, false, true)
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: unable to find %q for %q: %s\n", "cockroach-ea", defaultArch, err)
}
if roachtestflags.ARM64Probability > 0 && defaultArch != vm.ArchARM64 {
fmt.Printf("Locating and verifying binaries for os=%q, arch=%q\n", defaultOSName, vm.ArchARM64)
// We need to verify we have all the required binaries for arm64.
cockroach[vm.ArchARM64], _ = resolveBinary("cockroach", cockroachPath, vm.ArchARM64, true, false)
workload[vm.ArchARM64], _ = resolveBinary("workload", workloadPath, vm.ArchARM64, true, false)
cockroachEA[vm.ArchARM64], err = resolveBinary("cockroach-ea", cockroachEAPath, vm.ArchARM64, false, true)
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: unable to find %q for %q: %s\n", "cockroach-ea", vm.ArchARM64, err)
}
}
if roachtestflags.FIPSProbability > 0 && defaultArch != vm.ArchFIPS {
fmt.Printf("Locating and verifying binaries for os=%q, arch=%q\n", defaultOSName, vm.ArchFIPS)
// We need to verify we have all the required binaries for fips.
cockroach[vm.ArchFIPS], _ = resolveBinary("cockroach", cockroachPath, vm.ArchFIPS, true, false)
workload[vm.ArchFIPS], _ = resolveBinary("workload", workloadPath, vm.ArchFIPS, true, false)
cockroachEA[vm.ArchFIPS], err = resolveBinary("cockroach-ea", cockroachEAPath, vm.ArchFIPS, false, true)
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: unable to find %q for %q: %s\n", "cockroach-ea", vm.ArchFIPS, err)
}
}
// In v20.2 or higher, optionally expect certain library files to exist.
// Since they may not be found in older versions, do not hard error if they are not found.
for _, arch := range []vm.CPUArch{vm.ArchAMD64, vm.ArchARM64, vm.ArchFIPS} {
if roachtestflags.ARM64Probability == 0 && defaultArch != vm.ArchARM64 && arch == vm.ArchARM64 {
// arm64 isn't used, skip finding libs for it.
continue
}
if roachtestflags.FIPSProbability == 0 && arch == vm.ArchFIPS {
// fips isn't used, skip finding libs for it.
continue
}
paths := []string(nil)
for _, libraryName := range []string{"libgeos", "libgeos_c"} {
if libraryFilePath, err := findLibrary(libraryName, defaultOSName, arch); err != nil {
fmt.Fprintf(os.Stderr, "WARN: unable to find library %s, ignoring: %s\n", libraryName, err)
} else {
paths = append(paths, libraryFilePath)
}
}
libraryFilePaths[arch] = paths
}
// Looks like we have all the binaries we'll need. Let's print them out.
fmt.Printf("\nFound the following binaries:\n")
for arch, path := range cockroach {
if path != "" {
fmt.Printf("\tcockroach %q at: %s\n", arch, path)
}
}
for arch, path := range workload {
if path != "" {
fmt.Printf("\tworkload %q at: %s\n", arch, path)
}
}
for arch, path := range cockroachEA {
if path != "" {
fmt.Printf("\tcockroach-ea %q at: %s\n", arch, path)
}
}
for arch, paths := range libraryFilePaths {
if len(paths) > 0 {
fmt.Printf("\tlibraries %q at: %s\n", arch, strings.Join(paths, ", "))
}
}
}
type clusterRegistry struct {
mu struct {
syncutil.Mutex
clusters map[string]*clusterImpl
tagCount map[string]int
// savedClusters keeps track of clusters that have been saved for further
// debugging. Each cluster comes with a message about the test failure
// causing it to be saved for debugging.
savedClusters map[*clusterImpl]string
}
}
func newClusterRegistry() *clusterRegistry {
cr := &clusterRegistry{}
cr.mu.clusters = make(map[string]*clusterImpl)
cr.mu.savedClusters = make(map[*clusterImpl]string)
return cr
}
func (r *clusterRegistry) registerCluster(c *clusterImpl) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.mu.clusters[c.name] != nil {
return fmt.Errorf("cluster named %q already exists in registry", c.name)
}
r.mu.clusters[c.name] = c
if err := c.addLabels(map[string]string{VmLabelTestRunID: runID}); err != nil && c.l != nil {
c.l.Printf("failed to add label to cluster [%s] - %s", c.name, err)
}
return nil
}
func (r *clusterRegistry) unregisterCluster(c *clusterImpl) bool {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.mu.clusters[c.name]; !ok {
// If the cluster is not registered, no-op. This allows the
// method to be called defensively.
return false
}
if err := c.removeLabels([]string{VmLabelTestRunID}); err != nil && c.l != nil {
c.l.Printf("failed to remove label from cluster [%s] - %s", c.name, err)
}
delete(r.mu.clusters, c.name)
if c.tag != "" {
if _, ok := r.mu.tagCount[c.tag]; !ok {
panic(fmt.Sprintf("tagged cluster not accounted for: %s", c))
}
r.mu.tagCount[c.tag]--
}
return true
}
func (r *clusterRegistry) countForTag(tag string) int {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.tagCount[tag]
}
// markClusterAsSaved marks c such that it will not be destroyed by
// destroyAllClusters.
// msg is a message recording the reason why the cluster is being saved (i.e.
// generally a test failure error).
func (r *clusterRegistry) markClusterAsSaved(c *clusterImpl, msg string) {
r.mu.Lock()
r.mu.savedClusters[c] = msg
r.mu.Unlock()
}
type clusterWithMsg struct {
*clusterImpl
savedMsg string
}
// savedClusters returns the list of clusters that have been saved for
// debugging.
func (r *clusterRegistry) savedClusters() []clusterWithMsg {
r.mu.Lock()
defer r.mu.Unlock()
res := make([]clusterWithMsg, len(r.mu.savedClusters))
i := 0
for c, msg := range r.mu.savedClusters {
res[i] = clusterWithMsg{
clusterImpl: c,
savedMsg: msg,
}
i++
}
sort.Slice(res, func(i, j int) bool {
return strings.Compare(res[i].name, res[j].name) < 0
})
return res
}
// destroyAllClusters destroys all the clusters (except for "saved" ones) and
// blocks until they're destroyed. It responds to context cancelation by
// interrupting the waiting; the cluster destruction itself does not inherit the
// cancelation.
func (r *clusterRegistry) destroyAllClusters(ctx context.Context, l *logger.Logger) {
// Fire off a goroutine to destroy all of the clusters.
done := make(chan struct{})
go func() {
defer close(done)
var clusters []*clusterImpl
savedClusters := make(map[*clusterImpl]struct{})
r.mu.Lock()
for _, c := range r.mu.clusters {
clusters = append(clusters, c)
}
for c := range r.mu.savedClusters {
savedClusters[c] = struct{}{}
}
r.mu.Unlock()
var wg sync.WaitGroup
wg.Add(len(clusters))
for _, c := range clusters {
go func(c *clusterImpl) {
defer wg.Done()
if _, ok := savedClusters[c]; !ok {
// We don't close the logger here since the cluster may be still in use
// by a test, and so the logger might still be needed.
c.Destroy(ctx, dontCloseLogger, l)
}
}(c)
}
wg.Wait()
}()
select {
case <-done:
case <-ctx.Done():
}
}
func makeClusterName(name string) string {
return vm.DNSSafeName(name)
}
// MachineTypeToCPUs returns a CPU count for GCE, AWS, and Azure machine types.
// -1 is returned for unknown machine types.
func MachineTypeToCPUs(s string) int {
{
// GCE machine types.
var v int
if _, err := fmt.Sscanf(s, "n2-standard-%d", &v); err == nil {
return v
}
if _, err := fmt.Sscanf(s, "t2a-standard-%d", &v); err == nil {
return v
}
if _, err := fmt.Sscanf(s, "n2-highcpu-%d", &v); err == nil {
return v
}
if _, err := fmt.Sscanf(s, "n2-custom-%d", &v); err == nil {
return v
}
if _, err := fmt.Sscanf(s, "n2-highmem-%d", &v); err == nil {
return v
}
}
typeAndSize := strings.Split(s, ".")
if len(typeAndSize) == 2 {
size := typeAndSize[1]
switch size {
case "large":
return 2
case "xlarge":
return 4
case "2xlarge":
return 8
case "4xlarge":
return 16
case "8xlarge":
return 32
case "12xlarge":
return 48
case "16xlarge":
return 64
case "24xlarge":
return 96
}
}
// Azure doesn't have a standard way to size machines.
// This method is implemented for the default machine type.
// Not all of Azure machine types contain the number of vCPUs in the size and
// the sizing naming scheme is dependent on the machine type family.
switch s {
case "Standard_D2ds_v5", "Standard_D2pds_v5", "Standard_D2lds_v5",
"Standard_D2plds_v5", "Standard_E2ds_v5", "Standard_E2pds_v5":
return 2
case "Standard_D4ds_v5", "Standard_D4pds_v5", "Standard_D4lds_v5",
"Standard_D4plds_v5", "Standard_E4ds_v5", "Standard_E4pds_v5":
return 4
case "Standard_D8ds_v5", "Standard_D8pds_v5", "Standard_D8lds_v5",
"Standard_D8plds_v5", "Standard_E8ds_v5", "Standard_E8pds_v5":
return 8
case "Standard_D16ds_v5", "Standard_D16pds_v5", "Standard_D16lds_v5",
"Standard_D16plds_v5", "Standard_E16ds_v5", "Standard_E16pds_v5":
return 16
case "Standard_D32ds_v5", "Standard_D32pds_v5", "Standard_D32lds_v5",
"Standard_D32plds_v5", "Standard_E32ds_v5", "Standard_E32pds_v5":
return 32
case "Standard_D48ds_v5", "Standard_D48pds_v5", "Standard_D48lds_v5",
"Standard_D48plds_v5", "Standard_E48ds_v5", "Standard_E48pds_v5":
return 48
case "Standard_D64ds_v5", "Standard_D64pds_v5", "Standard_D64lds_v5",
"Standard_D64plds_v5", "Standard_E64ds_v5", "Standard_E64pds_v5":
return 64
case "Standard_D96ds_v5", "Standard_D96pds_v5", "Standard_D96lds_v5",
"Standard_D96plds_v5", "Standard_E96ds_v5", "Standard_E96pds_v5":
return 96
}
// Unknown or unsupported machine type.
return -1
}
type nodeSelector interface {
option.Option
Merge(option.NodeListOption) option.NodeListOption
}
// clusterImpl implements cluster.Cluster.
// It is safe for concurrent use by multiple goroutines.
type clusterImpl struct {
name string
tag string
cloud string
spec spec.ClusterSpec
t test.Test
f roachtestutil.Fataler
// r is the registry tracking this cluster. Destroying the cluster will
// unregister it.
r *clusterRegistry
// l is the logger used to log various cluster operations.
// DEPRECATED for use outside of cluster methods: Use a test's t.L() instead.
// This is generally set to the current test's logger.
l *logger.Logger
// localCertsDir is a local copy of the certs for this cluster. If this is empty,
// the cluster is running in insecure mode.
localCertsDir string
expiration time.Time
encAtRest bool // use encryption at rest
// clusterSettings are additional cluster settings set on the storage cluster startup.
clusterSettings map[string]string
// virtualClusterSettings are additional cluster settings to set on the
// virtual cluster startup.
virtualClusterSettings map[string]string
// goCoverDir is the directory for Go coverage data (if coverage is enabled).
// BAZEL_COVER_DIR will be set to this value when starting a node.
goCoverDir string
os string // OS of the cluster
arch vm.CPUArch // CPU architecture of the cluster
randomSeed struct {
mu syncutil.Mutex
seed *int64
}
// destroyState contains state related to the cluster's destruction.
destroyState destroyState
// grafanaTags contains the cluster and test information that grafana will separate
// test runs by. This is used by the roachtest grafana API to create appropriately
// tagged grafana annotations. If empty, grafana is not available.
grafanaTags []string
disableGrafanaAnnotations atomic.Bool
}
// Name returns the cluster name, i.e. something like `teamcity-....`
func (c *clusterImpl) Name() string {
return c.name
}
// Spec returns the spec underlying the cluster.
func (c *clusterImpl) Spec() spec.ClusterSpec {
return c.spec
}
// status is used to communicate the test's status. It's a no-op until the
// cluster is passed to a test, at which point it's hooked up to test.Status().
func (c *clusterImpl) status(args ...interface{}) {
if c.t == nil {
return
}
c.t.Status(args...)
}
func (c *clusterImpl) workerStatus(args ...interface{}) {
if impl, ok := c.t.(*testImpl); ok {
impl.WorkerStatus(args...)
}
}
func (c *clusterImpl) String() string {
return fmt.Sprintf("%s [tag:%s] (%d nodes)", c.name, c.tag, c.Spec().NodeCount)
}
type destroyState struct {
// owned is set if this instance is responsible for `roachprod destroy`ing the
// cluster. It is set when a new cluster is created, but not when we attach to
// an existing roachprod cluster.
// If not set, Destroy() only wipes the cluster.
owned bool
mu struct {
syncutil.Mutex
loggerClosed bool
// destroyed is used to coordinate between different goroutines that want to
// destroy a cluster. It is set once the destroy process starts. It it
// closed when the destruction is complete.
destroyed chan struct{}
// saved is set if this cluster should not be wiped or destroyed. It should
// be left alone for further debugging. This is kept in sync with the
// clusterRegistry which maintains a list of all saved clusters.
saved bool
// savedMsg records a message describing the reason why the cluster is being
// saved.
savedMsg string
}
}
// closeLogger closes c.l. It can be called multiple times.
func (c *clusterImpl) closeLogger() {
c.destroyState.mu.Lock()
defer c.destroyState.mu.Unlock()
if c.destroyState.mu.loggerClosed {
return
}
c.destroyState.mu.loggerClosed = true
c.l.Close()
}
type clusterConfig struct {
nameOverride string
spec spec.ClusterSpec
// artifactsDir is the path where log file will be stored.
artifactsDir string
// username is the username passed via the --username argument
// or the ROACHPROD_USER command-line option.
username string
localCluster bool
useIOBarrier bool
// Specifies CPU architecture which may require a custom AMI and cockroach binary.
arch vm.CPUArch
// Specifies the OS which may require a custom AMI and cockroach binary.
os string
}
// clusterFactory is a creator of clusters.
type clusterFactory struct {
// namePrefix is prepended to all cluster names.
namePrefix string
// counter is incremented with every new cluster. It's used as part of the cluster's name.
// Accessed atomically.
counter atomic.Uint64
// The registry with whom all clustered will be registered.
r *clusterRegistry
// artifactsDir is the directory in which the cluster creation log file will be placed.
artifactsDir string
// sem is a semaphore throttling the creation of clusters (because AWS has
// ridiculous API calls limits).
sem chan struct{}
}
func newClusterFactory(
user string, clustersID string, artifactsDir string, r *clusterRegistry, concurrentCreations int,
) *clusterFactory {
secs := timeutil.Now().Unix()
var prefix string
if clustersID != "" {
prefix = fmt.Sprintf("%s-%s-%d-", user, clustersID, secs)
} else {
prefix = fmt.Sprintf("%s-%d-", user, secs)
}
return &clusterFactory{
sem: make(chan struct{}, concurrentCreations),
namePrefix: prefix,
artifactsDir: artifactsDir,
r: r,
}
}
// acquireSem blocks until the semaphore allows a new cluster creation. The
// returned function needs to be called when cluster creation finished.
func (f *clusterFactory) acquireSem() func() {
f.sem <- struct{}{}
return f.releaseSem
}
func (f *clusterFactory) releaseSem() {
<-f.sem
}
func (f *clusterFactory) genName(cfg clusterConfig) string {
if cfg.localCluster {
return "local" // The roachprod tool understands this magic name.
}
if cfg.nameOverride != "" {
return cfg.nameOverride
}
count := f.counter.Add(1)
return makeClusterName(
fmt.Sprintf("%s-%02d-%s", f.namePrefix, count, cfg.spec.String()))
}
// createFlagsOverride updates opts with the override values passed from the cli.
func createFlagsOverride(opts *vm.CreateOpts) {
if roachtestflags.Changed(&roachtestflags.Lifetime) != nil {
opts.Lifetime = roachtestflags.Lifetime
}
if roachtestflags.Changed(&roachtestflags.OverrideUseLocalSSD) != nil {
opts.SSDOpts.UseLocalSSD = roachtestflags.OverrideUseLocalSSD
}
if roachtestflags.Changed(&roachtestflags.OverrideFilesystem) != nil {
opts.SSDOpts.FileSystem = roachtestflags.OverrideFilesystem
}
if roachtestflags.Changed(&roachtestflags.OverrideNoExt4Barrier) != nil {
opts.SSDOpts.NoExt4Barrier = roachtestflags.OverrideNoExt4Barrier
}
if roachtestflags.Changed(&roachtestflags.OverrideOSVolumeSizeGB) != nil {
opts.OsVolumeSize = roachtestflags.OverrideOSVolumeSizeGB
}
if roachtestflags.Changed(&roachtestflags.OverrideGeoDistributed) != nil {
opts.GeoDistributed = roachtestflags.OverrideGeoDistributed
}
}
// clusterMock creates a cluster to be used for (self) testing.
func (f *clusterFactory) clusterMock(cfg clusterConfig) *clusterImpl {
return &clusterImpl{
name: f.genName(cfg),
expiration: timeutil.Now().Add(24 * time.Hour),
r: f.r,
}
}
// create is a hook for tests to inject their own cluster create implementation.
// i.e. unit tests that don't want to actually access a provider.
var create = roachprod.Create
// newCluster creates a new roachprod cluster.
//
// setStatus is called with status messages indicating the stage of cluster
// creation.
//
// NOTE: setTest() needs to be called before a test can use this cluster.
func (f *clusterFactory) newCluster(
ctx context.Context, cfg clusterConfig, setStatus func(string), teeOpt logger.TeeOptType,
) (*clusterImpl, *vm.CreateOpts, error) {
if ctx.Err() != nil {
return nil, nil, errors.Wrap(ctx.Err(), "newCluster")
}
if roachtestflags.Changed(&roachtestflags.OverrideNumNodes) != nil {
cfg.spec.NodeCount = roachtestflags.OverrideNumNodes
}
if cfg.spec.NodeCount == 0 {
// For tests, use a mock cluster.
c := f.clusterMock(cfg)
if err := f.r.registerCluster(c); err != nil {
return nil, nil, err
}
return c, nil, nil
}
if cfg.localCluster {
// Local clusters never expire.
cfg.spec.Lifetime = 100000 * time.Hour
}
setStatus("acquiring cluster creation semaphore")
release := f.acquireSem()
defer release()
setStatus("roachprod create")
defer setStatus("idle")
providerOptsContainer := vm.CreateProviderOptionsContainer()
cloud := roachtestflags.Cloud
params := spec.RoachprodClusterConfig{
Cloud: cloud,
UseIOBarrierOnLocalSSD: cfg.useIOBarrier,
PreferredArch: cfg.arch,
}
params.Defaults.MachineType = roachtestflags.InstanceType
params.Defaults.Zones = roachtestflags.Zones
params.Defaults.PreferLocalSSD = roachtestflags.PreferLocalSSD
// The ClusterName is set below in the retry loop to ensure
// that each create attempt gets a unique cluster name.
// N.B. selectedArch may not be the same as PreferredArch, depending on (spec.CPU, spec.Mem)
createVMOpts, providerOpts, selectedArch, err := cfg.spec.RoachprodOpts(params)
if err != nil {
return nil, nil, err
}
if cloud != spec.Local {
providerOptsContainer.SetProviderOpts(cloud, providerOpts)
}
createFlagsOverride(&createVMOpts)
// Make sure expiration is changed if --lifetime override flag
// is passed.
cfg.spec.Lifetime = createVMOpts.Lifetime
// Attempt to create a cluster several times to be able to move past
// temporary flakiness in the cloud providers.
maxAttempts := 3
if cfg.nameOverride != "" {
// Usually when retrying we pick a new name (to avoid repeat failures due to
// partially created resources), but we were asked to use a specific
// name. To keep things simple, disable retries in that case.
maxAttempts = 1
}
// loop assumes maxAttempts is atleast (1).
for i := 1; ; i++ {
// NB: this intentionally avoids re-using the name across iterations in
// the loop. See:
//
// https://github.com/cockroachdb/cockroach/issues/67906#issuecomment-887477675
genName := f.genName(cfg)
// Logs for creating a new cluster go to a dedicated log file.
var retryStr string
if i > 1 {
retryStr = "-retry" + strconv.Itoa(i-1)
}
logPath := filepath.Join(f.artifactsDir, runnerLogsDir, "cluster-create", genName+retryStr+".log")
l, err := logger.RootLogger(logPath, teeOpt)
if err != nil {
log.Fatalf(ctx, "%v", err)
}
c := &clusterImpl{
cloud: cloud,
name: genName,
spec: cfg.spec,
expiration: cfg.spec.Expiration(),
r: f.r,
arch: selectedArch,
os: cfg.os,
destroyState: destroyState{
owned: true,
},
l: l,
}
c.status("creating cluster")
l.PrintfCtx(ctx, "Attempting cluster creation (attempt #%d/%d)", i, maxAttempts)
createVMOpts.ClusterName = c.name
err = create(ctx, l, cfg.username, cfg.spec.NodeCount, createVMOpts, providerOptsContainer)
if err == nil {
if err := f.r.registerCluster(c); err != nil {
return nil, nil, err
}
c.status("idle")
l.Close()
return c, &createVMOpts, nil
}
if errors.HasType(err, (*roachprod.ClusterAlreadyExistsError)(nil)) {
// If the cluster couldn't be created because it existed already, bail.
// In reality when this is hit is when running with the `local` flag
// or a destroy from the previous iteration failed.
return nil, nil, err
}
if errors.HasType(err, (*roachprod.MalformedClusterNameError)(nil)) {
return nil, nil, err
}
l.PrintfCtx(ctx, "cluster creation failed, cleaning up in case it was partially created: %s", err)
c.Destroy(ctx, closeLogger, l)
if i >= maxAttempts {
return nil, nil, err
}
// Try again to create the cluster.
}
}
type attachOpt struct {
skipValidation bool
// Implies skipWipe.
skipStop bool
skipWipe bool
}
// attachToExistingCluster creates a cluster object based on machines that have
// already been already allocated by roachprod.
//
// NOTE: setTest() needs to be called before a test can use this cluster.
func attachToExistingCluster(
ctx context.Context,
name string,