/
dev.go
1020 lines (900 loc) · 27.8 KB
/
dev.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 Chef Software
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptrace"
"os"
"reflect"
"strings"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
dc "github.com/chef/automate/api/config/deployment"
w "github.com/chef/automate/api/config/shared/wrappers"
api "github.com/chef/automate/api/interservice/deployment"
"github.com/chef/automate/components/automate-cli/pkg/adminmgmt"
"github.com/chef/automate/components/automate-cli/pkg/client/apiclient"
"github.com/chef/automate/components/automate-cli/pkg/dev/hab"
"github.com/chef/automate/components/automate-cli/pkg/docs"
"github.com/chef/automate/components/automate-cli/pkg/status"
"github.com/chef/automate/components/automate-deployment/pkg/a1upgrade"
"github.com/chef/automate/components/automate-deployment/pkg/bind"
"github.com/chef/automate/components/automate-deployment/pkg/bootstrap"
"github.com/chef/automate/components/automate-deployment/pkg/client"
"github.com/chef/automate/components/automate-deployment/pkg/constants"
"github.com/chef/automate/components/automate-deployment/pkg/habapi"
"github.com/chef/automate/components/automate-deployment/pkg/habpkg"
"github.com/chef/automate/components/automate-deployment/pkg/manifest"
mc "github.com/chef/automate/components/automate-deployment/pkg/manifest/client"
"github.com/chef/automate/components/automate-deployment/pkg/services"
"github.com/chef/automate/components/automate-deployment/pkg/target"
"github.com/chef/automate/components/automate-grpc/protoc-gen-a2-config/api/a2conf"
"github.com/chef/automate/lib/platform/command"
"github.com/chef/automate/lib/platform/pg"
"github.com/chef/automate/lib/stringutils"
)
// Since cobra's pattern for handling flag variables favors globals,
// we encapsulate flags used by this subcommand in a struct to avoid
// conflicts with other flags from other subcommands living in package
// main.
var devCmdFlags = struct {
configFilePath string
docsPath string
docsFormat string
hartifactsPath string
overrideOrigin string
withDeps bool
manifestDir string
enableChefServer bool
enableWorkflow bool
// service-deps option
reverse bool
}{}
func init() {
devCmd.AddCommand(configureDeploymentCmd())
devCmd.AddCommand(newBootstrapCmd())
devCmd.AddCommand(doDeployCmd)
devCmd.AddCommand(genDocsCmd())
devCmd.AddCommand(newDeploySomeCmd())
devCmd.AddCommand(removeSomeCmd)
devCmd.AddCommand(startConvergeCmd)
devCmd.AddCommand(stopConvergeCmd)
devCmd.AddCommand(newDumpA1PGCmd())
devCmd.AddCommand(newExtractA1UserData())
devCmd.AddCommand(newRunA1BackupCmd())
devCmd.AddCommand(newReindexEs2Cmd())
devCmd.AddCommand(psqlCmd)
devCmd.AddCommand(newDepsCmd())
devCmd.AddCommand(defaultCfg)
devCmd.AddCommand(grpCurlCmd)
devCmd.AddCommand(newGetURLCmd())
devCmd.AddCommand(newDevPortCmd())
devCmd.AddCommand(newVerifyPackagesCmd())
devCmd.AddCommand(newEnablePrometheusCmd())
devCmd.AddCommand(newDisablePrometheusCmd())
devCmd.AddCommand(newCreateIAMDevUsersCmd())
devCmd.AddCommand(newCerealCmd())
RootCmd.AddCommand(devCmd)
}
var devCmd = &cobra.Command{
Use: "dev COMMAND",
Short: "Utilities for Chef Automate development",
Hidden: true,
}
func newBootstrapCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "bootstrap",
Short: "Install hab and the deployment service on localhost.",
RunE: runBootstrapCmd,
}
cmd.Flags().StringVarP(&devCmdFlags.configFilePath,
"config", "c", "config.toml", "Config file path")
cmd.Flags().StringVar(&devCmdFlags.hartifactsPath,
"hartifacts", "results", "Path containing locally built hart packages to use instead of depot packages")
cmd.Flags().StringVar(&devCmdFlags.overrideOrigin,
"override-origin", os.Getenv("HAB_ORIGIN"), "Origin from which to install local hart packages")
cmd.Flags().StringVar(&devCmdFlags.manifestDir,
"manifest-dir", "", "Path for local manifest files")
return cmd
}
func runBootstrapCmd(cmd *cobra.Command, args []string) error {
conf, err := getDevDeploymentConfig()
if err != nil {
return status.Wrap(err, status.ConfigError, "Loading dev configuration failed")
}
tgt := target.NewLocalTarget(false)
writer.Println("Fetching release manifest")
manifestProvider := manifest.NewLocalHartManifestProvider(
mc.NewDefaultClient(devCmdFlags.manifestDir),
devCmdFlags.hartifactsPath,
devCmdFlags.overrideOrigin)
m, err := manifestProvider.GetCurrentManifest(context.Background(), "dev")
if err != nil {
return status.Wrap(err, status.DeployError, "Fetching the manifest failed")
}
mergedCfg, err := dc.MergeWithDefaults(conf)
if err != nil {
return status.Wrap(err, status.DeployError, "Merging config with defaults failed")
}
mergedCfg.SetGlobalConfig()
client.SetProxyEnvironment(conf.Deployment)
b := bootstrap.NewCompatBootstrapper(tgt)
err = bootstrap.FullBootstrap(context.TODO(), b, m, mergedCfg.GetDeployment(), "", writer)
if err != nil {
return status.Annotate(err, status.DeployError)
}
return nil
}
func configureDeploymentCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "configure-deployment",
RunE: runConfigureDeploymentCmd,
}
cmd.Flags().StringVarP(&devCmdFlags.configFilePath,
"config", "c", "config.toml", "Config file path")
cmd.Flags().StringVar(&devCmdFlags.hartifactsPath,
"hartifacts", "results", "Path containing locally built hart packages to use instead of depot packages")
cmd.Flags().StringVar(&devCmdFlags.overrideOrigin,
"override-origin", os.Getenv("HAB_ORIGIN"), "Origin from which to install local hart packages")
cmd.Flags().StringVar(&devCmdFlags.manifestDir,
"manifest-dir", "", "Directory containing A2 manifest files")
return cmd
}
func runConfigureDeploymentCmd(cmd *cobra.Command, args []string) error {
conf, err := getDevDeploymentConfig()
if err != nil {
return status.Wrap(err, status.ConfigError, "Loading dev configuration failed")
}
connection, err := client.Connection(client.DefaultClientTimeout)
if err != nil {
return err
}
ctx := context.Background()
dr := &api.ConfigureDeploymentRequest{Config: conf}
resp, err := connection.ConfigureDeployment(ctx, dr)
if err != nil {
return status.Wrap(
err,
status.DeploymentServiceCallError,
"Request to configure the deployment failed",
)
}
writer.Title("Configured deployment " + resp.DeploymentId.GetId())
return nil
}
func getDevDeploymentConfig() (*dc.AutomateConfig, error) {
return dc.LoadUserOverrideConfigFile(
devCmdFlags.configFilePath,
dc.WithManifestDir(devCmdFlags.manifestDir),
dc.WithHartifacts(devCmdFlags.hartifactsPath),
dc.WithOrigin(devCmdFlags.overrideOrigin),
)
}
var doDeployCmd = &cobra.Command{
Use: "deployinate",
RunE: runDoDeployCmd,
Short: "Deploys all services",
}
func runDoDeployCmd(cmd *cobra.Command, args []string) error {
//// DoDeploy runs the core deployment and skips the bootstrap steps
//func (cliApp *App) DoDeploy() error {
writer.Title("Starting execution of deployment")
connection, err := client.Connection(client.DefaultDeployTimeout)
if err != nil {
return err
}
ctx := context.Background()
resp, err := connection.Deploy(ctx, &api.DeployRequest{})
if err != nil {
return status.Wrap(
err,
status.DeployError,
"Request to deploy Chef Automate failed",
)
}
deploymentID := &api.DeploymentID{}
taskID := resp.TaskId
h := &client.CLIEventWriter{Writer: writer}
err = connection.StreamDeployEvents(taskID, deploymentID, h)
if err != nil {
return status.Wrap(
err,
status.DeploymentServiceCallError,
"Request to stream deployment events failed",
)
}
return nil
}
func newDeploySomeCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "deploy-some <svc1> ...",
RunE: runDeploySomeCmd,
Short: "Deploys the specified services.",
Long: "Deploys the specified services. Specify services as origin/name.",
}
cmd.Flags().BoolVar(&devCmdFlags.withDeps,
"with-deps", false, "Whether to deploy required dependencies as well")
return cmd
}
func runDeploySomeCmd(cmd *cobra.Command, args []string) error {
var servicesToDeploy []string
if devCmdFlags.withDeps {
serviceIDs, err := services.ServicesInCollection("automate-full")
if err != nil {
return status.Wrap(err, status.DeployError, "Failed to load list of services")
}
sortedDeps, err := bind.TopoSort(args, serviceIDs, services.AllBinds)
if err != nil {
return status.Wrap(err, status.DeployError, "Dependency resolution for given services failed")
}
servicesToDeploy = make([]string, len(sortedDeps))
for i, s := range sortedDeps {
servicesToDeploy[i] = habpkg.Ident(&s)
}
} else {
servicesToDeploy = args
}
msg := fmt.Sprintf("Starting deployment of %d services", len(servicesToDeploy))
writer.Title(msg)
connection, err := client.Connection(client.DefaultDeployTimeout)
if err != nil {
return err
}
ctx := context.Background()
req := &api.DeployRequest{
Services: servicesToDeploy,
}
resp, err := connection.DeploySome(ctx, req)
if err != nil {
return status.Wrap(
err,
status.DeploymentServiceCallError,
"Request to deploy some Chef Automate services failed",
)
}
deploymentID := &api.DeploymentID{}
h := &client.CLIEventWriter{Writer: writer}
err = connection.StreamDeployEvents(resp.TaskId, deploymentID, h)
if err != nil {
return status.Wrap(
err,
status.DeploymentServiceCallError,
"Request to stream deployment events failed",
)
}
return nil
}
func newDepsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "service-deps SERVICE...",
RunE: runDepsCmd,
Short: "Print the dependencies of the given service",
}
cmd.Flags().BoolVar(&devCmdFlags.reverse,
"reverse", false, "Print the reverse dependency list.")
return cmd
}
func runDepsCmd(cmd *cobra.Command, args []string) error {
serviceIDs, err := services.ServicesInCollection("automate-full")
if err != nil {
return status.Wrap(err, status.DeployError, "Failed to load list of services")
}
var sortedDeps []habpkg.HabPkg
if devCmdFlags.reverse {
sortedDeps, err = bind.RDeps(args, serviceIDs, services.AllBinds)
if err != nil {
return status.Wrap(err, status.DeployError, "Dependency resolution for given services failed")
}
} else {
sortedDeps, err = bind.TopoSort(args, serviceIDs, services.AllBinds)
if err != nil {
return status.Wrap(err, status.DeployError, "Dependency resolution for given services failed")
}
}
for _, s := range sortedDeps {
writer.Println(habpkg.Ident(&s))
}
return nil
}
var removeSomeCmd = &cobra.Command{
Use: "remove-some [svc1 svc2 svcN...]",
RunE: runRemoveSomeCmd,
Short: "Removes the specified services.",
Long: "Removes the specified services. Specify services as origin/name.",
}
func runRemoveSomeCmd(cmd *cobra.Command, svcNames []string) error {
//// RemoveSome removes the provided slice of services.
//// Elements of svcNames should be in the form origin/name.
//func (cliApp *App) RemoveSome(svcNames []string) error {
msg := fmt.Sprintf("Starting removal of %d services", len(svcNames))
writer.Title(msg)
// Use the same timeout for deploy and remove
connection, err := client.Connection(client.DefaultDeployTimeout)
if err != nil {
return err
}
ctx := context.Background()
req := &api.RemoveRequest{
Services: svcNames,
}
_, err = connection.RemoveSome(ctx, req)
if err != nil {
return status.Wrap(
err,
status.DeploymentServiceCallError,
"Request to remove some Chef Automate services failed",
)
}
writer.Title("Services removed.")
return nil
}
var stopConvergeCmd = &cobra.Command{
Use: "stop-converge",
RunE: runStopConvergeCmd,
Short: "Stops the periodic converge loop.",
Long: "Stops the periodic converge loop. Does nothing if the converge loop is already stopped.",
}
func runStopConvergeCmd(cmd *cobra.Command, _ []string) error {
//// StopConverge stops the periodic converge loop. Dev only for now
//func (cliApp *App) StopConverge() error {
connection, err := client.Connection(client.DefaultClientTimeout)
if err != nil {
return err
}
_, err = connection.StopConverge(context.Background(), &api.StopConvergeRequest{})
if err != nil {
return status.Wrap(
err,
status.DeploymentServiceCallError,
"Request to stop the deployment-service converge loop failed",
)
}
writer.Title("Stopped converge loop.")
return nil
}
var startConvergeCmd = &cobra.Command{
Use: "start-converge",
RunE: runStartConvergeCmd,
Short: "Starts the periodic converge loop.",
Long: "Starts the periodic converge loop. Does nothing if the converge loop is already running.",
}
func runStartConvergeCmd(cmd *cobra.Command, _ []string) error {
connection, err := client.Connection(client.DefaultClientTimeout)
if err != nil {
return err
}
_, err = connection.StartConverge(context.Background(), &api.StartConvergeRequest{})
if err != nil {
return status.Wrap(
err,
status.DeploymentServiceCallError,
"Request to start the deployment-service converge loop failed",
)
}
writer.Title("Started converge loop.")
return nil
}
func genDocsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "generate-docs",
RunE: runGenDocsCmd,
Short: "Generate docs.",
Long: "Generate docs.",
Annotations: map[string]string{
NoCheckVersionAnnotation: NoCheckVersionAnnotation,
NoRequireRootAnnotation: NoRequireRootAnnotation,
},
}
cmd.Flags().StringVar(&devCmdFlags.docsPath,
"docs-dir", "./", "Directory where generated documentation will be put")
cmd.Flags().StringVar(&devCmdFlags.docsFormat,
"format", "yaml", `Generated documentation format. Only "yaml" is supported for now`)
return cmd
}
func runGenDocsCmd(cmd *cobra.Command, _ []string) error {
switch devCmdFlags.docsFormat {
case "yaml":
if err := docs.GenYamlTree(RootCmd, devCmdFlags.docsPath); err != nil {
return status.Wrap(err, status.ConfigError, "Documentation generation failed")
}
default:
return status.New(status.InvalidCommandArgsError, `"yaml" is the only acceptable format.`)
}
return nil
}
func newDumpA1PGCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "a1-dump-pg",
RunE: runDumpA1PG,
Short: "Dump an A1 postgres database using the same method the actual upgrade does",
}
cmd.PersistentFlags().StringVarP(
&migrateCmdFlags.a2ConfigPath,
"config",
"c",
"",
"Path to an automate-deploy.toml")
cmd.PersistentFlags().BoolVar(
&migrateCmdFlags.enableChefServer,
"enable-chef-server",
false,
"Enable integrated Chef Server migration and deployment; only valid for all-in-one topology")
cmd.PersistentFlags().BoolVar(
&migrateCmdFlags.enableWorkflow,
"enable-workflow",
false,
"Enable integrated Workflow Server migration and deployment; only valid for all-in-one topology")
cmd.PersistentFlags().IntVar(
&migrateCmdFlags.pgDumpSeconds,
"postgres-dump-wait-seconds",
300,
"Optional max wait for Chef Automate v1 PostgreSQL dump (default = 300 seconds)")
return cmd
}
func newExtractA1UserData() *cobra.Command {
cmd := &cobra.Command{
Use: "a1-extract-user-data",
RunE: runExtractA1UserData,
Short: "Extract A1 User Data",
}
cmd.PersistentFlags().StringVarP(
&migrateCmdFlags.a2ConfigPath,
"config",
"c",
"",
"Path to an automate-deploy.toml")
cmd.PersistentFlags().IntVar(
&migrateCmdFlags.pgDumpSeconds,
"postgres-dump-wait-seconds",
300,
"Optional max wait for Chef Automate v1 PostgreSQL dump (default = 300 seconds)")
return cmd
}
func runDumpA1PG(cmd *cobra.Command, _ []string) error {
migration, err := newLocalMigration()
if err != nil {
return status.Wrap(err, status.ConfigError, "Configuring database dump operation failed")
}
if err = client.A1PgDump(writer, migration); err != nil {
return status.Wrap(err, status.UpgradeError, "Database dump failed")
}
return nil
}
func runExtractA1UserData(cmd *cobra.Command, _ []string) error {
migration, err := newLocalMigration()
if err != nil {
return status.Wrap(err, status.ConfigError, "Configuring database user data extraction failed")
}
if err = client.A1ExtractUserData(writer, migration); err != nil {
return status.Wrap(err, status.UpgradeError, "Database user data extraction failed")
}
if err = client.A1ExtractUserRolesData(writer, migration); err != nil {
return status.Wrap(err, status.UpgradeError, "Database user roles data extraction failed")
}
return nil
}
func newRunA1BackupCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "a1-create-backup",
RunE: runA1Backup,
Short: "Run automate-ctl create-backup and display progress",
}
return cmd
}
func runA1Backup(cmd *cobra.Command, backupNameList []string) error {
u, err := a1upgrade.NewA1Upgrade(
a1upgrade.WithDeliveryRunning("/etc/delivery/delivery-running.json"),
a1upgrade.WithDeliverySecrets("/etc/delivery/delivery-secrets.json"),
)
if err != nil {
return status.Wrap(err, status.ConfigError, "Configuring A1 backup failed")
}
if err = client.DevA1Backup(writer, u); err != nil {
return err
}
return nil
}
func newReindexEs2Cmd() *cobra.Command {
cmd := &cobra.Command{
Use: "a1-reindex-es2",
RunE: runReindexEs2,
Short: "Run es2 reindex process against localhost:9200",
}
return cmd
}
func runReindexEs2(cmd *cobra.Command, args []string) error {
r, err := a1upgrade.NewReindexer(writer, "http://localhost:9200")
if err != nil {
return status.Wrap(err, status.ConfigError, "Configuring A1 Elasticsearch re-indexer failed")
}
if err = r.RunReindex(); err != nil {
return status.Wrap(err, status.UpgradeError, "A1 Elasticsearch re-index failed")
}
return nil
}
var psqlCmd = &cobra.Command{
Use: "psql",
RunE: runPsql,
Short: "Run psql as the PostgreSQL superuser",
Args: cobra.ArbitraryArgs,
}
func runPsql(cmd *cobra.Command, args []string) error {
connInfo := pg.A2ConnInfo{
Host: "localhost",
Port: 5432,
User: "automate",
Certs: pg.A2SuperuserCerts,
}
pager := os.Getenv("PAGER")
if pager == "" {
pager = "less"
}
psqlArgs := append(pg.PSQLCmd(), args...)
psqlOpts := append(connInfo.PsqlCmdOptions(),
command.Envvar("PAGER", pager),
command.Args(psqlArgs[1:]...),
command.Stderr(os.Stderr),
command.Stdout(os.Stdout),
command.Stdin(os.Stdin))
return command.Run(psqlArgs[0], psqlOpts...)
}
var defaultCfg = &cobra.Command{
Use: "default-config",
RunE: runDefaultConfig,
Short: "Display the default config",
}
func runDefaultConfig(cmd *cobra.Command, args []string) error {
cfgToml, err := dc.DefaultAutomateConfig().MarshalToTOML()
if err != nil {
return status.Wrap(
err,
status.MarshalError,
"Marshaling configuration to TOML failed",
)
}
writer.Println(string(cfgToml))
return nil
}
func newGetURLCmd() *cobra.Command {
c := &cobra.Command{
Use: "get-url URL",
RunE: runGetURL,
Short: "Fetch the given URL using Go.",
Args: cobra.ExactArgs(1),
Long: "Fetches the given URL using Go. Useful for debugging CDN issues that can't be reproduced with curl",
Annotations: map[string]string{
NoRequireRootAnnotation: NoRequireRootAnnotation,
},
}
return c
}
func runGetURL(cmd *cobra.Command, args []string) error {
req, err := http.NewRequest("GET", args[0], nil)
if err != nil {
return errors.Wrap(err, "creating request")
}
trace := &httptrace.ClientTrace{
DNSDone: func(d httptrace.DNSDoneInfo) {
addrStrs := make([]string, len(d.Addrs))
for i, addr := range d.Addrs {
addrStrs[i] = addr.String()
}
if d.Err != nil {
// It wasn't clear to me in the docs
// whether d.Err != nil is always
// fatal, so we still log the
// addresses here.
logrus.Debugf("HTTP TRACE: %q resolved to %v (with error: %s)",
req.URL.Host, addrStrs, d.Err.Error())
return
}
logrus.Debugf("HTTP TRACE: %q resolved to %v", req.URL.Host, addrStrs)
},
GotConn: func(c httptrace.GotConnInfo) {
logrus.Debugf("HTTP TRACE: connected to %q (reused: %t) (was idle: %t)",
c.Conn.RemoteAddr(), c.Reused, c.WasIdle)
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
c := http.Client{}
response, err := c.Do(req)
if err != nil {
return errors.Wrap(err, "sending request")
}
defer func() {
_ = response.Body.Close()
}()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return errors.Wrap(err, "reading response body")
}
for k, v := range response.Header {
logrus.Debugf("HTTP RESPONSE HEADER %s: %s", k, strings.Join(v, ", "))
}
fmt.Println(string(bodyBytes))
return nil
}
var grpCurlCmd = &cobra.Command{
Use: "grpcurl SERVICE_NAME",
RunE: runGRPCurl,
Short: "Run grpcurl with connection information for SERVICE_NAME",
Args: cobra.MinimumNArgs(1),
Long: `Run grpcurl with connection information for SERVICE_NAME.
To pass options to grpcurl, use --
chef-automate dev grpcurl SERVICE_NAME -- GRPCURL_OPTIONS
`,
}
var grpcOptsWithArgs = []string{
"-H",
"-authority",
"-cacert",
"-cert",
"-connect-timeout",
"-d",
"-import-path",
"-keepalive-time",
"-key",
"-max-time",
"-proto",
"-protoset",
"-reflect-header",
"-rpc-header",
"-servername",
}
func runGRPCurl(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
svcName := args[0]
grpcPkg := habpkg.New("core", "grpcurl")
habcmd := target.NewHabCmd(command.DefaultExecutor, false)
installed, err := habcmd.IsInstalled(ctx, &grpcPkg)
if err != nil {
return status.Wrap(
err,
status.HabCommandError,
"Failed to determine if grpcurl is available",
)
}
if !installed {
return status.New(status.UnknownError, "core/grpcurl is not installed")
}
c := habapi.New("http://localhost:9631")
svcs, err := c.ListServices(ctx)
if err != nil {
return status.Wrap(
err,
status.HabAPIError,
"Failed to list services from habitat",
)
}
port, found := habapi.PortForService(svcs, svcName)
if !found {
return status.Errorf(status.HabAPIError, "Could not find port for %q", svcName)
}
// grpcurl has very finicky option parsing
grpcOpts := []string{}
grpcArgs := []string{}
for i := 1; i < len(args); i++ {
if strings.HasPrefix(args[i], "-") {
grpcOpts = append(grpcOpts, args[i])
if stringutils.SliceContains(grpcOptsWithArgs, args[i]) {
grpcOpts = append(grpcOpts, args[i+1])
i++
}
} else {
grpcArgs = append(grpcArgs, args[i])
}
}
cmdArgs := append([]string{
"pkg", "exec", "core/grpcurl", "grpcurl",
"-servername", svcName,
"-cacert", constants.RootCertPath,
"-key", constants.KeyPath,
"-cert", constants.CertPath,
}, grpcOpts...)
// TODO(multinode) 2018-11-02: Get host
cmdArgs = append(cmdArgs, fmt.Sprintf("localhost:%d", port))
cmdArgs = append(cmdArgs, grpcArgs...)
return command.Run("hab",
command.Envvar("HAB_LICENSE", "accept-no-persist"),
command.Args(cmdArgs...),
command.Stderr(os.Stderr),
command.Stdout(os.Stdout),
command.Stdin(os.Stdin))
}
func newDevPortCmd() *cobra.Command {
list := &cobra.Command{
Use: "list",
Short: "List used default ports",
RunE: func(cmd *cobra.Command, args []string) error {
cfg := dc.AutomateConfig{}
a2ServiceConfigType := reflect.TypeOf((*a2conf.A2ServiceConfig)(nil)).Elem()
a := reflect.TypeOf(cfg)
writer.Bodyf("%-30s%-10s\t%-10s\t%-10s", "Service Name", "Port Name", "Default", "Protocol")
for i := 0; i < a.NumField(); i++ {
f := a.Field(i)
if f.Type.Implements(a2ServiceConfigType) {
v := (reflect.New(f.Type.Elem()).Interface()).(a2conf.A2ServiceConfig)
ports := v.ListPorts()
for _, p := range ports {
writer.Bodyf("%-30s%-10s\t%-10d\t%-10s", v.ServiceName(), p.Name, p.Default, p.Protocol)
}
}
}
return nil
},
}
portMapFunc := func() (map[uint16]string, error) {
portMap := make(map[uint16]string)
cfg := dc.AutomateConfig{}
a2ServiceConfigType := reflect.TypeOf((*a2conf.A2ServiceConfig)(nil)).Elem()
a := reflect.TypeOf(cfg)
for i := 0; i < a.NumField(); i++ {
f := a.Field(i)
if f.Type.Implements(a2ServiceConfigType) {
v := (reflect.New(f.Type.Elem()).Interface()).(a2conf.A2ServiceConfig)
ports := v.ListPorts()
for _, p := range ports {
if n := portMap[p.Default]; n != "" {
return nil, errors.Errorf("Default port %d is being used by %s and %s/%s", p.Default, n, v.ServiceName(), p.Name)
}
portMap[p.Default] = fmt.Sprintf("%s/%s", v.ServiceName(), p.Name)
}
}
}
return portMap, nil
}
unique := &cobra.Command{
Use: "unique",
Short: "Asserts ports are unique",
RunE: func(cmd *cobra.Command, args []string) error {
_, err := portMapFunc()
if err != nil {
return err
}
return nil
},
}
free := &cobra.Command{
Use: "free",
Short: "List free ports",
RunE: func(cmd *cobra.Command, args []string) error {
portMap, err := portMapFunc()
if err != nil {
return err
}
c := 0
for i := uint16(10100); i < 10200; i++ {
if portMap[i] == "" {
writer.Printf("%-6d", i)
c++
}
if c%10 == 0 {
writer.Printf("\n")
}
}
if c%10 != 0 {
writer.Printf("\n")
}
return nil
},
}
cmd := &cobra.Command{
Use: "ports",
}
cmd.AddCommand(list)
cmd.AddCommand(unique)
cmd.AddCommand(free)
return cmd
}
func newVerifyPackagesCmd() *cobra.Command {
c := &cobra.Command{
Use: "verify-packages",
RunE: func(*cobra.Command, []string) error {
return hab.VerifyHabPackages()
},
Short: "Verify installed hab packages",
Args: cobra.NoArgs,
Annotations: map[string]string{
NoRequireRootAnnotation: NoRequireRootAnnotation,
},
}
return c
}
func newEnablePrometheusCmd() *cobra.Command {
return &cobra.Command{
Use: "enable-prometheus",
RunE: runEnablePrometheusCmd,
Short: "Configure automate to run the automate-prometheus metrics gathering service",
Args: cobra.NoArgs,
Annotations: map[string]string{
NoRequireRootAnnotation: NoRequireRootAnnotation,
},
}
}
func newDisablePrometheusCmd() *cobra.Command {
return &cobra.Command{
Use: "disable-prometheus",
RunE: runDisablePrometheusCmd,
Short: "Configure automate to no longer run the automate-prometheus metrics gathering service",
Args: cobra.NoArgs,
Annotations: map[string]string{
NoRequireRootAnnotation: NoRequireRootAnnotation,
},
}
}
func newCreateIAMDevUsersCmd() *cobra.Command {
return &cobra.Command{
Use: "create-iam-dev-users",
RunE: runCreateIAMDevUsersCmd,
Short: `Create IAM dev users ("viewer" and "editor") idempotently`,
Args: cobra.NoArgs,
}
}
// Equivalent to patching the config with the following toml:
// [deployment.v1.svc]
// enable_dev_monitoring = true
func runEnablePrometheusCmd(*cobra.Command, []string) error {
cfg := &dc.AutomateConfig{
Deployment: &dc.ConfigRequest{
V1: &dc.ConfigRequest_V1{
Svc: &dc.ConfigRequest_V1_Service{
EnableDevMonitoring: w.Bool(true),
},
},
},
}
if err := client.PatchAutomateConfig(configCmdFlags.timeout, cfg, writer); err != nil {
return err
}
return nil
}
func runDisablePrometheusCmd(*cobra.Command, []string) error {
cfg := &dc.AutomateConfig{
Deployment: &dc.ConfigRequest{
V1: &dc.ConfigRequest_V1{
Svc: &dc.ConfigRequest_V1_Service{
EnableDevMonitoring: w.Bool(false),
},
},
},
}
if err := client.PatchAutomateConfig(configCmdFlags.timeout, cfg, writer); err != nil {
return err
}
return nil
}
func runCreateIAMDevUsersCmd(*cobra.Command, []string) error {
ctx := context.TODO()
apiClient, err := apiclient.OpenConnection(ctx)
if err != nil {
return err
}
for username, data := range map[string]struct {
displayName, password, teamID string
}{
"viewer": {"Viewer User", "chefautomate", "viewers"},
"editor": {"Editor User", "chefautomate", "editors"},