-
Notifications
You must be signed in to change notification settings - Fork 221
/
machine.go
856 lines (713 loc) · 21.1 KB
/
machine.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
package cmd
import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/AlecAivazis/survey/v2"
surveyterminal "github.com/AlecAivazis/survey/v2/terminal"
"github.com/dustin/go-humanize"
"github.com/google/shlex"
"github.com/logrusorgru/aurora"
"github.com/olekukonko/tablewriter"
"github.com/pkg/errors"
"github.com/segmentio/textio"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/cmd/presenters"
"github.com/superfly/flyctl/cmdctx"
"github.com/superfly/flyctl/docstrings"
"github.com/superfly/flyctl/helpers"
"github.com/superfly/flyctl/internal/build/imgsrc"
"github.com/superfly/flyctl/internal/client"
"github.com/superfly/flyctl/internal/cmdutil"
"github.com/superfly/flyctl/pkg/logs"
"github.com/superfly/flyctl/terminal"
)
func newMachineCommand(client *client.Client) *Command {
keystrings := docstrings.Get("machine")
cmd := BuildCommandCobra(nil, nil, &cobra.Command{
Use: keystrings.Usage,
Short: keystrings.Short,
Long: keystrings.Long,
Aliases: []string{"machines", "m"},
}, client)
newMachineRunCommand(cmd, client)
newMachineListCommand(cmd, client)
newMachineStopCommand(cmd, client)
newMachineStartCommand(cmd, client)
newMachineKillCommand(cmd, client)
newMachineRemoveCommand(cmd, client)
newMachineCloneCommand(cmd, client)
newMachineStatusCommand(cmd, client)
return cmd
}
func newMachineListCommand(parent *Command, client *client.Client) {
keystrings := docstrings.Get("machine.list")
cmd := BuildCommandCobra(parent, runMachineList, &cobra.Command{
Use: keystrings.Usage,
Short: keystrings.Short,
Long: keystrings.Long,
Aliases: []string{"ls"},
}, client, requireSession, optionalAppName)
cmd.AddBoolFlag(BoolFlagOpts{
Name: "all",
Description: "Show machines in all states",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "state",
Default: "started",
Description: "List machines in a specific state",
})
cmd.AddBoolFlag(BoolFlagOpts{
Name: "quiet",
Shorthand: "q",
Description: "Only list machine ids",
})
}
func runMachineList(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
state := cmdCtx.Config.GetString("state")
if cmdCtx.Config.GetBool("all") {
state = ""
}
machines, err := cmdCtx.Client.API().ListMachines(ctx, cmdCtx.AppName, state)
if err != nil {
return errors.Wrap(err, "could not get list of machines")
}
if cmdCtx.Config.GetBool("quiet") {
for _, machine := range machines {
fmt.Println(machine.ID)
}
return nil
}
data := [][]string{}
for _, machine := range machines {
var ipv6 string
for _, ip := range machine.IPs.Nodes {
if ip.Family == "v6" && ip.Kind == "privatenet" {
ipv6 = ip.IP
}
}
row := []string{
machine.ID,
machine.Config.Image,
machine.CreatedAt.String(),
machine.State,
machine.Region,
machine.Name,
ipv6,
}
if cmdCtx.AppName == "" {
row = append(row, machine.App.Name)
}
data = append(data, row)
}
table := tablewriter.NewWriter(os.Stdout)
headers := []string{"ID", "Image", "Created", "State", "Region", "Name", "IP Address"}
if cmdCtx.AppName == "" {
headers = append(headers, "App")
}
table.SetHeader(headers)
table.SetAutoWrapText(false)
table.SetAutoFormatHeaders(true)
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetRowSeparator("")
table.SetHeaderLine(false)
table.SetBorder(false)
table.SetTablePadding("\t") // pad with tabs
table.SetNoWhiteSpace(true)
table.AppendBulk(data) // Add Bulk Data
table.Render()
return nil
}
func newMachineStopCommand(parent *Command, client *client.Client) {
cmd := BuildCommandKS(parent, runMachineStop, docstrings.Get("machine.stop"), client, requireSession, optionalAppName)
cmd.AddStringFlag(StringFlagOpts{
Name: "signal",
Shorthand: "s",
Description: "Signal to stop the machine with (default: SIGINT)",
})
cmd.AddIntFlag(IntFlagOpts{
Name: "time",
Description: "Seconds to wait before killing the machine",
})
cmd.Args = cobra.MinimumNArgs(1)
}
func runMachineStop(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
for _, arg := range cmdCtx.Args {
input := api.StopMachineInput{
AppID: cmdCtx.AppName,
ID: arg,
Signal: cmdCtx.Config.GetString("signal"),
KillTimeoutSecs: cmdCtx.Config.GetInt("time"),
}
machine, err := cmdCtx.Client.API().StopMachine(ctx, input)
if err != nil {
return errors.Wrap(err, "could not stop machine")
}
fmt.Println(machine.ID)
}
return nil
}
func newMachineStartCommand(parent *Command, client *client.Client) {
cmd := BuildCommandKS(parent, runMachineStart, docstrings.Get("machine.start"), client, requireSession, optionalAppName)
cmd.Args = cobra.ExactArgs(1)
}
func runMachineStart(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
input := api.StartMachineInput{
AppID: cmdCtx.AppName,
ID: cmdCtx.Args[0],
}
machine, err := cmdCtx.Client.API().StartMachine(ctx, input)
if err != nil {
return errors.Wrap(err, "could not stop machine")
}
fmt.Println(machine.ID)
return nil
}
func newMachineKillCommand(parent *Command, client *client.Client) {
cmd := BuildCommandKS(parent, runMachineKill, docstrings.Get("machine.kill"), client, requireSession, optionalAppName)
cmd.Args = cobra.MinimumNArgs(1)
}
func runMachineKill(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
for _, arg := range cmdCtx.Args {
input := api.KillMachineInput{
AppID: cmdCtx.AppName,
ID: arg,
}
machine, err := cmdCtx.Client.API().KillMachine(ctx, input)
if err != nil {
return errors.Wrap(err, "could not stop machine")
}
fmt.Println(machine.ID)
}
return nil
}
func newMachineCloneCommand(parent *Command, client *client.Client) {
keystrings := docstrings.Get("machine.clone")
cmd := BuildCommandCobra(parent, runMachineClone, &cobra.Command{
Use: keystrings.Usage,
Short: keystrings.Short,
Long: keystrings.Long,
Aliases: []string{"clone"},
}, client, requireSession, requireAppName)
cmd.AddStringFlag(StringFlagOpts{
Name: "region",
Shorthand: "r",
Description: "Target region",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "name",
Shorthand: "n",
Description: "The name of the machine",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "organization",
Shorthand: "o",
Description: "Target organization",
})
cmd.Args = cobra.MinimumNArgs(1)
}
func runMachineClone(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
client := cmdCtx.Client.API()
appName := cmdCtx.AppName
machineID := cmdCtx.Args[0]
name := cmdCtx.Config.GetString("name")
regionCode := cmdCtx.Config.GetString("region")
var region *api.Region
region, err := selectRegion(ctx, client, regionCode)
if err != nil {
return err
}
orgCode := cmdCtx.Config.GetString("organization")
org, err := selectOrganization(ctx, client, orgCode, nil)
if err != nil {
return err
}
// TODO - Add GetMachine endpoint so we don't have to query everything.
machines, err := cmdCtx.Client.API().ListMachines(ctx, appName, "")
if err != nil {
return err
}
var machine *api.Machine
for _, m := range machines {
if m.ID == machineID {
machine = m
break
}
}
if machine == nil {
return fmt.Errorf("failed to resolve machine with id: %s", machineID)
}
if len(machine.Config.Mounts) > 0 {
volumeHash, err := helpers.RandString(5)
if err != nil {
return err
}
// This copies the existing Volume spec and just renames it.
mount := machine.Config.Mounts[0]
mount.Volume = fmt.Sprintf("data_%s", volumeHash)
machine.Config.Mounts = []api.MachineMount{mount}
}
input := api.LaunchMachineInput{
AppID: appName,
Name: name,
OrgSlug: org.ID,
Region: region.Code,
Config: &machine.Config,
}
machine, app, err := client.LaunchMachine(ctx, input)
if err != nil {
return err
}
if cmdCtx.Config.GetBool("detach") {
fmt.Println(machine.ID)
return nil
}
opts := &logs.LogOptions{
AppName: app.Name,
VMID: machine.ID,
}
stream, err := logs.NewNatsStream(ctx, client, opts)
if err != nil {
terminal.Debugf("could not connect to wireguard tunnel, err: %v\n", err)
terminal.Debug("Falling back to log polling...")
stream, err = logs.NewPollingStream(ctx, client, opts)
if err != nil {
return err
}
}
presenter := presenters.LogPresenter{}
entries := stream.Stream(ctx, opts)
for {
select {
case <-ctx.Done():
return stream.Err()
case entry := <-entries:
presenter.FPrint(cmdCtx.Out, cmdCtx.OutputJSON(), entry)
}
}
}
func newMachineRemoveCommand(parent *Command, client *client.Client) {
keystrings := docstrings.Get("machine.remove")
cmd := BuildCommandCobra(parent, runMachineRemove, &cobra.Command{
Use: keystrings.Usage,
Short: keystrings.Short,
Long: keystrings.Long,
Aliases: []string{"rm"},
}, client, requireSession, optionalAppName)
cmd.AddBoolFlag(BoolFlagOpts{
Name: "force",
Shorthand: "f",
Description: "force kill machine if it's running",
})
cmd.Args = cobra.MinimumNArgs(1)
}
func runMachineRemove(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
for _, arg := range cmdCtx.Args {
input := api.RemoveMachineInput{
AppID: cmdCtx.AppName,
ID: arg,
Kill: cmdCtx.Config.GetBool("force"),
}
machine, err := cmdCtx.Client.API().RemoveMachine(ctx, input)
if err != nil {
return errors.Wrap(err, "could not stop machine")
}
fmt.Println(machine.ID)
}
return nil
}
func newMachineRunCommand(parent *Command, client *client.Client) {
cmd := BuildCommandKS(parent, runMachineRun, docstrings.Get("machine.run"), client, requireSession, optionalAppName)
cmd.AddStringFlag(StringFlagOpts{
Name: "id",
Description: "Machine ID, is previously known",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "name",
Shorthand: "n",
Description: "Machine name, will be generated if missing",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "org",
Description: `The organization that will own the app`,
})
cmd.AddStringFlag(StringFlagOpts{
Name: "region",
Shorthand: "r",
Description: "Region to deploy the machine to (see `flyctl platform regions`)",
})
cmd.AddStringSliceFlag(StringSliceFlagOpts{
Name: "port",
Shorthand: "p",
Description: "Exposed port mappings (format: edgePort[:machinePort]/[protocol[:handler]])",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "size",
Shorthand: "s",
Description: "Preset guest cpu and memory for a machine",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "cpu-kind",
Description: "Kind of CPU to use (shared, dedicated)",
})
cmd.AddIntFlag(IntFlagOpts{
Name: "cpus",
Description: "Number of CPUs",
})
cmd.AddIntFlag(IntFlagOpts{
Name: "memory",
Description: "Memory (in megabytes) to attribute to the machine",
})
cmd.AddStringSliceFlag(StringSliceFlagOpts{
Name: "env",
Shorthand: "e",
Description: "Set of environment variables in the form of NAME=VALUE pairs. Can be specified multiple times.",
})
cmd.AddStringSliceFlag(StringSliceFlagOpts{
Name: "volume",
Shorthand: "v",
Description: "Volumes to mount in the form of <volume_id_or_name>:/path/inside/machine[:<options>]",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "entrypoint",
Description: "ENTRYPOINT replacement",
})
cmd.AddBoolFlag(BoolFlagOpts{
Name: "detach",
Shorthand: "d",
Description: "Detach from the machine's logs",
})
cmd.AddBoolFlag(BoolFlagOpts{
Name: "build-only",
})
cmd.AddBoolFlag(BoolFlagOpts{
Name: "build-remote-only",
Description: "Perform builds remotely without using the local docker daemon",
})
cmd.AddBoolFlag(BoolFlagOpts{
Name: "build-local-only",
Description: "Only perform builds locally using the local docker daemon",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "dockerfile",
Description: "Path to a Dockerfile. Defaults to the Dockerfile in the working directory.",
})
cmd.AddStringSliceFlag(StringSliceFlagOpts{
Name: "build-arg",
Description: "Set of build time variables in the form of NAME=VALUE pairs. Can be specified multiple times.",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "image-label",
Description: "Image label to use when tagging and pushing to the fly registry. Defaults to \"deployment-{timestamp}\".",
})
cmd.AddStringFlag(StringFlagOpts{
Name: "build-target",
Description: "Set the target build stage to build if the Dockerfile has more than one stage",
})
cmd.AddBoolFlag(BoolFlagOpts{
Name: "no-build-cache",
Description: "Do not use the cache when building the image",
})
cmd.Command.Args = cobra.MinimumNArgs(1)
}
func newMachineStatusCommand(parent *Command, client *client.Client) {
cmd := BuildCommandKS(parent, getMachineStatus, docstrings.Get("machine.status"), client, requireSession, optionalAppName)
cmd.Args = cobra.ExactArgs(1)
}
func getMachineStatus(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
alloc, err := cmdCtx.Client.API().GetAllocationStatus(ctx, cmdCtx.AppName, cmdCtx.Args[0], 25)
if err != nil {
return err
}
if alloc == nil {
return api.ErrNotFound
}
err = cmdCtx.Frender(
cmdctx.PresenterOption{
Title: "Instance",
Presentable: &presenters.Allocations{
Allocations: []*api.AllocationStatus{alloc},
},
Vertical: true,
},
cmdctx.PresenterOption{
Title: "Recent Events",
Presentable: &presenters.AllocationEvents{
Events: alloc.Events,
},
},
cmdctx.PresenterOption{
Title: "Checks",
Presentable: &presenters.AllocationChecks{
Checks: alloc.Checks,
},
},
)
if err != nil {
return err
}
var p io.Writer
var pw *textio.PrefixWriter
if !cmdCtx.OutputJSON() {
fmt.Println(aurora.Bold("Recent Logs"))
pw = textio.NewPrefixWriter(cmdCtx.Out, " ")
p = pw
} else {
p = cmdCtx.Out
}
// logPresenter := presenters.LogPresenter{HideAllocID: true, HideRegion: true, RemoveNewlines: true}
// logPresenter.FPrint(p, ctx.OutputJSON(), alloc.RecentLogs)
if p != cmdCtx.Out {
_ = pw.Flush()
}
return nil
}
func runMachineRun(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
var org *api.Organization
var err error
if cmdCtx.AppName == "" {
confirm := false
prompt := &survey.Confirm{
Message: "Running a machine without specifying an app will create one for you, is this what you want?",
}
err := survey.AskOne(prompt, &confirm)
if err != nil {
if err == surveyterminal.InterruptErr {
return nil
}
return err
}
if !confirm {
return nil
}
orgSlug := cmdCtx.Config.GetString("org")
org, err = selectOrganization(ctx, cmdCtx.Client.API(), orgSlug, nil)
if err != nil {
return err
}
}
if cmdCtx.MachineConfig == nil {
cmdCtx.MachineConfig = &api.MachineConfig{}
}
if extraEnv := cmdCtx.Config.GetStringSlice("env"); len(extraEnv) > 0 {
parsedEnv, err := cmdutil.ParseKVStringsToMap(cmdCtx.Config.GetStringSlice("env"))
if err != nil {
return errors.Wrap(err, "invalid env")
}
cmdCtx.MachineConfig.Env = parsedEnv
}
machineConf := cmdCtx.MachineConfig
var img *imgsrc.DeploymentImage
daemonType := imgsrc.NewDockerDaemonType(!cmdCtx.Config.GetBool("build-remote-only"), !cmdCtx.Config.GetBool("build-local-only"))
resolver := imgsrc.NewResolver(daemonType, cmdCtx.Client.API(), cmdCtx.AppName, cmdCtx.IO)
imageOrPath := cmdCtx.Args[0]
// build if relative or absolute path
if strings.HasPrefix(imageOrPath, ".") || strings.HasPrefix(imageOrPath, "/") {
opts := imgsrc.ImageOptions{
AppName: cmdCtx.AppName,
WorkingDir: path.Join(cmdCtx.WorkingDir, imageOrPath),
Publish: !cmdCtx.Config.GetBool("build-only"),
ImageLabel: cmdCtx.Config.GetString("image-label"),
Target: cmdCtx.Config.GetString("build-target"),
NoCache: cmdCtx.Config.GetBool("no-build-cache"),
}
if dockerfilePath := cmdCtx.Config.GetString("dockerfile"); dockerfilePath != "" {
dockerfilePath, err := filepath.Abs(dockerfilePath)
if err != nil {
return err
}
opts.DockerfilePath = dockerfilePath
}
extraArgs, err := cmdutil.ParseKVStringsToMap(cmdCtx.Config.GetStringSlice("build-arg"))
if err != nil {
return errors.Wrap(err, "invalid build-arg")
}
opts.ExtraBuildArgs = extraArgs
img, err = resolver.BuildImage(ctx, cmdCtx.IO, opts)
if err != nil {
return err
}
if img == nil {
return errors.New("could not find an image to deploy")
}
} else {
opts := imgsrc.RefOptions{
AppName: cmdCtx.AppName,
WorkingDir: cmdCtx.WorkingDir,
Publish: !cmdCtx.Config.GetBool("build-only"),
ImageRef: imageOrPath,
ImageLabel: cmdCtx.Config.GetString("image-label"),
}
img, err = resolver.ResolveReference(ctx, cmdCtx.IO, opts)
if err != nil {
return err
}
}
if img == nil {
return errors.New("could not find an image to deploy")
}
fmt.Fprintf(cmdCtx.Client.IO.Out, "Image: %s\n", img.Tag)
fmt.Fprintf(cmdCtx.Client.IO.Out, "Image size: %s\n", humanize.Bytes(uint64(img.Size)))
if cmdCtx.Config.GetBool("build-only") {
return nil
}
machineConf.Image = img.Tag
guest := api.MachinePresets[cmdCtx.Config.GetString("size")]
if guest == nil {
cpuKind := cmdCtx.Config.GetString("cpu-kind")
if cpuKind == "" {
cpuKind = "shared"
}
cpus := cmdCtx.Config.GetInt("cpus")
if cpus == 0 {
cpus = 1
}
memory := cmdCtx.Config.GetInt("memory")
if memory == 0 {
memory = 256
}
guest = &api.MachineGuest{
CPUKind: cpuKind,
CPUs: cpus,
MemoryMB: memory,
}
} else {
if cpuKind := cmdCtx.Config.GetString("cpu-kind"); cpuKind != "" {
guest.CPUKind = cpuKind
}
if cpus := cmdCtx.Config.GetInt("cpus"); cpus != 0 {
guest.CPUs = cpus
}
if memory := cmdCtx.Config.GetInt("memory"); memory != 0 {
guest.MemoryMB = memory
}
}
machineConf.Guest = guest
if entrypoint := cmdCtx.Config.GetString("entrypoint"); entrypoint != "" {
splitted, err := shlex.Split(entrypoint)
if err != nil {
return errors.Wrap(err, "invalid entrypoint")
}
machineConf.Init.Entrypoint = splitted
}
if cmd := cmdCtx.Args[1:]; len(cmd) > 0 {
machineConf.Init.Cmd = cmd
}
svcs := make([]interface{}, len(cmdCtx.Config.GetStringSlice("port")))
for i, p := range cmdCtx.Config.GetStringSlice("port") {
proto := "tcp"
handlers := []string{}
splittedPortsProto := strings.Split(p, "/")
if len(splittedPortsProto) > 1 {
splittedProtoHandlers := strings.Split(splittedPortsProto[1], ":")
proto = splittedProtoHandlers[0]
handlers = append(handlers, splittedProtoHandlers[1:]...)
}
splittedPorts := strings.Split(splittedPortsProto[0], ":")
edgePort, err := strconv.Atoi(splittedPorts[0])
if err != nil {
return errors.Wrap(err, "invalid edge port")
}
machinePort := edgePort
if len(splittedPorts) > 1 {
machinePort, err = strconv.Atoi(splittedPorts[1])
if err != nil {
return errors.Wrap(err, "invalid machine (internal) port")
}
}
svcs[i] = map[string]interface{}{
"protocol": proto,
"internal_port": machinePort,
"ports": []map[string]interface{}{
{
"port": edgePort,
"handlers": handlers,
},
},
}
}
machineConf.Services = svcs
var mounts []api.MachineMount
for _, v := range cmdCtx.Config.GetStringSlice("volume") {
splittedIDDestOpts := strings.Split(v, ":")
mount := api.MachineMount{
Volume: splittedIDDestOpts[0],
Path: splittedIDDestOpts[1],
}
if len(splittedIDDestOpts) > 2 {
splittedOpts := strings.Split(splittedIDDestOpts[2], ",")
for _, opt := range splittedOpts {
splittedKeyValue := strings.Split(opt, "=")
if splittedKeyValue[0] == "size" {
i, err := strconv.Atoi(splittedKeyValue[1])
if err != nil {
return errors.Wrapf(err, "could not parse volume '%s' size option value '%s', must be an integer", splittedIDDestOpts[0], splittedKeyValue[1])
}
mount.SizeGb = i
} else if splittedKeyValue[0] == "encrypt" {
mount.Encrypted = true
}
}
}
mounts = append(mounts, mount)
}
machineConf.Mounts = mounts
input := api.LaunchMachineInput{
AppID: cmdCtx.AppName,
ID: cmdCtx.Config.GetString("id"),
Name: cmdCtx.Config.GetString("name"),
Region: cmdCtx.Config.GetString("region"),
Config: machineConf,
}
if org != nil {
input.OrgSlug = org.ID
}
machine, app, err := cmdCtx.Client.API().LaunchMachine(ctx, input)
if err != nil {
return err
}
if cmdCtx.Config.GetBool("detach") {
fmt.Println(machine.ID)
return nil
}
apiClient := cmdCtx.Client.API()
opts := &logs.LogOptions{
AppName: app.Name,
VMID: machine.ID,
}
stream, err := logs.NewNatsStream(ctx, apiClient, opts)
if err != nil {
terminal.Debugf("could not connect to wireguard tunnel, err: %v\n", err)
terminal.Debug("Falling back to log polling...")
stream, err = logs.NewPollingStream(ctx, apiClient, opts)
if err != nil {
return err
}
}
presenter := presenters.LogPresenter{}
entries := stream.Stream(ctx, opts)
for {
select {
case <-ctx.Done():
return stream.Err()
case entry := <-entries:
presenter.FPrint(cmdCtx.Out, cmdCtx.OutputJSON(), entry)
}
}
}