-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
main.go
1500 lines (1340 loc) · 48.1 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package main
import (
"context"
"encoding/json"
"fmt"
"net/url"
"os"
"os/user"
"path"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/cmd/roachprod/grafana"
"github.com/cockroachdb/cockroach/pkg/cmd/roachprod/upgrade"
"github.com/cockroachdb/cockroach/pkg/roachprod"
"github.com/cockroachdb/cockroach/pkg/roachprod/config"
rperrors "github.com/cockroachdb/cockroach/pkg/roachprod/errors"
"github.com/cockroachdb/cockroach/pkg/roachprod/install"
"github.com/cockroachdb/cockroach/pkg/roachprod/ui"
"github.com/cockroachdb/cockroach/pkg/roachprod/vm"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/fatih/color"
"github.com/spf13/cobra"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
var rootCmd = &cobra.Command{
Use: "roachprod [command] (flags)",
Short: "roachprod tool for manipulating test clusters",
Long: `roachprod is a tool for manipulating ephemeral test clusters, allowing easy
creating, destruction, starting, stopping and wiping of clusters along with
running load generators.
Examples:
roachprod create local -n 3
roachprod start local
roachprod sql local:2 -- -e "select * from crdb_internal.node_runtime_info"
roachprod stop local
roachprod wipe local
roachprod destroy local
The above commands will create a "local" 3 node cluster, start a cockroach
cluster on these nodes, run a sql command on the 2nd node, stop, wipe and
destroy the cluster.
`,
Version: "details:\n" + build.GetInfo().Long(),
PersistentPreRun: validateAndConfigure,
}
// Provide `cobra.Command` functions with a standard return code handler.
// Exit codes come from rperrors.Error.ExitCode().
//
// If the wrapped error tree of an error does not contain an instance of
// rperrors.Error, the error will automatically be wrapped with
// rperrors.Unclassified.
func wrap(f func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
err := f(cmd, args)
if err != nil {
roachprodError, ok := rperrors.AsError(err)
if !ok {
roachprodError = rperrors.Unclassified{Err: err}
err = roachprodError
}
cmd.Printf("Error: %+v\n", err)
os.Exit(roachprodError.ExitCode())
}
}
}
var createCmd = &cobra.Command{
Use: "create <cluster>",
Short: "create a cluster",
Long: `Create a local or cloud-based cluster.
A cluster is composed of a set of nodes, configured during cluster creation via
the --nodes flag. Creating a cluster does not start any processes on the nodes
other than the base system processes (e.g. sshd). See "roachprod start" for
starting cockroach nodes and "roachprod {run,ssh}" for running arbitrary
commands on the nodes of a cluster.
Cloud Clusters
Cloud-based clusters are ephemeral and come with a lifetime (specified by the
--lifetime flag) after which they will be automatically
destroyed. Cloud-based clusters require the associated command line tool for
the cloud to be installed and configured (e.g. "gcloud auth login").
Clusters names are required to be prefixed by the authenticated user of the
cloud service. The suffix is an arbitrary string used to distinguish
clusters. For example, "marc-test" is a valid cluster name for the user
"marc". The authenticated user for the cloud service is automatically
detected and can be override by the ROACHPROD_USER environment variable or
the --username flag.
The machine type and the use of local SSD storage can be specified during
cluster creation via the --{cloud}-machine-type and --local-ssd flags. The
machine-type is cloud specified. For example, --gce-machine-type=n1-highcpu-8
requests the "n1-highcpu-8" machine type for a GCE-based cluster. No attempt
is made (or desired) to abstract machine types across cloud providers. See
the cloud provider's documentation for details on the machine types
available.
The underlying filesystem can be provided using the --filesystem flag.
Use --filesystem=zfs, for zfs, and --filesystem=ext4, for ext4. The default
file system is ext4. The filesystem flag only works on gce currently.
Local Clusters
A local cluster stores the per-node data in ${HOME}/local on the machine
roachprod is being run on. Whether a cluster is local is specified on creation
by using the name 'local' or 'local-<anything>'. Local clusters have no expiration.
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) (retErr error) {
createVMOpts.ClusterName = args[0]
return roachprod.Create(context.Background(), config.Logger, username, numNodes, createVMOpts, providerOptsContainer)
}),
}
var setupSSHCmd = &cobra.Command{
Use: "setup-ssh <cluster>",
Short: "set up ssh for a cluster",
Long: `Sets up the keys and host keys for the vms in the cluster.
It first resets the machine credentials as though the cluster were newly created
using the cloud provider APIs and then proceeds to ensure that the hosts can
SSH into eachother and lastly adds additional public keys to AWS hosts as read
from the GCP project. This operation is performed as the last step of creating
a new cluster but can be useful to re-run if the operation failed previously or
if the user would like to update the keys on the remote hosts.
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) (retErr error) {
return roachprod.SetupSSH(context.Background(), config.Logger, args[0])
}),
}
var destroyCmd = &cobra.Command{
Use: "destroy [ --all-mine | --all-local | <cluster 1> [<cluster 2> ...] ]",
Short: "destroy clusters",
Long: `Destroy one or more local or cloud-based clusters.
The destroy command accepts the names of the clusters to destroy. Alternatively,
the --all-mine flag can be provided to destroy all (non-local) clusters that are
owned by the current user, or the --all-local flag can be provided to destroy
all local clusters.
Destroying a cluster releases the resources for a cluster. For a cloud-based
cluster the machine and associated disk resources are freed. For a local
cluster, any processes started by roachprod are stopped, and the node
directories inside ${HOME}/local directory are removed.
`,
Args: cobra.ArbitraryArgs,
Run: wrap(func(cmd *cobra.Command, args []string) error {
return roachprod.Destroy(config.Logger, destroyAllMine, destroyAllLocal, args...)
}),
}
var cachedHostsCmd = &cobra.Command{
Use: "cached-hosts",
Short: "list all clusters (and optionally their host numbers) from local cache",
Args: cobra.NoArgs,
Run: wrap(func(cmd *cobra.Command, args []string) error {
roachprod.CachedClusters(config.Logger, func(clusterName string, numVMs int) {
if strings.HasPrefix(clusterName, "teamcity") {
return
}
fmt.Printf("%s", clusterName)
// When invoked by bash-completion, cachedHostsCluster is what the user
// has currently typed -- if this cluster matches that, expand its hosts.
if strings.HasPrefix(cachedHostsCluster, clusterName) {
for i := 1; i <= numVMs; i++ {
fmt.Printf(" %s:%d", clusterName, i)
}
}
fmt.Printf("\n")
})
return nil
}),
}
var listCmd = &cobra.Command{
Use: "list [--details | --json] [ --mine | --pattern ]",
Short: "list all clusters",
Long: `List all clusters.
The list command accepts a flag --pattern which is a regular
expression that will be matched against the cluster name pattern. Alternatively,
the --mine flag can be provided to list the clusters that are owned by the current
user.
The default output shows one line per cluster, including the local cluster if
it exists:
~ roachprod list
local: [local] 1 (-)
marc-test: [aws gce] 4 (5h34m35s)
Syncing...
The second column lists the cloud providers that host VMs for the cluster.
The third and fourth columns are the number of nodes in the cluster and the
time remaining before the cluster will be automatically destroyed. Note that
local clusters do not have an expiration.
The --details flag adjusts the output format to include per-node details:
~ roachprod list --details
local [local]: (no expiration)
localhost 127.0.0.1 127.0.0.1
marc-test: [aws gce] 5h33m57s remaining
marc-test-0001 marc-test-0001.us-east1-b.cockroach-ephemeral 10.142.0.18 35.229.60.91
marc-test-0002 marc-test-0002.us-east1-b.cockroach-ephemeral 10.142.0.17 35.231.0.44
marc-test-0003 marc-test-0003.us-east1-b.cockroach-ephemeral 10.142.0.19 35.229.111.100
marc-test-0004 marc-test-0004.us-east1-b.cockroach-ephemeral 10.142.0.20 35.231.102.125
Syncing...
The first and second column are the node hostname and fully qualified name
respectively. The third and fourth column are the private and public IP
addresses.
The --json flag sets the format of the command output to json.
Listing clusters has the side-effect of syncing ssh keys/configs and the local
hosts file.
`,
Args: cobra.NoArgs,
Run: wrap(func(cmd *cobra.Command, args []string) error {
if listJSON && listDetails {
return errors.New("'json' option cannot be combined with 'details' option")
}
filteredCloud, err := roachprod.List(config.Logger, listMine, listPattern, vm.ListOptions{ComputeEstimatedCost: true})
if err != nil {
return err
}
// sort by cluster names for stable output.
names := make([]string, len(filteredCloud.Clusters))
maxClusterName := 0
i := 0
for name := range filteredCloud.Clusters {
names[i] = name
if len(name) > maxClusterName {
maxClusterName = len(name)
}
i++
}
sort.Strings(names)
p := message.NewPrinter(language.English)
if listJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(filteredCloud); err != nil {
return err
}
} else {
machineType := func(clusterVMs vm.List) string {
return clusterVMs[0].MachineType
}
cpuArch := func(clusterVMs vm.List) string {
// Display CPU architecture and family.
if clusterVMs[0].CPUArch == "" {
// N.B. Either a local cluster or unsupported cloud provider.
return ""
}
if clusterVMs[0].CPUFamily != "" {
return clusterVMs[0].CPUFamily
}
if clusterVMs[0].CPUArch != vm.ArchAMD64 {
return string(clusterVMs[0].CPUArch)
}
// AMD64 is the default, so don't display it.
return ""
}
// Align columns left and separate with at least two spaces.
tw := tabwriter.NewWriter(os.Stdout, 0, 8, 2, ' ', tabwriter.AlignRight)
// N.B. colors use escape codes which don't play nice with tabwriter [1].
// We use a hacky workaround below to color the empty string.
// [1] https://github.com/golang/go/issues/12073
// Print header.
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n",
"Cluster", "Clouds", "Size", "VM", "Arch",
color.HiWhiteString("$/hour"), color.HiWhiteString("$ Spent"),
color.HiWhiteString("Uptime"), color.HiWhiteString("TTL"),
color.HiWhiteString("$/TTL"))
// Print separator.
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n",
"", "", "", "",
color.HiWhiteString(""), color.HiWhiteString(""),
color.HiWhiteString(""), color.HiWhiteString(""),
color.HiWhiteString(""))
totalCostPerHour := 0.0
for _, name := range names {
c := filteredCloud.Clusters[name]
if listDetails {
c.PrintDetails(config.Logger)
} else {
// N.B. Tabwriter doesn't support per-column alignment. It looks odd to have the cluster names right-aligned,
// so we make it left-aligned.
fmt.Fprintf(tw, "%s\t%s\t%d\t%s\t%s", name+strings.Repeat(" ", maxClusterName-len(name)), c.Clouds(),
len(c.VMs), machineType(c.VMs), cpuArch(c.VMs))
if !c.IsLocal() {
colorByCostBucket := func(cost float64) func(string, ...interface{}) string {
switch {
case cost <= 100:
return color.HiGreenString
case cost <= 1000:
return color.HiBlueString
default:
return color.HiRedString
}
}
timeRemaining := c.LifetimeRemaining().Round(time.Second)
formatTTL := func(ttl time.Duration) string {
if c.VMs[0].Preemptible {
return color.HiMagentaString(ttl.String())
} else {
return color.HiBlueString(ttl.String())
}
}
cost := c.CostPerHour
totalCostPerHour += cost
alive := timeutil.Since(c.CreatedAt).Round(time.Minute)
costSinceCreation := cost * float64(alive) / float64(time.Hour)
costRemaining := cost * float64(timeRemaining) / float64(time.Hour)
if cost > 0 {
fmt.Fprintf(tw, "\t%s\t%s\t%s\t%s\t%s\t",
color.HiGreenString(p.Sprintf("$%.2f", cost)),
colorByCostBucket(costSinceCreation)(p.Sprintf("$%.2f", costSinceCreation)),
color.HiWhiteString(alive.String()),
formatTTL(timeRemaining),
colorByCostBucket(costRemaining)(p.Sprintf("$%.2f", costRemaining)))
} else {
fmt.Fprintf(tw, "\t%s\t%s\t%s\t%s\t%s\t",
color.HiGreenString(""),
color.HiGreenString(""),
color.HiWhiteString(alive.String()),
formatTTL(timeRemaining),
color.HiGreenString(""))
}
} else {
fmt.Fprintf(tw, "\t(-)")
}
fmt.Fprintf(tw, "\n")
}
}
if err := tw.Flush(); err != nil {
return err
}
if totalCostPerHour > 0 {
_, _ = p.Printf("\nTotal cost per hour: $%.2f\n", totalCostPerHour)
}
// Optionally print any dangling instances with errors
if listDetails {
collated := filteredCloud.BadInstanceErrors()
// Sort by Error() value for stable output
var errors ui.ErrorsByError
for err := range collated {
errors = append(errors, err)
}
sort.Sort(errors)
for _, e := range errors {
fmt.Printf("%s: %s\n", e, collated[e].Names())
}
}
}
return nil
}),
}
var bashCompletion = os.ExpandEnv("$HOME/.roachprod/bash-completion.sh")
// TODO(peter): Do we need this command given that the "list" command syncs as
// a side-effect. If you don't care about the list output, just "roachprod list
// &>/dev/null".
var syncCmd = &cobra.Command{
Use: "sync",
Short: "sync ssh keys/config and hosts files",
Long: ``,
Args: cobra.NoArgs,
Run: wrap(func(cmd *cobra.Command, args []string) error {
_, err := roachprod.Sync(config.Logger, vm.ListOptions{IncludeVolumes: listOpts.IncludeVolumes})
_ = rootCmd.GenBashCompletionFile(bashCompletion)
return err
}),
}
var gcCmd = &cobra.Command{
Use: "gc",
Short: "GC expired clusters and unused AWS keypairs\n",
Long: `Garbage collect expired clusters and unused SSH keypairs in AWS.
Destroys expired clusters, sending email if properly configured. Usually run
hourly by a cronjob so it is not necessary to run manually.
`,
Args: cobra.NoArgs,
Run: wrap(func(cmd *cobra.Command, args []string) error {
return roachprod.GC(config.Logger, dryrun)
}),
}
var extendCmd = &cobra.Command{
Use: "extend <cluster>",
Short: "extend the lifetime of a cluster",
Long: `Extend the lifetime of the specified cluster to prevent it from being
destroyed:
roachprod extend marc-test --lifetime=6h
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
return roachprod.Extend(config.Logger, args[0], extendLifetime)
}),
}
const tagHelp = `
The --tag flag can be used to to associate a tag with the process. This tag can
then be used to restrict the processes which are operated on by the status and
stop commands. Tags can have a hierarchical component by utilizing a slash
separated string similar to a filesystem path. A tag matches if a prefix of the
components match. For example, the tag "a/b" will match both "a/b" and
"a/b/c/d".
`
var startCmd = &cobra.Command{
Use: "start <cluster>",
Short: "start nodes on a cluster",
Long: `Start nodes on a cluster.
The --secure flag can be used to start nodes in secure mode (i.e. using
certs). When specified, there is a one time initialization for the cluster to
create and distribute the certs. Note that running some modes in secure mode
and others in insecure mode is not a supported Cockroach configuration.
As a debugging aid, the --sequential flag starts the nodes sequentially so node
IDs match hostnames. Otherwise nodes are started in parallel.
The --binary flag specifies the remote binary to run. It is up to the roachprod
user to ensure this binary exists, usually via "roachprod put". Note that no
cockroach software is installed by default on a newly created cluster.
The --args and --env flags can be used to pass arbitrary command line flags and
environment variables to the cockroach process.
` + tagHelp + `
The "start" command takes care of setting up the --join address and specifying
reasonable defaults for other flags. One side-effect of this convenience is
that node 1 is special and if started, is used to auto-initialize the cluster.
The --skip-init flag can be used to avoid auto-initialization (which can then
separately be done using the "init" command).
If the COCKROACH_DEV_LICENSE environment variable is set the enterprise.license
cluster setting will be set to its value.
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
clusterSettingsOpts := []install.ClusterSettingOption{
install.TagOption(tag),
install.PGUrlCertsDirOption(pgurlCertsDir),
install.SecureOption(secure),
install.UseTreeDistOption(useTreeDist),
install.EnvOption(nodeEnv),
install.NumRacksOption(numRacks),
}
return roachprod.Start(context.Background(), config.Logger, args[0], startOpts, clusterSettingsOpts...)
}),
}
var stopCmd = &cobra.Command{
Use: "stop <cluster> [--sig] [--wait]",
Short: "stop nodes on a cluster",
Long: `Stop nodes on a cluster.
Stop roachprod created processes running on the nodes in a cluster, including
processes started by the "start", "run" and "ssh" commands. Every process
started by roachprod is tagged with a ROACHPROD environment variable which is
used by "stop" to locate the processes and terminate them. By default processes
are killed with signal 9 (SIGKILL) giving them no chance for a graceful exit.
The --sig flag will pass a signal to kill to allow us finer control over how we
shutdown cockroach. The --wait flag causes stop to loop waiting for all
processes with the right ROACHPROD environment variable to exit. Note that stop
will wait forever if you specify --wait with a non-terminating signal (e.g.
SIGHUP), unless you also configure --max-wait.
--wait defaults to true for signal 9 (SIGKILL) and false for all other signals.
` + tagHelp + `
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
wait := waitFlag
if sig == 9 /* SIGKILL */ && !cmd.Flags().Changed("wait") {
wait = true
}
stopOpts := roachprod.StopOpts{Wait: wait, MaxWait: maxWait, ProcessTag: tag, Sig: sig}
return roachprod.Stop(context.Background(), config.Logger, args[0], stopOpts)
}),
}
var startInstanceCmd = &cobra.Command{
Use: "start-sql <name> --storage-cluster <storage-cluster> [--external-cluster <virtual-cluster-nodes]",
Short: "start the SQL/HTTP service for a virtual cluster as a separate process",
Long: `Start SQL/HTTP instances for a virtual cluster as separate processes.
The --storage-cluster flag must be used to specify a storage cluster
(with optional node selector) which is already running. The command
will create the virtual cluster on the storage cluster if it does not
exist already. If creating multiple virtual clusters on the same
node, the --sql-instance flag must be passed to differentiate them.
The instance is started in shared process (in memory) mode by
default. To start an external process instance, pass the
--external-cluster flag indicating where the SQL server processes
should be started.
The --secure flag can be used to start nodes in secure mode (i.e. using
certs). When specified, there is a one time initialization for the cluster to
create and distribute the certs. Note that running some modes in secure mode
and others in insecure mode is not a supported Cockroach configuration.
As a debugging aid, the --sequential flag starts the services
sequentially; otherwise services are started in parallel.
The --binary flag specifies the remote binary to run, if starting
external services. It is up to the roachprod user to ensure this
binary exists, usually via "roachprod put". Note that no cockroach
software is installed by default on a newly created cluster.
The --args and --env flags can be used to pass arbitrary command line flags and
environment variables to the cockroach process.
` + tagHelp + `
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
clusterSettingsOpts := []install.ClusterSettingOption{
install.TagOption(tag),
install.PGUrlCertsDirOption(pgurlCertsDir),
install.SecureOption(secure),
install.UseTreeDistOption(useTreeDist),
install.EnvOption(nodeEnv),
install.NumRacksOption(numRacks),
}
// Always pick a random available port when starting virtual
// clusters. We do not expose the functionality of choosing a
// specific port for separate-process deployments; for
// shared-process, the port always be based on the system tenant
// service.
//
// TODO(renato): remove this once #111052 is addressed.
startOpts.SQLPort = 0
startOpts.AdminUIPort = 0
startOpts.Target = install.StartSharedProcessForVirtualCluster
if externalProcessNodes != "" {
startOpts.Target = install.StartServiceForVirtualCluster
}
startOpts.VirtualClusterName = args[0]
return roachprod.StartServiceForVirtualCluster(context.Background(),
config.Logger, externalProcessNodes, storageCluster, startOpts, clusterSettingsOpts...)
}),
}
var stopInstanceCmd = &cobra.Command{
Use: "stop-sql <cluster> --cluster <name> --sql-instance <instance> [--sig] [--wait]",
Short: "stop sql instances on a cluster",
Long: `Stop sql instances on a cluster.
Stop roachprod created virtual clusters (shared or separate process). By default,
separate processes are killed with signal 9 (SIGKILL) giving them no chance for a
graceful exit.
The --sig flag will pass a signal to kill to allow us finer control over how we
shutdown processes. The --wait flag causes stop to loop waiting for all
processes to exit. Note that stop will wait forever if you specify --wait with a
non-terminating signal (e.g. SIGHUP), unless you also configure --max-wait.
--wait defaults to true for signal 9 (SIGKILL) and false for all other signals.
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
wait := waitFlag
if sig == 9 /* SIGKILL */ && !cmd.Flags().Changed("wait") {
wait = true
}
stopOpts := roachprod.StopOpts{
Wait: wait,
MaxWait: maxWait,
Sig: sig,
VirtualClusterName: virtualClusterName,
SQLInstance: sqlInstance,
}
clusterName := args[0]
return roachprod.StopServiceForVirtualCluster(context.Background(), config.Logger, clusterName, stopOpts)
}),
}
var initCmd = &cobra.Command{
Use: "init <cluster>",
Short: "initialize the cluster",
Long: `Initialize the cluster.
The "init" command bootstraps the cluster (using "cockroach init"). It also sets
default cluster settings. It's intended to be used in conjunction with
'roachprod start --skip-init'.
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
return roachprod.Init(context.Background(), config.Logger, args[0], startOpts)
}),
}
var statusCmd = &cobra.Command{
Use: "status <cluster>",
Short: "retrieve the status of nodes in a cluster",
Long: `Retrieve the status of nodes in a cluster.
The "status" command outputs the binary and PID for the specified nodes:
~ roachprod status local
local: status 3/3
1: cockroach 29688
2: cockroach 29687
3: cockroach 29689
` + tagHelp + `
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
statuses, err := roachprod.Status(context.Background(), config.Logger, args[0], tag)
if err != nil {
return err
}
for _, status := range statuses {
if status.Err != nil {
config.Logger.Printf(" %2d: %s %s\n", status.NodeID, status.Err.Error())
} else if !status.Running {
// TODO(irfansharif): Surface the staged version here?
config.Logger.Printf(" %2d: not running\n", status.NodeID)
} else {
config.Logger.Printf(" %2d: %s %s\n", status.NodeID, status.Version, status.Pid)
}
}
return nil
}),
}
var logsCmd = &cobra.Command{
Use: "logs",
Short: "retrieve and merge logs in a cluster",
Long: `Retrieve and merge logs in a cluster.
The "logs" command runs until terminated. It works similarly to get but is
specifically focused on retrieving logs periodically and then merging them
into a single stream.
`,
Args: cobra.RangeArgs(1, 2),
Run: wrap(func(cmd *cobra.Command, args []string) error {
logsOpts := roachprod.LogsOpts{
Dir: logsDir, Filter: logsFilter, ProgramFilter: logsProgramFilter,
Interval: logsInterval, From: logsFrom, To: logsTo, Out: cmd.OutOrStdout(),
}
var dest string
if len(args) == 2 {
dest = args[1]
} else {
dest = args[0] + ".logs"
}
return roachprod.Logs(config.Logger, args[0], dest, username, logsOpts)
}),
}
var monitorCmd = &cobra.Command{
Use: "monitor",
Short: "monitor the status of nodes in a cluster",
Long: `Monitor the status of cockroach nodes in a cluster.
The "monitor" command runs until terminated. At startup it outputs a line for
each specified node indicating the status of the node (either the PID of the
node if alive, or "dead" otherwise). It then watches for changes in the status
of nodes, outputting a line whenever a change is detected:
~ roachprod monitor local
1: 29688
3: 29689
2: 29687
3: dead
3: 30718
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
eventChan, err := roachprod.Monitor(context.Background(), config.Logger, args[0], monitorOpts)
if err != nil {
return err
}
for info := range eventChan {
fmt.Println(info.String())
}
return nil
}),
}
var signalCmd = &cobra.Command{
Use: "signal <cluster> <signal>",
Short: "send signal to cluster",
Long: "Send a POSIX signal, specified by its integer code, to every process started via roachprod in a cluster.",
Args: cobra.ExactArgs(2),
Run: wrap(func(cmd *cobra.Command, args []string) error {
sig, err := strconv.ParseInt(args[1], 10, 8)
if err != nil {
return errors.Wrapf(err, "invalid signal argument")
}
return roachprod.Signal(context.Background(), config.Logger, args[0], int(sig))
}),
}
var wipeCmd = &cobra.Command{
Use: "wipe <cluster>",
Short: "wipe a cluster",
Long: `Wipe the nodes in a cluster.
The "wipe" command first stops any processes running on the nodes in a cluster
(via the "stop" command) and then deletes the data directories used by the
nodes.
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
return roachprod.Wipe(context.Background(), config.Logger, args[0], wipePreserveCerts)
}),
}
var reformatCmd = &cobra.Command{
Use: "reformat <cluster> <filesystem>",
Short: "reformat disks in a cluster\n",
Long: `
Reformat disks in a cluster to use the specified filesystem.
WARNING: Reformatting will delete all existing data in the cluster.
Filesystem options:
ext4
zfs
When running with ZFS, you can create a snapshot of the filesystem's current
state using the 'zfs snapshot' command:
$ roachprod run <cluster> 'sudo zfs snapshot data1@pristine'
You can then nearly instantaneously restore the filesystem to this state with
the 'zfs rollback' command:
$ roachprod run <cluster> 'sudo zfs rollback data1@pristine'
`,
Args: cobra.ExactArgs(2),
Run: wrap(func(cmd *cobra.Command, args []string) error {
return roachprod.Reformat(context.Background(), config.Logger, args[0], args[1])
}),
}
var runCmd = &cobra.Command{
Use: "run <cluster> <command> [args]",
Aliases: []string{"ssh"},
Short: "run a command on the nodes in a cluster",
Long: `Run a command on the nodes in a cluster.
`,
Args: cobra.MinimumNArgs(1),
Run: wrap(func(_ *cobra.Command, args []string) error {
return roachprod.Run(context.Background(), config.Logger, args[0], extraSSHOptions, tag,
secure, os.Stdout, os.Stderr, args[1:], install.WithWaitOnFail())
}),
}
var resetCmd = &cobra.Command{
Use: "reset <cluster>",
Short: "reset *all* VMs in a cluster",
Long: `Reset a cloud VM. This may not be implemented for all
environments and will fall back to a no-op.`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) (retErr error) {
return roachprod.Reset(config.Logger, args[0])
}),
}
var installCmd = &cobra.Command{
Use: "install <cluster> <software>",
Short: "install 3rd party software",
Long: `Install third party software. Currently available installation options are:
` + strings.Join(install.SortedCmds(), "\n ") + `
`,
Args: cobra.MinimumNArgs(2),
Run: wrap(func(cmd *cobra.Command, args []string) error {
return roachprod.Install(context.Background(), config.Logger, args[0], args[1:])
}),
}
var downloadCmd = &cobra.Command{
Use: "download <cluster> <url> <sha256> [DESTINATION]",
Short: "download 3rd party tools",
Long: "Downloads 3rd party tools, using a GCS cache if possible.",
Args: cobra.RangeArgs(3, 4),
Run: wrap(func(cmd *cobra.Command, args []string) error {
src, sha := args[1], args[2]
var dest string
if len(args) == 4 {
dest = args[3]
}
return roachprod.Download(context.Background(), config.Logger, args[0], src, sha, dest)
}),
}
var stageURLCmd = &cobra.Command{
Use: "stageurl <application> [<sha/version>]",
Short: "print URL to cockroach binaries",
Long: `Prints URL for release and edge binaries.
Currently available application options are:
cockroach - Cockroach Unofficial. Can provide an optional SHA, otherwise
latest build version is used.
workload - Cockroach workload application.
release - Official CockroachDB Release. Must provide a specific release
version.
`,
Args: cobra.RangeArgs(1, 2),
Run: wrap(func(cmd *cobra.Command, args []string) error {
versionArg := ""
if len(args) == 2 {
versionArg = args[1]
}
urls, err := roachprod.StageURL(config.Logger, args[0], versionArg, stageOS, stageArch)
if err != nil {
return err
}
for _, u := range urls {
fmt.Println(u)
}
return nil
}),
}
var stageCmd = &cobra.Command{
Use: "stage <cluster> <application> [<sha/version>]",
Short: "stage cockroach binaries",
Long: `Stages release and edge binaries to the cluster.
Currently available application options are:
cockroach - Cockroach Unofficial. Can provide an optional SHA, otherwise
latest build version is used.
workload - Cockroach workload application.
release - Official CockroachDB Release. Must provide a specific release
version.
Some examples of usage:
-- stage edge build of cockroach build at a specific SHA:
roachprod stage my-cluster cockroach e90e6903fee7dd0f88e20e345c2ddfe1af1e5a97
-- Stage the most recent edge build of the workload tool:
roachprod stage my-cluster workload
-- Stage the official release binary of CockroachDB at version 2.0.5
roachprod stage my-cluster release v2.0.5
`,
Args: cobra.RangeArgs(2, 3),
Run: wrap(func(cmd *cobra.Command, args []string) error {
versionArg := ""
if len(args) == 3 {
versionArg = args[2]
}
return roachprod.Stage(context.Background(), config.Logger, args[0], stageOS, stageArch, stageDir, args[1], versionArg)
}),
}
var distributeCertsCmd = &cobra.Command{
Use: "distribute-certs <cluster>",
Short: "distribute certificates to the nodes in a cluster",
Long: `Distribute certificates to the nodes in a cluster.
If the certificates already exist, no action is taken. Note that this command is
invoked automatically when a secure cluster is bootstrapped by "roachprod
start."
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
return roachprod.DistributeCerts(context.Background(), config.Logger, args[0])
}),
}
var putCmd = &cobra.Command{
Use: "put <cluster> <src> [<dest>]",
Short: "copy a local file to the nodes in a cluster",
Long: `Copy a local file to the nodes in a cluster.
`,
Args: cobra.RangeArgs(2, 3),
Run: wrap(func(cmd *cobra.Command, args []string) error {
src := args[1]
dest := path.Base(src)
if len(args) == 3 {
dest = args[2]
}
return roachprod.Put(context.Background(), config.Logger, args[0], src, dest, useTreeDist)
}),
}
var getCmd = &cobra.Command{
Use: "get <cluster> <src> [<dest>]",
Short: "copy a remote file from the nodes in a cluster",
Long: `Copy a remote file from the nodes in a cluster. If the file is retrieved from
multiple nodes the destination file name will be prefixed with the node number.
`,
Args: cobra.RangeArgs(2, 3),
Run: wrap(func(cmd *cobra.Command, args []string) error {
src := args[1]
dest := path.Base(src)
if len(args) == 3 {
dest = args[2]
}
return roachprod.Get(context.Background(), config.Logger, args[0], src, dest)
}),
}
var sqlCmd = &cobra.Command{
Use: "sql <cluster> -- [args]",
Short: "run `cockroach sql` on a remote cluster",
Long: "Run `cockroach sql` on a remote cluster.\n",
Args: cobra.MinimumNArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
return roachprod.SQL(context.Background(), config.Logger, args[0], secure, virtualClusterName, sqlInstance, args[1:])
}),
}
var pgurlCmd = &cobra.Command{
Use: "pgurl <cluster>",
Short: "generate pgurls for the nodes in a cluster",
Long: `Generate pgurls for the nodes in a cluster.
`,
Args: cobra.ExactArgs(1),
Run: wrap(func(cmd *cobra.Command, args []string) error {
urls, err := roachprod.PgURL(context.Background(), config.Logger, args[0], pgurlCertsDir, roachprod.PGURLOptions{
External: external,
Secure: secure,
VirtualClusterName: virtualClusterName,
SQLInstance: sqlInstance,
})
if err != nil {
return err
}
fmt.Println(strings.Join(urls, " "))
return nil
}),
}
var pprofCmd = &cobra.Command{
Use: "pprof <cluster>",
Args: cobra.ExactArgs(1),
Aliases: []string{"pprof-heap"},
Short: "capture a pprof profile from the specified nodes",
Long: `Capture a pprof profile from the specified nodes.
Examples:
# Capture CPU profile for all nodes in the cluster
roachprod pprof CLUSTERNAME
# Capture CPU profile for the first node in the cluster for 60 seconds
roachprod pprof CLUSTERNAME:1 --duration 60s
# Capture a Heap profile for the first node in the cluster
roachprod pprof CLUSTERNAME:1 --heap
# Same as above
roachprod pprof-heap CLUSTERNAME:1
`,
Run: wrap(func(cmd *cobra.Command, args []string) error {