-
Notifications
You must be signed in to change notification settings - Fork 224
/
deploy.go
634 lines (510 loc) · 15.8 KB
/
deploy.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
package deploy
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"time"
"github.com/briandowns/spinner"
"github.com/dustin/go-humanize"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
"github.com/superfly/flyctl/cmd/presenters"
"github.com/superfly/flyctl/pkg/iostreams"
"github.com/superfly/flyctl/pkg/logs"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/internal/build/imgsrc"
"github.com/superfly/flyctl/internal/cli/internal/app"
"github.com/superfly/flyctl/internal/cli/internal/command"
"github.com/superfly/flyctl/internal/cli/internal/config"
"github.com/superfly/flyctl/internal/cli/internal/flag"
"github.com/superfly/flyctl/internal/cli/internal/format"
"github.com/superfly/flyctl/internal/cli/internal/render"
"github.com/superfly/flyctl/internal/cli/internal/state"
"github.com/superfly/flyctl/internal/client"
"github.com/superfly/flyctl/internal/cmdutil"
"github.com/superfly/flyctl/internal/deployment"
"github.com/superfly/flyctl/internal/flyerr"
"github.com/superfly/flyctl/internal/logger"
)
func New() (cmd *cobra.Command) {
const (
long = `Deploy Fly applications from source or an image using a local or remote builder.
`
short = "Deploy Fly applications"
)
cmd = command.New("deploy [WORKING_DIRECTORY]", short, long, run,
command.RequireSession,
swapWorkingDirectoryIfRequired,
command.RequireAppName,
)
cmd.Args = cobra.MaximumNArgs(1)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
flag.Region(),
flag.Image(),
flag.Now(),
flag.RemoteOnly(),
flag.LocalOnly(),
flag.BuildOnly(),
flag.Detach(),
flag.String{
Name: "strategy",
Description: "The strategy for replacing running instances. Options are canary, rolling, bluegreen, or immediate. Default is canary, or rolling when max-per-region is set.",
},
flag.String{
Name: "dockerfile",
Description: "Path to a Dockerfile. Defaults to the Dockerfile in the working directory.",
},
flag.StringSlice{
Name: "env",
Shorthand: "e",
Description: "Set of environment variables in the form of NAME=VALUE pairs. Can be specified multiple times.",
},
flag.String{
Name: "image-label",
Description: `Image label to use when tagging and pushing to the fly registry. Defaults to "deployment-{timestamp}".`,
},
flag.StringSlice{
Name: "build-arg",
Description: "Set of build time variables in the form of NAME=VALUE pairs. Can be specified multiple times.",
},
flag.String{
Name: "build-target",
Description: "Set the target build stage to build if the Dockerfile has more than one stage",
},
flag.Bool{
Name: "no-cache",
Description: "Do not use the build cache when building the image",
},
)
return
}
func swapWorkingDirectoryIfRequired(ctx context.Context) (context.Context, error) {
wd := flag.FirstArg(ctx)
if wd == "" {
return ctx, nil
}
if !filepath.IsAbs(wd) {
p, err := filepath.Abs(wd)
if err != nil {
return nil, fmt.Errorf("failed converting %s to an absolute path: %w", wd, err)
}
wd = p
}
if err := os.Chdir(wd); err != nil {
return nil, fmt.Errorf("failed changing working directory: %w", err)
}
return state.WithWorkingDirectory(ctx, wd), nil
}
func run(ctx context.Context) error {
appConfig, err := determineAppConfig(ctx)
if err != nil {
return err
}
// Fetch an image ref or build from source to get the final image reference to deploy
img, err := determineImage(ctx, appConfig)
if err != nil {
return fmt.Errorf("failed to fetch an image or build from source: %w", err)
}
if flag.GetBuildOnly(ctx) {
return nil
}
release, releaseCommand, err := createRelease(ctx, appConfig, img)
if err != nil {
return err
}
if flag.GetDetach(ctx) {
return nil
}
// TODO: This is a single message that doesn't belong to any block output, so we should have helpers to allow that
tb := render.NewTextBlock(ctx)
tb.Done("You can detach the terminal anytime without stopping the deployment")
// Run the pre-deployment release command if it's set
if releaseCommand != nil {
// TODO: don't use text block here
tb := render.NewTextBlock(ctx, fmt.Sprintf("Release command detected: %s\n", releaseCommand.Command))
tb.Done("This release will not be available until the release command succeeds.")
if err := watchReleaseCommand(ctx, releaseCommand.ID); err != nil {
return err
}
}
if release.DeploymentStrategy == "IMMEDIATE" {
logger := logger.FromContext(ctx)
logger.Debug("immediate deployment strategy, nothing to monitor")
return nil
}
err = watchDeployment(ctx)
return err
}
// determineAppConfig fetches the app config from a local file, or in its absence, from the API
func determineAppConfig(ctx context.Context) (cfg *app.Config, err error) {
tb := render.NewTextBlock(ctx, "Verifying app config")
client := client.FromContext(ctx).API()
if cfg = app.ConfigFromContext(ctx); cfg == nil {
logger := logger.FromContext(ctx)
logger.Debug("no local app config detected; fetching from backend ...")
var apiConfig *api.AppConfig
if apiConfig, err = client.GetConfig(ctx, app.NameFromContext(ctx)); err != nil {
err = fmt.Errorf("failed fetching existing app config: %w", err)
return
}
cfg = &app.Config{
Definition: apiConfig.Definition,
}
}
if env := flag.GetStringSlice(ctx, "env"); len(env) > 0 {
var parsedEnv map[string]string
if parsedEnv, err = cmdutil.ParseKVStringsToMap(env); err != nil {
err = fmt.Errorf("failed parsing environment: %w", err)
return
}
cfg.SetEnvVariables(parsedEnv)
}
tb.Done("Verified app config")
return
}
func determineImage(ctx context.Context, appConfig *app.Config) (img *imgsrc.DeploymentImage, err error) {
tb := render.NewTextBlock(ctx, "Building image")
daemonType := imgsrc.NewDockerDaemonType(!flag.GetRemoteOnly(ctx), !flag.GetLocalOnly(ctx))
appName := app.NameFromContext(ctx)
client := client.FromContext(ctx).API()
io := iostreams.FromContext(ctx)
resolver := imgsrc.NewResolver(daemonType, client, appName, io)
var imageRef string
if imageRef, err = fetchImageRef(ctx, appConfig); err != nil {
return
}
// we're using a pre-built Docker image
if imageRef != "" {
opts := imgsrc.RefOptions{
AppName: app.NameFromContext(ctx),
WorkingDir: state.WorkingDirectory(ctx),
Publish: !flag.GetBuildOnly(ctx),
ImageRef: imageRef,
ImageLabel: flag.GetString(ctx, "image-label"),
}
img, err = resolver.ResolveReference(ctx, io, opts)
return
}
build := appConfig.Build
if build == nil {
build = new(app.Build)
}
var buildArgs map[string]string
if buildArgs, err = mergeBuildArgs(ctx, build.Args); err != nil {
return
}
// We're building from source
opts := imgsrc.ImageOptions{
AppName: app.NameFromContext(ctx),
WorkingDir: state.WorkingDirectory(ctx),
Publish: !flag.GetBuildOnly(ctx),
ImageLabel: flag.GetString(ctx, "image-label"),
NoCache: flag.GetBool(ctx, "no-cache"),
BuildArgs: buildArgs,
BuiltIn: build.Builtin,
BuiltInSettings: build.Settings,
Builder: build.Builder,
Buildpacks: build.Buildpacks,
}
if opts.DockerfilePath, err = resolveDockerfilePath(ctx, appConfig); err != nil {
return
}
if target := appConfig.DockerBuildTarget(); target != "" {
opts.Target = target
} else if target := flag.GetString(ctx, "build-target"); target != "" {
opts.Target = target
}
// finally, build the image
if img, err = resolver.BuildImage(ctx, io, opts); err == nil && img == nil {
err = errors.New("no image specified")
}
if err == nil {
tb.Printf("image: %s\n", img.Tag)
tb.Printf("image size: %s\n", humanize.Bytes(uint64(img.Size)))
}
return
}
// resolveDockerfilePath returns the absolute path to the Dockerfile
// if one was specified in the app config or a command line argument
func resolveDockerfilePath(ctx context.Context, appConfig *app.Config) (path string, err error) {
defer func() {
if err == nil && path != "" {
path, err = filepath.Abs(path)
}
}()
if path = appConfig.Dockerfile(); path != "" {
path = filepath.Join(filepath.Dir(appConfig.Path), path)
} else {
path = flag.GetString(ctx, "dockerfile")
}
return
}
func mergeBuildArgs(ctx context.Context, args map[string]string) (map[string]string, error) {
if args == nil {
args = make(map[string]string)
}
// set additional Docker build args from the command line, overriding similar ones from the config
cliBuildArgs, err := cmdutil.ParseKVStringsToMap(flag.GetStringSlice(ctx, "build-arg"))
if err != nil {
return nil, fmt.Errorf("invalid build args: %w", err)
}
for k, v := range cliBuildArgs {
args[k] = v
}
return args, nil
}
func fetchImageRef(ctx context.Context, cfg *app.Config) (ref string, err error) {
if ref = flag.GetString(ctx, "image"); ref != "" {
return
}
if cfg != nil && cfg.Build != nil {
if ref = cfg.Build.Image; ref != "" {
return
}
}
return ref, nil
}
func createRelease(ctx context.Context, appConfig *app.Config, img *imgsrc.DeploymentImage) (*api.Release, *api.ReleaseCommand, error) {
tb := render.NewTextBlock(ctx, "Creating release")
input := api.DeployImageInput{
AppID: app.NameFromContext(ctx),
Image: img.Tag,
}
// Set the deployment strategy
if val := flag.GetString(ctx, "strategy"); val != "" {
input.Strategy = api.StringPointer(strings.ToUpper(val))
}
if len(appConfig.Definition) > 0 {
input.Definition = api.DefinitionPtr(appConfig.Definition)
}
// Start deployment of the determined image
client := client.FromContext(ctx).API()
release, releaseCommand, err := client.DeployImage(ctx, input)
if err == nil {
tb.Donef("release v%d created\n", release.Version)
}
return release, releaseCommand, err
}
func watchReleaseCommand(ctx context.Context, id string) error {
g, ctx := errgroup.WithContext(ctx)
io := iostreams.FromContext(ctx)
client := client.FromContext(ctx).API()
interactive := io.IsInteractive()
appName := app.NameFromContext(ctx)
s := spinner.New(spinner.CharSets[11], 100*time.Millisecond)
s.Writer = os.Stderr
s.Prefix = "Running release task..."
if interactive {
s.Start()
defer s.Stop()
}
rcUpdates := make(chan api.ReleaseCommand)
var once sync.Once
startLogs := func(ctx context.Context, vmid string) {
once.Do(func() {
g.Go(func() error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
opts := &logs.LogOptions{MaxBackoff: 1 * time.Second, AppName: appName, VMID: vmid}
ls, err := logs.NewPollingStream(ctx, client, opts)
if err != nil {
return err
}
for entry := range ls.Stream(ctx, opts) {
func() {
if interactive {
s.Stop()
defer s.Start()
}
fmt.Println("\t", entry.Message)
// watch for the shutdown message
if entry.Message == "Starting clean up." {
cancel()
}
}()
}
return ls.Err()
})
})
}
g.Go(func() error {
var lastValue *api.ReleaseCommand
var errorCount int
defer close(rcUpdates)
for {
rc, err := client.GetReleaseCommand(ctx, id)
if err != nil {
errorCount += 1
if errorCount < 3 {
continue
}
return err
}
if !reflect.DeepEqual(lastValue, rc) {
lastValue = rc
rcUpdates <- *rc
}
if !rc.InProgress {
break
}
time.Sleep(500 * time.Millisecond)
}
return nil
})
g.Go(func() error {
// The logs goroutine will stop itself when it sees a shutdown log message.
// If the message never comes (delayed logs, etc) the deploy will hang.
// This timeout makes sure they always stop a few seconds after the release task is done.
logsCtx, logsCancel := context.WithCancel(ctx)
defer time.AfterFunc(3*time.Second, logsCancel)
for rc := range rcUpdates {
if interactive {
s.Prefix = fmt.Sprintf("Running release task (%s)...", rc.Status)
}
if rc.InstanceID != nil {
startLogs(logsCtx, *rc.InstanceID)
}
if !rc.InProgress && rc.Failed {
if rc.Succeeded && interactive {
s.FinalMSG = "Running release task...Done\n"
} else if rc.Failed {
return errors.New("Release command failed, deployment aborted")
}
}
}
return nil
})
return g.Wait()
}
func watchDeployment(ctx context.Context) error {
tb := render.NewTextBlock(ctx, "Monitoring deployment")
io := iostreams.FromContext(ctx)
appName := app.NameFromContext(ctx)
client := client.FromContext(ctx).API()
endmessage := ""
monitor := deployment.NewDeploymentMonitor(client, appName)
monitor.DeploymentStarted = func(idx int, d *api.DeploymentStatus) error {
if idx > 0 {
tb.Println()
}
tb.Println(format.DeploymentSummary(d))
return nil
}
// TODO check we aren't asking for JSON
monitor.DeploymentUpdated = func(d *api.DeploymentStatus, updatedAllocs []*api.AllocationStatus) error {
if io.IsInteractive() {
tb.Overwrite()
tb.Println(format.DeploymentAllocSummary(d))
} else {
for _, alloc := range updatedAllocs {
tb.Println(format.AllocSummary(alloc))
}
}
return nil
}
monitor.DeploymentFailed = func(d *api.DeploymentStatus, failedAllocs []*api.AllocationStatus) error {
// cmdCtx.Statusf("deploy", cmdctx.SDETAIL, "v%d %s - %s\n", d.Version, d.Status, d.Description)
if endmessage == "" && d.Status == "failed" {
if strings.Contains(d.Description, "no stable release to revert to") {
endmessage = fmt.Sprintf("v%d %s - %s\n", d.Version, d.Status, d.Description)
} else {
endmessage = fmt.Sprintf("v%d %s - %s and deploying as v%d \n", d.Version, d.Status, d.Description, d.Version+1)
}
}
if len(failedAllocs) > 0 {
tb.Println("Failed Instances")
x := make(chan *api.AllocationStatus)
var wg sync.WaitGroup
wg.Add(len(failedAllocs))
for _, a := range failedAllocs {
a := a
go func() {
defer wg.Done()
alloc, err := client.GetAllocationStatus(ctx, appName, a.ID, 30)
if err != nil {
//cmdCtx.Status("deploy", cmdctx.SERROR, "Error fetching alloc", a.ID, err)
tb.Printf("failed fetching alloc %s: %s", a.ID, err)
return
}
x <- alloc
}()
}
go func() {
wg.Wait()
close(x)
}()
var count int
for alloc := range x {
count++
tb.Println()
tb.Printf("Failure #%d\n", count)
tb.Println()
as, err := renderAllocationStatus(nil, alloc)
if err != nil {
return fmt.Errorf("failed rendering alloc status: %w", err)
}
tb.Println(as)
re, err := renderRecentEvents(alloc.Events)
if err != nil {
return fmt.Errorf("failed rendering recent events: %w", err)
}
tb.Println(re)
renderLogs(ctx, alloc)
}
}
return nil
}
monitor.DeploymentSucceeded = func(d *api.DeploymentStatus) error {
tb.Donef("v%d deployed successfully\n", d.Version)
return nil
}
monitor.Start(ctx)
if err := monitor.Error(); err != nil {
return err
}
if endmessage != "" {
tb.Done(endmessage)
}
if !monitor.Success() {
tb.Done("Troubleshooting guide at https://fly.io/docs/getting-started/troubleshooting/")
return flyerr.ErrAbort
}
return nil
}
func renderAllocationStatus(br []api.Region, s ...*api.AllocationStatus) (string, error) {
var sb strings.Builder
err := render.AllocationStatuses(&sb, "Instance", br, s...)
return sb.String(), err
}
func renderRecentEvents(events []api.AllocationEvent) (string, error) {
var sb strings.Builder
err := render.AllocationEvents(&sb, "Recent Events", events...)
return sb.String(), err
}
func renderLogs(ctx context.Context, alloc *api.AllocationStatus) {
out := iostreams.FromContext(ctx).Out
cfg := config.FromContext(ctx).JSONOutput
logPresenter := presenters.LogPresenter{
HideAllocID: true,
HideRegion: true,
RemoveNewlines: true,
}
for _, e := range alloc.RecentLogs {
entry := logs.LogEntry{
Instance: e.Instance,
Level: e.Level,
Message: e.Message,
Region: e.Region,
Timestamp: e.Timestamp,
Meta: e.Meta,
}
logPresenter.FPrint(out, cfg, entry)
}
}