-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
cluster.go
2738 lines (2484 loc) · 87.2 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"
"fmt"
"io"
"io/fs"
"net"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/armon/circbuf"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/cluster"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/option"
"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/roachprod"
"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/util/httputil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/quotapool"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
_ "github.com/lib/pq"
"github.com/spf13/pflag"
)
func init() {
_ = roachprod.InitProviders()
}
var (
// user-specified path to crdb binary
cockroachPath string
// maps cpuArch to the corresponding crdb binary's absolute path
cockroach = make(map[vm.CPUArch]string)
// user-specified path to crdb binary with runtime assertions enabled (EA)
cockroachEAPath string
// maps cpuArch to the corresponding crdb binary with runtime assertions enabled (EA)
cockroachEA = make(map[vm.CPUArch]string)
// user-specified path to workload binary
workloadPath 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)
cloud = spec.GCE
// encryptionProbability controls when encryption-at-rest is enabled
// in a cluster for tests that have opted-in to metamorphic
// encryption (EncryptionMetamorphic).
//
// Tests that have opted-in to metamorphic encryption will run with
// encryption enabled by default (probability 1). In order to run
// them with encryption disabled (perhaps to reproduce a test
// failure), roachtest can be invoked with --metamorphic-encryption-probability=0
encryptionProbability float64
// Total probability with which new ARM64 clusters are provisioned, modulo test specs. which are incompatible.
// N.B. if all selected tests are incompatible with ARM64, then arm64Probability is effectively 0.
// In other words, ClusterSpec.Arch takes precedence over the arm64Probability flag.
arm64Probability float64
// Conditional probability with which new FIPS clusters are provisioned, modulo test specs. The total probability
// is the product of this and 1-arm64Probability.
// As in the case of arm64Probability, ClusterSpec.Arch takes precedence over the fipsProbability flag.
fipsProbability float64
instanceType string
localSSDArg bool
deprecatedRoachprodBinary string
// overrideOpts contains vm.CreateOpts override values passed from the cli.
overrideOpts vm.CreateOpts
// overrideFlagset represents the flags passed from the cli for
// `run` command (used to know if the value of a flag changed,
// for example: overrideFlagset("lifetime").Changed().
// TODO(ahmad/healthy-pod): extract runCmd (and other commands) from main
// to make it global and operate on runCmd.Flags() directly.
overrideFlagset *pflag.FlagSet
overrideNumNodes = -1
clusterName string
clusterWipe bool
zonesF string
teamCity bool
disableIssue bool
)
const (
defaultEncryptionProbability = 1
defaultFIPSProbability = 0
defaultARM64Probability = 0
defaultCockroachPath = "./cockroach-default"
)
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 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'.
// That is, each hardcoded path is searched for a file named 'name' or 'name.nameSuffix.archSuffix', respectively.
//
// 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
if path, err = exec.LookPath(filepath.Join(dir, name+nameSuffix)); err == nil {
return validateBinaryFormat(path, arch, checkEA)
}
for _, archSuffix := range archSuffixes {
if path, err = exec.LookPath(filepath.Join(dir, name+archSuffix+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 cloud == spec.Local {
defaultOSName = runtime.GOOS
if 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
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 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 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 arm64Probability == 0 && defaultArch != vm.ArchARM64 && arch == vm.ArchARM64 {
// arm64 isn't used, skip finding libs for it.
continue
}
if 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, ", "))
}
}
}
// execCmd is like execCmdEx, but doesn't return the command's output.
func execCmd(
ctx context.Context, l *logger.Logger, clusterName string, secure bool, args ...string,
) error {
return execCmdEx(ctx, l, clusterName, secure, args...).err
}
type cmdRes struct {
err error
// stdout and stderr are the commands output. Note that this is truncated and
// only a tail is returned.
stdout, stderr string
}
// execCmdEx runs a command and returns its error and output.
//
// Note that the output is truncated; only a tail is returned.
// Also note that if the command exits with an error code, its output is also
// included in cmdRes.err.
func execCmdEx(
ctx context.Context, l *logger.Logger, clusterName string, secure bool, args ...string,
) cmdRes {
var cancel func()
ctx, cancel = context.WithCancel(ctx)
defer cancel()
l.Printf("> %s\n", strings.Join(args, " "))
var roachprodRunStdout, roachprodRunStderr io.Writer
debugStdoutBuffer, _ := circbuf.NewBuffer(4096)
debugStderrBuffer, _ := circbuf.NewBuffer(4096)
// Do a dance around https://github.com/golang/go/issues/23019.
// When the command we run launches a subprocess, that subprocess receives
// a copy of our Command's Stdout/Stderr file descriptor, which effectively
// means that the file descriptors close only when that subcommand returns.
// However, proactively killing the subcommand is not really possible - we
// will only manage to kill the parent process that we launched directly.
// In practice this means that if we try to react to context cancellation,
// the pipes we read the output from will wait for the *subprocess* to
// terminate, leaving us hanging, potentially indefinitely.
// To work around it, use pipes and set a read deadline on our (read) end of
// the pipes when we detect a context cancellation.
var closePipes func(ctx context.Context)
var wg sync.WaitGroup
{
var wOut, wErr, rOut, rErr *os.File
var cwOnce sync.Once
closePipes = func(ctx context.Context) {
// Idempotently closes the writing end of the pipes. This is called either
// when the process returns or when it was killed due to context
// cancellation. In the former case, close the writing ends of the pipe
// so that the copy goroutines started below return (without missing any
// output). In the context cancellation case, we set a deadline to force
// the goroutines to quit eagerly. This is important since the command
// may have duplicated wOut and wErr to its possible subprocesses, which
// may continue to run for long periods of time, and would otherwise
// block this command. In theory this is possible also when the command
// returns on its own accord, so we set a (more lenient) deadline in the
// first case as well.
//
// NB: there's also the option (at least on *nix) to use a process group,
// but it doesn't look portable:
// https://medium.com/@felixge/killing-a-child-process-and-all-of-its-children-in-go-54079af94773
cwOnce.Do(func() {
if wOut != nil {
_ = wOut.Close()
}
if wErr != nil {
_ = wErr.Close()
}
dur := 10 * time.Second // wait up to 10s for subprocesses
if ctx.Err() != nil {
dur = 10 * time.Millisecond
}
deadline := timeutil.Now().Add(dur)
if rOut != nil {
_ = rOut.SetReadDeadline(deadline)
}
if rErr != nil {
_ = rErr.SetReadDeadline(deadline)
}
})
}
defer closePipes(ctx)
var err error
rOut, wOut, err = os.Pipe()
if err != nil {
return cmdRes{err: err}
}
rErr, wErr, err = os.Pipe()
if err != nil {
return cmdRes{err: err}
}
roachprodRunStdout = wOut
wg.Add(1)
go func() {
defer wg.Done()
_, _ = io.Copy(l.Stdout, io.TeeReader(rOut, debugStdoutBuffer))
}()
if l.Stderr == l.Stdout {
// If l.Stderr == l.Stdout, we use only one pipe to avoid
// duplicating everything.
roachprodRunStderr = wOut
} else {
roachprodRunStderr = wErr
wg.Add(1)
go func() {
defer wg.Done()
_, _ = io.Copy(l.Stderr, io.TeeReader(rErr, debugStderrBuffer))
}()
}
}
err := roachprod.Run(ctx, l, clusterName, "" /* SSHOptions */, "" /* processTag */, secure, roachprodRunStdout, roachprodRunStderr, args)
closePipes(ctx)
wg.Wait()
stdoutString := debugStdoutBuffer.String()
if debugStdoutBuffer.TotalWritten() > debugStdoutBuffer.Size() {
stdoutString = "<... some data truncated by circular buffer; go to artifacts for details ...>\n" + stdoutString
}
stderrString := debugStderrBuffer.String()
if debugStderrBuffer.TotalWritten() > debugStderrBuffer.Size() {
stderrString = "<... some data truncated by circular buffer; go to artifacts for details ...>\n" + stderrString
}
if err != nil {
// Context errors opaquely appear as "signal killed" when manifested.
// We surface this error explicitly.
if ctx.Err() != nil {
err = errors.CombineErrors(ctx.Err(), err)
}
if err != nil {
err = &cluster.WithCommandDetails{
Wrapped: err,
Cmd: strings.Join(args, " "),
Stderr: stderrString,
Stdout: stdoutString,
}
}
}
return cmdRes{
err: err,
stdout: stdoutString,
stderr: stderrString,
}
}
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
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
}
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 makeGCEClusterName(name string) string {
name = strings.ToLower(name)
name = regexp.MustCompile(`[^-a-z0-9]+`).ReplaceAllString(name, "-")
name = regexp.MustCompile(`-+`).ReplaceAllString(name, "-")
return name
}
func makeClusterName(name string) string {
return makeGCEClusterName(name)
}
// MachineTypeToCPUs returns a CPU count for either a GCE or AWS
// machine type.
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, "n2-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-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 int he size and
// the sizing naming scheme is dependent on the machine type family.
switch s {
case "Standard_D2_v3":
return 2
case "Standard_D4_v3":
return 4
case "Standard_D8_v3":
return 8
case "Standard_D16_v3":
return 16
case "Standard_D32_v3":
return 32
case "Standard_D48_v3":
return 48
case "Standard_D64_v3":
return 64
}
// TODO(pbardea): Non-default Azure machine types are not supported
// and will return unknown machine type error.
fmt.Fprintf(os.Stderr, "unknown machine type: %s\n", s)
os.Exit(1)
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
spec spec.ClusterSpec
t test.Test
// 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 cluster startup.
clusterSettings map[string]string
os string // OS of the cluster
arch vm.CPUArch // CPU architecture of the cluster
// destroyState contains state related to the cluster's destruction.
destroyState destroyState
}
// 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
// alloc is set if owned is set. If set, it represents resources in a
// QuotaPool that need to be released when the cluster is destroyed.
alloc *quotapool.IntAlloc
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
alloc *quotapool.IntAlloc
// 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 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 := atomic.AddUint64(&f.counter, 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(flags *pflag.FlagSet, opts *vm.CreateOpts) {
if flags != nil {
if flags.Changed("lifetime") {
opts.Lifetime = overrideOpts.Lifetime
}
if flags.Changed("roachprod-local-ssd") {
opts.SSDOpts.UseLocalSSD = overrideOpts.SSDOpts.UseLocalSSD
}
if flags.Changed("filesystem") {
opts.SSDOpts.FileSystem = overrideOpts.SSDOpts.FileSystem
}
if flags.Changed("local-ssd-no-ext4-barrier") {
opts.SSDOpts.NoExt4Barrier = overrideOpts.SSDOpts.NoExt4Barrier
}
if flags.Changed("os-volume-size") {