-
Notifications
You must be signed in to change notification settings - Fork 239
/
cmd.go
335 lines (288 loc) · 8.81 KB
/
cmd.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
package launch
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"time"
"github.com/samber/lo"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/internal/command"
"github.com/superfly/flyctl/internal/command/deploy"
"github.com/superfly/flyctl/internal/flag"
"github.com/superfly/flyctl/internal/flyerr"
"github.com/superfly/flyctl/internal/metrics"
"github.com/superfly/flyctl/internal/prompt"
"github.com/superfly/flyctl/internal/tracing"
"github.com/superfly/flyctl/iostreams"
"go.opentelemetry.io/otel/attribute"
)
func New() (cmd *cobra.Command) {
const (
long = `Create and configure a new app from source code or a Docker image. Options passed after double dashes ("--") will be passed to the language specific scanner/dockerfile generator.`
short = `Create and configure a new app from source code or a Docker image`
)
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.Region(),
flag.Org(),
flag.NoDeploy(),
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,
},
flag.Int{
Name: "internal-port",
Description: "Set internal_port for all services in the generated fly.toml",
Default: -1,
},
flag.String{
Name: "from",
Description: "A github repo URL to use as a template for the new app",
},
flag.Bool{
Name: "manifest",
Description: "Output the generated manifest to stdout",
Hidden: true,
},
flag.String{
Name: "from-manifest",
Description: "Path to a manifest file for Launch ('-' reads from stdin)",
Hidden: true,
},
// legacy launch flags (deprecated)
flag.Bool{
Name: "legacy",
Description: "Use the legacy CLI interface (deprecated)",
Hidden: true,
},
flag.Bool{
Name: "reuse-app",
Description: "Continue even if app name clashes with an existent app",
Default: false,
Hidden: true,
},
)
return
}
func getManifestArgument(ctx context.Context) (*LaunchManifest, error) {
path := flag.GetString(ctx, "from-manifest")
if path == "" {
return nil, nil
}
var jsonDecoder *json.Decoder
if path != "-" {
manifestJson, err := os.ReadFile(path)
if err != nil {
return nil, err
}
reader := bytes.NewReader(manifestJson)
jsonDecoder = json.NewDecoder(reader)
} else {
// Read from stdin
stdin := iostreams.FromContext(ctx).In
jsonDecoder = json.NewDecoder(stdin)
}
var manifest LaunchManifest
err := jsonDecoder.Decode(&manifest)
if err != nil {
return nil, err
}
return &manifest, nil
}
func setupFromTemplate(ctx context.Context) (context.Context, error) {
from := flag.GetString(ctx, "from")
if from == "" {
return ctx, nil
}
entries, err := os.ReadDir(".")
if err != nil {
return ctx, fmt.Errorf("failed to read directory: %w", err)
}
if len(entries) > 0 {
return ctx, errors.New("directory not empty, refusing to clone from git")
}
fmt.Printf("Launching from git repo %s\n", from)
cmd := exec.Command("git", "clone", from, ".")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return ctx, err
}
ctx, err = command.LoadAppConfigIfPresent(ctx)
return ctx, err
}
func run(ctx context.Context) (err error) {
io := iostreams.FromContext(ctx)
tp, err := tracing.InitTraceProviderWithoutApp(ctx)
if err != nil {
fmt.Fprintf(io.ErrOut, "failed to initialize tracing library: =%v", err)
return err
}
defer tp.Shutdown(ctx)
ctx, span := tracing.CMDSpan(ctx, "cmd.launch")
defer span.End()
startTime := time.Now()
var status metrics.LaunchStatusPayload
metrics.Started(ctx, "launch")
var state *launchState = nil
defer func() {
if err != nil {
status.Error = err.Error()
if state != nil && state.sourceInfo != nil && state.sourceInfo.FailureCallback != nil {
err = state.sourceInfo.FailureCallback(err)
}
}
status.TraceID = span.SpanContext().TraceID().String()
status.Duration = time.Since(startTime)
metrics.LaunchStatus(ctx, "launch", status)
}()
if err := warnLegacyBehavior(ctx); err != nil {
return err
}
var (
launchManifest *LaunchManifest
cache *planBuildCache
)
launchManifest, err = getManifestArgument(ctx)
if err != nil {
return err
}
// "--from" arg handling
ctx, err = setupFromTemplate(ctx)
if err != nil {
return err
}
incompleteLaunchManifest := false
canEnterUi := !flag.GetBool(ctx, "manifest")
if launchManifest == nil {
launchManifest, cache, err = buildManifest(ctx, canEnterUi)
if err != nil {
var recoverableErr recoverableInUiError
if errors.As(err, &recoverableErr) && canEnterUi {
fmt.Fprintln(io.ErrOut, "The following problems must be fixed in the Launch UI:")
fmt.Fprintln(io.ErrOut, recoverableErr.Error())
incompleteLaunchManifest = true
} else {
return err
}
}
if flag.GetBool(ctx, "manifest") {
jsonEncoder := json.NewEncoder(io.Out)
jsonEncoder.SetIndent("", " ")
return jsonEncoder.Encode(launchManifest)
}
}
span.SetAttributes(attribute.String("app.name", launchManifest.Plan.AppName))
status.AppName = launchManifest.Plan.AppName
status.OrgSlug = launchManifest.Plan.OrgSlug
status.Region = launchManifest.Plan.RegionCode
status.HighAvailability = launchManifest.Plan.HighAvailability
if len(launchManifest.Plan.Compute) > 0 {
vm := launchManifest.Plan.Compute[0]
status.VM.Size = vm.Size
status.VM.Memory = vm.Memory
status.VM.ProcessN = len(vm.Processes)
}
status.HasPostgres = launchManifest.Plan.Postgres.FlyPostgres != nil
status.HasRedis = launchManifest.Plan.Redis.UpstashRedis != nil
status.HasSentry = launchManifest.Plan.Sentry
status.ScannerFamily = launchManifest.Plan.ScannerFamily
status.FlyctlVersion = launchManifest.Plan.FlyctlVersion.String()
state, err = stateFromManifest(ctx, *launchManifest, cache)
if err != nil {
return err
}
summary, err := state.PlanSummary(ctx)
if err != nil {
return err
}
family := ""
if state.sourceInfo != nil {
family = state.sourceInfo.Family
}
fmt.Fprintf(
io.Out,
"We're about to launch your %s on Fly.io. Here's what you're getting:\n\n%s\n",
familyToAppType(family),
summary,
)
editInUi := false
if !flag.GetBool(ctx, "yes") {
message := lo.Ternary(
incompleteLaunchManifest,
"Would you like to continue in the web UI?",
"Do you want to tweak these settings before proceeding?",
)
editInUi, err = prompt.Confirm(ctx, message)
if err != nil && !errors.Is(err, prompt.ErrNonInteractive) {
return err
}
}
if editInUi {
err = state.EditInWebUi(ctx)
if err != nil {
return err
}
} else if incompleteLaunchManifest {
// UI was required to reconcile launch issues, but user denied. Abort.
return errors.New("launch can not continue with errors present")
}
err = state.Launch(ctx)
if err != nil {
return err
}
return nil
}
// familyToAppType returns a string that describes the app type based on the source info
// For example, "Dockerfile" apps would return "app" but a rails app would return "Rails app"
func familyToAppType(family string) string {
switch family {
case "Dockerfile":
return "app"
case "":
return "app"
}
return fmt.Sprintf("%s app", family)
}
// warnLegacyBehavior warns the user if they are using a legacy flag
func warnLegacyBehavior(ctx context.Context) error {
// TODO(Allison): We probably want to support re-configuring an existing app, but
// that is different from the launch-into behavior of reuse-app, which basically just deployed.
if flag.IsSpecified(ctx, "reuse-app") {
return flyerr.GenericErr{
Err: "the --reuse-app flag is no longer supported. you are likely looking for 'fly deploy'",
Suggest: "for now, you can use 'fly launch --legacy --reuse-app', but this will be removed in a future release",
}
}
return nil
}