-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
cluster_synced.go
3045 lines (2768 loc) · 93.5 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 CockroachDB Software License
// included in the /LICENSE file.
package install
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/fs"
"math"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"text/template"
"time"
"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"
"golang.org/x/sys/unix"
)
// scpTimeout is the timeout enforced on every `scp` command performed
// by roachprod. The default of 10 minutes should be more than
// sufficient for roachtests and common roachprod operations.
//
// Callers can customize the timeout using the ROACHPROD_SCP_TIMEOUT
// environment variable.
var scpTimeout = func() time.Duration {
var defaultTimeout = 10 * time.Minute
if durStr := os.Getenv("ROACHPROD_SCP_TIMEOUT"); durStr != "" {
dur, err := time.ParseDuration(durStr)
if err != nil {
panic(fmt.Errorf("invalid scp timeout %q: %w", durStr, err))
}
return dur
}
return defaultTimeout
}()
// 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,
}
var DefaultShouldRetryFn = func(res *RunResultDetails) bool { return rperrors.IsTransient(res.Err) }
// 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 defaultSCPShouldRetryFn = func(res *RunResultDetails) bool {
out := strings.ToLower(res.Output(false))
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 `retryOpts` is nil
//
// Any RunResultDetails containing a non nil err from `f` is passed to `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.
//
// If a non-nil error (as opposed to the result containing a non-nil error) is returned,
// the function will *not* be retried.
//
// 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 *retry.Options,
shouldRetryFn func(*RunResultDetails) bool,
f func(ctx context.Context) (*RunResultDetails, error),
) (*RunResultDetails, error) {
if retryOpts == nil {
res, err := f(ctx)
if err != nil {
return nil, err
}
res.Attempt = 1
return res, nil
}
var res = &RunResultDetails{}
var cmdErr, err error
for r := retry.StartWithCtx(ctx, *retryOpts); r.Next(); {
res, err = f(ctx)
if err != nil {
// non retryable roachprod error
return nil, err
}
res.Attempt = r.CurrentAttempt() + 1
if res.Err != nil {
cmdErr = errors.CombineErrors(cmdErr, res.Err)
if shouldRetryFn == nil || 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, nil
}
func scpWithRetry(
ctx context.Context, l *logger.Logger, src, dest string,
) (*RunResultDetails, error) {
scpCtx, cancel := context.WithTimeout(ctx, scpTimeout)
defer cancel()
return runWithMaybeRetry(scpCtx, l, DefaultRetryOpt, defaultSCPShouldRetryFn,
func(ctx context.Context) (*RunResultDetails, error) { return scp(ctx, 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, "/")
}
func envVarRegex(name, value string) string {
escaped := strings.ReplaceAll(value, "/", "\\/")
// We look for either a trailing space or a slash (in which case, we
// tolerate any remaining tag suffix). The env var may also be the
// last environment variable declared, so we also account for that.
return fmt.Sprintf(`(%[1]s=%[2]s$|%[1]s=%[2]s[ \/])`, name, escaped)
}
// roachprodEnvRegex returns a regexp that matches the ROACHPROD value for the
// given node.
func (c *SyncedCluster) roachprodEnvRegex(node Node) string {
return envVarRegex("ROACHPROD", c.roachprodEnvValue(node))
}
// 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 {
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"
exit 1
%s
`, isValidHost, errMsg, 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, WithNodes(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: c.validateHostnameCmd(cmd, node),
}
for _, opt := range options {
opt(command)
}
return newRemoteSession(l, command)
}
// Stop is used to stop processes or virtual clusters.
//
// It sends a signal to all processes that have been started with
// ROACHPROD env var and optionally waits until the processes stop. If
// the virtualClusterLabel is not empty, then only the corresponding
// virtual cluster is stopped (stopping the corresponding sql server
// process for separate process deployments, or stopping the service
// for shared-process configurations.)
//
// When Stop needs to kill a process without other flags, the signal
// is 9 (SIGKILL) and wait is true. If gracePeriod is non-zero, Stop
// stops waiting after that approximate number of seconds, sending a
// SIGKILL if the process is still running after that time.
func (c *SyncedCluster) Stop(
ctx context.Context,
l *logger.Logger,
sig int,
wait bool,
gracePeriod int,
virtualClusterLabel string,
) error {
// virtualClusterDisplay includes information about the virtual
// cluster associated with OS processes being stopped in this
// function.
var virtualClusterDisplay string
// virtualClusterName is the virtualClusterName associated with the
// label passed, if any.
var virtualClusterName string
// killProcesses indicates whether processed need to be stopped.
killProcesses := true
if virtualClusterLabel != "" {
name, sqlInstance, err := VirtualClusterInfoFromLabel(virtualClusterLabel)
if err != nil {
return err
}
services, err := c.DiscoverServices(ctx, name, ServiceTypeSQL)
if err != nil {
return err
}
if len(services) == 0 {
return fmt.Errorf("no service for virtual cluster %q", virtualClusterName)
}
virtualClusterName = name
if services[0].ServiceMode == ServiceModeShared {
// For shared process virtual clusters, we just stop the service
// via SQL.
killProcesses = false
} else {
virtualClusterDisplay = fmt.Sprintf(" virtual cluster %q, instance %d", virtualClusterName, sqlInstance)
}
}
if killProcesses {
display := fmt.Sprintf("%s: stopping%s", c.Name, virtualClusterDisplay)
if wait {
display += " and waiting"
}
return c.kill(ctx, l, "stop", display, sig, wait, gracePeriod, virtualClusterLabel)
} else {
cmd := fmt.Sprintf("ALTER TENANT '%s' STOP SERVICE", virtualClusterName)
res, err := c.ExecSQL(ctx, l, c.Nodes[:1], "", 0, DefaultAuthMode(), "", /* database */
[]string{"-e", cmd})
if err != nil || res[0].Err != nil {
if len(res) > 0 {
return errors.CombineErrors(err, res[0].Err)
}
return err
}
}
return nil
}
// 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 /* gracePeriod */, "")
}
// 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 gracePeriod seconds.
func (c *SyncedCluster) kill(
ctx context.Context,
l *logger.Logger,
cmdName, display string,
sig int,
wait bool,
gracePeriod int,
virtualClusterLabel string,
) error {
const timedOutMessage = "timed out"
if sig == int(unix.SIGKILL) {
// `kill -9` without wait is never what a caller wants. See #77334.
wait = true
}
return c.Parallel(ctx, l, WithNodes(c.Nodes).WithDisplay(display).WithRetryDisabled(),
func(ctx context.Context, node Node) (*RunResultDetails, error) {
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
echo "%[3]s"
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, "", 0), // [1]
gracePeriod, // [2]
timedOutMessage, // [3]
)
}
var virtualClusterFilter string
if virtualClusterLabel != "" {
virtualClusterFilter = fmt.Sprintf(
"grep -E '%s' |",
envVarRegex("ROACHPROD_VIRTUAL_CLUSTER", virtualClusterLabel),
)
}
// 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
mkdir -p %[2]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 | \
%[3]s \
sed 's/export ROACHPROD=//g' | \
awk '/%[4]s/ { print $1 }')
if [ -n "${pids}" ]; then
kill -%[5]d ${pids}
%[6]s
fi`,
cmdName, // [1]
c.LogDir(node, "", 0), // [2]
virtualClusterFilter, // [3]
c.roachprodEnvRegex(node), // [4]
sig, // [5]
waitCmd, // [6]
)
res, err := c.runCmdOnSingleNode(ctx, l, node, cmd, defaultCmdOpts("kill"))
if err != nil {
return res, err
}
// If the process has not terminated after the grace period,
// perform a forceful termination.
if wait && sig != int(unix.SIGKILL) && strings.Contains(res.CombinedOut, timedOutMessage) {
l.Printf("n%d did not shutdown after %ds, performing a SIGKILL", node, gracePeriod)
return res, errors.Wrapf(
c.kill(ctx, l, cmdName, display, int(unix.SIGKILL), true, 0, virtualClusterLabel),
"failed to forcefully terminate n%d", node,
)
}
return res, nil
})
}
// 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, int(unix.SIGKILL), true /* wait */, 0 /* gracePeriod */, ""); err != nil {
return err
}
return c.Parallel(ctx, l, WithNodes(c.Nodes).WithDisplay(display), func(ctx context.Context, node Node) (*RunResultDetails, error) {
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, fmt.Sprintf("%s*", CockroachNodeCertsDir))
dirs = append(dirs, fmt.Sprintf("%s*", CockroachNodeTenantCertsDir))
}
for _, dir := range dirs {
cmd += fmt.Sprintf(`rm -fr %s/%s ;`, c.localVMDir(node), dir)
}
} else {
rmCmds := []string{
fmt.Sprintf(`sudo find /mnt/data* -maxdepth 1 -type f -not -name %s -exec rm -f {} \;`, vm.InitializedFile),
`sudo rm -fr /mnt/data*/{auxiliary,local,tmp,cassandra,cockroach,cockroach-temp*,mongo-data}`,
`sudo rm -fr logs* data*`,
}
if !preserveCerts {
rmCmds = append(rmCmds,
fmt.Sprintf("sudo rm -fr %s*", CockroachNodeCertsDir),
fmt.Sprintf("sudo rm -fr %s*", CockroachNodeTenantCertsDir),
)
}
cmd = strings.Join(rmCmds, " && ")
}
return c.runCmdOnSingleNode(ctx, l, node, cmd, defaultCmdOpts("wipe"))
})
}
// 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)
res, _, err := c.ParallelE(ctx, l, WithNodes(c.Nodes).WithDisplay(display), func(ctx context.Context, node Node) (*RunResultDetails, error) {
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
`
return c.runCmdOnSingleNode(ctx, l, node, cmd, defaultCmdOpts("status"))
})
if err != nil {
return nil, err
}
statuses := make([]NodeStatus, len(c.Nodes))
for i, res := range res {
msg := strings.TrimSpace(res.CombinedOut)
if msg == "" || strings.HasPrefix(msg, "not-running") {
statuses[i] = NodeStatus{NodeID: int(res.Node), Running: false}
if msg != "" {
info := strings.Split(msg, " ")
statuses[i].Version = info[1]
}
continue
}
info := strings.Split(msg, " ")
statuses[i] = NodeStatus{NodeID: int(res.Node), Running: true, Version: info[0], Pid: info[1]}
}
return statuses, nil
}
// MonitorProcessSkipped represents a cockroach process whose status
// was not checked.
type MonitorProcessSkipped struct {
VirtualClusterName string
SQLInstance int
}
// MonitorProcessRunning represents the cockroach process running on a
// node.
type MonitorProcessRunning struct {
VirtualClusterName string
SQLInstance int
PID string
}
// MonitorProcessDead represents the cockroach process dying on a node.
type MonitorProcessDead struct {
VirtualClusterName string
SQLInstance int
ExitCode string
}
type MonitorError struct {
Err error
}
// MonitorNoCockroachProcessesError is the error returned when the
// monitor is called on a node that is not running a `cockroach`
// process by the time the monitor runs.
var MonitorNoCockroachProcessesError = errors.New("no cockroach processes running")
// 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
// Event describes what happened to the node; it is one of
// MonitorProcessSkipped (no store directory was found);
// MonitorProcessRunning, sent when cockroach is running on a node;
// MonitorProcessDead, when the cockroach process stops running on a
// node; or MonitorError, typically indicate networking issues or
// nodes that have (physically) shut down.
Event interface{}
}
func (nmi NodeMonitorInfo) String() string {
var status string
virtualClusterDesc := func(name string, instance int) string {
if name == SystemInterfaceName {
return "system interface"
}
return fmt.Sprintf("virtual cluster %q, instance %d", name, instance)
}
switch event := nmi.Event.(type) {
case MonitorProcessRunning:
status = fmt.Sprintf("cockroach process for %s is running (PID: %s)",
virtualClusterDesc(event.VirtualClusterName, event.SQLInstance), event.PID,
)
case MonitorProcessSkipped:
status = fmt.Sprintf("%s was skipped", virtualClusterDesc(event.VirtualClusterName, event.SQLInstance))
case MonitorProcessDead:
status = fmt.Sprintf("cockroach process for %s died (exit code %s)",
virtualClusterDesc(event.VirtualClusterName, event.SQLInstance), event.ExitCode,
)
case MonitorError:
status = fmt.Sprintf("error: %s", event.Err.Error())
}
return fmt.Sprintf("n%d: %s", nmi.Node, status)
}
// 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 Node the event refers to, and the
// event itself. See documentation for NodeMonitorInfo for possible event types.
//
// 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, tenants on which no CockroachDB data is found
// (in {store-dir}) will not be probed and single event, MonitorTenantSkipped,
// will be emitted for each tenant.
//
// Note that the monitor will only send events for tenants that exist
// at the time this function is called. In other words, this function
// will not emit events for tenants started *after* a call to
// Monitor().
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
monitorCtx, cancel := context.WithCancel(ctx)
// sendEvent sends the NodeMonitorInfo passed through the channel
// that is listened to by the caller. Bails if the context is
// canceled.
sendEvent := func(info NodeMonitorInfo) {
// if the monitor's context is already canceled, do not attempt to
// send the error down the channel, as it is most likely *caused*
// by the cancelation itself.
if monitorCtx.Err() != nil {
return
}
select {
case ch <- info:
// We were able to send the info through the channel.
case <-monitorCtx.Done():
// Don't block trying to send the info.
}
}
const (
separator = "|"
skippedMsg = "skipped"
runningMsg = "running"
deadMsg = "dead"
)
wg.Add(len(nodes))
for i := range nodes {
go func(i int) {
defer wg.Done()
node := nodes[i]
// We first find out all cockroach processes that are currently
// running in this node.
cockroachProcessesCmd := fmt.Sprintf(`ps axeww -o command | `+
`grep -E '%s' | `+ // processes started by roachprod
`grep -E -o 'ROACHPROD_VIRTUAL_CLUSTER=[^ ]*' | `+ // ROACHPROD_VIRTUAL_CLUSTER indicates this is a cockroach process
`cut -d= -f2`, // grab the virtual cluster label
c.roachprodEnvRegex(node),
)
result, err := c.runCmdOnSingleNode(
ctx, l, node, cockroachProcessesCmd, defaultCmdOpts("list-processes"),
)
if err := errors.CombineErrors(err, result.Err); err != nil {
err := errors.Wrap(err, "failed to list cockroach processes")
sendEvent(NodeMonitorInfo{Node: node, Event: MonitorError{err}})
return
}
type virtualClusterInfo struct {
Name string
Instance int
}
// Make the collection of virtual clusters a set to handle the
// unlikely but possible case that, in `local` runs, we'll find
// two processes associated with the same virtual cluster
// label. This can happen if we invoke the command above while the
// parent cockroach process already created the child,
// background process, but has not terminated yet.
vcs := map[virtualClusterInfo]struct{}{}
vcLines := strings.TrimSuffix(result.CombinedOut, "\n")
if vcLines == "" {
sendEvent(NodeMonitorInfo{Node: node, Event: MonitorError{MonitorNoCockroachProcessesError}})
return
}
for _, label := range strings.Split(vcLines, "\n") {
name, instance, err := VirtualClusterInfoFromLabel(label)
if err != nil {
sendEvent(NodeMonitorInfo{Node: node, Event: MonitorError{err}})
return
}
vcs[virtualClusterInfo{name, instance}] = struct{}{}
}
data := struct {
OneShot bool
Node Node
IgnoreEmpty bool
Store string
Local bool
Separator string
SkippedMsg string
RunningMsg string
DeadMsg string
Processes []virtualClusterInfo
}{
OneShot: opts.OneShot,
Node: node,
IgnoreEmpty: opts.IgnoreEmptyNodes,
Store: c.NodeDir(node, 1 /* storeIndex */),
Local: c.IsLocal(),
Separator: separator,
SkippedMsg: skippedMsg,
RunningMsg: runningMsg,
DeadMsg: deadMsg,
Processes: maps.Keys(vcs),
}
storeFor := func(name string, instance int) string {
return c.InstanceStoreDir(node, name, instance)
}
localPIDFile := func(name string, instance int) string {
return filepath.Join(c.LogDir(node, name, instance), "cockroach.pid")
}
// NB.: we parse the output of every line this script
// prints. Every call to `echo` must match the parsing logic
// down below in order to produce structured results to the
// caller.
snippet := `
dead_parent() {
! ps -p "$1" >/dev/null || ps -o ucomm -p "$1" | grep -q defunct
}
{{ range .Processes }}
monitor_process_{{$.Node}}_{{.Name}}_{{.Instance}}() {
{{ if $.IgnoreEmpty }}
if ! ls {{storeFor .Name .Instance}}/marker.* 1> /dev/null 2>&1; then
echo "{{.Name}}{{$.Separator}}{{.Instance}}{{$.Separator}}{{$.SkippedMsg}}"
return 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 parent process terminated, quit as well.
if dead_parent "$1"; then
return 0
fi
{{ if $.Local }}
pidFile=$(cat "{{pidFile .Name .Instance}}")
# Make sure the process is still running
pid=$(test -n "${pidFile}" && ps -p "${pidFile}" >/dev/null && echo "${pidFile}")
pid=${pid:-0} # default to 0
status="unknown"
{{- else }}
# When CRDB is not running, this is zero.
pid=$(systemctl show "{{virtualClusterLabel .Name .Instance}}" --property MainPID --value)
status=$(systemctl show "{{virtualClusterLabel .Name .Instance}}" --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 "{{.Name}}{{$.Separator}}{{.Instance}}{{$.Separator}}{{$.DeadMsg}}{{$.Separator}}${status}"
fi
if [ "${pid}" != 0 ]; then
echo "{{.Name}}{{$.Separator}}{{.Instance}}{{$.Separator}}{{$.RunningMsg}}{{$.Separator}}${pid}"
fi
lastpid=${pid}
fi
{{ if $.OneShot }}
return 0
{{- end }}
sleep 1
if [ "${pid}" != 0 ]; then
while kill -0 "${pid}" && ! dead_parent "$1"; do
sleep 1
done
fi
done
}
{{ end }}
# monitor every cockroach process in parallel.
{{ range .Processes }}
monitor_process_{{$.Node}}_{{.Name}}_{{.Instance}} $$ &
{{ end }}
wait
`
t := template.Must(template.New("script").Funcs(template.FuncMap{
"storeFor": storeFor,
"pidFile": localPIDFile,
"virtualClusterLabel": VirtualClusterLabel,
}).Parse(snippet))
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
err := errors.Wrap(err, "failed to execute template")
sendEvent(NodeMonitorInfo{Node: node, Event: MonitorError{err}})
return
}
// This is the exception to funneling all SSH traffic through `c.runCmdOnSingleNode`
sess := c.newSession(l, node, buf.String(), withDebugDisabled())
defer sess.Close()
p, err := sess.StdoutPipe()
if err != nil {
err := errors.Wrap(err, "failed to read stdout pipe")
sendEvent(NodeMonitorInfo{Node: node, Event: MonitorError{err}})
return
}
// Request a PTY so that the script will receive a SIGPIPE when the
// session is closed.
if err := sess.RequestPty(); err != nil {
err := errors.Wrap(err, "failed to request PTY")
sendEvent(NodeMonitorInfo{Node: node, Event: MonitorError{err}})
return
}
var readerWg sync.WaitGroup
readerWg.Add(1)
go func(p io.Reader) {
defer readerWg.Done()
r := bufio.NewReader(p)