-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathcommands.go
More file actions
1347 lines (1168 loc) · 44.1 KB
/
commands.go
File metadata and controls
1347 lines (1168 loc) · 44.1 KB
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 command
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/DefangLabs/defang/src/pkg"
"github.com/DefangLabs/defang/src/pkg/cli"
cliClient "github.com/DefangLabs/defang/src/pkg/cli/client"
"github.com/DefangLabs/defang/src/pkg/cli/client/byoc"
"github.com/DefangLabs/defang/src/pkg/cli/client/byoc/gcp"
"github.com/DefangLabs/defang/src/pkg/cli/compose"
"github.com/DefangLabs/defang/src/pkg/clouds/aws"
"github.com/DefangLabs/defang/src/pkg/github"
"github.com/DefangLabs/defang/src/pkg/logs"
"github.com/DefangLabs/defang/src/pkg/mcp"
"github.com/DefangLabs/defang/src/pkg/scope"
"github.com/DefangLabs/defang/src/pkg/term"
"github.com/DefangLabs/defang/src/pkg/track"
"github.com/DefangLabs/defang/src/pkg/types"
defangv1 "github.com/DefangLabs/defang/src/protos/io/defang/v1"
"github.com/bufbuild/connect-go"
composeTypes "github.com/compose-spec/compose-go/v2/types"
"github.com/spf13/cobra"
)
const authNeeded = "auth-needed" // annotation to indicate that a command needs authorization
var authNeededAnnotation = map[string]string{authNeeded: ""}
var P = track.P
// GLOBALS
var (
client *cliClient.GrpcClient
cluster string
colorMode = ColorAuto
doDebug = false
hasTty = term.IsTerminal() && !pkg.GetenvBool("CI")
hideUpdate = pkg.GetenvBool("DEFANG_HIDE_UPDATE")
mode = Mode(defangv1.DeploymentMode_MODE_UNSPECIFIED)
modelId = os.Getenv("DEFANG_MODEL_ID") // for Pro users only
nonInteractive = !hasTty
org string
providerID = cliClient.ProviderID(pkg.Getenv("DEFANG_PROVIDER", "auto"))
verbose = false
)
func getCluster() string {
if org == "" {
return cluster
}
return org + "@" + cluster
}
func prettyError(err error) error {
// To avoid printing the internal gRPC error code
var cerr *connect.Error
if errors.As(err, &cerr) {
term.Debug("Server error:", cerr)
err = errors.Unwrap(cerr)
}
if cli.IsNetworkError(err) {
return fmt.Errorf("%w; please check network settings and try again", err)
}
return err
}
func Execute(ctx context.Context) error {
if term.StdoutCanColor() {
restore := term.EnableANSI()
defer restore()
}
if err := RootCmd.ExecuteContext(ctx); err != nil {
if !(errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)) {
term.Error("Error:", prettyError(err))
}
if err == cli.ErrDryRun {
return nil
}
if cerr := new(cli.ComposeError); errors.As(err, &cerr) {
compose := "compose"
fileFlag := RootCmd.Flag("file")
if fileFlag.Changed {
compose += " -f " + fileFlag.Value.String()
}
printDefangHint("Fix the error and try again. To validate the compose file, use:", compose+" config")
}
if strings.Contains(err.Error(), "config") {
printDefangHint("To manage sensitive service config, use:", "config")
}
if strings.Contains(err.Error(), "maximum number of projects") {
projectName := "<name>"
provider, err := newProvider(ctx, nil)
if err != nil {
return err
}
if resp, err := provider.RemoteProjectName(ctx); err == nil {
projectName = resp
}
printDefangHint("To deactivate a project, do:", "compose down --project-name "+projectName)
}
if cerr := new(cli.CancelError); errors.As(err, &cerr) {
printDefangHint("Detached. The deployment will keep running.\nTo continue the logs from where you left off, do:", cerr.Error())
}
code := connect.CodeOf(err)
if code == connect.CodeUnauthenticated {
printDefangHint("Please use the following command to log in:", "login")
}
if code == connect.CodeFailedPrecondition && (strings.Contains(err.Error(), "EULA") || strings.Contains(err.Error(), "terms")) {
printDefangHint("Please use the following command to see the Defang terms of service:", "terms")
}
if cde := new(gcp.ConflictDelegateDomainError); errors.As(err, cde) {
hint := fmt.Sprintf("Domain verification is required for the delegated domain %q, as indicated by the Google Cloud API.", cde.NewDomain)
if cde.ConflictDomain != "" {
hint += fmt.Sprintf(" This is likely due to a legacy tenant-level delegated zone named %v (%v).", cde.ConflictZone, cde.ConflictDomain)
} else {
hint += " This is likely caused by a conflicting legacy tenant-level delegated DNS zone."
}
hint += " Please check if this legacy zone is still needed. If not, remove it from your Google Cloud account and try again."
printDefangHint(hint)
}
if credError := new(gcp.CredentialsError); errors.As(err, &credError) {
fmt.Print("\nPlease log in by running: \n\n\t gcloud auth application-default login\n\n")
}
return ExitCode(code)
}
if hasTty && term.HadWarnings() {
fmt.Println("For help with warnings, check our FAQ at https://s.defang.io/warnings")
}
if hasTty && !hideUpdate && pkg.RandomIndex(10) == 0 {
if latest, err := github.GetLatestReleaseTag(ctx); err == nil && isNewer(GetCurrentVersion(), latest) {
term.Debug("Latest Version:", latest, "Current Version:", GetCurrentVersion())
fmt.Println("A newer version of the CLI is available at https://github.com/DefangLabs/defang/releases/latest")
if pkg.RandomIndex(10) == 0 && !pkg.GetenvBool("DEFANG_HIDE_HINTS") {
fmt.Println("To silence these notices, do: export DEFANG_HIDE_UPDATE=1")
}
}
}
return nil
}
func SetupCommands(ctx context.Context, version string) {
cobra.EnableTraverseRunHooks = true // we always need to run the RootCmd's pre-run hook
RootCmd.Version = version
RootCmd.PersistentFlags().Var(&colorMode, "color", fmt.Sprintf(`colorize output; one of %v`, allColorModes))
RootCmd.PersistentFlags().StringVarP(&cluster, "cluster", "s", cli.DefangFabric, "Defang cluster to connect to")
RootCmd.PersistentFlags().MarkHidden("cluster")
RootCmd.PersistentFlags().StringVar(&org, "org", os.Getenv("DEFANG_ORG"), "override GitHub organization name (tenant)")
RootCmd.PersistentFlags().VarP(&providerID, "provider", "P", fmt.Sprintf(`bring-your-own-cloud provider; one of %v`, cliClient.AllProviders()))
// RootCmd.Flag("provider").NoOptDefVal = "auto" NO this will break the "--provider aws"
RootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose logging") // backwards compat: only used by tail
RootCmd.PersistentFlags().BoolVar(&doDebug, "debug", pkg.GetenvBool("DEFANG_DEBUG"), "debug logging for troubleshooting the CLI")
RootCmd.PersistentFlags().BoolVar(&cli.DoDryRun, "dry-run", false, "dry run (don't actually change anything)")
RootCmd.PersistentFlags().BoolVarP(&nonInteractive, "non-interactive", "T", !hasTty, "disable interactive prompts / no TTY")
RootCmd.PersistentFlags().StringP("project-name", "p", "", "project name")
RootCmd.PersistentFlags().StringP("cwd", "C", "", "change directory before running the command")
_ = RootCmd.MarkPersistentFlagDirname("cwd")
RootCmd.PersistentFlags().StringArrayP("file", "f", []string{}, `compose file path(s)`)
_ = RootCmd.MarkPersistentFlagFilename("file", "yml", "yaml")
// Create a temporary gRPC client for tracking events before login
cli.Connect(ctx, cluster)
// CD command
RootCmd.AddCommand(cdCmd)
cdCmd.PersistentFlags().Bool("utc", false, "show logs in UTC timezone (ie. TZ=UTC)")
cdCmd.PersistentFlags().Bool("json", pkg.GetenvBool("DEFANG_JSON"), "show logs in JSON format")
cdCmd.PersistentFlags().StringVar(&byoc.DefangPulumiBackend, "pulumi-backend", "", `specify an alternate Pulumi backend URL or "pulumi-cloud"`)
cdCmd.AddCommand(cdDestroyCmd)
cdCmd.AddCommand(cdDownCmd)
cdCmd.AddCommand(cdRefreshCmd)
cdTearDownCmd.Flags().Bool("force", false, "force the teardown of the CD stack")
cdCmd.AddCommand(cdTearDownCmd)
cdListCmd.Flags().Bool("remote", false, "invoke the command on the remote cluster")
cdCmd.AddCommand(cdListCmd)
cdCmd.AddCommand(cdCancelCmd)
cdPreviewCmd.Flags().VarP(&mode, "mode", "m", fmt.Sprintf("deployment mode; one of %v", allModes()))
cdCmd.AddCommand(cdPreviewCmd)
// Eula command
tosCmd.Flags().Bool("agree-tos", false, "agree to the Defang terms of service")
RootCmd.AddCommand(tosCmd)
// Upgrade command
RootCmd.AddCommand(upgradeCmd)
// Token command
tokenCmd.Flags().Duration("expires", 24*time.Hour, "validity duration of the token")
tokenCmd.Flags().String("scope", "", fmt.Sprintf("scope of the token; one of %v (required)", scope.All())) // TODO: make it an Option
_ = tokenCmd.MarkFlagRequired("scope")
RootCmd.AddCommand(tokenCmd)
// Login Command
loginCmd.Flags().Bool("training-opt-out", false, "Opt out of ML training (Pro users only)")
// loginCmd.Flags().Bool("skip-prompt", false, "skip the login prompt if already logged in"); TODO: Implement this
RootCmd.AddCommand(loginCmd)
// Whoami Command
RootCmd.AddCommand(whoamiCmd)
// Logout Command
RootCmd.AddCommand(logoutCmd)
// Generate Command
generateCmd.Flags().StringVar(&modelId, "model", modelId, "LLM model to use for generating the code (Pro users only)")
RootCmd.AddCommand(generateCmd)
RootCmd.AddCommand(newCmd)
// Get Services Command
lsCommand := makeComposePsCmd()
lsCommand.Use = "services"
// TODO: when we add multi-project support to the playground, differentiate
// between ls and ps
lsCommand.Aliases = []string{"getServices", "ps", "ls", "list"}
RootCmd.AddCommand(lsCommand)
// Get Status Command
RootCmd.AddCommand(getVersionCmd)
// Config Command (was: secrets)
configSetCmd.Flags().BoolP("name", "n", false, "name of the config (backwards compat)")
configSetCmd.Flags().BoolP("env", "e", false, "set the config from an environment variable")
configSetCmd.Flags().Bool("random", false, "set a secure randomly generated value for config")
_ = configSetCmd.Flags().MarkHidden("name")
configCmd.AddCommand(configSetCmd)
configDeleteCmd.Flags().BoolP("name", "n", false, "name of the config(s) (backwards compat)")
_ = configDeleteCmd.Flags().MarkHidden("name")
configCmd.AddCommand(configDeleteCmd)
configCmd.AddCommand(configListCmd)
RootCmd.AddCommand(configCmd)
RootCmd.AddCommand(setupComposeCommand())
// Add up/down commands to the root as well
down := makeComposeDownCmd()
down.Hidden = true // hidden from top-level menu
RootCmd.AddCommand(down)
up := makeComposeUpCmd()
up.Hidden = true // hidden from top-level menu
RootCmd.AddCommand(up)
restart := makeComposeRestartCmd()
restart.Hidden = true // hidden from top-level menu
RootCmd.AddCommand(restart)
estimateCmd := makeEstimateCmd()
RootCmd.AddCommand(estimateCmd)
// Debug Command
debugCmd.Flags().String("etag", "", "deployment ID (ETag) of the service")
debugCmd.Flags().MarkHidden("etag")
debugCmd.Flags().String("deployment", "", "deployment ID of the service")
debugCmd.Flags().String("since", "", "start time for logs (RFC3339 format)")
debugCmd.Flags().String("until", "", "end time for logs (RFC3339 format)")
debugCmd.Flags().StringVar(&modelId, "model", modelId, "LLM model to use for debugging (Pro users only)")
RootCmd.AddCommand(debugCmd)
// Tail Command
tailCmd := makeComposeLogsCmd()
tailCmd.Use = "tail [SERVICE...]"
tailCmd.Aliases = []string{"logs"}
RootCmd.AddCommand(tailCmd)
// Delete Command
deleteCmd.Flags().BoolP("name", "n", false, "name of the service(s) (backwards compat)")
_ = deleteCmd.Flags().MarkHidden("name")
deleteCmd.Flags().Bool("tail", false, "tail the service logs after deleting")
RootCmd.AddCommand(deleteCmd)
// Deployments Command
deploymentsCmd.AddCommand(deploymentsListCmd)
deploymentsCmd.PersistentFlags().Bool("utc", false, "show logs in UTC timezone (ie. TZ=UTC)")
RootCmd.AddCommand(deploymentsCmd)
// MCP Command
mcpCmd.AddCommand(mcpSetupCmd)
mcpCmd.AddCommand(mcpServerCmd)
mcpSetupCmd.Flags().String("client", "", fmt.Sprintf("MCP setup client %v", mcp.ValidClients))
mcpServerCmd.Flags().Int("auth-server", 0, "auth server port")
mcpSetupCmd.MarkFlagRequired("client")
RootCmd.AddCommand(mcpCmd)
// Send Command
sendCmd.Flags().StringP("subject", "n", "", "subject to send the message to (required)")
sendCmd.Flags().StringP("type", "t", "", "type of message to send (required)")
sendCmd.Flags().String("id", "", "ID of the message")
sendCmd.Flags().StringP("data", "d", "", "string data to send")
sendCmd.Flags().StringP("content-type", "c", "", "Content-Type of the data")
_ = sendCmd.MarkFlagRequired("subject")
_ = sendCmd.MarkFlagRequired("type")
RootCmd.AddCommand(sendCmd)
// Cert management
// TODO: Add list, renew etc.
certCmd.AddCommand(certGenerateCmd)
RootCmd.AddCommand(certCmd)
if term.StdoutCanColor() { // TODO: should use DoColor(…) instead
// Add some emphasis to the help command
re := regexp.MustCompile(`(?m)^[A-Za-z ]+?:`)
templ := re.ReplaceAllString(RootCmd.UsageTemplate(), "\033[1m$0\033[0m") // bold
RootCmd.SetUsageTemplate(templ)
}
origHelpFunc := RootCmd.HelpFunc()
RootCmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
track.Cmd(cmd, "Help", P("args", args))
origHelpFunc(cmd, args)
})
}
var RootCmd = &cobra.Command{
SilenceUsage: true,
SilenceErrors: true,
Use: "defang",
Args: cobra.NoArgs,
Short: "Defang CLI is used to take your app from Docker Compose to a secure and scalable deployment on your favorite cloud in minutes.",
PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
term.SetDebug(doDebug)
// Don't track/connect the completion commands
if IsCompletionCommand(cmd) {
return nil
}
// Use "defer" to track any errors that occur during the command
defer func() {
track.Cmd(cmd, "Invoked", P("args", args), P("err", err), P("non-interactive", nonInteractive), P("provider", providerID))
}()
// Do this first, since any errors will be printed to the console
switch colorMode {
case ColorNever:
term.ForceColor(false)
case ColorAlways:
term.ForceColor(true)
}
if cwd, _ := cmd.Flags().GetString("cwd"); cwd != "" {
// Change directory before running the command
if err = os.Chdir(cwd); err != nil {
return err
}
}
client, err = cli.Connect(cmd.Context(), getCluster())
if v, err := client.GetVersions(cmd.Context()); err == nil {
version := cmd.Root().Version // HACK to avoid circular dependency with RootCmd
term.Debug("Fabric:", v.Fabric, "CLI:", version, "CLI-Min:", v.CliMin)
if hasTty && isNewer(version, v.CliMin) && !isUpgradeCommand(cmd) {
term.Warn("Your CLI version is outdated. Please upgrade to the latest version by running:\n\n defang upgrade\n")
hideUpdate = true // hide the upgrade hint at the end
}
}
// Check if we are correctly logged in, but only if the command needs authorization
if _, ok := cmd.Annotations[authNeeded]; !ok {
return nil
}
if err = client.CheckLoginAndToS(cmd.Context()); err != nil {
if nonInteractive {
return err
}
// Login interactively now; only do this for authorization-related errors
if connect.CodeOf(err) == connect.CodeUnauthenticated {
term.Debug("Server error:", err)
term.Warn("Please log in to continue.")
term.ResetWarnings() // clear any previous warnings so we don't show them again
defer func() { track.Cmd(nil, "Login", P("reason", err)) }()
if err = cli.InteractiveLogin(cmd.Context(), client, getCluster()); err != nil {
return err
}
// Reconnect with the new token
if client, err = cli.Connect(cmd.Context(), getCluster()); err != nil {
return err
}
if err = client.CheckLoginAndToS(cmd.Context()); err == nil { // recheck (new token = new user)
return nil // success
}
}
// Check if the user has agreed to the terms of service and show a prompt if needed
if connect.CodeOf(err) == connect.CodeFailedPrecondition {
term.Warn(prettyError(err))
defer func() { track.Cmd(nil, "Terms", P("reason", err)) }()
if err = cli.InteractiveAgreeToS(cmd.Context(), client); err != nil {
return err // fatal
}
}
}
return err
},
}
var loginCmd = &cobra.Command{
Use: "login",
Args: cobra.NoArgs,
Short: "Authenticate to Defang",
RunE: func(cmd *cobra.Command, args []string) error {
trainingOptOut, _ := cmd.Flags().GetBool("training-opt-out")
if nonInteractive {
if err := cli.NonInteractiveGitHubLogin(cmd.Context(), client, getCluster()); err != nil {
return err
}
} else {
err := cli.InteractiveLogin(cmd.Context(), client, getCluster())
if err != nil {
return err
}
printDefangHint("To generate a sample service, do:", "generate")
}
if trainingOptOut {
req := &defangv1.SetOptionsRequest{TrainingOptOut: trainingOptOut}
if err := client.SetOptions(cmd.Context(), req); err != nil {
return err
}
term.Info("Options updated successfully")
}
return nil
},
}
var whoamiCmd = &cobra.Command{
Use: "whoami",
Args: cobra.NoArgs,
Short: "Show the current user",
RunE: func(cmd *cobra.Command, args []string) error {
loader := configureLoader(cmd)
nonInteractive = true // don't show provider prompt
provider, err := newProvider(cmd.Context(), loader)
if err != nil {
term.Debug("unable to get provider:", err)
}
str, err := cli.Whoami(cmd.Context(), client, provider)
if err != nil {
return err
}
term.Info(str)
return nil
},
}
var certCmd = &cobra.Command{
Use: "cert",
Args: cobra.NoArgs,
Short: "Manage certificates",
}
var certGenerateCmd = &cobra.Command{
Use: "generate",
Aliases: []string{"gen"},
Args: cobra.NoArgs,
Short: "Generate a TLS certificate",
RunE: func(cmd *cobra.Command, args []string) error {
loader := configureLoader(cmd)
project, err := loader.LoadProject(cmd.Context())
if err != nil {
return err
}
provider, err := newProvider(cmd.Context(), loader)
if err != nil {
return err
}
if err := cli.GenerateLetsEncryptCert(cmd.Context(), project, client, provider); err != nil {
return err
}
return nil
},
}
var generateCmd = &cobra.Command{
Use: "generate",
Args: cobra.MaximumNArgs(1),
Aliases: []string{"gen"},
Short: "Generate a sample Defang project",
RunE: func(cmd *cobra.Command, args []string) error {
var sample, language, defaultFolder string
if len(args) > 0 {
sample = args[0]
}
if nonInteractive {
if sample == "" {
return errors.New("cannot run in non-interactive mode")
}
return cli.InitFromSamples(cmd.Context(), "", []string{sample})
}
sampleList, fetchSamplesErr := cli.FetchSamples(cmd.Context())
if sample == "" {
// Fetch the list of samples from the Defang repository
if fetchSamplesErr != nil {
term.Debug("unable to fetch samples:", fetchSamplesErr)
} else if len(sampleList) > 0 {
const generateWithAI = "Generate with AI"
sampleNames := []string{generateWithAI}
sampleTitles := []string{"Generate a sample from scratch using a language prompt"}
sampleIndex := []string{"unused first entry because we always show genAI option"}
for _, sample := range sampleList {
sampleNames = append(sampleNames, sample.Name)
sampleTitles = append(sampleTitles, sample.Title)
sampleIndex = append(sampleIndex, strings.ToLower(sample.Name+" "+sample.Title+" "+
strings.Join(sample.Tags, " ")+" "+strings.Join(sample.Languages, " ")))
}
if err := survey.AskOne(&survey.Select{
Message: "Choose a sample service:",
Options: sampleNames,
Help: "The project code will be based on the sample you choose here.",
Filter: func(filter string, value string, i int) bool {
return i == 0 || strings.Contains(sampleIndex[i], strings.ToLower(filter))
},
Description: func(value string, i int) string {
return sampleTitles[i]
},
}, &sample, survey.WithStdio(term.DefaultTerm.Stdio())); err != nil {
return err
}
if sample == generateWithAI {
if err := survey.AskOne(&survey.Select{
Message: "Choose the language you'd like to use:",
Options: cli.SupportedLanguages,
Help: "The project code will be in the language you choose here.",
}, &language, survey.WithStdio(term.DefaultTerm.Stdio())); err != nil {
return err
}
sample = ""
defaultFolder = "project1"
} else {
defaultFolder = sample
}
}
}
var qs = []*survey.Question{
{
Name: "description",
Prompt: &survey.Input{
Message: "Please describe the service you'd like to build:",
Help: `Here are some example prompts you can use:
"A simple 'hello world' function"
"A service with 2 endpoints, one to upload and the other to download a file from AWS S3"
"A service with a default endpoint that returns an HTML page with a form asking for the user's name and then a POST endpoint to handle the form post when the user clicks the 'submit' button"`,
},
Validate: survey.MinLength(5),
},
{
Name: "folder",
Prompt: &survey.Input{
Message: "What folder would you like to create the project in?",
Default: defaultFolder, // dynamically set based on chosen sample
Help: "The generated code will be in the folder you choose here. If the folder does not exist, it will be created.",
},
Validate: survey.Required,
},
}
if sample != "" {
qs = qs[1:] // user picked a sample, so we skip the description question
sampleExists := slices.ContainsFunc(sampleList, func(s cli.Sample) bool {
return s.Name == sample
})
if !sampleExists {
return cli.ErrSampleNotFound
}
}
prompt := struct {
Description string // or you can tag fields to match a specific name
Folder string
}{}
// ask the remaining questions
err := survey.Ask(qs, &prompt, survey.WithStdio(term.DefaultTerm.Stdio()))
if err != nil {
return err
}
if client.CheckLoginAndToS(cmd.Context()) != nil {
// The user is either not logged in or has not agreed to the terms of service; ask for agreement to the terms now
if err := cli.InteractiveAgreeToS(cmd.Context(), client); err != nil {
// This might fail because the user did not log in. This is fine: server won't save the terms agreement, but can proceed with the generation
if connect.CodeOf(err) != connect.CodeUnauthenticated {
return err
}
}
}
track.Evt("Generate Started", P("language", language), P("sample", sample), P("description", prompt.Description), P("folder", prompt.Folder), P("model", modelId))
// Check if the current folder is empty
if empty, err := pkg.IsDirEmpty(prompt.Folder); !os.IsNotExist(err) && !empty {
nonEmptyFolder := fmt.Sprintf("The folder %q is not empty. We recommend running this command in an empty folder.", prompt.Folder)
var confirm bool
err := survey.AskOne(&survey.Confirm{
Message: nonEmptyFolder + " Continue creating project?",
}, &confirm, survey.WithStdio(term.DefaultTerm.Stdio()))
if err == nil && !confirm {
os.Exit(1)
}
}
if sample != "" {
term.Info("Fetching sample from the Defang repository...")
err := cli.InitFromSamples(cmd.Context(), prompt.Folder, []string{sample})
if err != nil {
return err
}
} else {
term.Info("Working on it. This may take 1 or 2 minutes...")
args := cli.GenerateArgs{
Description: prompt.Description,
Folder: prompt.Folder,
Language: language,
ModelId: modelId,
}
_, err := cli.GenerateWithAI(cmd.Context(), client, args)
if err != nil {
return err
}
}
term.Info("Code generated successfully in folder", prompt.Folder)
editor := pkg.Getenv("DEFANG_EDITOR", "code") // TODO: should we use EDITOR env var instead?
cmdd := exec.Command(editor, prompt.Folder)
err = cmdd.Start()
if err != nil {
term.Debugf("unable to launch editor %q: %v", editor, err)
}
cd := ""
if prompt.Folder != "." {
cd = "`cd " + prompt.Folder + "` and "
}
// Load the project and check for empty environment variables
loader := compose.NewLoader(compose.WithPath(filepath.Join(prompt.Folder, "compose.yaml")))
project, err := loader.LoadProject(cmd.Context())
if err != nil {
term.Debugf("unable to load new project: %v", err)
}
var envInstructions []string
for _, envVar := range collectUnsetEnvVars(project) {
envInstructions = append(envInstructions, "config create "+envVar)
}
if len(envInstructions) > 0 {
printDefangHint("Check the files in your favorite editor.\nTo configure the service, do "+cd, envInstructions...)
} else {
printDefangHint("Check the files in your favorite editor.\nTo deploy the service, do "+cd, "compose up")
}
return nil
},
}
var newCmd = &cobra.Command{
Use: "new [SAMPLE]",
Args: cobra.MaximumNArgs(1),
Aliases: []string{"init"},
Short: "Create a new Defang project from a sample",
RunE: generateCmd.RunE,
}
func collectUnsetEnvVars(project *composeTypes.Project) []string {
if project == nil {
return nil // in case loading failed
}
err := compose.ValidateProjectConfig(context.TODO(), project, func(ctx context.Context) ([]string, error) {
return nil, nil // assume no config
})
var missingConfig compose.ErrMissingConfig
if errors.As(err, &missingConfig) {
return missingConfig
}
return nil
}
var getVersionCmd = &cobra.Command{
Use: "version",
Args: cobra.NoArgs,
Aliases: []string{"ver", "stat", "status"}, // for backwards compatibility
Short: "Get version information for the CLI and Fabric service",
RunE: func(cmd *cobra.Command, args []string) error {
term.Printc(term.BrightCyan, "Defang CLI: ")
fmt.Println(GetCurrentVersion())
term.Printc(term.BrightCyan, "Latest CLI: ")
ver, err := github.GetLatestReleaseTag(cmd.Context())
fmt.Println(ver)
term.Printc(term.BrightCyan, "Defang Fabric: ")
ver, err2 := cli.GetVersion(cmd.Context(), client)
fmt.Println(ver)
return errors.Join(err, err2)
},
}
var configCmd = &cobra.Command{
Use: "config", // like Docker
Args: cobra.NoArgs,
Aliases: []string{"secrets", "secret"},
Short: "Add, update, or delete service config",
}
var configSetCmd = &cobra.Command{
Use: "create CONFIG [file|-]", // like Docker
Annotations: authNeededAnnotation,
Args: cobra.RangeArgs(1, 2),
Aliases: []string{"set", "add", "put"},
Short: "Adds or updates a sensitive config value",
RunE: func(cmd *cobra.Command, args []string) error {
fromEnv, _ := cmd.Flags().GetBool("env")
random, _ := cmd.Flags().GetBool("random")
// Make sure we have a project to set config for before asking for a value
loader := configureLoader(cmd)
provider, err := newProvider(cmd.Context(), loader)
if err != nil {
return err
}
projectName, err := cliClient.LoadProjectNameWithFallback(cmd.Context(), loader, provider)
if err != nil {
return err
}
parts := strings.SplitN(args[0], "=", 2)
name := parts[0]
if !pkg.IsValidSecretName(name) {
return fmt.Errorf("invalid config name: %q", name)
}
var value string
if fromEnv {
if len(args) == 2 || len(parts) == 2 {
return errors.New("cannot specify config value or input file when using --env")
}
var ok bool
value, ok = os.LookupEnv(name)
if !ok {
return fmt.Errorf("environment variable %q not found", name)
}
} else if len(parts) == 2 {
// Handle name=value; can't also specify a file in this case
if len(args) == 2 {
return errors.New("cannot specify both config value and input file")
}
value = parts[1]
} else if nonInteractive || len(args) == 2 {
// Read the value from a file or stdin
var err error
var bytes []byte
if len(args) == 2 && args[1] != "-" {
bytes, err = os.ReadFile(args[1])
} else {
bytes, err = io.ReadAll(os.Stdin)
}
if err != nil && err != io.EOF {
return fmt.Errorf("failed reading the config value: %w", err)
}
// Trim the newline at the end because single line values are common
value = strings.TrimSuffix(string(bytes), "\n")
} else if random {
// Generate a random value for the config
value = cli.CreateRandomConfigValue()
term.Info("Generated random value: " + value)
} else {
// Prompt for sensitive value
var sensitivePrompt = &survey.Password{
Message: fmt.Sprintf("Enter value for %q:", name),
Help: "The value will be stored securely and cannot be retrieved later.",
}
err := survey.AskOne(sensitivePrompt, &value, survey.WithStdio(term.DefaultTerm.Stdio()))
if err != nil {
return err
}
}
if err := cli.ConfigSet(cmd.Context(), projectName, provider, name, value); err != nil {
return err
}
term.Info("Updated value for", name)
printDefangHint("To update the deployed values, do:", "compose up")
return nil
},
}
var configDeleteCmd = &cobra.Command{
Use: "rm CONFIG...", // like Docker
Annotations: authNeededAnnotation,
Args: cobra.MinimumNArgs(1),
Aliases: []string{"del", "delete", "remove"},
Short: "Removes one or more config values",
RunE: func(cmd *cobra.Command, names []string) error {
loader := configureLoader(cmd)
provider, err := newProvider(cmd.Context(), loader)
if err != nil {
return err
}
projectName, err := cliClient.LoadProjectNameWithFallback(cmd.Context(), loader, provider)
if err != nil {
return err
}
if err := cli.ConfigDelete(cmd.Context(), projectName, provider, names...); err != nil {
// Show a warning (not an error) if the config was not found
if connect.CodeOf(err) == connect.CodeNotFound {
term.Warn(prettyError(err))
return nil
}
return err
}
term.Info("Deleted", names)
printDefangHint("To list the configs (but not their values), do:", "config ls")
return nil
},
}
var configListCmd = &cobra.Command{
Use: "ls", // like Docker
Annotations: authNeededAnnotation,
Args: cobra.NoArgs,
Aliases: []string{"list"},
Short: "List configs",
RunE: func(cmd *cobra.Command, args []string) error {
loader := configureLoader(cmd)
provider, err := newProvider(cmd.Context(), loader)
if err != nil {
return err
}
projectName, err := cliClient.LoadProjectNameWithFallback(cmd.Context(), loader, provider)
if err != nil {
return err
}
return cli.ConfigList(cmd.Context(), projectName, provider)
},
}
var debugCmd = &cobra.Command{
Use: "debug [SERVICE...]",
Annotations: authNeededAnnotation,
Hidden: true,
Short: "Debug a build, deployment, or service failure",
RunE: func(cmd *cobra.Command, args []string) error {
etag, _ := cmd.Flags().GetString("etag")
deployment, _ := cmd.Flags().GetString("deployment")
since, _ := cmd.Flags().GetString("since")
until, _ := cmd.Flags().GetString("until")
if etag != "" && deployment == "" {
deployment = etag
}
loader := configureLoader(cmd)
provider, err := newProvider(cmd.Context(), loader)
if err != nil {
return err
}
project, err := loader.LoadProject(cmd.Context())
if err != nil {
return err
}
now := time.Now()
sinceTs, err := cli.ParseTimeOrDuration(since, now)
if err != nil {
return fmt.Errorf("invalid 'since' time: %w", err)
}
untilTs, err := cli.ParseTimeOrDuration(until, now)
if err != nil {
return fmt.Errorf("invalid 'until' time: %w", err)
}
debugConfig := cli.DebugConfig{
Deployment: deployment,
FailedServices: args,
ModelId: modelId,
Project: project,
Provider: provider,
Since: sinceTs.UTC(),
Until: untilTs.UTC(),
}
return cli.DebugDeployment(cmd.Context(), client, debugConfig)
},
}
var deleteCmd = &cobra.Command{
Use: "delete SERVICE...",
Annotations: authNeededAnnotation,
Args: cobra.MinimumNArgs(1),
Aliases: []string{"del", "rm", "remove"},
Hidden: true,
Short: "Delete a service from the cluster",
Deprecated: "use 'compose down' instead",
RunE: func(cmd *cobra.Command, names []string) error {
var tail, _ = cmd.Flags().GetBool("tail")
loader := configureLoader(cmd)
provider, err := newProvider(cmd.Context(), loader)
if err != nil {
return err
}
projectName, err := cliClient.LoadProjectNameWithFallback(cmd.Context(), loader, provider)
if err != nil {
return err
}
err = canIUseProvider(cmd.Context(), provider, projectName)
if err != nil {
return err
}
since := time.Now()
deployment, err := cli.Delete(cmd.Context(), projectName, client, provider, names...)
if err != nil {
if connect.CodeOf(err) == connect.CodeNotFound {
// Show a warning (not an error) if the service was not found
term.Warn(prettyError(err))
return nil
}
return err
}
term.Info("Deleted service", names, "with deployment ID", deployment)
if !tail {
printDefangHint("To track the update, do:", "tail --deployment "+deployment)
return nil
}
term.Info("Tailing logs for update; press Ctrl+C to detach:")
tailOptions := cli.TailOptions{
Deployment: deployment,
LogType: logs.LogTypeAll,
Since: since,
Verbose: verbose,
}
tailCtx := cmd.Context() // FIXME: stop Tail when the deployment is done
return cli.TailAndWaitForCD(tailCtx, provider, projectName, tailOptions)
},
}
// deploymentsCmd and deploymentsListCmd do the same thing. deploymentsListCmd is for backward compatibility.
var deploymentsCmd = &cobra.Command{