-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathcluster_synced.go
1987 lines (1820 loc) · 53.4 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/ioutil"
"math"
"os"
"os/exec"
"os/signal"
"path/filepath"
"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/ssh"
"github.com/cockroachdb/cockroach/pkg/roachprod/ui"
"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/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/version"
"github.com/cockroachdb/errors"
"golang.org/x/sync/errgroup"
)
// ClusterImpl TODO(peter): document
type ClusterImpl interface {
Start(c *SyncedCluster, extraArgs []string) error
CertsDir(c *SyncedCluster, index int) string
NodeDir(c *SyncedCluster, index, storeIndex int) string
LogDir(c *SyncedCluster, index int) string
NodeURL(c *SyncedCluster, host string, port int) string
NodePort(c *SyncedCluster, index int) int
NodeUIPort(c *SyncedCluster, index int) int
}
// ClusterSettings contains various knobs that affect operations on a cluster.
type ClusterSettings struct {
Secure bool
CertsDir string
Env []string
Args []string
Tag string
UseTreeDist bool
Quiet bool
NumRacks int
MaxConcurrency int // used in Parallel
}
// DefaultClusterSettings returns the default settings.
func DefaultClusterSettings() ClusterSettings {
return ClusterSettings{
Tag: "",
CertsDir: "./certs",
Secure: false,
Quiet: false,
UseTreeDist: true,
Args: nil,
Env: []string{
"COCKROACH_ENABLE_RPC_COMPRESSION=false",
"COCKROACH_UI_RELEASE_NOTES_SIGNUP_DISMISSED=true",
},
NumRacks: 0,
MaxConcurrency: 32,
}
}
var _ = DefaultClusterSettings
// A SyncedCluster is created from the information in the synced hosts file
// and is used as the target for installing and managing various software
// components.
//
// TODO(radu): SyncedCluster is currently used in two "modes": it can be just a
// metadata holder (only Cluster and DebugDir initialized) or it can be a usable
// object (once Prepare() is called). This makes things harder to follow,
// especially when we modify entries in the Clusters map in place. We should
// separate the metadata.
type SyncedCluster struct {
// Cluster metadata, obtained from the respective cloud provider.
cloud.Cluster
// Used to stash debug information.
DebugDir string
// Nodes is used by various commands like Start.
Nodes []int
ClusterSettings
Impl ClusterImpl
Localities []string
// AuthorizedKeys is used by SetupSSH to add additional authorized keys.
AuthorizedKeys []byte
}
// Prepare the SyncedCluster object for use, applying any ClusterSettings.
func (c *SyncedCluster) Prepare(settings ClusterSettings) error {
c.Impl = Cockroach{}
c.ClusterSettings = settings
c.Localities = make([]string, len(c.VMs))
for i := range c.VMs {
var err error
c.Localities[i], err = c.VMs[i].Locality()
if err != nil {
return err
}
if c.NumRacks > 0 {
rack := fmt.Sprintf("rack=%d", i%c.NumRacks)
if c.Localities[i] != "" {
rack = "," + rack
}
c.Localities[i] += rack
}
}
return nil
}
func (c *SyncedCluster) host(index int) string {
return c.VMs[index-1].PublicIP
}
func (c *SyncedCluster) user(index int) string {
return c.VMs[index-1].RemoteUser
}
func (c *SyncedCluster) locality(index int) string {
return c.Localities[index-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(nodeIdx int) string {
return local.VMDir(c.Name, nodeIdx)
}
// ServerNodes 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) ServerNodes() []int {
return append([]int{}, c.Nodes...)
}
// GetInternalIP returns the internal IP address of the specified node.
func (c *SyncedCluster) GetInternalIP(index int) (string, error) {
if c.IsLocal() {
return c.host(index), nil
}
session, err := c.newSession(index)
if err != nil {
return "", errors.Wrapf(err, "GetInternalIP: failed dial %s:%d", c.Name, index)
}
defer session.Close()
var stdout, stderr strings.Builder
session.SetStdout(&stdout)
session.SetStderr(&stderr)
cmd := `hostname --all-ip-addresses`
if err := session.Run(cmd); err != nil {
return "", errors.Wrapf(err,
"GetInternalIP: failed to execute hostname on %s:%d:\n(stdout) %s\n(stderr) %s",
c.Name, index, stdout.String(), stderr.String())
}
ip := strings.TrimSpace(stdout.String())
if ip == "" {
return "", errors.Errorf(
"empty internal IP returned, stdout:\n%s\nstderr:\n%s",
stdout.String(), stderr.String(),
)
}
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 int) 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 int) 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).
return fmt.Sprintf(`ROACHPROD=%s[ \/]`, escaped)
}
// Start TODO(peter): document
func (c *SyncedCluster) Start() error {
return c.Impl.Start(c, c.Args)
}
func (c *SyncedCluster) newSession(i int) (session, error) {
if c.IsLocal() {
return newLocalSession(), nil
}
return newRemoteSession(c.user(i), c.host(i), c.DebugDir)
}
// 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.
func (c *SyncedCluster) Stop(sig int, wait bool) error {
display := fmt.Sprintf("%s: stopping", c.Name)
if wait {
display += " and waiting"
}
err := c.Parallel(display, len(c.Nodes), 0, func(i int) ([]byte, error) {
sess, err := c.newSession(c.Nodes[i])
if err != nil {
return nil, err
}
defer sess.Close()
var waitCmd string
if wait {
waitCmd = fmt.Sprintf(`
for pid in ${pids}; do
echo "${pid}: checking" >> %[1]s/roachprod.log
while kill -0 ${pid}; do
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
done
echo "${pid}: dead" >> %[1]s/roachprod.log
done`,
c.Impl.LogDir(c, c.Nodes[i]), // [1]
)
}
// 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 stop: $(date)" >> %[1]s/roachprod.log
ps axeww -o pid -o command >> %[1]s/roachprod.log
pids=$(ps axeww -o pid -o command | \
sed 's/export ROACHPROD=//g' | \
awk '/%[2]s/ { print $1 }')
if [ -n "${pids}" ]; then
kill -%[3]d ${pids}
%[4]s
fi`,
c.Impl.LogDir(c, c.Nodes[i]), // [1]
c.roachprodEnvRegex(c.Nodes[i]), // [2]
sig, // [3]
waitCmd, // [4]
)
return sess.CombinedOutput(cmd)
})
return err
}
// Wipe TODO(peter): document
func (c *SyncedCluster) Wipe(preserveCerts bool) error {
display := fmt.Sprintf("%s: wiping", c.Name)
err := c.Stop(9, true /* wait */)
if err != nil {
return err
}
err = c.Parallel(display, len(c.Nodes), 0, func(i int) ([]byte, error) {
sess, err := c.newSession(c.Nodes[i])
if err != nil {
return nil, err
}
defer sess.Close()
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*")
}
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"
}
}
return sess.CombinedOutput(cmd)
})
return err
}
// Status TODO(peter): document
func (c *SyncedCluster) Status() error {
display := fmt.Sprintf("%s: status", c.Name)
results := make([]string, len(c.Nodes))
err := c.Parallel(display, len(c.Nodes), 0, func(i int) ([]byte, error) {
sess, err := c.newSession(c.Nodes[i])
if err != nil {
results[i] = err.Error()
return nil, nil
}
defer sess.Close()
binary := cockroachNodeBinary(c, c.Nodes[i])
cmd := fmt.Sprintf(`out=$(ps axeww -o pid -o ucomm -o command | \
sed 's/export ROACHPROD=//g' | \
awk '/%s/ {print $2, $1}'`,
c.roachprodEnvRegex(c.Nodes[i]))
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"
else
echo ${out}
fi
`
out, err := sess.CombinedOutput(cmd)
var msg string
if err != nil {
return nil, errors.Wrapf(err, "~ %s\n%s", cmd, out)
}
msg = strings.TrimSpace(string(out))
if msg == "" {
msg = "not running"
}
results[i] = msg
return nil, nil
})
for i, r := range results {
fmt.Printf(" %2d: %s\n", c.Nodes[i], r)
}
return err
}
// 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.
Index int
// 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
}
// 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(ignoreEmptyNodes bool, oneShot bool) chan NodeMonitorInfo {
ch := make(chan NodeMonitorInfo)
nodes := c.ServerNodes()
var wg sync.WaitGroup
for i := range nodes {
wg.Add(1)
go func(i int) {
defer wg.Done()
sess, err := c.newSession(nodes[i])
if err != nil {
ch <- NodeMonitorInfo{Index: nodes[i], Err: err}
wg.Done()
return
}
defer sess.Close()
p, err := sess.StdoutPipe()
if err != nil {
ch <- NodeMonitorInfo{Index: nodes[i], Err: err}
wg.Done()
return
}
// On each monitored node, we loop looking for a cockroach process.
data := struct {
OneShot bool
IgnoreEmpty bool
Store string
Port int
Local bool
}{
OneShot: oneShot,
IgnoreEmpty: ignoreEmptyNodes,
Store: Cockroach{}.NodeDir(c, nodes[i], 1 /* storeIndex */),
Port: Cockroach{}.NodePort(c, nodes[i]),
Local: c.IsLocal(),
}
snippet := `
{{ if .IgnoreEmpty }}
if [ ! -f "{{.Store}}/CURRENT" ]; 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{Index: nodes[i], Err: err}
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{Index: nodes[i], 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{Index: nodes[i], Msg: string(line)}
}
}(p)
if err := sess.Start(buf.String()); err != nil {
ch <- NodeMonitorInfo{Index: nodes[i], Err: err}
return
}
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{Index: nodes[i], Err: err}
return
}
}(i)
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}
// 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(stdout, stderr io.Writer, nodes []int, title, cmd string) 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)
}
errs := make([]error, len(nodes))
results := make([]string, len(nodes))
err := c.Parallel(display, len(nodes), 0, func(i int) ([]byte, error) {
sess, err := c.newSession(nodes[i])
if err != nil {
errs[i] = err
results[i] = err.Error()
return nil, nil
}
defer sess.Close()
// Argument template expansion is node specific (e.g. for {store-dir}).
e := expander{
node: nodes[i],
}
expandedCmd, err := e.expand(c, cmd)
if err != nil {
return nil, 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.
nodeCmd := fmt.Sprintf(`export ROACHPROD=%s GOTRACEBACK=crash && bash -c %s`,
c.roachprodEnvValue(nodes[i]), ssh.Escape1(expandedCmd))
if c.IsLocal() {
nodeCmd = fmt.Sprintf("cd %s; %s", c.localVMDir(nodes[i]), nodeCmd)
}
if stream {
sess.SetStdout(stdout)
sess.SetStderr(stderr)
errs[i] = sess.Run(nodeCmd)
if errs[i] != nil {
detailMsg := fmt.Sprintf("Node %d. Command with error:\n```\n%s\n```\n", nodes[i], cmd)
err = errors.WithDetail(errs[i], detailMsg)
err = rperrors.ClassifyCmdError(err)
errs[i] = err
}
return nil, nil
}
out, err := sess.CombinedOutput(nodeCmd)
msg := strings.TrimSpace(string(out))
if err != nil {
detailMsg := fmt.Sprintf("Node %d. Command with error:\n```\n%s\n```\n", nodes[i], cmd)
err = errors.WithDetail(err, detailMsg)
err = rperrors.ClassifyCmdError(err)
errs[i] = err
msg += fmt.Sprintf("\n%v", err)
}
results[i] = msg
return nil, nil
})
if !stream {
for i, r := range results {
fmt.Fprintf(stdout, " %2d: %s\n", nodes[i], r)
}
}
if err != nil {
return err
}
return rperrors.SelectPriorityError(errs)
}
// Wait TODO(peter): document
func (c *SyncedCluster) Wait() error {
display := fmt.Sprintf("%s: waiting for nodes to start", c.Name)
errs := make([]error, len(c.Nodes))
err := c.Parallel(display, len(c.Nodes), 0, func(i int) ([]byte, error) {
for j := 0; j < 600; j++ {
sess, err := c.newSession(c.Nodes[i])
if err != nil {
time.Sleep(500 * time.Millisecond)
continue
}
defer sess.Close()
_, err = sess.CombinedOutput("test -e /mnt/data1/.roachprod-initialized")
if err != nil {
time.Sleep(500 * time.Millisecond)
continue
}
return nil, nil
}
errs[i] = errors.New("timed out after 5m")
return nil, nil
})
if err != nil {
return err
}
var foundErr bool
for i, err := range errs {
if err != nil {
fmt.Printf(" %2d: %v\n", c.Nodes[i], err)
foundErr = true
}
}
if foundErr {
return errors.New("not all nodes booted successfully")
}
return nil
}
// SetupSSH configures the cluster for use with SSH. This is generally run after
// the cloud.Cluster has been synced which resets the SSH credentials on the
// machines and sets them up for the current user. This method enables the
// hosts to talk to eachother and optionally configures additional keys to be
// added to the hosts via the c.AuthorizedKeys field. It does so in the following
// steps:
//
// 1. Creates an ssh key pair on the first host to be used on all hosts if
// none exists.
// 2. Distributes the public key, private key, and authorized_keys file from
// the first host to the others.
// 3. Merges the data in c.AuthorizedKeys with the existing authorized_keys
// files on all hosts.
//
// This call strives to be idempotent.
func (c *SyncedCluster) SetupSSH() error {
if c.IsLocal() {
return nil
}
if len(c.Nodes) == 0 || len(c.VMs) == 0 {
return fmt.Errorf("%s: invalid cluster: nodes=%d hosts=%d",
c.Name, len(c.Nodes), len(c.VMs))
}
// Generate an ssh key that we'll distribute to all of the nodes in the
// cluster in order to allow inter-node ssh.
var sshTar []byte
err := c.Parallel("generating ssh key", 1, 0, func(i int) ([]byte, error) {
sess, err := c.newSession(1)
if err != nil {
return nil, err
}
defer sess.Close()
// Create the ssh key and then tar up the public, private and
// authorized_keys files and output them to stdout. We'll take this output
// and pipe it back into tar on the other nodes in the cluster.
cmd := `
test -f .ssh/id_rsa || \
(ssh-keygen -q -f .ssh/id_rsa -t rsa -N '' && \
cat .ssh/id_rsa.pub >> .ssh/authorized_keys);
tar cf - .ssh/id_rsa .ssh/id_rsa.pub .ssh/authorized_keys
`
var stdout bytes.Buffer
var stderr bytes.Buffer
sess.SetStdout(&stdout)
sess.SetStderr(&stderr)
if err := sess.Run(cmd); err != nil {
return nil, errors.Wrapf(err, "%s: stderr:\n%s", cmd, stderr.String())
}
sshTar = stdout.Bytes()
return nil, nil
})
if err != nil {
return err
}
// Skip the first node which is where we generated the key.
nodes := c.Nodes[1:]
err = c.Parallel("distributing ssh key", len(nodes), 0, func(i int) ([]byte, error) {
sess, err := c.newSession(nodes[i])
if err != nil {
return nil, err
}
defer sess.Close()
sess.SetStdin(bytes.NewReader(sshTar))
cmd := `tar xf -`
if out, err := sess.CombinedOutput(cmd); err != nil {
return nil, errors.Wrapf(err, "%s: output:\n%s", cmd, out)
}
return nil, nil
})
if err != nil {
return err
}
// Populate the known_hosts file with both internal and external IPs of all
// of the nodes in the cluster. Note that as a side effect, this creates the
// known hosts file in unhashed format, working around a limitation of jsch
// (which is used in jepsen tests).
ips := make([]string, len(c.Nodes), len(c.Nodes)*2)
err = c.Parallel("retrieving hosts", len(c.Nodes), 0, func(i int) ([]byte, error) {
for j := 0; j < 20 && ips[i] == ""; j++ {
var err error
ips[i], err = c.GetInternalIP(c.Nodes[i])
if err != nil {
return nil, errors.Wrapf(err, "pgurls")
}
time.Sleep(time.Second)
}
if ips[i] == "" {
return nil, fmt.Errorf("retrieved empty IP address")
}
return nil, nil
})
if err != nil {
return err
}
for _, i := range c.Nodes {
ips = append(ips, c.host(i))
}
var knownHostsData []byte
err = c.Parallel("scanning hosts", 1, 0, func(i int) ([]byte, error) {
sess, err := c.newSession(c.Nodes[i])
if err != nil {
return nil, err
}
defer sess.Close()
// ssh-keyscan may return fewer than the desired number of entries if the
// remote nodes are not responding yet, so we loop until we have a scan that
// found host keys for all of the IPs. Merge the newly scanned keys with the
// existing list to make this process idempotent.
cmd := `
set -e
tmp="$(tempfile -d ~/.ssh -p 'roachprod' )"
on_exit() {
rm -f "${tmp}"
}
trap on_exit EXIT
for i in {1..20}; do
ssh-keyscan -T 60 -t rsa ` + strings.Join(ips, " ") + ` > "${tmp}"
if [[ "$(wc < ${tmp} -l)" -eq "` + fmt.Sprint(len(ips)) + `" ]]; then
[[ -f .ssh/known_hosts ]] && cat .ssh/known_hosts >> "${tmp}"
sort -u < "${tmp}"
exit 0
fi
sleep 1
done
exit 1
`
var stdout bytes.Buffer
var stderr bytes.Buffer
sess.SetStdout(&stdout)
sess.SetStderr(&stderr)
if err := sess.Run(cmd); err != nil {
return nil, errors.Wrapf(err, "%s: stderr:\n%s", cmd, stderr.String())
}
knownHostsData = stdout.Bytes()
return nil, nil
})
if err != nil {
return err
}
err = c.Parallel("distributing known_hosts", len(c.Nodes), 0, func(i int) ([]byte, error) {
sess, err := c.newSession(c.Nodes[i])
if err != nil {
return nil, err
}
defer sess.Close()
sess.SetStdin(bytes.NewReader(knownHostsData))
const cmd = `
known_hosts_data="$(cat)"
set -e
tmp="$(tempfile -p 'roachprod' -m 0644 )"
on_exit() {
rm -f "${tmp}"
}
trap on_exit EXIT
echo "${known_hosts_data}" > "${tmp}"
cat "${tmp}" >> ~/.ssh/known_hosts
# If our bootstrapping user is not the shared user install all of the
# relevant ssh files from the bootstrapping user into the shared user's
# .ssh directory.
if [[ "$(whoami)" != "` + config.SharedUser + `" ]]; then
# Ensure that the shared user has a .ssh directory
sudo -u ` + config.SharedUser +
` bash -c "mkdir -p ~` + config.SharedUser + `/.ssh"
# This somewhat absurd incantation ensures that we properly shell quote
# filenames so that they both aren't expanded and work even if the filenames
# include spaces.
sudo find ~/.ssh -type f -execdir bash -c 'install \
--owner ` + config.SharedUser + ` \
--group ` + config.SharedUser + ` \
--mode $(stat -c "%a" '"'"'{}'"'"') \
'"'"'{}'"'"' ~` + config.SharedUser + `/.ssh' \;
fi
`
if out, err := sess.CombinedOutput(cmd); err != nil {
return nil, errors.Wrapf(err, "%s: output:\n%s", cmd, out)
}
return nil, nil
})
if err != nil {
return err
}
if len(c.AuthorizedKeys) > 0 {
// When clusters are created using cloud APIs they only have a subset of
// desired keys installed on a subset of users. This code distributes
// additional authorized_keys to both the current user (your username on
// gce and the shared user on aws) as well as to the shared user on both
// platforms.
err = c.Parallel("adding additional authorized keys", len(c.Nodes), 0, func(i int) ([]byte, error) {
sess, err := c.newSession(c.Nodes[i])
if err != nil {
return nil, err
}
defer sess.Close()
sess.SetStdin(bytes.NewReader(c.AuthorizedKeys))
const cmd = `
keys_data="$(cat)"
set -e
tmp1="$(tempfile -d ~/.ssh -p 'roachprod' )"
tmp2="$(tempfile -d ~/.ssh -p 'roachprod' )"
on_exit() {
rm -f "${tmp1}" "${tmp2}"
}
trap on_exit EXIT
if [[ -f ~/.ssh/authorized_keys ]]; then
cat ~/.ssh/authorized_keys > "${tmp1}"
fi
echo "${keys_data}" >> "${tmp1}"
sort -u < "${tmp1}" > "${tmp2}"
install --mode 0600 "${tmp2}" ~/.ssh/authorized_keys
if [[ "$(whoami)" != "` + config.SharedUser + `" ]]; then
sudo install --mode 0600 \
--owner ` + config.SharedUser + `\
--group ` + config.SharedUser + `\
"${tmp2}" ~` + config.SharedUser + `/.ssh/authorized_keys
fi
`
if out, err := sess.CombinedOutput(cmd); err != nil {
return nil, errors.Wrapf(err, "~ %s\n%s", cmd, out)
}
return nil, nil
})
if err != nil {
return err
}
}
return nil
}
// DistributeCerts will generate and distribute certificates to all of the
// nodes.
func (c *SyncedCluster) DistributeCerts() error {
dir := ""
if c.IsLocal() {
dir = c.localVMDir(1)
}
// Check to see if the certs have already been initialized.
var existsErr error
display := fmt.Sprintf("%s: checking certs", c.Name)
err := c.Parallel(display, 1, 0, func(i int) ([]byte, error) {
sess, err := c.newSession(1)
if err != nil {
return nil, err
}
defer sess.Close()
_, existsErr = sess.CombinedOutput(`test -e ` + filepath.Join(dir, `certs.tar`))
return nil, nil
})
if err != nil {
return err
}
if existsErr == nil {
return nil
}
// Gather the internal IP addresses for every node in the cluster, even
// if it won't be added to the cluster itself we still add the IP address
// to the node cert.
var msg string
display = fmt.Sprintf("%s: initializing certs", c.Name)
nodes := allNodes(len(c.VMs))
var ips []string
if !c.IsLocal() {
ips = make([]string, len(nodes))
err = c.Parallel("", len(nodes), 0, func(i int) ([]byte, error) {
var err error
ips[i], err = c.GetInternalIP(nodes[i])
return nil, errors.Wrapf(err, "IPs")
})
if err != nil {
return err
}
}