-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
cluster_synced.go
2725 lines (2473 loc) · 80.2 KB
/
cluster_synced.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 install
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/fs"
"math"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"syscall"
"text/template"
"time"
"github.com/cockroachdb/cockroach/pkg/cli/exit"
"github.com/cockroachdb/cockroach/pkg/roachprod/cloud"
"github.com/cockroachdb/cockroach/pkg/roachprod/config"
rperrors "github.com/cockroachdb/cockroach/pkg/roachprod/errors"
"github.com/cockroachdb/cockroach/pkg/roachprod/logger"
"github.com/cockroachdb/cockroach/pkg/roachprod/ssh"
"github.com/cockroachdb/cockroach/pkg/roachprod/ui"
"github.com/cockroachdb/cockroach/pkg/roachprod/vm"
"github.com/cockroachdb/cockroach/pkg/roachprod/vm/aws"
"github.com/cockroachdb/cockroach/pkg/roachprod/vm/local"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"golang.org/x/exp/maps"
"golang.org/x/sync/errgroup"
)
// A SyncedCluster is created from the cluster metadata in the synced clusters
// cache and is used as the target for installing and managing various software
// components.
type SyncedCluster struct {
// Cluster metadata, obtained from the respective cloud provider.
cloud.Cluster
// Nodes is used by most commands (e.g. Start, Stop, Monitor). It describes
// the list of nodes the operation pertains to.
Nodes Nodes
ClusterSettings
Localities []string
// AuthorizedKeys is used by SetupSSH to add additional authorized keys.
AuthorizedKeys []byte
}
// NewSyncedCluster creates a SyncedCluster, given the cluster metadata, node
// selector string, and settings.
//
// See ListNodes for a description of the node selector string.
func NewSyncedCluster(
metadata *cloud.Cluster, nodeSelector string, settings ClusterSettings,
) (*SyncedCluster, error) {
c := &SyncedCluster{
Cluster: *metadata,
ClusterSettings: settings,
}
c.Localities = make([]string, len(c.VMs))
for i := range c.VMs {
locality, err := c.VMs[i].Locality()
if err != nil {
return nil, err
}
if c.NumRacks > 0 {
if locality != "" {
locality += ","
}
locality += fmt.Sprintf("rack=%d", i%c.NumRacks)
}
c.Localities[i] = locality
}
nodes, err := ListNodes(nodeSelector, len(c.VMs))
if err != nil {
return nil, err
}
c.Nodes = nodes
return c, nil
}
// ErrAfterRetry marks an error that has occurred/persisted after retries
var ErrAfterRetry = errors.New("error occurred after retries")
// The first retry is after 5s, the second and final is after 25s
var defaultRetryOpt = retry.Options{
InitialBackoff: 5 * time.Second,
Multiplier: 5,
MaxBackoff: 1 * time.Minute,
// This will run a total of 3 times `runWithMaybeRetry`
MaxRetries: 2,
}
type RunRetryOpts struct {
retry.Options
shouldRetryFn func(*RunResultDetails) bool
}
func newRunRetryOpts(
retryOpts retry.Options, shouldRetryFn func(*RunResultDetails) bool,
) *RunRetryOpts {
return &RunRetryOpts{
Options: retryOpts,
shouldRetryFn: shouldRetryFn,
}
}
var DefaultSSHRetryOpts = newRunRetryOpts(defaultRetryOpt, func(res *RunResultDetails) bool { return errors.Is(res.Err, rperrors.ErrSSH255) })
// defaultSCPRetry won't retry if the error output contains any of the following
// substrings, in which cases retries are unlikely to help.
var noScpRetrySubstrings = []string{"no such file or directory", "permission denied", "connection timed out"}
var defaultSCPRetry = newRunRetryOpts(defaultRetryOpt,
func(res *RunResultDetails) bool {
out := strings.ToLower(res.Stderr)
for _, s := range noScpRetrySubstrings {
if strings.Contains(out, s) {
return false
}
}
return true
},
)
// runWithMaybeRetry will run the specified function `f` at least once, or only
// once if `runRetryOpts` is nil
// Any returned error from `f` is passed to `runRetryOpts.shouldRetryFn` which,
// if it returns true, will result in `f` being retried using the `retryOpts`
// If the `shouldRetryFn` is not specified (nil), then retries will be performed
// regardless of the previous result / error
//
// We operate on a pointer to RunResultDetails as it has already been
// captured in a *RunResultDetails[] in Run, but here we may enrich with attempt
// number and a wrapper error.
func runWithMaybeRetry(
ctx context.Context,
l *logger.Logger,
retryOpts *RunRetryOpts,
f func(ctx context.Context) (*RunResultDetails, error),
) (*RunResultDetails, error) {
if retryOpts == nil {
res, err := f(ctx)
res.Attempt = 1
return res, err
}
var res *RunResultDetails
var err error
var cmdErr error
for r := retry.StartWithCtx(ctx, retryOpts.Options); r.Next(); {
res, err = f(ctx)
res.Attempt = r.CurrentAttempt() + 1
// nil err (non-nil denotes a roachprod error) indicates a potentially retryable res.Err
if err == nil && res.Err != nil {
cmdErr = errors.CombineErrors(cmdErr, res.Err)
if retryOpts.shouldRetryFn == nil || retryOpts.shouldRetryFn(res) {
l.Printf("encountered [%v] on attempt %v of %v", res.Err, r.CurrentAttempt()+1, retryOpts.MaxRetries+1)
continue
}
}
break
}
if res.Attempt > 1 {
if res.Err != nil {
// An error cannot be marked with more than one reference error. Since res.Err may already be marked, we create
// a new error here and mark it.
res.Err = errors.Mark(errors.Wrapf(cmdErr, "error persisted after %v attempts", res.Attempt), ErrAfterRetry)
} else {
l.Printf("command successful after %v attempts", res.Attempt)
}
}
return res, err
}
func scpWithRetry(
ctx context.Context, l *logger.Logger, src, dest string,
) (*RunResultDetails, error) {
return runWithMaybeRetry(ctx, l, defaultSCPRetry, func(ctx context.Context) (*RunResultDetails, error) { return scp(l, src, dest) })
}
// Host returns the public IP of a node.
func (c *SyncedCluster) Host(n Node) string {
return c.VMs[n-1].PublicIP
}
func (c *SyncedCluster) user(n Node) string {
return c.VMs[n-1].RemoteUser
}
func (c *SyncedCluster) locality(n Node) string {
return c.Localities[n-1]
}
// IsLocal returns true if this is a local cluster (see vm/local).
func (c *SyncedCluster) IsLocal() bool {
return config.IsLocalClusterName(c.Name)
}
func (c *SyncedCluster) localVMDir(n Node) string {
return local.VMDir(c.Name, int(n))
}
// TargetNodes is the fully expanded, ordered list of nodes that any given
// roachprod command is intending to target.
//
// $ roachprod create local -n 4
// $ roachprod start local # [1, 2, 3, 4]
// $ roachprod start local:2-4 # [2, 3, 4]
// $ roachprod start local:2,1,4 # [1, 2, 4]
func (c *SyncedCluster) TargetNodes() Nodes {
return append(Nodes{}, c.Nodes...)
}
// GetInternalIP returns the internal IP address of the specified node.
func (c *SyncedCluster) GetInternalIP(n Node) (string, error) {
if c.IsLocal() {
return c.Host(n), nil
}
ip := c.VMs[n-1].PrivateIP
if ip == "" {
return "", errors.Errorf("no private IP for node %d", n)
}
return ip, nil
}
// roachprodEnvValue returns the value of the ROACHPROD environment variable
// that is set when starting a process. This value is used to recognize the
// correct process, when monitoring or stopping.
//
// Normally, the value is of the form:
//
// [<local-cluster-name>/]<node-id>[/tag]
//
// Examples:
//
// - non-local cluster without tags:
// ROACHPROD=1
//
// - non-local cluster with tag foo:
// ROACHPROD=1/foo
//
// - non-local cluster with hierarchical tag foo/bar:
// ROACHPROD=1/foo/bar
//
// - local cluster:
// ROACHPROD=local-foo/1
//
// - local cluster with tag bar:
// ROACHPROD=local-foo/1/bar
func (c *SyncedCluster) roachprodEnvValue(node Node) string {
var parts []string
if c.IsLocal() {
parts = append(parts, c.Name)
}
parts = append(parts, fmt.Sprintf("%d", node))
if c.Tag != "" {
parts = append(parts, c.Tag)
}
return strings.Join(parts, "/")
}
// roachprodEnvRegex returns a regexp that matches the ROACHPROD value for the
// given node.
func (c *SyncedCluster) roachprodEnvRegex(node Node) string {
escaped := strings.Replace(c.roachprodEnvValue(node), "/", "\\/", -1)
// We look for either a trailing space or a slash (in which case, we tolerate
// any remaining tag suffix). ROACHPROD may also be the last environment
// variable declared, so we also account for that.
return fmt.Sprintf(`(ROACHPROD=%[1]s$|ROACHPROD=%[1]s[ \/])`, escaped)
}
// validateHostnameCmd wraps the command given with a check that the
// remote node is still part of the `SyncedCluster`. When `cmd` is
// empty, the command returned can be used to validate whether the
// host matches the name expected by roachprod, and can be used to
// validate the contents of the cache for that cluster.
//
// Since `SyncedCluster` is created from a potentially stale cache, it
// is possible for the following events to happen:
//
// Client 1:
// - cluster A is created and information is persisted in roachprod's cache.
// - cluster's A lifetime expires, VMs are destroyed.
//
// Client 2
// - cluster B is created; public IP of one of the VMs of cluster
// A is reused and assigned to one of cluster B's VMs.
//
// Client 1:
// - command with side-effects is run on cluster A (e.g.,
// `roachprod stop`). Public IP now belongs to a VM in cluster
// B. Client unknowingly disturbs cluster B, thinking it's cluster A.
//
// Client 2:
// - notices that cluster B is behaving strangely (e.g., cockroach
// process died). A lot of time is spent trying to debug the
// issue.
//
// This scenario is possible and has happened a number of times in the
// past (for one such occurrence, see #97100). A particularly
// problematic instance of this bug happens when "cluster B" is
// running a roachtest. This interaction leads to issues that are hard
// to debug or make sense of, which ultimately wastes a lot of
// engineering time.
//
// By wrapping every command with a hostname check as is done here, we
// ensure that the cached cluster information is still correct.
func (c *SyncedCluster) validateHostnameCmd(cmd string, node Node) string {
// TODO(renato): remove this logic once we no longer have AWS clusters
// created with the default hostnames.
var awsNote string
nodeVM := c.VMs[node-1]
if nodeVM.Provider == aws.ProviderName {
awsNote = fmt.Sprintf(
"\nNOTE: host validation failed in AWS cluster. If you are sure this cluster still "+
"exists (i.e., you can see it when you run 'roachprod list'), then please run:\n\t"+
"roachprod fix-long-running-aws-hostnames %s",
c.Name,
)
}
isValidHost := fmt.Sprintf("[[ `hostname` == '%s' ]]", vm.Name(c.Name, int(node)))
errMsg := fmt.Sprintf("expected host to be part of %s, but is `hostname`", c.Name)
elseBranch := "fi"
if cmd != "" {
elseBranch = fmt.Sprintf(`
else
%s
fi
`, cmd)
}
return fmt.Sprintf(`
if ! %s; then
echo "%s%s"
exit 1
%s
`, isValidHost, errMsg, awsNote, elseBranch)
}
// validateHost will run `validateHostnameCmd` on the node passed to
// make sure it still belongs to the SyncedCluster. Returns an error
// when the hostnames don't match, indicating that the roachprod cache
// is stale.
func (c *SyncedCluster) validateHost(ctx context.Context, l *logger.Logger, node Node) error {
if c.IsLocal() {
return nil
}
cmd := c.validateHostnameCmd("", node)
return c.Run(ctx, l, l.Stdout, l.Stderr, Nodes{node}, "validate-ssh-host", cmd)
}
// cmdDebugName is the suffix of the generated ssh debug file
// If it is "", a suffix will be generated from the cmd string
func (c *SyncedCluster) newSession(
l *logger.Logger, node Node, cmd string, options ...remoteSessionOption,
) session {
if c.IsLocal() {
return newLocalSession(cmd)
}
command := &remoteCommand{
node: node,
user: c.user(node),
host: c.Host(node),
cmd: cmd,
}
for _, opt := range options {
opt(command)
}
if !command.hostValidationDisabled {
command.cmd = c.validateHostnameCmd(cmd, node)
}
return newRemoteSession(l, command)
}
// Stop is used to stop cockroach on all nodes in the cluster.
//
// It sends a signal to all processes that have been started with ROACHPROD env
// var and optionally waits until the processes stop.
//
// When running roachprod stop without other flags, the signal is 9 (SIGKILL)
// and wait is true.
//
// If maxWait is non-zero, Stop stops waiting after that approximate
// number of seconds.
func (c *SyncedCluster) Stop(
ctx context.Context, l *logger.Logger, sig int, wait bool, maxWait int,
) error {
display := fmt.Sprintf("%s: stopping", c.Name)
if wait {
display += " and waiting"
}
return c.kill(ctx, l, "stop", display, sig, wait, maxWait)
}
// Signal sends a signal to the CockroachDB process.
func (c *SyncedCluster) Signal(ctx context.Context, l *logger.Logger, sig int) error {
display := fmt.Sprintf("%s: sending signal %d", c.Name, sig)
return c.kill(ctx, l, "signal", display, sig, false /* wait */, 0 /* maxWait */)
}
// kill sends the signal sig to all nodes in the cluster using the kill command.
// cmdName and display specify the roachprod subcommand and a status message,
// for output/logging. If wait is true, the command will wait for the processes
// to exit, up to maxWait seconds.
func (c *SyncedCluster) kill(
ctx context.Context, l *logger.Logger, cmdName, display string, sig int, wait bool, maxWait int,
) error {
if sig == 9 {
// `kill -9` without wait is never what a caller wants. See #77334.
wait = true
}
return c.Parallel(ctx, l, len(c.Nodes), func(ctx context.Context, i int) (*RunResultDetails, error) {
node := c.Nodes[i]
var waitCmd string
if wait {
waitCmd = fmt.Sprintf(`
for pid in ${pids}; do
echo "${pid}: checking" >> %[1]s/roachprod.log
waitcnt=0
while kill -0 ${pid}; do
if [ %[2]d -gt 0 -a $waitcnt -gt %[2]d ]; then
echo "${pid}: max %[2]d attempts reached, aborting wait" >>%[1]s/roachprod.log
break
fi
kill -0 ${pid} >> %[1]s/roachprod.log 2>&1
echo "${pid}: still alive [$?]" >> %[1]s/roachprod.log
ps axeww -o pid -o command >> %[1]s/roachprod.log
sleep 1
waitcnt=$(expr $waitcnt + 1)
done
echo "${pid}: dead" >> %[1]s/roachprod.log
done`,
c.LogDir(node), // [1]
maxWait, // [2]
)
}
// NB: the awkward-looking `awk` invocation serves to avoid having the
// awk process match its own output from `ps`.
cmd := fmt.Sprintf(`
mkdir -p %[1]s
echo ">>> roachprod %[1]s: $(date)" >> %[2]s/roachprod.log
ps axeww -o pid -o command >> %[2]s/roachprod.log
pids=$(ps axeww -o pid -o command | \
sed 's/export ROACHPROD=//g' | \
awk '/%[3]s/ { print $1 }')
if [ -n "${pids}" ]; then
kill -%[4]d ${pids}
%[5]s
fi`,
cmdName, // [1]
c.LogDir(node), // [2]
c.roachprodEnvRegex(node), // [3]
sig, // [4]
waitCmd, // [5]
)
sess := c.newSession(l, node, cmd, withDebugName("node-"+cmdName))
defer sess.Close()
out, cmdErr := sess.CombinedOutput(ctx)
res := newRunResultDetails(node, cmdErr)
res.CombinedOut = out
return res, res.Err
}, WithDisplay(display), WithRetryOpts(nil)) // Disable SSH Retries
}
// Wipe TODO(peter): document
func (c *SyncedCluster) Wipe(ctx context.Context, l *logger.Logger, preserveCerts bool) error {
display := fmt.Sprintf("%s: wiping", c.Name)
if err := c.Stop(ctx, l, 9, true /* wait */, 0 /* maxWait */); err != nil {
return err
}
return c.Parallel(ctx, l, len(c.Nodes), func(ctx context.Context, i int) (*RunResultDetails, error) {
node := c.Nodes[i]
var cmd string
if c.IsLocal() {
// Not all shells like brace expansion, so we'll do it here
dirs := []string{"data", "logs"}
if !preserveCerts {
dirs = append(dirs, "certs*")
dirs = append(dirs, "tenant-certs*")
}
for _, dir := range dirs {
cmd += fmt.Sprintf(`rm -fr %s/%s ;`, c.localVMDir(c.Nodes[i]), dir)
}
} else {
cmd = `sudo find /mnt/data* -maxdepth 1 -type f -exec rm -f {} \; &&
sudo rm -fr /mnt/data*/{auxiliary,local,tmp,cassandra,cockroach,cockroach-temp*,mongo-data} &&
sudo rm -fr logs &&
`
if !preserveCerts {
cmd += "sudo rm -fr certs* ;\n"
cmd += "sudo rm -fr tenant-certs* ;\n"
}
}
sess := c.newSession(l, node, cmd, withDebugName("node-wipe"))
defer sess.Close()
out, cmdErr := sess.CombinedOutput(ctx)
res := newRunResultDetails(node, cmdErr)
res.CombinedOut = out
return res, res.Err
}, WithDisplay(display))
}
// NodeStatus contains details about the status of a node.
type NodeStatus struct {
NodeID int
Running bool
Version string
Pid string
Err error
}
// Status TODO(peter): document
func (c *SyncedCluster) Status(ctx context.Context, l *logger.Logger) ([]NodeStatus, error) {
display := fmt.Sprintf("%s: status", c.Name)
results := make([]NodeStatus, len(c.Nodes))
if err := c.Parallel(ctx, l, len(c.Nodes), func(ctx context.Context, i int) (*RunResultDetails, error) {
node := c.Nodes[i]
binary := cockroachNodeBinary(c, node)
cmd := fmt.Sprintf(`out=$(ps axeww -o pid -o ucomm -o command | \
sed 's/export ROACHPROD=//g' | \
awk '/%s/ {print $2, $1}'`,
c.roachprodEnvRegex(node))
cmd += ` | sort | uniq);
vers=$(` + binary + ` version 2>/dev/null | awk '/Build Tag:/ {print $NF}')
if [ -n "${out}" -a -n "${vers}" ]; then
echo ${out} | sed "s/cockroach/cockroach-${vers}/g"
elif [ -n "${vers}" ]; then
echo "not-running cockroach-${vers}"
else
echo ${out}
fi
`
sess := c.newSession(l, node, cmd, withDebugName("node-status"))
defer sess.Close()
out, cmdErr := sess.CombinedOutput(ctx)
res := newRunResultDetails(node, cmdErr)
res.CombinedOut = out
if res.Err != nil {
return res, errors.Wrapf(res.Err, "~ %s\n%s", cmd, res.CombinedOut)
}
msg := strings.TrimSpace(string(res.CombinedOut))
if msg == "" || strings.HasPrefix(msg, "not-running") {
results[i] = NodeStatus{Running: false}
if msg != "" {
info := strings.Split(msg, " ")
results[i].Version = info[1]
}
return res, nil
}
info := strings.Split(msg, " ")
results[i] = NodeStatus{Running: true, Version: info[0], Pid: info[1]}
return res, nil
}, WithDisplay(display)); err != nil {
return nil, err
}
for i := 0; i < len(results); i++ {
results[i].NodeID = int(c.Nodes[i])
}
return results, nil
}
// NodeMonitorInfo is a message describing a cockroach process' status.
type NodeMonitorInfo struct {
// The index of the node (in a SyncedCluster) at which the message originated.
Node Node
// A message about the node. This is either a PID, "dead", "nc exited", or
// "skipped".
// Anything but a PID or "skipped" is an indication that there is some
// problem with the node and that the process is not running.
Msg string
// Err is an error that may occur when trying to probe the status of the node.
// If Err is non-nil, Msg is empty. After an error is returned, the node with
// the given index will no longer be probed. Errors typically indicate networking
// issues or nodes that have (physically) shut down.
Err error
}
// MonitorOpts is used to pass the options needed by Monitor.
type MonitorOpts struct {
OneShot bool // Report the status of all targeted nodes once, then exit.
IgnoreEmptyNodes bool // Only monitor nodes with a nontrivial data directory.
}
// Monitor writes NodeMonitorInfo for the cluster nodes to the returned channel.
// Infos sent to the channel always have the Index and exactly one of Msg or Err
// set.
//
// If oneShot is true, infos are retrieved only once for each node and the
// channel is subsequently closed; otherwise the process continues indefinitely
// (emitting new information as the status of the cockroach process changes).
//
// If ignoreEmptyNodes is true, nodes on which no CockroachDB data is found
// (in {store-dir}) will not be probed and single message, "skipped", will
// be emitted for them.
func (c *SyncedCluster) Monitor(
l *logger.Logger, ctx context.Context, opts MonitorOpts,
) chan NodeMonitorInfo {
ch := make(chan NodeMonitorInfo)
nodes := c.TargetNodes()
var wg sync.WaitGroup
for i := range nodes {
wg.Add(1)
go func(i int) {
defer wg.Done()
node := nodes[i]
// On each monitored node, we loop looking for a cockroach process.
data := struct {
OneShot bool
IgnoreEmpty bool
Store string
Port int
Local bool
}{
OneShot: opts.OneShot,
IgnoreEmpty: opts.IgnoreEmptyNodes,
Store: c.NodeDir(node, 1 /* storeIndex */),
Port: c.NodePort(node),
Local: c.IsLocal(),
}
snippet := `
{{ if .IgnoreEmpty }}
if ! ls {{.Store}}/marker.* 1> /dev/null 2>&1; then
echo "skipped"
exit 0
fi
{{- end}}
# Init with -1 so that when cockroach is initially dead, we print
# a dead event for it.
lastpid=-1
while :; do
{{ if .Local }}
pid=$(lsof -i :{{.Port}} -sTCP:LISTEN | awk '!/COMMAND/ {print $2}')
pid=${pid:-0} # default to 0
status="unknown"
{{- else }}
# When CRDB is not running, this is zero.
pid=$(systemctl show cockroach --property MainPID --value)
status=$(systemctl show cockroach --property ExecMainStatus --value)
{{- end }}
if [[ "${lastpid}" == -1 && "${pid}" != 0 ]]; then
# On the first iteration through the loop, if the process is running,
# don't register a PID change (which would trigger an erroneous dead
# event).
lastpid=0
fi
# Output a dead event whenever the PID changes from a nonzero value to
# any other value. In particular, we emit a dead event when the node stops
# (lastpid is nonzero, pid is zero), but not when the process then starts
# again (lastpid is zero, pid is nonzero).
if [ "${pid}" != "${lastpid}" ]; then
if [ "${lastpid}" != 0 ]; then
if [ "${pid}" != 0 ]; then
# If the PID changed but neither is zero, then the status refers to
# the new incarnation. We lost the actual exit status of the old PID.
status="unknown"
fi
echo "dead (exit status ${status})"
fi
if [ "${pid}" != 0 ]; then
echo "${pid}"
fi
lastpid=${pid}
fi
{{ if .OneShot }}
exit 0
{{- end }}
sleep 1
if [ "${pid}" != 0 ]; then
while kill -0 "${pid}"; do
sleep 1
done
fi
done
`
t := template.Must(template.New("script").Parse(snippet))
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
ch <- NodeMonitorInfo{Node: node, Err: err}
return
}
sess := c.newSession(l, node, buf.String(), withDebugDisabled())
defer sess.Close()
p, err := sess.StdoutPipe()
if err != nil {
ch <- NodeMonitorInfo{Node: node, Err: err}
wg.Done()
return
}
// Request a PTY so that the script will receive a SIGPIPE when the
// session is closed.
if err := sess.RequestPty(); err != nil {
ch <- NodeMonitorInfo{Node: node, Err: err}
return
}
var readerWg sync.WaitGroup
readerWg.Add(1)
go func(p io.Reader) {
defer readerWg.Done()
r := bufio.NewReader(p)
for {
line, _, err := r.ReadLine()
if err == io.EOF {
return
}
ch <- NodeMonitorInfo{Node: node, Msg: string(line)}
}
}(p)
if err := sess.Start(); err != nil {
ch <- NodeMonitorInfo{Node: node, Err: err}
return
}
// Watch for context cancellation.
go func() {
<-ctx.Done()
sess.Close()
}()
readerWg.Wait()
// We must call `sess.Wait()` only after finishing reading from the stdout
// pipe. Otherwise it can be closed under us, causing the reader to loop
// infinitely receiving a non-`io.EOF` error.
if err := sess.Wait(); err != nil {
ch <- NodeMonitorInfo{Node: node, Err: err}
return
}
}(i)
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}
// RunResultDetails holds details of the result of commands executed by Run().
type RunResultDetails struct {
Node Node
Stdout string
Stderr string
CombinedOut []byte
Err error
RemoteExitStatus int
Attempt int
}
func newRunResultDetails(node Node, err error) *RunResultDetails {
res := RunResultDetails{
Node: node,
Err: err,
}
if exitCode, success := rperrors.GetExitCode(err); success {
res.RemoteExitStatus = exitCode
}
return &res
}
func (c *SyncedCluster) runCmdOnSingleNode(
ctx context.Context,
l *logger.Logger,
node Node,
cmd string,
combined bool,
stdout, stderr io.Writer,
) (*RunResultDetails, error) {
// Argument template expansion is node specific (e.g. for {store-dir}).
e := expander{
node: node,
}
expandedCmd, err := e.expand(ctx, l, c, cmd)
if err != nil {
return newRunResultDetails(node, err), err
}
// Be careful about changing these command strings. In particular, we need
// to support running commands in the background on both local and remote
// nodes. For example:
//
// roachprod run cluster -- "sleep 60 &> /dev/null < /dev/null &"
//
// That command should return immediately. And a "roachprod status" should
// reveal that the sleep command is running on the cluster.
envVars := append([]string{
fmt.Sprintf("ROACHPROD=%s", c.roachprodEnvValue(node)), "GOTRACEBACK=crash",
}, config.DefaultEnvVars()...)
nodeCmd := fmt.Sprintf(`export %s && bash -c %s`,
strings.Join(envVars, " "), ssh.Escape1(expandedCmd))
if c.IsLocal() {
nodeCmd = fmt.Sprintf("cd %s; %s", c.localVMDir(node), nodeCmd)
}
sess := c.newSession(l, node, nodeCmd, withDebugName(GenFilenameFromArgs(20, expandedCmd)))
defer sess.Close()
var res *RunResultDetails
if combined {
out, cmdErr := sess.CombinedOutput(ctx)
res = newRunResultDetails(node, cmdErr)
res.CombinedOut = out
} else {
// We stream the output if running on a single node.
var stdoutBuffer, stderrBuffer bytes.Buffer
multStdout := io.MultiWriter(&stdoutBuffer, stdout)
multStderr := io.MultiWriter(&stderrBuffer, stderr)
sess.SetStdout(multStdout)
sess.SetStderr(multStderr)
res = newRunResultDetails(node, sess.Run(ctx))
res.Stderr = stderrBuffer.String()
res.Stdout = stdoutBuffer.String()
}
if res.Err != nil {
detailMsg := fmt.Sprintf("Node %d. Command with error:\n```\n%s\n```\n", node, cmd)
res.Err = errors.WithDetail(res.Err, detailMsg)
}
return res, nil
}
// Run a command on >= 1 node in the cluster.
//
// When running on just one node, the command output is streamed to stdout.
// When running on multiple nodes, the commands run in parallel, their output
// is cached and then emitted all together once all commands are completed.
//
// stdout: Where stdout messages are written
// stderr: Where stderr messages are written
// nodes: The cluster nodes where the command will be run.
// title: A description of the command being run that is output to the logs.
// cmd: The command to run.
func (c *SyncedCluster) Run(
ctx context.Context,
l *logger.Logger,
stdout, stderr io.Writer,
nodes Nodes,
title, cmd string,
opts ...ParallelOption,
) error {
// Stream output if we're running the command on only 1 node.
stream := len(nodes) == 1
var display string
if !stream {
display = fmt.Sprintf("%s: %s", c.Name, title)
}
results := make([]*RunResultDetails, len(nodes))
// A result is the output of running a command (could be interpreted as an error)
if _, err := c.ParallelE(ctx, l, len(nodes), func(ctx context.Context, i int) (*RunResultDetails, error) {
// An err returned here is an unexpected state within roachprod (non-command error).
// For errors that occur as part of running a command over ssh, the `result` will contain
// the actual error on a specific node.
result, err := c.runCmdOnSingleNode(ctx, l, nodes[i], cmd, !stream, stdout, stderr)
results[i] = result
return result, err
}, append(opts, WithDisplay(display))...); err != nil {
return err
}
return processResults(results, stream, stdout)
}
// processResults returns the error from the RunResultDetails with the highest RemoteExitStatus
func processResults(results []*RunResultDetails, stream bool, stdout io.Writer) error {
var resultWithError *RunResultDetails
for i, r := range results {
// We no longer wait for all nodes to complete before returning in the case of an error (#100403)
// which means that some node results may be nil.
if r == nil {
continue
}
if !stream {
fmt.Fprintf(stdout, " %2d: %s\n%v\n", i+1, strings.TrimSpace(string(r.CombinedOut)), r.Err)
}
if r.Err != nil {
if resultWithError == nil {
resultWithError = r
continue
}
if r.RemoteExitStatus > resultWithError.RemoteExitStatus {
resultWithError = r
}
}
}
if resultWithError != nil {
return resultWithError.Err
}
return nil
}
// RunWithDetails runs a command on the specified nodes and returns results details and an error.
// This will wait for all commands to complete before returning unless encountering a roachprod error.
func (c *SyncedCluster) RunWithDetails(
ctx context.Context, l *logger.Logger, nodes Nodes, title, cmd string,
) ([]RunResultDetails, error) {
display := fmt.Sprintf("%s: %s", c.Name, title)
// We use pointers here as we are capturing the state of a result even though it may
// be processed further by the caller.
resultPtrs := make([]*RunResultDetails, len(nodes))
// Failing slow here allows us to capture the output of all nodes even if one fails with a command error.
if _, err := c.ParallelE(ctx, l, len(nodes), func(ctx context.Context, i int) (*RunResultDetails, error) { //nolint:errcheck
result, err := c.runCmdOnSingleNode(ctx, l, nodes[i], cmd, false, l.Stdout, l.Stderr)
resultPtrs[i] = result
return result, err
}, WithDisplay(display), WithWaitOnFail()); err != nil {
return nil, err
}
// Return values to preserve API
results := make([]RunResultDetails, len(nodes))
for i, v := range resultPtrs {
if v != nil {
results[i] = *v
}
}
return results, nil
}
var roachprodRetryOptions = retry.Options{
InitialBackoff: 10 * time.Second,
Multiplier: 2,
MaxBackoff: 5 * time.Minute,
MaxRetries: 10,
}
// RepeatRun is the same function as c.Run, but with an automatic retry loop.
func (c *SyncedCluster) RepeatRun(
ctx context.Context, l *logger.Logger, stdout, stderr io.Writer, nodes Nodes, title,
cmd string,
) error {
var lastError error
for attempt, r := 0, retry.StartWithCtx(ctx, roachprodRetryOptions); r.Next(); {
if ctx.Err() != nil {
return ctx.Err()
}
attempt++
l.Printf("attempt %d - %s", attempt, title)
lastError = c.Run(ctx, l, stdout, stderr, nodes, title, cmd)
if lastError != nil {
l.Printf("error - retrying: %s", lastError)
continue
}
return nil
}
return errors.Wrapf(lastError, "all attempts failed for %s", title)
}