-
Notifications
You must be signed in to change notification settings - Fork 8
/
cmd.go
652 lines (530 loc) · 16.6 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
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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package cluster
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"os"
"os/exec"
"time"
"github.com/charmbracelet/bubbles/table"
"github.com/dustin/go-humanize"
"github.com/spf13/cobra"
"namespacelabs.dev/foundation/internal/cli/fncobra"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/console/tui"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/fnnet"
"namespacelabs.dev/foundation/internal/localexec"
"namespacelabs.dev/foundation/internal/providers/nscloud/api"
"namespacelabs.dev/foundation/internal/providers/nscloud/ctl"
"namespacelabs.dev/foundation/internal/sdk/host"
"namespacelabs.dev/foundation/internal/sdk/kubectl"
"namespacelabs.dev/foundation/internal/workspace/dirs"
)
func NewClusterCmd(hidden bool) *cobra.Command {
cmd := &cobra.Command{
Use: "cluster",
Short: "Cluster-related activities.",
Hidden: hidden,
}
cmd.AddCommand(newCreateCmd())
cmd.AddCommand(newListCmd())
cmd.AddCommand(newSshCmd())
cmd.AddCommand(newPortForwardCmd())
cmd.AddCommand(newDestroyCmd())
cmd.AddCommand(NewKubectlCmd())
cmd.AddCommand(newKubeconfigCmd())
cmd.AddCommand(newBuildctlCmd())
cmd.AddCommand(newBuildCmd())
cmd.AddCommand(newHistoryCmd())
cmd.AddCommand(newLogsCmd())
return cmd
}
func newCreateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "create",
Short: "Creates a new cluster.",
Args: cobra.NoArgs,
}
machineType := cmd.Flags().String("machine_type", "", "Specify the machine type.")
ephemeral := cmd.Flags().Bool("ephemeral", false, "Create an ephemeral cluster.")
features := cmd.Flags().StringSlice("features", nil, "A set of features to attach to the cluster.")
waitKubeSystem := cmd.Flags().Bool("wait_kube_system", false, "If true, wait until kube-system resources (e.g. coredns and local-path-provisioner) are ready.")
outputPath := cmd.Flags().String("output_to", "", "If specified, write the cluster id to this path.")
outputRegistryPath := cmd.Flags().String("output_registry_to", "", "If specified, write the registry address to this path.")
userSshey := cmd.Flags().String("ssh_key", "", "Injects the specified ssh public key in the created cluster.")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
opts := api.CreateClusterOpts{
MachineType: *machineType,
Ephemeral: *ephemeral,
KeepAlive: true,
Purpose: "manually created",
Features: *features,
}
if *userSshey != "" {
keyData, err := os.ReadFile(*userSshey)
if err != nil {
return fnerrors.New("failed to load key: %w", err)
}
opts.AuthorizedSshKeys = append(opts.AuthorizedSshKeys, string(keyData))
}
cluster, err := api.CreateAndWaitCluster(ctx, api.Endpoint, opts)
if err != nil {
return err
}
if *waitKubeSystem {
if err := ctl.WaitKubeSystem(ctx, cluster.Cluster); err != nil {
return err
}
}
if *outputPath != "" {
if err := os.WriteFile(*outputPath, []byte(cluster.ClusterId), 0644); err != nil {
return fnerrors.New("failed to write %q: %w", *outputPath, err)
}
}
if *outputRegistryPath != "" {
if err := os.WriteFile(*outputRegistryPath, []byte(cluster.Registry.EndpointAddress), 0644); err != nil {
return fnerrors.New("failed to write %q: %w", *outputRegistryPath, err)
}
}
stdout := console.Stdout(ctx)
fmt.Fprintf(stdout, "Created cluster %q\n", cluster.ClusterId)
if cluster.Deadline != nil {
fmt.Fprintf(stdout, " deadline: %s\n", cluster.Deadline.Format(time.RFC3339))
} else {
fmt.Fprintf(stdout, " no deadline\n")
}
return nil
})
return cmd
}
func newListCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "Lists all of your clusters.",
Args: cobra.NoArgs,
}
rawOutput := cmd.Flags().Bool("raw_output", false, "Dump the resulting server response, without formatting.")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
history := false
clusters, err := api.ListClusters(ctx, api.Endpoint, history)
if err != nil {
return err
}
stdout := console.Stdout(ctx)
if *rawOutput {
enc := json.NewEncoder(stdout)
enc.SetIndent("", " ")
return enc.Encode(clusters)
}
return staticTableClusters(ctx, clusters.Clusters, history)
})
return cmd
}
func newSshCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "ssh [cluster-id]",
Short: "Start an SSH session.",
Args: cobra.MaximumNArgs(1),
}
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
cluster, err := selectCluster(ctx, args)
if err != nil {
return err
}
if cluster == nil {
return nil
}
return dossh(ctx, cluster, nil)
})
return cmd
}
func newPortForwardCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "port-forward [cluster-id]",
Short: "Opens a local port which connects to the cluster.",
Args: cobra.MaximumNArgs(1),
}
port := cmd.Flags().Int("target_port", 0, "Which port to forward to.")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
if *port == 0 {
return fnerrors.New("--target_port is required")
}
cluster, err := selectCluster(ctx, args)
if err != nil {
return err
}
if cluster == nil {
return nil
}
return portForward(ctx, cluster, *port)
})
return cmd
}
func newDestroyCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "destroy [cluster-id]",
Short: "Destroys an existing cluster.",
Args: cobra.ArbitraryArgs,
}
force := cmd.Flags().Bool("force", false, "Skip the confirmation step.")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
clusters, err := selectClusters(ctx, args)
if err != nil {
return err
}
for _, cluster := range clusters {
if !*force {
result, err := tui.Ask(ctx, "Do you want to remove this cluster?",
fmt.Sprintf(`This is a destructive action.
Type %q for it to be removed.`, cluster.ClusterId), "")
if err != nil {
return err
}
if result != cluster.ClusterId {
return context.Canceled
}
}
if err := api.DestroyCluster(ctx, api.Endpoint, cluster.ClusterId); err != nil {
return err
}
}
return nil
})
return cmd
}
func NewKubectlCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "kubectl -- ...",
Short: "Run kubectl on the target cluster.",
Args: cobra.MinimumNArgs(1),
}
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
clusterName := args[0]
args = args[1:]
response, err := api.GetCluster(ctx, api.Endpoint, clusterName)
if err != nil {
return err
}
cluster := response.Cluster
cfg, err := kubectl.WriteRawKubeconfig(ctx, ctl.MakeConfig(cluster), false)
if err != nil {
return err
}
defer func() { _ = cfg.Cleanup() }()
cmdLine := append(cfg.BaseArgs(), args...)
kubectlBin, err := kubectl.EnsureSDK(ctx, host.HostPlatform())
if err != nil {
return fnerrors.New("failed to download Kubernetes SDK: %w", err)
}
kubectl := exec.CommandContext(ctx, string(kubectlBin), cmdLine...)
return localexec.RunInteractive(ctx, kubectl)
})
return cmd
}
func newKubeconfigCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "kubeconfig",
Short: "Write Kubeconfig for the target cluster.",
}
outputPath := cmd.Flags().String("output_to", "", "If specified, write the path of the Kubeconfig to this path.")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
cluster, err := selectCluster(ctx, args)
if err != nil {
return err
}
if cluster == nil {
return nil
}
cfg, err := kubectl.WriteRawKubeconfig(ctx, ctl.MakeConfig(cluster), false)
if err != nil {
return err
}
if *outputPath != "" {
if err := os.WriteFile(*outputPath, []byte(cfg.Kubeconfig), 0644); err != nil {
return fnerrors.New("failed to write %q: %w", *outputPath, err)
}
}
fmt.Fprintf(console.Stdout(ctx), "Wrote Kubeconfig for cluster %s to %s.\n", cluster.ClusterId, cfg.Kubeconfig)
return nil
})
return cmd
}
func newHistoryCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "history",
Short: "History of your previous running clusters.",
Args: cobra.NoArgs,
}
rawOutput := cmd.Flags().Bool("raw_output", false, "Dump the resulting server response, without formatting.")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
history := true
clusters, err := api.ListClusters(ctx, api.Endpoint, history)
if err != nil {
return err
}
stdout := console.Stdout(ctx)
if *rawOutput {
enc := json.NewEncoder(stdout)
enc.SetIndent("", " ")
return enc.Encode(clusters)
}
return staticTableClusters(ctx, clusters.Clusters, history)
})
return cmd
}
func newLogsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "logs [cluster-id]",
Short: "Prints log for a cluster.",
Args: cobra.MaximumNArgs(1),
}
follow := cmd.Flags().BoolP("follow", "f", false, "Specify if the logs should be streamed.")
namespace := cmd.Flags().StringP("namespace", "n", "", "Print the logs of this namespace.")
pod := cmd.Flags().StringP("pod", "p", "", "Print the logs of this pod.")
container := cmd.Flags().StringP("container", "c", "", "Print the logs of this container.")
since := cmd.Flags().Duration("since", time.Duration(0), "Show logs since a relative timestamp (e.g. 42m for 42 minutes). The flag can't be use with --follow.")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
cluster, err := selectCluster(ctx, args)
if err != nil {
return err
}
if cluster == nil {
return nil
}
if *follow && *since != time.Duration(0) {
return fnerrors.New("--follow flag can't be used with --since flag")
}
stdout := console.Stdout(ctx)
if *follow {
return api.TailClusterLogs(ctx, api.Endpoint, &api.LogsOpts{
ClusterID: cluster.ClusterId,
Namespace: *namespace,
Pod: *pod,
Container: *container,
}, stdout)
}
logOpts := &api.LogsOpts{
ClusterID: cluster.ClusterId,
Namespace: *namespace,
Pod: *pod,
Container: *container,
}
if *since != time.Duration(0) {
ts := time.Now().Add(-1 * (*since))
logOpts.StartTs = &ts
}
logs, err := api.GetClusterLogs(ctx, api.Endpoint, logOpts)
if err != nil {
return fnerrors.New("failed to get cluster logs: %w", err)
}
for _, lb := range logs.LogBlock {
for _, l := range lb.Line {
fmt.Fprintln(stdout, l.String())
}
}
return nil
})
return cmd
}
func selectClusters(ctx context.Context, names []string) ([]*api.KubernetesCluster, error) {
var res []*api.KubernetesCluster
previousRuns := false
for _, name := range names {
response, err := api.GetCluster(ctx, api.Endpoint, name)
if err != nil {
return nil, err
}
res = append(res, response.Cluster)
}
if len(res) > 0 {
return res, nil
}
clusters, err := api.ListClusters(ctx, api.Endpoint, previousRuns)
if err != nil {
return nil, err
}
cl, err := selectTableClusters(ctx, clusters.Clusters, previousRuns)
if err != nil {
return nil, err
}
return []*api.KubernetesCluster{cl}, nil
}
func selectCluster(ctx context.Context, args []string) (*api.KubernetesCluster, error) {
clusters, err := selectClusters(ctx, args)
if err != nil {
return nil, err
}
switch len(clusters) {
case 1:
return clusters[0], nil
case 0:
return nil, nil
default:
return nil, fnerrors.InternalError("got %d clusters - expected one", len(clusters))
}
}
func tableClusters(ctx context.Context,
clusters []api.KubernetesCluster, previousRuns, selectCluster bool) (*api.KubernetesCluster, error) {
clusterIdMap := map[string]api.KubernetesCluster{}
cols := []table.Column{
{Title: "Cluster ID", Width: 15},
{Title: "CPU", Width: 5},
{Title: "Memory", Width: 7},
{Title: "Created", Width: 15},
}
if previousRuns {
cols = append(cols, table.Column{Title: "Duration", Width: 10})
} else {
cols = append(cols, table.Column{Title: "Time to live", Width: 20})
}
cols = append(cols, table.Column{Title: "Purpose", Width: 10})
rows := []table.Row{}
for _, cluster := range clusters {
clusterIdMap[cluster.ClusterId] = cluster
if previousRuns && cluster.DestroyedAt == "" {
continue
}
cpu := fmt.Sprintf("%d", cluster.Shape.VirtualCpu)
ram := humanize.IBytes(uint64(cluster.Shape.MemoryMegabytes) * humanize.MiByte)
created, _ := time.Parse(time.RFC3339, cluster.Created)
deadline, _ := time.Parse(time.RFC3339, cluster.Deadline)
row := []string{cluster.ClusterId,
cpu,
ram,
humanize.Time(created.Local()),
}
if previousRuns {
destroyedAt, _ := time.Parse(time.RFC3339, cluster.DestroyedAt)
row = append(row, destroyedAt.Sub(created).Truncate(time.Second).String())
} else {
row = append(row, humanize.Time(deadline.Local()))
}
purpose := "-"
if cluster.DocumentedPurpose != "" {
purpose = cluster.DocumentedPurpose
}
row = append(row, purpose)
rows = append(rows, row)
}
if selectCluster {
row, err := tui.SelectTable(ctx, cols, rows)
if err != nil {
return nil, err
}
cl := clusterIdMap[row[0]]
return &cl, nil
}
err := tui.StaticTable(ctx, cols, rows)
return nil, err
}
func staticTableClusters(ctx context.Context,
clusters []api.KubernetesCluster, previousRuns bool) error {
_, err := tableClusters(ctx, clusters, previousRuns, false)
return err
}
func selectTableClusters(ctx context.Context,
clusters []api.KubernetesCluster, previousRuns bool) (*api.KubernetesCluster, error) {
return tableClusters(ctx, clusters, previousRuns, true)
}
type cluster api.KubernetesCluster
func (d cluster) Cluster() api.KubernetesCluster { return api.KubernetesCluster(d) }
func (d cluster) Title() string { return d.ClusterId }
func (d cluster) Description() string { return formatDescription(api.KubernetesCluster(d), false) }
func (d cluster) FilterValue() string { return d.ClusterId }
func formatDescription(cluster api.KubernetesCluster, history bool) string {
cpu := "<unknown>"
ram := "<unknown>"
if shape := cluster.Shape; shape != nil {
cpu = fmt.Sprintf("%d", shape.VirtualCpu)
ram = humanize.IBytes(uint64(shape.MemoryMegabytes) * humanize.MiByte)
}
created, _ := time.Parse(time.RFC3339, cluster.Created)
deadline, _ := time.Parse(time.RFC3339, cluster.Deadline)
destroyedAt, _ := time.Parse(time.RFC3339, cluster.DestroyedAt)
if history {
return fmt.Sprintf("[cpu: %s ram: %s] (created %v, destroyed %v, lasted %v, dist: %s): %s",
cpu, ram, created.Local(), destroyedAt.Local(), destroyedAt.Sub(created),
cluster.KubernetesDistribution, cluster.DocumentedPurpose)
}
return fmt.Sprintf("[cpu: %s ram: %s] (created %v, for %v, dist: %s): %s",
cpu, ram, created.Local(), time.Until(deadline),
cluster.KubernetesDistribution, cluster.DocumentedPurpose)
}
func dossh(ctx context.Context, cluster *api.KubernetesCluster, args []string) error {
lst, err := fnnet.ListenPort(ctx, "127.0.0.1", 0, 0)
if err != nil {
return err
}
go func() {
for {
conn, err := lst.Accept()
if err != nil {
return
}
go func() {
defer conn.Close()
peerConn, err := api.DialPort(ctx, cluster, 22)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to connect: %v\n", err)
return
}
go func() {
_, _ = io.Copy(conn, peerConn)
}()
_, _ = io.Copy(peerConn, conn)
}()
}
}()
localPort := lst.Addr().(*net.TCPAddr).Port
args = append(args,
"-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "UpdateHostKeys no",
"-p", fmt.Sprintf("%d", localPort), "root@127.0.0.1")
if cluster.SshPrivateKey != nil {
f, err := dirs.CreateUserTemp("ssh", "privatekey")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(cluster.SshPrivateKey); err != nil {
return err
}
args = append(args, "-i", f.Name())
}
cmd := exec.CommandContext(ctx, "ssh", args...)
return localexec.RunInteractive(ctx, cmd)
}
func portForward(ctx context.Context, cluster *api.KubernetesCluster, targetPort int) error {
lst, err := fnnet.ListenPort(ctx, "127.0.0.1", 0, targetPort)
if err != nil {
return err
}
localPort := lst.Addr().(*net.TCPAddr).Port
fmt.Fprintf(console.Stdout(ctx), "Listening on 127.0.0.1:%d\n", localPort)
for {
conn, err := lst.Accept()
if err != nil {
return err
}
fmt.Fprintf(console.Stdout(ctx), "New connection from %v\n", conn.RemoteAddr())
go func() {
defer conn.Close()
proxyConn, err := api.DialPort(ctx, cluster, targetPort)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to connect: %v\n", err)
return
}
go func() {
_, _ = io.Copy(conn, proxyConn)
}()
_, _ = io.Copy(proxyConn, conn)
}()
}
}