-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathcluster.go
2406 lines (2180 loc) · 72.5 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/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/contextutil"
"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 (
// TODO(tbg): this is redundant with --cloud==local. Make the --local flag an
// alias for `--cloud=local` and remove this variable.
local bool
cockroach string
cockroachShort string
libraryFilePaths []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
instanceType string
localSSDArg bool
workload string
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
buildTag string
clusterName string
clusterWipe bool
zonesF string
teamCity bool
disableIssue bool
)
const (
defaultEncryptionProbability = 1
)
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 filepathAbs(path string) (string, error) {
path, err := filepath.Abs(path)
if err != nil {
return "", errors.WithStack(err)
}
return path, nil
}
func findBinary(binary, defValue string) (abspath string, err error) {
if binary == "" {
binary = defValue
}
// Check to see if binary exists and is a regular file and executable.
if fi, err := os.Stat(binary); err == nil && fi.Mode().IsRegular() && (fi.Mode()&0111) != 0 {
return filepathAbs(binary)
}
return findBinaryOrLibrary("bin", binary)
}
func findLibrary(libraryName string) (string, error) {
suffix := ".so"
if 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)
}
func findBinaryOrLibrary(binOrLib string, name string) (string, error) {
// Find the binary to run and translate it to an absolute path. First, look
// for the binary in PATH.
path, err := exec.LookPath(name)
if err != nil {
if strings.HasPrefix(name, "/") {
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")
}
var suffix string
if !local {
suffix = ".docker_amd64"
}
dirs := []string{
filepath.Join(gopath, "/src/github.com/cockroachdb/cockroach/"),
filepath.Join(gopath, "/src/github.com/cockroachdb/cockroach/artifacts/"),
filepath.Join(gopath, "/src/github.com/cockroachdb/cockroach", binOrLib+suffix),
filepath.Join(os.ExpandEnv("$PWD"), binOrLib+suffix),
filepath.Join(gopath, "/src/github.com/cockroachdb/cockroach", binOrLib),
}
for _, dir := range dirs {
path = filepath.Join(dir, name)
var err2 error
path, err2 = exec.LookPath(path)
if err2 == nil {
return filepathAbs(path)
}
}
return "", errBinaryOrLibraryNotFound{name}
}
return filepathAbs(path)
}
// VerifyLibraries verifies that the required libraries, specified by name, are
// available for the target environment.
func VerifyLibraries(requiredLibs []string) error {
for _, requiredLib := range requiredLibs {
if !contains(libraryFilePaths, libraryNameFromPath, requiredLib) {
return errors.Wrap(errors.Errorf("missing required library %s", requiredLib), "cluster.VerifyLibraries")
}
}
return nil
}
// libraryNameFromPath returns the name of a library without the extension, for a
// given path.
func libraryNameFromPath(path string) string {
filename := filepath.Base(path)
return strings.TrimSuffix(filename, filepath.Ext(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() {
// If we're running against an existing "local" cluster, force the local flag
// to true in order to get the "local" test configurations.
if clusterName == "local" {
local = true
}
if local {
cloud = spec.Local
}
cockroachDefault := "cockroach"
if !local {
cockroachDefault = "cockroach-linux-2.6.32-gnu-amd64"
}
var err error
cockroach, err = findBinary(cockroach, cockroachDefault)
if err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
if cockroachShort != "" {
// defValue doesn't matter since cockroachShort is a non-empty string.
cockroachShort, err = findBinary(cockroachShort, "" /* defValue */)
if err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
}
workload, err = findBinary(workload, "workload")
if errors.As(err, &errBinaryOrLibraryNotFound{}) {
fmt.Fprintln(os.Stderr, "workload binary not provided, proceeding anyway")
} else if err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
// 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 _, libraryName := range []string{"libgeos", "libgeos_c"} {
if libraryFilePath, err := findLibrary(libraryName); err != nil {
fmt.Fprintf(os.Stderr, "error finding library %s, ignoring: %+v\n", libraryName, err)
} else {
libraryFilePaths = append(libraryFilePaths, libraryFilePath)
}
}
}
// 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, "n1-standard-%d", &v); err == nil {
return v
}
if _, err := fmt.Sscanf(s, "n1-highcpu-%d", &v); err == nil {
return v
}
if _, err := fmt.Sscanf(s, "n1-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 "9xlarge":
return 36
case "12xlarge":
return 48
case "18xlarge":
return 72
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
// 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
}
// 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") {
opts.OsVolumeSize = overrideOpts.OsVolumeSize
}
if flags.Changed("geo") {
opts.GeoDistributed = overrideOpts.GeoDistributed
}
}
}
// 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,
}
}
// 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 overrideFlagset != nil && overrideFlagset.Changed("nodes") {
cfg.spec.NodeCount = 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()
// The ClusterName is set below in the retry loop to ensure
// that each create attempt gets a unique cluster name.
createVMOpts, providerOpts, err := cfg.spec.RoachprodOpts("", cfg.useIOBarrier)
if err != nil {
// We must release the allocation because cluster creation is not possible at this point.
cfg.alloc.Release()
return nil, nil, err
}
if cfg.spec.Cloud != spec.Local {
providerOptsContainer.SetProviderOpts(cfg.spec.Cloud, providerOpts)
}
createFlagsOverride(overrideFlagset, &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 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++ {
c := &clusterImpl{
// NB: this intentionally avoids re-using the name across iterations in
// the loop. See:
//
// https://github.com/cockroachdb/cockroach/issues/67906#issuecomment-887477675
name: f.genName(cfg),
spec: cfg.spec,
expiration: cfg.spec.Expiration(),
r: f.r,
destroyState: destroyState{
owned: true,
alloc: cfg.alloc,
},
}
c.status("creating cluster")
// 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", c.name+retryStr+".log")
l, err := logger.RootLogger(logPath, teeOpt)
if err != nil {
log.Fatalf(ctx, "%v", err)
}
l.PrintfCtx(ctx, "Attempting cluster creation (attempt #%d/%d)", i, maxAttempts)
createVMOpts.ClusterName = c.name
err = roachprod.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
}
l.PrintfCtx(ctx, "cluster creation failed, cleaning up in case it was partially created: %s", err)
// Set the alloc to nil so that Destroy won't release it.
// This is ugly, but given that the alloc is created very far away from this code
// (when selecting the test) it's the best we can do for now.
c.destroyState.alloc = nil
c.Destroy(ctx, closeLogger, l)
if i >= maxAttempts {
// Here we have to release the alloc, as we are giving up.
cfg.alloc.Release()
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,
l *logger.Logger,
spec spec.ClusterSpec,
opt attachOpt,
r *clusterRegistry,
) (*clusterImpl, error) {
exp := spec.Expiration()
if name == "local" {
exp = timeutil.Now().Add(100000 * time.Hour)
}
c := &clusterImpl{
name: name,
spec: spec,
l: l,
expiration: exp,
destroyState: destroyState{
// If we're attaching to an existing cluster, we're not going to destroy it.
owned: false,
},
r: r,
}