-
Notifications
You must be signed in to change notification settings - Fork 222
/
console.go
446 lines (398 loc) · 13.4 KB
/
console.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
package console
import (
"context"
"errors"
"fmt"
"maps"
"slices"
"github.com/google/shlex"
"github.com/samber/lo"
"github.com/spf13/cobra"
fly "github.com/superfly/fly-go"
"github.com/superfly/fly-go/flaps"
"github.com/superfly/flyctl/internal/appconfig"
"github.com/superfly/flyctl/internal/cmdutil"
"github.com/superfly/flyctl/internal/command"
"github.com/superfly/flyctl/internal/command/ssh"
"github.com/superfly/flyctl/internal/config"
"github.com/superfly/flyctl/internal/flag"
"github.com/superfly/flyctl/internal/flapsutil"
"github.com/superfly/flyctl/internal/machine"
"github.com/superfly/flyctl/internal/prompt"
"github.com/superfly/flyctl/iostreams"
"github.com/superfly/flyctl/terminal"
)
func New() *cobra.Command {
const (
usage = "console"
short = "Run a console in a new or existing machine"
long = "Run a console in a new or existing machine. The console command is\n" +
"specified by the `console_command` configuration field. By default, a\n" +
"new machine is created by default using the app's most recently deployed\n" +
"image. An existing machine can be used instead with --machine."
)
cmd := command.New(usage, short, long, runConsole, command.RequireSession, command.RequireAppName)
cmd.Args = cobra.NoArgs
flag.Add(
cmd,
flag.App(),
flag.AppConfig(),
flag.Region(),
flag.Wireguard(),
flag.String{
Name: "machine",
Description: "Run the console in the existing machine with the specified ID",
},
flag.Bool{
Name: "select",
Shorthand: "s",
Description: "Select the machine on which to execute the console from a list.",
Default: false,
},
flag.String{
Name: "user",
Shorthand: "u",
Description: "Unix username to connect as",
Default: ssh.DefaultSshUsername,
},
flag.String{
Name: "image",
Shorthand: "i",
Description: "image to use (default: current release)",
},
flag.StringArray{
Name: "env",
Shorthand: "e",
Description: "Set of environment variables in the form of NAME=VALUE pairs. Can be specified multiple times.",
},
flag.String{
Name: "entrypoint",
Description: "ENTRYPOINT replacement",
},
flag.Bool{
Name: "build-only",
Description: "Only build the image without running the machine",
Hidden: true,
},
flag.Bool{
Name: "build-remote-only",
Description: "Perform builds remotely without using the local docker daemon",
Hidden: true,
},
flag.Bool{
Name: "build-local-only",
Description: "Only perform builds locally using the local docker daemon",
Hidden: true,
},
flag.Bool{
Name: "build-nixpacks",
Description: "Build your image with nixpacks",
Hidden: true,
},
flag.String{
Name: "dockerfile",
Description: "Path to a Dockerfile. Defaults to the Dockerfile in the working directory.",
},
flag.StringArray{
Name: "build-arg",
Description: "Set of build time variables in the form of NAME=VALUE pairs. Can be specified multiple times.",
Hidden: true,
},
flag.String{
Name: "image-label",
Description: "Image label to use when tagging and pushing to the fly registry. Defaults to \"deployment-{timestamp}\".",
Hidden: true,
},
flag.String{
Name: "build-target",
Description: "Set the target build stage to build if the Dockerfile has more than one stage",
Hidden: true,
},
flag.Bool{
Name: "no-build-cache",
Description: "Do not use the cache when building the image",
Hidden: true,
},
flag.String{
Name: "command",
Shorthand: "C",
Default: "",
Description: "command to run on SSH session",
},
flag.StringSlice{
Name: "port",
Shorthand: "p",
Description: `Publish ports, format: port[:machinePort][/protocol[:handler[:handler...]]])
i.e.: --port 80/tcp --port 443:80/tcp:http:tls --port 5432/tcp:pg_tls
To remove a port mapping use '-' as handler, i.e.: --port 80/tcp:-`,
},
flag.Bool{
Name: "skip-dns-registration",
Description: "Do not register the machine's 6PN IP with the internal DNS system",
Default: true,
Hidden: true,
},
flag.StringArray{
Name: "file-local",
Description: "Set of files to write to the Machine, in the form of /path/inside/machine=<local/path> pairs. Can be specified multiple times.",
},
flag.StringArray{
Name: "file-literal",
Description: "Set of literals to write to the Machine, in the form of /path/inside/machine=VALUE pairs, where VALUE is the base64-encoded raw content. Can be specified multiple times.",
},
flag.StringArray{
Name: "file-secret",
Description: "Set of secrets to write to the Machine, in the form of /path/inside/machine=SECRET pairs, where SECRET is the name of the secret. The content of the secret must be base64 encoded. Can be specified multiple times.",
},
flag.VMSizeFlags,
)
return cmd
}
func runConsole(ctx context.Context) error {
var (
io = iostreams.FromContext(ctx)
appName = appconfig.NameFromContext(ctx)
apiClient = fly.ClientFromContext(ctx)
)
app, err := apiClient.GetAppCompact(ctx, appName)
if err != nil {
return fmt.Errorf("failed to get app: %w", err)
}
network, err := apiClient.GetAppNetwork(ctx, app.Name)
if err != nil {
return fmt.Errorf("failed to get app network: %w", err)
}
flapsClient, err := flapsutil.NewClientWithOptions(ctx, flaps.NewClientOpts{
AppCompact: app,
AppName: app.Name,
})
if err != nil {
return fmt.Errorf("failed to create flaps client: %w", err)
}
ctx = flaps.NewContext(ctx, flapsClient)
appConfig := appconfig.ConfigFromContext(ctx)
if appConfig == nil {
appConfig, err = appconfig.FromRemoteApp(ctx, appName)
if err != nil {
return fmt.Errorf("failed to fetch app config from backend: %w", err)
}
}
if err, extraInfo := appConfig.Validate(ctx); err != nil {
fmt.Fprintln(io.ErrOut, extraInfo)
return err
}
machine, cleanup, err := selectMachine(ctx, app, appConfig)
if err != nil {
return err
}
if cleanup != nil {
defer cleanup()
}
_, dialer, err := ssh.BringUpAgent(ctx, apiClient, app, *network, false)
if err != nil {
return err
}
params := &ssh.ConnectParams{
Ctx: ctx,
Org: app.Organization,
Dialer: dialer,
Username: flag.GetString(ctx, "user"),
DisableSpinner: false,
AppNames: []string{app.Name},
}
sshClient, err := ssh.Connect(params, machine.PrivateIP)
if err != nil {
return err
}
consoleCommand := appConfig.ConsoleCommand
if flag.IsSpecified(ctx, "command") {
consoleCommand = flag.GetString(ctx, "command")
}
return ssh.Console(ctx, sshClient, consoleCommand, true)
}
func selectMachine(ctx context.Context, app *fly.AppCompact, appConfig *appconfig.Config) (*fly.Machine, func(), error) {
if flag.GetBool(ctx, "select") {
return promptForMachine(ctx, app, appConfig)
} else if flag.IsSpecified(ctx, "machine") {
return getMachineByID(ctx)
} else {
guest, err := determineEphemeralConsoleMachineGuest(ctx, appConfig)
if err != nil {
return nil, nil, err
}
return makeEphemeralConsoleMachine(ctx, app, appConfig, guest)
}
}
func promptForMachine(ctx context.Context, app *fly.AppCompact, appConfig *appconfig.Config) (*fly.Machine, func(), error) {
if flag.IsSpecified(ctx, "machine") {
return nil, nil, errors.New("--machine can't be used with -s/--select")
}
flapsClient := flaps.FromContext(ctx)
machines, err := flapsClient.ListActive(ctx)
if err != nil {
return nil, nil, err
}
machines = lo.Filter(machines, func(machine *fly.Machine, _ int) bool {
return machine.State == fly.MachineStateStarted
})
ephemeralGuest, err := determineEphemeralConsoleMachineGuest(ctx, appConfig)
if err != nil {
return nil, nil, err
}
cpuS := lo.Ternary(ephemeralGuest.CPUs == 1, "", "s")
ephemeralGuestStr := fmt.Sprintf("%d %s CPU%s, %d MB of memory", ephemeralGuest.CPUs, ephemeralGuest.CPUKind, cpuS, ephemeralGuest.MemoryMB)
options := []string{fmt.Sprintf("create an ephemeral machine (%s)", ephemeralGuestStr)}
for _, machine := range machines {
options = append(options, fmt.Sprintf("%s: %s %s %s", machine.Region, machine.ID, machine.PrivateIP, machine.Name))
}
index := 0
if err := prompt.Select(ctx, &index, "Select a machine:", "", options...); err != nil {
return nil, nil, fmt.Errorf("failed to prompt for a machine: %w", err)
}
if index == 0 {
return makeEphemeralConsoleMachine(ctx, app, appConfig, ephemeralGuest)
} else {
return machines[index-1], nil, nil
}
}
func getMachineByID(ctx context.Context) (*fly.Machine, func(), error) {
if flag.IsSpecified(ctx, "vm-cpus") {
return nil, nil, errors.New("--vm-cpus can't be used with --machine")
}
if flag.IsSpecified(ctx, "vm-memory") {
return nil, nil, errors.New("--vm-memory can't be used with --machine")
}
if flag.IsSpecified(ctx, "region") {
return nil, nil, errors.New("--region can't be used with --machine")
}
flapsClient := flaps.FromContext(ctx)
machineID := flag.GetString(ctx, "machine")
machine, err := flapsClient.Get(ctx, machineID)
if err != nil {
return nil, nil, err
}
if machine.State != fly.MachineStateStarted {
return nil, nil, fmt.Errorf("machine %s is not started", machineID)
}
if machine.IsFlyAppsReleaseCommand() {
return nil, nil, fmt.Errorf("machine %s is a release command machine", machineID)
}
return machine, nil, nil
}
func makeEphemeralConsoleMachine(ctx context.Context, app *fly.AppCompact, appConfig *appconfig.Config, guest *fly.MachineGuest) (*fly.Machine, func(), error) {
apiClient := fly.ClientFromContext(ctx)
currentRelease, err := apiClient.GetAppCurrentReleaseMachines(ctx, app.Name)
if err != nil {
return nil, nil, err
}
if !flag.IsSpecified(ctx, "image") && flag.IsSpecified(ctx, "dockerfile") {
flag.SetString(ctx, "image", ".")
}
if currentRelease == nil && !flag.IsSpecified(ctx, "image") {
return nil, nil, errors.New("can't create an ephemeral console machine since the app has not yet been released")
}
machConfig, err := appConfig.ToConsoleMachineConfig()
if err != nil {
return nil, nil, fmt.Errorf("failed to generate ephemeral console machine configuration: %w", err)
}
machConfig.Mounts, err = command.DetermineMounts(ctx, machConfig.Mounts, config.FromContext(ctx).Region)
if err != nil {
return nil, nil, fmt.Errorf("unable to process mounts: %w", err)
}
if flag.IsSpecified(ctx, "image") {
img, err := command.DetermineImage(ctx, app.Name, flag.GetString(ctx, "image"))
if err != nil {
return nil, nil, fmt.Errorf("failed to get image: %w", err)
}
machConfig.Image = img.Tag
} else {
machConfig.Image = currentRelease.ImageRef
}
if env := flag.GetStringArray(ctx, "env"); len(env) > 0 {
parsedEnv, err := cmdutil.ParseKVStringsToMap(env)
if err != nil {
return nil, nil, fmt.Errorf("failed parsing environment: %w", err)
}
maps.Copy(machConfig.Env, parsedEnv)
}
if machConfig.DNS == nil {
machConfig.DNS = &fly.DNSConfig{}
}
machConfig.DNS.SkipRegistration = flag.GetBool(ctx, "skip-dns-registration")
machineFiles, err := command.FilesFromCommand(ctx)
if err != nil {
return nil, nil, fmt.Errorf("failed parsing files: %w", err)
}
fly.MergeFiles(machConfig, machineFiles)
machConfig.Guest = guest
services, err := command.DetermineServices(ctx, machConfig.Services)
if err != nil {
return nil, nil, fmt.Errorf("failed parsing port: %w", err)
}
machConfig.Services = services
if entrypoint := flag.GetString(ctx, "entrypoint"); entrypoint != "" {
splitted, err := shlex.Split(entrypoint)
if err != nil {
return nil, nil, fmt.Errorf("invalid entrypoint: %w", err)
}
machConfig.Init.Entrypoint = splitted
}
if hdid := appConfig.HostDedicationID; hdid != "" {
machConfig.Guest.HostDedicationID = hdid
}
input := &machine.EphemeralInput{
LaunchInput: fly.LaunchMachineInput{
Config: machConfig,
Region: config.FromContext(ctx).Region,
},
What: "to run the console",
}
return machine.LaunchEphemeral(ctx, input)
}
func determineEphemeralConsoleMachineGuest(ctx context.Context, appConfig *appconfig.Config) (*fly.MachineGuest, error) {
var guest *fly.MachineGuest
haveConsoleVMSection := 0 <= slices.IndexFunc(
appConfig.Compute,
func(c *appconfig.Compute) bool {
return slices.Index(c.Processes, "console") >= 0
},
)
if haveConsoleVMSection {
groupConfig, err := appConfig.ToMachineConfig("console", nil)
if err != nil {
return nil, fmt.Errorf("failed to check Machine configuration for the 'console' group: %w", err)
}
guest = groupConfig.Guest
}
guest, err := flag.GetMachineGuest(ctx, guest)
if err != nil {
return nil, fmt.Errorf("invalid arguments: %w", err)
}
var minMemory, maxMemory int
switch guest.CPUKind {
case "shared":
minMemory = guest.CPUs * fly.MIN_MEMORY_MB_PER_SHARED_CPU
maxMemory = guest.CPUs * fly.MAX_MEMORY_MB_PER_SHARED_CPU
case "performance":
minMemory = guest.CPUs * fly.MIN_MEMORY_MB_PER_CPU
maxMemory = guest.CPUs * fly.MAX_MEMORY_MB_PER_CPU
default:
return nil, fmt.Errorf("invalid CPU kind '%s'; this is a bug", guest.CPUKind)
}
adjusted := lo.Clamp(guest.MemoryMB, minMemory, maxMemory)
if adjusted != guest.MemoryMB {
action := lo.Ternary(adjusted < guest.MemoryMB, "lowered", "raised")
cpuS := lo.Ternary(guest.CPUs == 1, "", "s")
terminal.Warnf(
"Ephemeral machine memory will be %s from %d MB to %d MB to be compatible with %d %s CPU%s.",
action,
guest.MemoryMB,
adjusted,
guest.CPUs,
guest.CPUKind,
cpuS,
)
}
guest.MemoryMB = adjusted
return guest, nil
}