-
Notifications
You must be signed in to change notification settings - Fork 221
/
launch.go
711 lines (592 loc) · 18.2 KB
/
launch.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
package launch
import (
"bufio"
"bytes"
"context"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/logrusorgru/aurora"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/client"
"github.com/superfly/flyctl/flyctl"
"github.com/superfly/flyctl/helpers"
"github.com/superfly/flyctl/internal/app"
"github.com/superfly/flyctl/internal/build/imgsrc"
"github.com/superfly/flyctl/internal/command"
"github.com/superfly/flyctl/internal/command/apps"
"github.com/superfly/flyctl/internal/command/deploy"
"github.com/superfly/flyctl/internal/command/postgres"
"github.com/superfly/flyctl/internal/filemu"
"github.com/superfly/flyctl/internal/flag"
"github.com/superfly/flyctl/internal/prompt"
"github.com/superfly/flyctl/iostreams"
"github.com/superfly/flyctl/scanner"
"github.com/superfly/flyctl/terminal"
"github.com/superfly/graphql"
)
func New() (cmd *cobra.Command) {
const (
long = `Create and configure a new app from source code or a Docker image.`
short = long
)
cmd = command.New("launch", short, long, run, command.RequireSession, command.LoadAppConfigIfPresent)
cmd.Args = cobra.NoArgs
flag.Add(cmd,
// Since launch can perform a deployment, we offer the full set of deployment flags for those using
// the launch command in CI environments. We may want to rescind this decision down the line, because
// the list of flags is long, but it follows from the precedent of already offering some deployment flags.
// See a proposed 'flag grouping' feature in Viper that could help with DX: https://github.com/spf13/cobra/pull/1778
deploy.CommonFlags,
flag.Org(),
flag.Bool{
Name: "no-deploy",
Description: "Do not prompt for deployment",
},
flag.Bool{
Name: "generate-name",
Description: "Always generate a name for the app, without prompting",
},
flag.String{
Name: "path",
Description: `Path to the app source root, where fly.toml file will be saved`,
Default: ".",
},
flag.String{
Name: "name",
Description: `Name of the new app`,
},
flag.Bool{
Name: "copy-config",
Description: "Use the configuration file if present without prompting",
Default: false,
},
flag.Bool{
Name: "dockerignore-from-gitignore",
Description: "If a .dockerignore does not exist, create one from .gitignore files",
Default: false,
},
)
return
}
func run(ctx context.Context) (err error) {
io := iostreams.FromContext(ctx)
client := client.FromContext(ctx).API()
workingDir := flag.GetString(ctx, "path")
// Determine the working directory
if absDir, err := filepath.Abs(workingDir); err == nil {
workingDir = absDir
}
appConfig := app.NewConfig()
var importedConfig bool
configFilePath := filepath.Join(workingDir, "fly.toml")
if exists, _ := flyctl.ConfigFileExistsAtPath(configFilePath); exists {
cfg, err := app.LoadConfig(ctx, configFilePath, "nomad")
if err != nil {
return err
}
var deployExisting bool
if cfg.AppName != "" {
fmt.Fprintln(io.Out, "An existing fly.toml file was found for app", cfg.AppName)
deployExisting, err = shouldDeployExistingApp(ctx, cfg.AppName)
if err != nil {
return err
}
} else {
fmt.Fprintln(io.Out, "An existing fly.toml file was found")
}
if deployExisting {
fmt.Fprintln(io.Out, "App is not running, deploy...")
return deploy.DeployWithConfig(ctx, appConfig)
}
copyConfig := false
if flag.GetBool(ctx, "copy-config") {
copyConfig = true
} else {
copy, err := prompt.Confirm(ctx, "Would you like to copy its configuration to the new app?")
if copy && err == nil {
copyConfig = true
}
}
if copyConfig {
appConfig.Definition = cfg.Definition
importedConfig = true
}
}
fmt.Fprintln(io.Out, "Creating app in", workingDir)
srcInfo := new(scanner.SourceInfo)
if img := flag.GetString(ctx, "image"); img != "" {
fmt.Fprintln(io.Out, "Using image", img)
appConfig.Build = &app.Build{
Image: img,
}
} else if dockerfile := flag.GetString(ctx, "dockerfile"); dockerfile != "" {
fmt.Fprintln(io.Out, "Using dockerfile", dockerfile)
appConfig.Build = &app.Build{
Dockerfile: dockerfile,
}
} else {
fmt.Fprintln(io.Out, "Scanning source code")
if si, err := scanner.Scan(workingDir); err != nil {
return err
} else {
srcInfo = si
}
if srcInfo == nil {
fmt.Fprintln(io.Out, aurora.Green("Could not find a Dockerfile, nor detect a runtime or framework from source code. Continuing with a blank app."))
} else {
var article string = "a"
matched, _ := regexp.MatchString(`^[aeiou]`, strings.ToLower(srcInfo.Family))
if matched {
article += "n"
}
appType := srcInfo.Family
if srcInfo.Version != "" {
appType = appType + " " + srcInfo.Version
}
fmt.Fprintf(io.Out, "Detected %s %s app\n", article, aurora.Green(appType))
if srcInfo.Builder != "" {
fmt.Fprintln(io.Out, "Using the following build configuration:")
fmt.Fprintln(io.Out, "\tBuilder:", srcInfo.Builder)
if srcInfo.Buildpacks != nil && len(srcInfo.Buildpacks) > 0 {
fmt.Fprintln(io.Out, "\tBuildpacks:", strings.Join(srcInfo.Buildpacks, " "))
}
appConfig.Build = &app.Build{
Builder: srcInfo.Builder,
Buildpacks: srcInfo.Buildpacks,
}
}
}
}
if srcInfo != nil {
for _, f := range srcInfo.Files {
path := filepath.Join(workingDir, f.Path)
if helpers.FileExists(path) {
if flag.GetBool(ctx, "now") {
fmt.Fprintf(io.Out, "You specified --now, so not overwriting %s\n", path)
continue
}
confirm, err := prompt.ConfirmOverwrite(ctx, path)
if !confirm || err != nil {
continue
}
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
perms := 0o600
if strings.Contains(string(f.Contents), "#!") {
perms = 0o700
}
if err := os.WriteFile(path, f.Contents, fs.FileMode(perms)); err != nil {
return err
}
}
}
// Attempt to create a .dockerignore from .gitignore
determineDockerIgnore(ctx, workingDir)
// Prompt for an app name or fetch from flags
appName := ""
if !flag.GetBool(ctx, "generate-name") {
appName = flag.GetString(ctx, "name")
if appName == "" {
// Prompt the user for the app name
inputName, err := apps.SelectAppName(ctx)
if err != nil {
return err
}
appName = inputName
} else {
fmt.Fprintf(io.Out, "Selected App Name: %s\n", appName)
}
}
// Prompt for an org
// TODO: determine if eager remote builder is still required here
org, err := prompt.Org(ctx)
if err != nil {
return
}
// If we potentially are deploying, launch a remote builder to prepare for deployment.
if !flag.GetBool(ctx, "no-deploy") {
go imgsrc.EagerlyEnsureRemoteBuilder(ctx, client, org.Slug)
}
region, err := prompt.Region(ctx, prompt.RegionParams{
Message: "Choose a region for deployment:",
})
if err != nil {
return err
}
input := api.CreateAppInput{
Name: appName,
OrganizationID: org.ID,
PreferredRegion: ®ion.Code,
}
createdApp, err := client.CreateApp(ctx, input)
if err != nil {
return err
}
if !importedConfig {
appConfig.Definition = createdApp.Config.Definition
}
appConfig.AppName = createdApp.Name
if srcInfo != nil {
if srcInfo.Port > 0 {
appConfig.SetInternalPort(srcInfo.Port)
}
for envName, envVal := range srcInfo.Env {
if envVal == "APP_FQDN" {
appConfig.SetEnvVariable(envName, createdApp.Name+".fly.dev")
} else {
appConfig.SetEnvVariable(envName, envVal)
}
}
if len(srcInfo.Statics) > 0 {
appConfig.SetStatics(srcInfo.Statics)
}
if len(srcInfo.Volumes) > 0 {
appConfig.SetVolumes(srcInfo.Volumes)
}
for procName, procCommand := range srcInfo.Processes {
appConfig.SetProcess(procName, procCommand)
}
if srcInfo.ReleaseCmd != "" {
appConfig.SetReleaseCommand(srcInfo.ReleaseCmd)
}
if srcInfo.DockerCommand != "" {
appConfig.SetDockerCommand(srcInfo.DockerCommand)
}
if srcInfo.DockerEntrypoint != "" {
appConfig.SetDockerEntrypoint(srcInfo.DockerEntrypoint)
}
if srcInfo.KillSignal != "" {
appConfig.SetKillSignal(srcInfo.KillSignal)
}
}
fmt.Fprintf(io.Out, "Created app %s in organization %s\n", createdApp.Name, org.Slug)
// If secrets are requested by the launch scanner, ask the user to input them
if srcInfo != nil && len(srcInfo.Secrets) > 0 {
secrets := make(map[string]string)
keys := []string{}
for _, secret := range srcInfo.Secrets {
val := ""
// If a secret should be a random default, just generate it without displaying
// Otherwise, prompt to type it in
if secret.Generate != nil {
if val, err = secret.Generate(); err != nil {
return fmt.Errorf("could not generate random string: %w", err)
}
} else if secret.Value != "" {
val = secret.Value
} else {
prompt := fmt.Sprintf("Set secret %s:", secret.Key)
surveyInput := &survey.Input{
Message: prompt,
Help: secret.Help,
}
survey.AskOne(surveyInput, &val)
}
if val != "" {
secrets[secret.Key] = val
keys = append(keys, secret.Key)
}
}
if len(secrets) > 0 {
_, err := client.SetSecrets(ctx, createdApp.Name, secrets)
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Set secrets on %s: %s\n", createdApp.Name, strings.Join(keys, ", "))
}
}
// If volumes are requested by the launch scanner, create them
if srcInfo != nil && len(srcInfo.Volumes) > 0 {
for _, vol := range srcInfo.Volumes {
appID, err := client.GetAppID(ctx, createdApp.Name)
if err != nil {
return err
}
volume, err := client.CreateVolume(ctx, api.CreateVolumeInput{
AppID: appID,
Name: vol.Source,
Region: region.Code,
SizeGb: 1,
Encrypted: true,
})
if err != nil {
return err
} else {
fmt.Fprintf(io.Out, "Created a %dGB volume %s in the %s region\n", volume.SizeGb, volume.ID, region.Code)
}
}
}
// Run any initialization commands
if srcInfo != nil && len(srcInfo.InitCommands) > 0 {
for _, cmd := range srcInfo.InitCommands {
if err := execInitCommand(ctx, cmd); err != nil {
return err
}
}
}
// Append any requested Dockerfile entries
if srcInfo != nil && len(srcInfo.DockerfileAppendix) > 0 {
if err := appendDockerfileAppendix(srcInfo.DockerfileAppendix); err != nil {
return fmt.Errorf("failed appending Dockerfile appendix: %w", err)
}
}
if srcInfo != nil && len(srcInfo.BuildArgs) > 0 {
appConfig.Build = &app.Build{}
appConfig.Build.Args = srcInfo.BuildArgs
}
// Finally, write the config
if err = appConfig.WriteToDisk(ctx, filepath.Join(workingDir, "fly.toml")); err != nil {
return err
}
if srcInfo == nil {
return nil
}
if !flag.GetBool(ctx, "no-deploy") && !flag.GetBool(ctx, "now") && !srcInfo.SkipDatabase {
confirm, err := prompt.Confirm(ctx, "Would you like to set up a Postgresql database now?")
if confirm && err == nil {
clusterAppName := createdApp.Name + "-db"
err = postgres.CreateCluster(ctx, org, region, "machines",
&postgres.ClusterParams{
PostgresConfiguration: postgres.PostgresConfiguration{
Name: clusterAppName,
},
})
if err != nil {
fmt.Fprintf(io.Out, "Failed creating the Postgres cluster %s: %s", clusterAppName, err)
} else {
err = postgres.AttachCluster(ctx, postgres.AttachParams{
PgAppName: clusterAppName,
AppName: createdApp.Name,
})
if err != nil {
msg := `Failed attaching %s to the Postgres cluster %s: %w.\nTry attaching manually with 'fly postgres attach --app %s %s'`
fmt.Fprintf(io.Out, msg, createdApp.Name, clusterAppName, err, createdApp.Name, clusterAppName)
} else {
fmt.Fprintf(io.Out, "Postgres cluster %s is now attached to %s\n", clusterAppName, createdApp.Name)
}
}
}
// Run any initialization commands required for postgres support
if len(srcInfo.PostgresInitCommands) > 0 {
for _, cmd := range srcInfo.PostgresInitCommands {
if cmd.Condition {
if err := execInitCommand(ctx, cmd); err != nil {
return err
}
}
}
}
}
// Notices from a launcher about its behavior that should always be displayed
if srcInfo.Notice != "" {
fmt.Fprintln(io.Out, srcInfo.Notice)
}
deployNow := false
promptForDeploy := true
if srcInfo.SkipDeploy || flag.GetBool(ctx, "no-deploy") {
deployNow = false
promptForDeploy = false
}
if flag.GetBool(ctx, "now") {
deployNow = true
promptForDeploy = false
}
if promptForDeploy {
confirm, err := prompt.Confirm(ctx, "Would you like to deploy now?")
if confirm && err == nil {
deployNow = true
}
}
if deployNow {
return deploy.DeployWithConfig(ctx, appConfig)
}
// Alternative deploy documentation if our standard deploy method is not correct
if srcInfo.DeployDocs != "" {
fmt.Fprintln(io.Out, srcInfo.DeployDocs)
} else {
fmt.Fprintln(io.Out, "Your app is ready! Deploy with `flyctl deploy`")
}
return nil
}
func execInitCommand(ctx context.Context, command scanner.InitCommand) (err error) {
io := iostreams.FromContext(ctx)
binary, err := exec.LookPath(command.Command)
if err != nil {
return fmt.Errorf("%s not found in $PATH - make sure app dependencies are installed and try again", command.Command)
}
fmt.Fprintln(io.Out, command.Description)
// Run a requested generator command, for example to generate a Dockerfile
cmd := exec.CommandContext(ctx, binary, command.Args...)
if err = cmd.Start(); err != nil {
return err
}
if err = cmd.Wait(); err != nil {
err = fmt.Errorf("failed running %s: %w ", cmd.String(), err)
}
return err
}
func appendDockerfileAppendix(appendix []string) (err error) {
const dockerfilePath = "Dockerfile"
var b bytes.Buffer
b.WriteString("\n# Appended by flyctl\n")
for _, value := range appendix {
_, _ = b.WriteString(value)
_ = b.WriteByte('\n')
}
var unlock filemu.UnlockFunc
if unlock, err = filemu.Lock(context.Background(), dockerfilePath); err != nil {
return
}
defer func() {
if e := unlock(); err == nil {
err = e
}
}()
var f *os.File
// TODO: we don't flush
if f, err = os.OpenFile(dockerfilePath, os.O_APPEND|os.O_WRONLY, 0o600); err != nil {
return
}
defer func() {
if e := f.Close(); err == nil {
err = e
}
}()
_, err = b.WriteTo(f)
return
}
func shouldDeployExistingApp(ctx context.Context, appName string) (bool, error) {
client := client.FromContext(ctx).API()
status, err := client.GetAppStatus(ctx, appName, false)
if err != nil {
if api.IsNotFoundError(err) || graphql.IsNotFoundError(err) {
return false, nil
}
return false, err
}
if !status.Deployed {
return true, nil
}
for _, a := range status.Allocations {
if a.Healthy {
return false, nil
}
}
return true, nil
}
func createDockerignoreFromGitignores(root string, gitIgnores []string) (string, error) {
dockerIgnore := filepath.Join(root, ".dockerignore")
f, err := os.Create(dockerIgnore)
if err != nil {
return "", err
}
defer func() {
if err := f.Close(); err != nil {
terminal.Debugf("error closing %s file after writing: %v\n", dockerIgnore, err)
}
}()
firstHeaderWritten := false
linebreak := []byte("\n")
for _, gitIgnore := range gitIgnores {
gitF, err := os.Open(gitIgnore)
defer func() {
if err := gitF.Close(); err != nil {
terminal.Debugf("error closing %s file after reading: %v\n", gitIgnore, err)
}
}()
if err != nil {
terminal.Debugf("error opening %s file: %v\n", gitIgnore, err)
continue
}
relDir, err := filepath.Rel(root, filepath.Dir(gitIgnore))
if err != nil {
terminal.Debugf("error finding relative directory of %s relative to root %s: %v\n", gitIgnore, root, err)
continue
}
relFile, err := filepath.Rel(root, gitIgnore)
if err != nil {
terminal.Debugf("error finding relative file of %s relative to root %s: %v\n", gitIgnore, root, err)
continue
}
headerWritten := false
scanner := bufio.NewScanner(gitF)
for scanner.Scan() {
line := scanner.Text()
if !headerWritten {
if !firstHeaderWritten {
firstHeaderWritten = true
} else {
f.Write(linebreak)
}
_, err := f.WriteString(fmt.Sprintf("# flyctl launch added from %s\n", relFile))
if err != nil {
return "", err
}
headerWritten = true
}
var dockerIgnoreLine string
if strings.TrimSpace(line) == "" {
dockerIgnoreLine = ""
} else if strings.HasPrefix(line, "#") {
dockerIgnoreLine = line
} else if strings.HasPrefix(line, "!/") {
dockerIgnoreLine = fmt.Sprintf("!%s", filepath.Join(relDir, line[2:]))
} else if strings.HasPrefix(line, "!") {
dockerIgnoreLine = fmt.Sprintf("!%s", filepath.Join(relDir, "**", line[1:]))
} else if strings.HasPrefix(line, "/") {
dockerIgnoreLine = filepath.Join(relDir, line[1:])
} else {
dockerIgnoreLine = filepath.Join(relDir, "**", line)
}
if _, err := f.WriteString(dockerIgnoreLine); err != nil {
return "", err
}
if _, err := f.Write(linebreak); err != nil {
return "", err
}
}
}
return dockerIgnore, nil
}
func determineDockerIgnore(ctx context.Context, workingDir string) (err error) {
io := iostreams.FromContext(ctx)
dockerIgnore := ".dockerignore"
gitIgnore := ".gitignore"
allGitIgnores := scanner.FindGitignores(workingDir)
createDockerignoreFromGitignore := false
// An existing .dockerignore should always be used instead of .gitignore
if helpers.FileExists(dockerIgnore) {
terminal.Debugf("Found %s file. Will use when deploying to Fly.\n", dockerIgnore)
return
}
// If we find .gitignore files, determine whether they should be converted to .dockerignore
if len(allGitIgnores) > 0 {
if flag.GetBool(ctx, "dockerignore-from-gitignore") {
createDockerignoreFromGitignore = true
} else {
confirm, err := prompt.Confirm(ctx, fmt.Sprintf("Create %s from %d %s files?", dockerIgnore, len(allGitIgnores), gitIgnore))
if confirm && err == nil {
createDockerignoreFromGitignore = true
}
}
if createDockerignoreFromGitignore {
createdDockerIgnore, err := createDockerignoreFromGitignores(workingDir, allGitIgnores)
if err != nil {
terminal.Warnf("Error creating %s from %d %s files: %v\n", dockerIgnore, len(allGitIgnores), gitIgnore, err)
} else {
fmt.Fprintf(io.Out, "Created %s from %d %s files.\n", createdDockerIgnore, len(allGitIgnores), gitIgnore)
}
return nil
}
}
return
}