-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
sg_msp.go
1034 lines (943 loc) · 34.5 KB
/
sg_msp.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
// Package msp exports the 'sg msp' command for the Managed Services Platform.
package msp
import (
"context"
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"github.com/jomei/notionapi" // we use this for file uploads
"github.com/urfave/cli/v2"
"go.uber.org/atomic"
"golang.org/x/exp/maps"
"github.com/sourcegraph/conc/pool"
"github.com/sourcegraph/notionreposync/notion"
"github.com/sourcegraph/run"
"github.com/sourcegraph/sourcegraph/dev/managedservicesplatform"
"github.com/sourcegraph/sourcegraph/dev/managedservicesplatform/googlesecretsmanager"
"github.com/sourcegraph/sourcegraph/dev/managedservicesplatform/operationdocs"
"github.com/sourcegraph/sourcegraph/dev/managedservicesplatform/spec"
"github.com/sourcegraph/sourcegraph/dev/managedservicesplatform/stacks"
"github.com/sourcegraph/sourcegraph/dev/managedservicesplatform/stacks/cloudrun"
"github.com/sourcegraph/sourcegraph/dev/managedservicesplatform/stacks/iam"
"github.com/sourcegraph/sourcegraph/dev/managedservicesplatform/terraformcloud"
"github.com/sourcegraph/sourcegraph/dev/sg/cloudsqlproxy"
"github.com/sourcegraph/sourcegraph/dev/sg/internal/category"
"github.com/sourcegraph/sourcegraph/dev/sg/internal/open"
"github.com/sourcegraph/sourcegraph/dev/sg/internal/secrets"
"github.com/sourcegraph/sourcegraph/dev/sg/internal/std"
"github.com/sourcegraph/sourcegraph/dev/sg/msp/example"
msprepo "github.com/sourcegraph/sourcegraph/dev/sg/msp/repo"
"github.com/sourcegraph/sourcegraph/dev/sg/msp/schema"
"github.com/sourcegraph/sourcegraph/lib/errors"
"github.com/sourcegraph/sourcegraph/lib/output"
"github.com/sourcegraph/sourcegraph/lib/pointers"
)
// Command is the 'sg msp' toolchain for the Managed Services Platform:
// https://handbook.sourcegraph.com/departments/engineering/teams/core-services/managed-services/platform
var Command = &cli.Command{
Name: "managed-services-platform",
Aliases: []string{"msp"},
Usage: "Generate and manage services deployed on the Sourcegraph Managed Services Platform (MSP)",
Description: `To learm more about MSP, refer to go/msp (https://sourcegraph.notion.site/712a0389f54c4d3a90d069aa2d979a59).
MSP infrastructure manifests are managed in https://github.com/sourcegraph/managed-services - many commands expect you to be operating within a local copy of this repository.
Refer to https://github.com/sourcegraph/managed-services/blob/main/README.md#tooling-setup for more information.
Please reach out to #discuss-core-services for assistance if you have any questions!`,
Category: category.Company,
Subcommands: []*cli.Command{
{
Name: "init",
ArgsUsage: "<service ID>",
Usage: "Initialize a template Managed Services Platform service spec",
UsageText: `
sg msp init -owner core-services -name "MSP Example Service" msp-example
`,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "kind",
Usage: "Kind of service (one of: 'service', 'job')",
Value: "service",
},
&cli.StringFlag{
Name: "owner",
Usage: "Name of team owning this new service",
},
&cli.StringFlag{
Name: "name",
Usage: "Specify a human-readable name for this service",
},
&cli.BoolFlag{
Name: "dev",
Usage: "Generate a dev environment",
},
&cli.IntFlag{
Name: "project-id-suffix-length",
Usage: "Length of random suffix appended to generated project IDs",
Value: spec.DefaultSuffixLength,
},
},
Before: msprepo.UseManagedServicesRepo,
Action: func(c *cli.Context) error {
if c.Args().Len() > 1 {
return errors.New("exactly 1 argument allowed: the desired service ID, or no arguments to use interactive setup")
}
// Track if no args were provided at all to guide interactive
// setup features
fullyInteractive := c.Args().Len() == 0
// Collect required inputs
template := example.Template{
ID: c.Args().First(),
Name: c.String("name"),
Owner: c.String("owner"),
Dev: c.Bool("dev"),
ProjectIDSuffixLength: c.Int("project-id-suffix-length"),
}
if template.ID == "" {
std.Out.Write("Please provide an all-lowercase, dash-delimited, machine-friendly identifier for your new service, e.g. 'my-service'.")
ok, err := std.PromptAndScan(std.Out, "Service ID:", &template.ID)
if err != nil {
return err
} else if !ok {
return errors.New("response is required")
}
}
if allServices, err := msprepo.ListServices(); err != nil {
return errors.Wrap(err, "checking existing services")
} else if slices.Contains(allServices, template.ID) {
return errors.Newf("service with ID %q already exists", template.ID)
}
if template.Name == "" {
std.Out.Write("Please provide a human-readable name for your new service, e.g. 'My Service'.")
// optional, we can automatically generate one
if _, err := std.PromptAndScan(std.Out, "Service name (optional):", &template.Name); err != nil {
return err
}
}
if template.Owner == "" {
std.Out.Write("Please provide the name of the Opsgenie team that owns this new service - this MUST be an existing team listed in https://sourcegraph.app.opsgenie.com/teams/list")
ok, err := std.PromptAndScan(std.Out, "Service owner:", &template.Owner)
if err != nil {
return err
} else if !ok {
return errors.New("response is required")
}
}
if fullyInteractive && !c.IsSet("dev") { // ask only in interactive setup
std.Out.Write("We are going to scaffold an initial environment for your service - do you want to start with a 'dev' environment?")
std.Out.WriteSuggestionf("You can scaffold additional environments later using 'sg msp init-env %s'.", template.ID)
var dev string
ok, err := std.PromptAndScan(std.Out, "Start with a 'dev' environment (y/N):", &dev)
if err != nil {
return err
} else if !ok {
return errors.New("response is required")
}
template.Dev = strings.EqualFold(dev, "y")
}
var kind = c.String("kind")
if fullyInteractive && !c.IsSet("kind") { // ask only in interactive setup
std.Out.Write("MSP supports long-running services, or cron jobs.")
ok, err := std.PromptAndScan(std.Out, "Service kind (one of: 'service', 'job'):", &kind)
if err != nil {
return err
} else if !ok {
return errors.New("response is required")
}
}
var exampleSpec []byte
switch kind {
case "service":
var err error
exampleSpec, err = example.NewService(template)
if err != nil {
return errors.Wrap(err, "example.NewService")
}
case "job":
var err error
exampleSpec, err = example.NewJob(template)
if err != nil {
return errors.Wrap(err, "example.NewJob")
}
default:
return errors.Newf("unsupported service kind: %q", kind)
}
outputPath := msprepo.ServiceYAMLPath(template.ID)
_ = os.MkdirAll(filepath.Dir(outputPath), 0o755)
if err := os.WriteFile(outputPath, exampleSpec, 0o644); err != nil {
return err
}
std.Out.WriteSuccessf("Rendered %s template spec in %s",
c.String("kind"), outputPath)
std.Out.WriteSuggestionf("Take a look at the spec to see what you can change! "+
"When you are done, run 'sg msp generate -all %s' to render the required manifests and assets, and open a pull request for Core Services review.",
template.ID)
return nil
},
},
{
Name: "init-env",
ArgsUsage: "<service ID> <env ID>",
Usage: "Add an environment to an existing Managed Services Platform service",
Description: fmt.Sprintf(`Templates a new environment to be added to an existing Managed Services Platform service.
If your service does not exist yet, use 'sg msp init' to get started.
%s`, msprepo.DescribeServicesOptions()),
Flags: []cli.Flag{
&cli.IntFlag{
Name: "project-id-suffix-length",
Usage: "Length of random suffix appended to generated project IDs",
Value: spec.DefaultSuffixLength,
},
},
Before: msprepo.UseManagedServicesRepo,
BashComplete: msprepo.ServicesCompletions(),
Action: func(c *cli.Context) error {
svc, err := useServiceArgument(c, false) // we're expecting a potential second argument
if err != nil {
// A bad argument suggests a user misunderstanding of this
// command, so provide a hint with the error
return errors.Wrap(err,
"this command is for adding an environment to an existing service, did you mean to use 'sg msp init' instead?")
}
envID := c.Args().Get(1)
if envID == "" {
std.Out.Write("Please provide an all-lowercase, dash-delimited, machine-friendly identifier for your new environment, e.g. 'dev' or 'prod'.")
ok, err := std.PromptAndScan(std.Out, "Environment ID:", &envID)
if err != nil {
return err
} else if !ok {
return errors.New("response is required")
}
}
if existing := svc.GetEnvironment(envID); existing != nil {
return errors.Newf("environment %q already exists for service %q", envID, svc.Service.ID)
}
envNode, err := example.NewEnvironment(example.EnvironmentTemplate{
ServiceID: svc.Service.ID,
EnvironmentID: envID,
ProjectIDSuffixLength: c.Int("project-id-suffix-length"),
})
if err != nil {
return errors.Wrap(err, "example.NewEnvironment")
}
specPath := msprepo.ServiceYAMLPath(svc.Service.ID)
specData, err := os.ReadFile(specPath)
if err != nil {
return errors.Wrap(err, "ReadFile")
}
specData, err = spec.AppendEnvironment(specData, envNode)
if err != nil {
return errors.Wrap(err, "spec.AppendEnvironment")
}
if err := os.WriteFile(specPath, specData, 0o644); err != nil {
return err
}
std.Out.WriteSuccessf("Initialized environment %q in %s",
envID, specPath)
return nil
},
},
{
Name: "generate",
Aliases: []string{"gen"},
ArgsUsage: "<service ID> <env ID>",
Usage: "Generate Terraform assets for a Managed Services Platform service spec",
Description: fmt.Sprintf(`Optionally use '-all' to sync all environments for a service.
This command supports completions on services and environments.
%s`, msprepo.DescribeServicesOptions()),
UsageText: `
# generate single env for a single service
sg msp generate <service> <env>
# generate all envs for a single service
sg msp generate -all <service>
# generate all envs across all services
sg msp generate -all
# generate all test envs across all services
sg msp generate -all -category=test
`,
Before: msprepo.UseManagedServicesRepo,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "all",
Usage: "Generate infrastructure stacks for all services, or all envs for a service if service ID is provided",
Value: false,
},
&cli.StringFlag{
Name: "category",
Usage: "Filter generated environments by category (one of 'test', 'internal', 'external') - must be used with '-all'",
},
&cli.BoolFlag{
Name: "stable",
Usage: "Configure updating of any values that are evaluated at generation time",
Value: true,
},
},
BashComplete: msprepo.ServicesAndEnvironmentsCompletion(),
Action: func(c *cli.Context) error {
var (
generateAll = c.Bool("all")
generateCategory = spec.EnvironmentCategory(c.String("category"))
stableGenerate = c.Bool("stable")
)
if stableGenerate {
std.Out.WriteSuggestionf("Using stable generate - tfvars will not be updated.")
}
if generateCategory != "" {
if !generateAll {
return errors.New("'-category' must be used with '-all'")
}
if err := generateCategory.Validate(); err != nil {
return errors.Wrap(err, "invalid value for '-category'")
}
}
toolingChecker := &toolingLockfileChecker{
version: c.App.Version,
categories: make(map[spec.EnvironmentCategory]*sync.Once),
}
// Generate a specific service environment if '-all' is not provided
if !generateAll {
std.Out.WriteNoticef("Generating a specific service environment...")
svc, env, err := useServiceAndEnvironmentArguments(c, true)
if err != nil {
return err
}
return generateTerraform(svc, generateTerraformOptions{
tooling: toolingChecker,
targetEnv: env.ID,
stableGenerate: stableGenerate,
})
}
// 1+ argument indicates we are generating all envs for a single service
if c.Args().Len() > 0 {
std.Out.WriteNoticef("Generating all environments for a specific service...")
svc, err := useServiceArgument(c, true) // error if additional arguments are provided
if err != nil {
return err
}
return generateTerraform(svc, generateTerraformOptions{
tooling: toolingChecker,
stableGenerate: stableGenerate,
targetCategory: generateCategory,
})
}
// Otherwise, generate all environments for all services
serviceIDs, err := msprepo.ListServices()
if err != nil {
return errors.Wrap(err, "list services")
}
if len(serviceIDs) == 0 {
return errors.New("no services found")
}
for _, serviceID := range serviceIDs {
s, err := spec.Open(msprepo.ServiceYAMLPath(serviceID))
if err != nil {
return err
}
if err := generateTerraform(s, generateTerraformOptions{
tooling: toolingChecker,
stableGenerate: stableGenerate,
targetCategory: generateCategory,
}); err != nil {
return errors.Wrap(err, serviceID)
}
}
return nil
},
},
{
Name: "operations",
Aliases: []string{"ops"},
Usage: "Generate operational reference for a service",
ArgsUsage: `<service ID>`,
UsageText: "sg msp ops [command options] <service ID>",
Description: fmt.Sprintf(`Directly view operational reference documentation for a service - also available in go/msp-ops.
This command supports completions on services and environments.
%s`, msprepo.DescribeServicesOptions()),
Before: msprepo.UseManagedServicesRepo,
BashComplete: msprepo.ServicesCompletions(),
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "pretty",
Usage: "Render syntax-highlighed Markdown",
Value: true,
},
},
Action: func(c *cli.Context) error {
svc, err := useServiceArgument(c, true)
if err != nil {
return err
}
repoRev, err := msprepo.GitRevision(c.Context)
if err != nil {
return errors.Wrap(err, "msprepo.GitRevision")
}
collectedAlerts, err := collectAlertPolicies(svc)
if err != nil {
return errors.Wrap(err, "CollectAlertPolicies")
}
doc, err := operationdocs.Render(*svc, operationdocs.Options{
ManagedServicesRevision: repoRev,
AlertPolicies: collectedAlerts,
})
if err != nil {
return errors.Wrap(err, "operationdocs.Render")
}
if c.Bool("pretty") {
return std.Out.WriteCode("markdown", doc)
}
std.Out.Write(doc)
return nil
},
Subcommands: []*cli.Command{
{
Name: "generate-handbook-pages",
Usage: "Generate operations handbook pages for all services",
Hidden: true, // not meant for day-to-day use
Description: ``,
Before: msprepo.UseManagedServicesRepo,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "concurrency",
Value: 3,
Usage: "Maximum number of concurrent updates to Notion pages",
},
},
Action: func(c *cli.Context) (err error) {
services, err := msprepo.ListServices()
if err != nil {
return err
}
repoRev, err := msprepo.GitRevision(c.Context)
if err != nil {
return errors.Wrap(err, "msprepo.GitRevision")
}
opts := operationdocs.Options{
ManagedServicesRevision: repoRev,
GenerateCommand: strings.Join(os.Args, " "),
}
sec, err := secrets.FromContext(c.Context)
if err != nil {
return err
}
notionToken, err := sec.GetExternal(c.Context,
secrets.ExternalSecret{
Project: "sourcegraph-secrets",
Name: "CORE_SERVICES_NOTION_API_TOKEN",
},
func(ctx context.Context) (string, error) {
v, ok := os.LookupEnv("NOTION_API_TOKEN")
if !ok {
return "", errors.New("environment variable NOTION_API_TOKEN not set")
}
std.Out.WriteSuggestionf("Using NOTION_API_TOKEN from environment")
return v, nil
})
if err != nil {
return errors.Wrap(err, "failed to get Notion token from gcloud secrets")
}
notionClient := notionapi.NewClient(notionapi.Token(notionToken))
type task struct {
svc *spec.Spec
noNotionPage bool
}
var tasks []task
var serviceSpecs []*spec.Spec
var statusBars []*output.StatusBar
for _, s := range services {
status := output.NewStatusBarWithLabel(s)
statusBars = append(statusBars, status)
svc, err := spec.Open(msprepo.ServiceYAMLPath(s))
if err != nil {
return errors.Wrapf(err, "load service %q", s)
}
serviceSpecs = append(serviceSpecs, svc)
if svc.Service.NotionPageID == nil {
tasks = append(tasks, task{
svc: svc,
noNotionPage: true,
})
continue
}
tasks = append(tasks, task{svc: svc})
}
// Prepare nice progress bars to look at while slowly
// updating Notion pages
concurrency := c.Int("concurrency")
prog := std.Out.ProgressWithStatusBars(
[]output.ProgressBar{{
Label: fmt.Sprintf("Generating service handbook pages (concurrency: %d)", concurrency),
Max: float64(len(services)),
}},
statusBars,
nil)
// Do work concurrently, counting how many tasks are done
wg := pool.New().WithErrors().WithMaxGoroutines(concurrency)
completedCount := atomic.NewInt32(0)
for i, t := range tasks {
if t.noNotionPage {
prog.SetValue(0, float64(completedCount.Inc()))
prog.StatusBarCompletef(i, "Skipped: no Notion page provided in service spec")
continue
}
svc := t.svc
s := svc.Service.ID
wg.Go(func() (err error) {
defer func() {
if err != nil {
prog.StatusBarFailf(i, err.Error())
}
}()
prog.StatusBarUpdatef(i, "Collecting alert policies")
collectedAlerts, err := collectAlertPolicies(svc)
if err != nil {
return errors.Wrapf(err, "%s: CollectAlertPolicies", s)
}
prog.StatusBarUpdatef(i, "Rendering Markdown docs")
opts.AlertPolicies = collectedAlerts
doc, err := operationdocs.Render(*svc, opts)
if err != nil {
return errors.Wrap(err, s)
}
prog.StatusBarUpdatef(i, "Preparing target Notion page %s",
operationdocs.NotionHandbookURL(*svc.Service.NotionPageID))
if err := resetNotionPage(
c.Context,
notionClient,
*svc.Service.NotionPageID,
fmt.Sprintf("%s infrastructure operations", svc.Service.GetName()),
); err != nil {
return errors.Wrapf(err, "%s: reset page %s",
s, operationdocs.NotionHandbookURL(*svc.Service.NotionPageID))
}
prog.StatusBarUpdatef(i, "Rendering target Notion page %s",
operationdocs.NotionHandbookURL(*svc.Service.NotionPageID))
blockUpdater := notion.NewPageBlockUpdater(notionClient, *svc.Service.NotionPageID)
if err := operationdocs.NewNotionConverter(c.Context, blockUpdater).
ProcessMarkdown([]byte(doc)); err != nil {
return errors.Wrap(err, s)
}
prog.StatusBarCompletef(i, "Wrote %q",
operationdocs.NotionHandbookURL(*svc.Service.NotionPageID))
prog.SetValue(0, float64(completedCount.Inc()))
return nil
})
}
if err := wg.Wait(); err != nil {
prog.Close()
return errors.Wrap(err, "failed to generate some pages")
}
prog.Complete()
pending := std.Out.Pending(output.StylePending.Linef(
"Generating MSP operations index page"))
if err := resetNotionPage(
c.Context,
notionClient,
operationdocs.IndexNotionPageID(),
"Managed Services infrastructure",
); err != nil {
return errors.Wrapf(err, "index: reset page %s",
operationdocs.NotionHandbookURL(operationdocs.IndexNotionPageID()))
}
blockUpdater := notion.NewPageBlockUpdater(notionClient, operationdocs.IndexNotionPageID())
doc := operationdocs.RenderIndexPage(serviceSpecs, opts)
if err := operationdocs.NewNotionConverter(c.Context, blockUpdater).
ProcessMarkdown([]byte(doc)); err != nil {
return errors.Wrap(err, "apply index page")
}
pending.Complete(output.Linef(output.EmojiSuccess, output.StyleReset,
"Wrote index page %q", operationdocs.NotionHandbookURL(operationdocs.IndexNotionPageID())))
std.Out.WriteSuccessf("All pages generated!")
return nil
},
},
},
},
{
Name: "logs",
Usage: "Quick links for logs of various MSP components",
ArgsUsage: "<service ID> <environment ID>",
Description: fmt.Sprintf(`View logs of various MSP infrastructure components for a specified service environment and component.
This command supports completions on services and environments.
%s`, msprepo.DescribeServicesOptions()),
Before: msprepo.UseManagedServicesRepo,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "component",
Aliases: []string{"c"},
Value: "service",
},
},
BashComplete: msprepo.ServicesAndEnvironmentsCompletion(),
Action: func(c *cli.Context) error {
svc, env, err := useServiceAndEnvironmentArguments(c, true)
if err != nil {
return err
}
switch component := c.String("component"); component {
case "service":
std.Out.WriteNoticef("Opening link to service logs in browser...")
return open.URL(operationdocs.ServiceLogsURL(pointers.DerefZero(svc.Service.Kind), env.ProjectID))
default:
return errors.Newf("unsupported -component=%s", component)
}
},
},
{
Name: "postgresql",
Aliases: []string{"pg"},
Usage: "Interact with PostgreSQL instances provisioned by MSP",
Before: msprepo.UseManagedServicesRepo,
Subcommands: []*cli.Command{
{
Name: "connect",
Usage: "Connect to the PostgreSQL instance",
Description: fmt.Sprintf(`
This command runs 'cloud-sql-proxy' authenticated against the specified MSP
service environment, and provides 'psql' commands for interacting with the
database through the proxy.
If this is your first time using this command, include the '-download' flag to
install 'cloud-sql-proxy'.
By default, you will only have 'SELECT' privileges through the connection - for
full access, use the '-write-access' flag.
You may need Entitle grants to use this command - see go/msp-ops for more details.
This command supports completions on services and environments.
%s`, msprepo.DescribeServicesOptions()),
ArgsUsage: "<service ID> <environment ID>",
Flags: []cli.Flag{
&cli.IntFlag{
Name: "port",
Value: 5433,
Usage: "Port to use for the cloud-sql-proxy",
},
&cli.BoolFlag{
Name: "download",
Usage: "Install or update the cloud-sql-proxy",
},
&cli.BoolFlag{
Name: "write-access",
Usage: "Connect to the database with write access - by default, only select access is granted.",
},
// db proxy provides privileged access to the database,
// so we want to avoid having it dangling around for too long unattended
&cli.IntFlag{
Name: "session.timeout",
Usage: "Timeout for the proxy session in seconds - 0 means no timeout",
Value: 300,
},
},
BashComplete: msprepo.ServicesAndEnvironmentsCompletion(),
Action: func(c *cli.Context) error {
svc, env, err := useServiceAndEnvironmentArguments(c, true)
if err != nil {
return err
}
if env.Resources.PostgreSQL == nil {
return errors.New("no postgresql instance provisioned")
}
err = cloudsqlproxy.Init(c.Bool("download"))
if err != nil {
return err
}
secretStore, err := secrets.FromContext(c.Context)
if err != nil {
return err
}
var serviceAccountEmail string
if c.Bool("write-access") {
// Use the workload identity if all access is requested
serviceAccountEmail, err = secretStore.GetExternal(c.Context, secrets.ExternalSecret{
Name: stacks.OutputSecretID(iam.StackName, iam.OutputCloudRunServiceAccount),
Project: env.ProjectID,
})
if err != nil {
return errors.Wrap(err, "find IAM output")
}
std.Out.WriteAlertf("Preparing a connection with write access - proceed with caution!")
} else {
// Otherwise, use the operator access account which
// is a bit more limited.
serviceAccountEmail, err = secretStore.GetExternal(c.Context, secrets.ExternalSecret{
Name: stacks.OutputSecretID(iam.StackName, iam.OutputOperatorServiceAccount),
Project: env.ProjectID,
})
if err != nil {
return errors.Wrap(err, "find IAM output")
}
std.Out.WriteSuggestionf("Preparing a connection with read-only access - for write access, use the '-write-access' flag.")
}
connectionName, err := secretStore.GetExternal(c.Context, secrets.ExternalSecret{
Name: stacks.OutputSecretID(cloudrun.StackName, cloudrun.OutputCloudSQLConnectionName),
Project: env.ProjectID,
})
if err != nil {
return errors.Wrap(err, "find Cloud Run output")
}
proxyPort := c.Int("port")
proxy, err := cloudsqlproxy.NewCloudSQLProxy(
connectionName,
serviceAccountEmail,
proxyPort,
svc.Service.GetGoLink(env.ID))
if err != nil {
return err
}
for _, db := range env.Resources.PostgreSQL.Databases {
std.Out.WriteNoticef("Use this command to connect to database %q:", db)
saUsername := strings.ReplaceAll(serviceAccountEmail,
".gserviceaccount.com", "")
if err := std.Out.WriteCode("bash",
fmt.Sprintf(`psql -U %s -d %s -h 127.0.0.1 -p %d`,
saUsername,
db,
proxyPort)); err != nil {
return errors.Wrapf(err, "write command for db %q", db)
}
}
// Run proxy until stopped
return proxy.Start(c.Context, c.Int("session.timeout"))
},
},
},
},
{
Name: "terraform-cloud",
Aliases: []string{"tfc"},
Usage: "Manage Terraform Cloud workspaces for a service",
Before: msprepo.UseManagedServicesRepo,
Subcommands: []*cli.Command{
{
Name: "view",
Usage: "View MSP Terraform Cloud workspaces",
Description: fmt.Sprintf(`View Terraform Cloud workspaces for a given service or service environment.
You may need to request access to the workspaces via Entitle - refer to go/msp-ops for more details.
This command supports completions on services and environments.
%s`, msprepo.DescribeServicesOptions()),
UsageText: `
# View all workspaces for all MSP services
sg msp tfc view
# View all workspaces for all environments for a MSP service
sg msp tfc view <service>
# View all workspaces for a specific MSP service environment
sg msp tfc view <service> <environment>
`,
ArgsUsage: "[service ID] [environment ID]",
BashComplete: msprepo.ServicesAndEnvironmentsCompletion(),
Action: func(c *cli.Context) error {
if c.Args().Len() == 0 {
std.Out.WriteNoticef("Opening link to all MSP Terraform Cloud workspaces in browser...")
return open.URL(fmt.Sprintf("https://app.terraform.io/app/sourcegraph/workspaces?tag=%s",
terraformcloud.MSPWorkspaceTag))
}
service, err := useServiceArgument(c, false)
if err != nil {
return err
}
if c.Args().Len() == 1 {
std.Out.WriteNoticef("Opening link to service Terraform Cloud workspaces in browser...")
return open.URL(fmt.Sprintf("https://app.terraform.io/app/sourcegraph/workspaces?tag=%s",
terraformcloud.ServiceWorkspaceTag(service.Service)))
}
env := service.GetEnvironment(c.Args().Get(1))
if env == nil {
return errors.Wrapf(err, "environment %q not found", c.Args().Get(1))
}
std.Out.WriteNoticef("Opening link to service environment Terraform Cloud workspaces in browser...")
return open.URL(fmt.Sprintf("https://app.terraform.io/app/sourcegraph/workspaces?tag=%s",
terraformcloud.EnvironmentWorkspaceTag(service.Service, *env)))
},
},
{
Name: "sync",
Usage: "Create or update all required Terraform Cloud workspaces for an environment",
Description: fmt.Sprintf(`Optionally use '-all' to sync all environments for a service.
This command supports completions on services and environments.
%s`, msprepo.DescribeServicesOptions()),
ArgsUsage: "<service ID> [environment ID]",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "all",
Usage: "Generate Terraform Cloud workspaces for all environments",
Value: false,
},
&cli.StringFlag{
Name: "workspace-run-mode",
Usage: "One of 'vcs', 'cli'",
Value: "vcs",
},
&cli.BoolFlag{
Name: "delete",
Usage: "Delete workspaces and projects - does NOT apply a teardown run",
Value: false,
},
},
BashComplete: msprepo.ServicesAndEnvironmentsCompletion(),
Action: func(c *cli.Context) error {
secretStore, err := secrets.FromContext(c.Context)
if err != nil {
return err
}
tfcAccessToken, err := secretStore.GetExternal(c.Context, secrets.ExternalSecret{
Name: googlesecretsmanager.SecretTFCOrgToken,
Project: googlesecretsmanager.SharedSecretsProjectID,
})
if err != nil {
return errors.Wrap(err, "get AccessToken")
}
tfcOAuthClient, err := secretStore.GetExternal(c.Context, secrets.ExternalSecret{
Name: googlesecretsmanager.SecretTFCOAuthClientID,
Project: googlesecretsmanager.SharedSecretsProjectID,
})
if err != nil {
return errors.Wrap(err, "get TFC OAuth client ID")
}
tfcClient, err := terraformcloud.NewClient(tfcAccessToken, tfcOAuthClient,
terraformcloud.WorkspaceConfig{
RunMode: terraformcloud.WorkspaceRunMode(c.String("workspace-run-mode")),
})
if err != nil {
return errors.Wrap(err, "init Terraform Cloud client")
}
// If we are not syncing all environments for a service,
// then we are syncing a specific service environment.
if !c.Bool("all") {
std.Out.WriteNoticef("Syncing a specific service environment...")
svc, env, err := useServiceAndEnvironmentArguments(c, true)
if err != nil {
return err
}
return syncEnvironmentWorkspaces(c, tfcClient, svc.Service, *env)
}
// Otherwise, we are syncing all environments for a service.
std.Out.WriteNoticef("Syncing all environments for a specific service ...")
svc, err := useServiceArgument(c, true)
if err != nil {
return err
}
for _, env := range svc.Environments {
if err := syncEnvironmentWorkspaces(c, tfcClient, svc.Service, env); err != nil {
return errors.Wrapf(err, "sync env %q", env.ID)
}
}
return nil
},
},
{
Name: "graph",
Usage: "EXPERIMENTAL: Graph the core resources within a Terraform workspace",
ArgsUsage: "<service ID> <environment ID> <stack ID>",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "dot",
Usage: "Dump dot graph configuration instead of rendering the image with 'dot'",
},
},
BashComplete: msprepo.ServicesAndEnvironmentsCompletion(
func(cli.Args) (options []string) {
return managedservicesplatform.StackNames()
},
),
Action: func(c *cli.Context) error {
service, env, err := useServiceAndEnvironmentArguments(c, false)
if err != nil {
return err
}
stack := c.Args().Get(2)
if stack == "" {
return errors.New("third argument <stack ID> is required")
}
dotgraph, err := msprepo.TerraformGraph(c.Context, service.Service.ID, env.ID, stack)
if err != nil {
return err
}
if c.Bool("dot") {
std.Out.Write(dotgraph)
return nil
}
output := fmt.Sprintf("./%s-%s.%s.png", service.Service.ID, env.ID, stack)
f, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE, 0o644)
if err != nil {
return errors.Wrapf(err, "open %q", output)
}
defer f.Close()
if err := run.Cmd(c.Context, "dot -Tpng").
Input(strings.NewReader(dotgraph + "\n")).
Environ(os.Environ()).
Run().
Stream(f); err != nil {
return err
}
std.Out.WriteSuccessf("Graph rendered in %q", output)
return nil
},
},
},
},
{
Name: "fleet",
Usage: "Summarize aspects of the MSP fleet",
Before: msprepo.UseManagedServicesRepo,
Action: func(c *cli.Context) error {
services, err := msprepo.ListServices()
if err != nil {
return err
}
var environmentCount int
categories := make(map[spec.EnvironmentCategory]int)
teams := make(map[string]int)
for _, s := range services {
svc, err := spec.Open(msprepo.ServiceYAMLPath(s))
if err != nil {
return err
}
for _, t := range svc.Service.Owners {
teams[t] += 1
}
for _, e := range svc.Environments {
environmentCount += 1
categories[e.Category] += 1
}
}
teamNames := maps.Keys(teams)
sort.Strings(teamNames)
summary := fmt.Sprintf(`Managed Services Platform fleet summary:
- %d services
- %d teams (%s)
- %d environments
`, len(services), len(teams), strings.Join(teamNames, ", "), environmentCount)
for category, count := range categories {