-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathls.go
More file actions
782 lines (702 loc) · 23.5 KB
/
Copy pathls.go
File metadata and controls
782 lines (702 loc) · 23.5 KB
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
// Package ls lists workspaces in the current org
package ls
import (
"context"
"encoding/json"
"fmt"
"os"
"sync"
nodev1 "buf.build/gen/go/brevdev/devplane/protocolbuffers/go/devplaneapi/v1"
"connectrpc.com/connect"
"github.com/brevdev/brev-cli/pkg/analytics"
"github.com/brevdev/brev-cli/pkg/externalnode"
"github.com/brevdev/brev-cli/pkg/cmd/cmderrors"
"github.com/brevdev/brev-cli/pkg/cmd/completions"
"github.com/brevdev/brev-cli/pkg/cmd/gpusearch"
"github.com/brevdev/brev-cli/pkg/cmd/hello"
"github.com/brevdev/brev-cli/pkg/cmd/register"
cmdutil "github.com/brevdev/brev-cli/pkg/cmd/util"
"github.com/brevdev/brev-cli/pkg/cmdcontext"
"github.com/brevdev/brev-cli/pkg/config"
"github.com/brevdev/brev-cli/pkg/entity"
breverrors "github.com/brevdev/brev-cli/pkg/errors"
"github.com/brevdev/brev-cli/pkg/featureflag"
"github.com/brevdev/brev-cli/pkg/store"
"github.com/brevdev/brev-cli/pkg/terminal"
"github.com/brevdev/brev-cli/pkg/util"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
)
type LsStore interface {
GetWorkspaces(organizationID string, options *store.GetWorkspacesOptions) ([]entity.Workspace, error)
GetActiveOrganizationOrDefault() (*entity.Organization, error)
GetCurrentUser() (*entity.User, error)
GetUsers(queryParams map[string]string) ([]entity.User, error)
GetWorkspace(workspaceID string) (*entity.Workspace, error)
GetOrganizations(options *store.GetOrganizationsOptions) ([]entity.Organization, error)
GetAccessToken() (string, error)
GetInstanceTypes(includeCPU bool) (*gpusearch.InstanceTypesResponse, error)
hello.HelloStore
}
func NewCmdLs(t *terminal.Terminal, loginLsStore LsStore, noLoginLsStore LsStore) *cobra.Command {
var showAll bool
var org string
var jsonOutput bool
cmd := &cobra.Command{
Annotations: map[string]string{"workspace": ""},
Use: "ls",
Aliases: []string{"list"},
Short: "List instances within active org",
Long: `List instances within your active org. List all instances if no active org is set.
Subcommands:
instances List cloud instances
nodes List external nodes only
orgs List organizations
When stdout is piped, outputs instance names only (one per line) for easy chaining
with other commands like stop, start, or delete.`,
Example: `
brev ls
brev ls instances
brev ls nodes
brev ls --json
brev ls | grep running | brev stop
brev ls orgs
brev ls orgs --json
`,
PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
if hello.ShouldWeRunOnboardingLSStep(noLoginLsStore) && hello.ShouldWeRunOnboarding(noLoginLsStore) {
// Getting the workspaces should go in the hello.go file but then
// requires passing in stores and that makes it hard to use in other commands
org, err := getOrgForRunLs(loginLsStore, org)
if err != nil {
return err
}
allWorkspaces, err := loginLsStore.GetWorkspaces(org.ID, nil)
if err != nil {
return breverrors.WrapAndTrace(err)
}
user, err := loginLsStore.GetCurrentUser()
if err != nil {
return breverrors.WrapAndTrace(err)
}
var myWorkspaces []entity.Workspace
for _, v := range allWorkspaces {
if v.CreatedByUserID == user.ID {
myWorkspaces = append(myWorkspaces, v)
}
}
err = hello.Step1(t, myWorkspaces, user, loginLsStore)
if err != nil {
return breverrors.WrapAndTrace(err)
}
}
return cmdcontext.InvokeParentPersistentPostRun(cmd, args)
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
err := cmdcontext.InvokeParentPersistentPreRun(cmd, args)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
},
Args: cmderrors.TransformToValidationError(cobra.MinimumNArgs(0)),
ValidArgs: []string{"orgs", "workspaces", "nodes", "instances"},
RunE: func(cmd *cobra.Command, args []string) error {
err := RunLs(t, loginLsStore, args, org, showAll, jsonOutput)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if !jsonOutput {
trackLsAnalytics(loginLsStore)
}
return nil
},
}
cmd.Flags().StringVarP(&org, "org", "o", "", "organization (will override active org)")
err := cmd.RegisterFlagCompletionFunc("org", completions.GetOrgsNameCompletionHandler(noLoginLsStore, t))
if err != nil {
breverrors.GetDefaultErrorReporter().ReportError(breverrors.WrapAndTrace(err))
fmt.Print(breverrors.WrapAndTrace(err))
}
cmd.Flags().BoolVar(&showAll, "all", false, "show all workspaces in org")
cmd.Flags().BoolVar(&jsonOutput, "json", false, "output as JSON")
return cmd
}
// trackLsAnalytics sends analytics event for ls command
func trackLsAnalytics(store LsStore) {
userID := ""
user, err := store.GetCurrentUser()
if err == nil {
userID = user.ID
}
data := analytics.EventData{
EventName: "Brev ls",
UserID: userID,
}
_ = analytics.TrackEvent(data)
}
func getOrgForRunLs(lsStore LsStore, orgflag string) (*entity.Organization, error) {
var org *entity.Organization
if orgflag != "" {
var orgs []entity.Organization
orgs, err := lsStore.GetOrganizations(&store.GetOrganizationsOptions{Name: orgflag})
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
if len(orgs) == 0 {
return nil, breverrors.NewValidationError(fmt.Sprintf("no org found with name %s", orgflag))
} else if len(orgs) > 1 {
return nil, breverrors.NewValidationError(fmt.Sprintf("more than one org found with name %s", orgflag))
}
org = &orgs[0]
} else {
var currOrg *entity.Organization
currOrg, err := lsStore.GetActiveOrganizationOrDefault()
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
if currOrg == nil {
return nil, breverrors.NewValidationError("no orgs exist")
}
org = currOrg
}
return org, nil
}
func RunLs(t *terminal.Terminal, lsStore LsStore, args []string, orgflag string, showAll bool, jsonOutput bool) error {
ls := NewLs(lsStore, t, jsonOutput)
user, err := lsStore.GetCurrentUser()
if err != nil {
return breverrors.WrapAndTrace(err)
}
org, err := getOrgForRunLs(lsStore, orgflag)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if len(args) > 1 {
return breverrors.NewValidationError("too many args provided")
}
if len(args) == 1 { //nolint:gocritic // don't want to switch
err = handleLsArg(ls, args[0], user, org, showAll)
if err != nil {
return breverrors.WrapAndTrace(err)
}
} else if len(args) == 0 {
err = ls.RunWorkspaces(org, user, showAll)
if err != nil {
return breverrors.WrapAndTrace(err)
}
} else {
return fmt.Errorf("unhandle ls arguments")
}
return nil
}
func handleLsArg(ls *Ls, arg string, user *entity.User, org *entity.Organization, showAll bool) error {
// todo refactor this to cmd.register
//nolint:gocritic // idk how to write this as a switch
if util.IsSingularOrPlural(arg, "org") || util.IsSingularOrPlural(arg, "organization") { // handle org, orgs, and organization(s)
err := ls.RunOrgs()
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
} else if util.IsSingularOrPlural(arg, "workspace") {
err := ls.RunWorkspaces(org, user, showAll)
if err != nil {
return breverrors.WrapAndTrace(err)
}
} else if util.IsSingularOrPlural(arg, "user") && featureflag.IsAdmin(user.GlobalUserType) {
err := ls.RunUser(showAll)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
} else if util.IsSingularOrPlural(arg, "host") && featureflag.IsAdmin(user.GlobalUserType) {
err := ls.RunHosts(org)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
} else if util.IsSingularOrPlural(arg, "node") {
err := ls.RunNodes(org)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
} else if util.IsSingularOrPlural(arg, "instance") {
err := ls.RunInstances(org, user, showAll)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
return nil
}
type Ls struct {
lsStore LsStore
terminal *terminal.Terminal
jsonOutput bool
piped bool
}
func NewLs(lsStore LsStore, terminal *terminal.Terminal, jsonOutput bool) *Ls {
piped := false
if fi, err := os.Stdout.Stat(); err == nil {
piped = fi.Mode()&os.ModeCharDevice == 0
}
return &Ls{
lsStore: lsStore,
terminal: terminal,
jsonOutput: jsonOutput,
piped: piped,
}
}
// OrgInfo represents organization data for JSON output
type OrgInfo struct {
Name string `json:"name"`
ID string `json:"id"`
IsActive bool `json:"is_active"`
}
func (ls Ls) RunOrgs() error {
orgs, err := ls.lsStore.GetOrganizations(nil)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if len(orgs) == 0 {
if ls.jsonOutput {
fmt.Println("[]")
return nil
}
ls.terminal.Vprint(ls.terminal.Yellow(fmt.Sprintf("You don't have any orgs. Create one! %s", config.GlobalConfig.GetConsoleURL())))
return nil
}
defaultOrg, err := ls.lsStore.GetActiveOrganizationOrDefault()
if err != nil {
return breverrors.WrapAndTrace(err)
}
// Handle JSON output
if ls.jsonOutput {
return ls.outputOrgsJSON(orgs, defaultOrg)
}
// Table output with colors and help text
ls.terminal.Vprint(ls.terminal.Yellow("Your organizations:"))
displayOrgTable(ls.terminal, orgs, defaultOrg)
if len(orgs) > 1 {
fmt.Print("\n")
ls.terminal.Vprintf("%s", ls.terminal.Green("Switch orgs:\n"))
notDefaultOrg := getOtherOrg(orgs, *defaultOrg)
// TODO suggest org with max workspaces
ls.terminal.Vprintf("%s", ls.terminal.Yellow("\tbrev set <NAME> ex: brev set %s\n", notDefaultOrg.Name))
}
return nil
}
func (ls Ls) outputOrgsJSON(orgs []entity.Organization, defaultOrg *entity.Organization) error {
var infos []OrgInfo
for _, o := range orgs {
infos = append(infos, OrgInfo{
Name: o.Name,
ID: o.ID,
IsActive: defaultOrg != nil && o.ID == defaultOrg.ID,
})
}
output, err := json.MarshalIndent(infos, "", " ")
if err != nil {
return breverrors.WrapAndTrace(err)
}
fmt.Println(string(output))
return nil
}
func getOtherOrg(orgs []entity.Organization, org entity.Organization) *entity.Organization {
for _, o := range orgs {
if org.ID != o.ID {
return &o
}
}
return nil
}
func (ls Ls) RunUser(_ bool) error {
params := make(map[string]string)
params["verificationStatus"] = "UnVerified"
users, err := ls.lsStore.GetUsers(params)
if err != nil {
return breverrors.WrapAndTrace(err)
}
for _, user := range users {
fmt.Printf("%s %s %s\n", user.ID, user.Name, user.Email)
}
return nil
}
func (ls Ls) ShowAllWorkspaces(org *entity.Organization, otherOrgs []entity.Organization, user *entity.User, allWorkspaces []entity.Workspace, gpuLookup map[string]string) {
userWorkspaces := store.FilterForUserWorkspaces(allWorkspaces, user.ID)
ls.displayWorkspacesAndHelp(org, otherOrgs, userWorkspaces, allWorkspaces, gpuLookup)
}
func (ls Ls) ShowUserWorkspaces(org *entity.Organization, otherOrgs []entity.Organization, user *entity.User, allWorkspaces []entity.Workspace, gpuLookup map[string]string) {
userWorkspaces := store.FilterForUserWorkspaces(allWorkspaces, user.ID)
ls.displayWorkspacesAndHelp(org, otherOrgs, userWorkspaces, allWorkspaces, gpuLookup)
}
func (ls Ls) displayWorkspacesAndHelp(org *entity.Organization, otherOrgs []entity.Organization, userWorkspaces []entity.Workspace, allWorkspaces []entity.Workspace, gpuLookup map[string]string) {
if len(userWorkspaces) == 0 {
ls.terminal.Vprint(ls.terminal.Yellow("No instances in org %s\n", org.Name))
if len(allWorkspaces) > 0 {
ls.terminal.Vprintf("%s", ls.terminal.Green("See teammates' instances:\n"))
ls.terminal.Vprintf("%s", ls.terminal.Yellow("\tbrev ls --all\n"))
} else {
ls.terminal.Vprintf("%s", ls.terminal.Green("Start a new instance:\n"))
}
if len(otherOrgs) > 1 {
ls.terminal.Vprintf("%s", ls.terminal.Green("Switch to another org:\n"))
// TODO suggest org with max workspaces
ls.terminal.Vprintf("%s", ls.terminal.Yellow(fmt.Sprintf("\tbrev set %s\n", getOtherOrg(otherOrgs, *org).Name)))
}
} else {
ls.terminal.Vprintf("You have %d instances in Org %s\n", len(userWorkspaces), ls.terminal.Yellow(org.Name))
displayWorkspacesTable(ls.terminal, userWorkspaces, gpuLookup)
fmt.Print("\n")
displayLsResetBreadCrumb(ls.terminal, userWorkspaces)
}
}
func displayLsResetBreadCrumb(t *terminal.Terminal, workspaces []entity.Workspace) {
foundAResettableWorkspace := false
for _, w := range workspaces {
if w.Status == entity.Failure || getWorkspaceDisplayStatus(w) == entity.Unhealthy {
if !foundAResettableWorkspace {
t.Vprintf("%s", t.Red("Reset unhealthy or failed instance:\n"))
}
t.Vprintf("%s", t.Yellow(fmt.Sprintf("\tbrev reset %s\n", w.Name)))
foundAResettableWorkspace = true
}
}
if foundAResettableWorkspace {
t.Vprintf("%s", t.Yellow("If this problem persists, run the command again with the --hard flag (warning: the --hard flag will not preserve uncommitted files!) \n\n"))
}
}
// buildGPULookup builds a map of instance type name to GPU name.
// Returns nil if the fetch fails (graceful degradation).
func buildGPULookup(s LsStore) map[string]string {
resp, err := s.GetInstanceTypes(true)
if err != nil || resp == nil {
return nil
}
lookup := make(map[string]string, len(resp.Items))
for _, item := range resp.Items {
if len(item.SupportedGPUs) > 0 {
lookup[item.Type] = item.SupportedGPUs[0].Name
} else {
lookup[item.Type] = "-"
}
}
return lookup
}
func (ls Ls) RunWorkspaces(org *entity.Organization, user *entity.User, showAll bool) error {
// Fetch workspaces and instance types concurrently
var allWorkspaces []entity.Workspace
var wsErr error
var gpuLookup map[string]string
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
allWorkspaces, wsErr = ls.lsStore.GetWorkspaces(org.ID, nil)
}()
go func() {
defer wg.Done()
gpuLookup = buildGPULookup(ls.lsStore)
}()
wg.Wait()
if wsErr != nil {
return breverrors.WrapAndTrace(wsErr)
}
// Determine which workspaces to show
var workspacesToShow []entity.Workspace
if showAll {
workspacesToShow = allWorkspaces
} else {
workspacesToShow = store.FilterForUserWorkspaces(allWorkspaces, user.ID)
}
// Handle JSON output
if ls.jsonOutput {
return ls.outputWorkspacesJSON(workspacesToShow, gpuLookup)
}
// Table output with colors and help text
orgs, err := ls.lsStore.GetOrganizations(nil)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if showAll {
ls.ShowAllWorkspaces(org, orgs, user, allWorkspaces, gpuLookup)
} else {
ls.ShowUserWorkspaces(org, orgs, user, allWorkspaces, gpuLookup)
}
return nil
}
func (ls Ls) RunInstances(org *entity.Organization, user *entity.User, showAll bool) error {
if err := ls.RunWorkspaces(org, user, showAll); err != nil {
return err
}
return nil
}
// WorkspaceInfo represents workspace data for JSON output
type WorkspaceInfo struct {
Name string `json:"name"`
ID string `json:"id"`
Status string `json:"status"`
BuildStatus string `json:"build_status"`
ShellStatus string `json:"shell_status"`
HealthStatus string `json:"health_status"`
InstanceType string `json:"instance_type"`
InstanceKind string `json:"instance_kind"`
GPU string `json:"gpu"`
}
// getGPUForInstance returns the GPU name for an instance type using the lookup map.
// Returns the GPU name (e.g. "A100"), "-" for CPU-only, or "-" if unknown.
func getGPUForInstance(w entity.Workspace, gpuLookup map[string]string) string {
if w.InstanceType != "" && gpuLookup != nil {
if gpu, ok := gpuLookup[w.InstanceType]; ok {
return gpu
}
}
if w.InstanceType == "" && w.WorkspaceClassID != "" {
return "-"
}
return "-"
}
// getInstanceTypeAndKind returns the instance type and kind (gpu/cpu)
func getInstanceTypeAndKind(w entity.Workspace, gpuLookup map[string]string) (string, string) {
if w.InstanceType != "" {
gpu := getGPUForInstance(w, gpuLookup)
if gpu != "-" {
return w.InstanceType, "gpu"
}
return w.InstanceType, "cpu"
}
if w.WorkspaceClassID != "" {
return w.WorkspaceClassID, "cpu"
}
return "", ""
}
func (ls Ls) outputWorkspacesJSON(workspaces []entity.Workspace, gpuLookup map[string]string) error {
var infos []WorkspaceInfo
for _, w := range workspaces {
instanceType, instanceKind := getInstanceTypeAndKind(w, gpuLookup)
infos = append(infos, WorkspaceInfo{
Name: w.Name,
ID: w.ID,
Status: getWorkspaceDisplayStatus(w),
BuildStatus: string(w.VerbBuildStatus),
ShellStatus: getShellDisplayStatus(w),
HealthStatus: w.HealthStatus,
InstanceType: instanceType,
InstanceKind: instanceKind,
GPU: getGPUForInstance(w, gpuLookup),
})
}
output, err := json.MarshalIndent(infos, "", " ")
if err != nil {
return breverrors.WrapAndTrace(err)
}
fmt.Println(string(output))
return nil
}
func (ls Ls) RunHosts(org *entity.Organization) error {
user, err := ls.lsStore.GetCurrentUser()
if err != nil {
return breverrors.WrapAndTrace(err)
}
var workspaces []entity.Workspace
workspaces, err = ls.lsStore.GetWorkspaces(org.ID, &store.GetWorkspacesOptions{UserID: user.ID})
if err != nil {
return breverrors.WrapAndTrace(err)
}
for _, workspace := range workspaces {
fmt.Println(workspace.GetNodeIdentifierForVPN())
}
return nil
}
func getBrevTableOptions() table.Options {
options := table.OptionsDefault
options.DrawBorder = false
options.SeparateColumns = false
options.SeparateRows = false
options.SeparateHeader = false
return options
}
func displayWorkspacesTable(t *terminal.Terminal, workspaces []entity.Workspace, gpuLookup map[string]string) {
ta := table.NewWriter()
ta.SetOutputMirror(os.Stdout)
ta.Style().Options = getBrevTableOptions()
header := table.Row{"Name", "Status", "Build", "Shell", "ID", "Machine", "GPU"}
ta.AppendHeader(header)
for _, w := range workspaces {
status := getWorkspaceDisplayStatus(w)
instanceString := cmdutil.GetInstanceString(w)
gpu := getGPUForInstance(w, gpuLookup)
workspaceRow := []table.Row{{w.Name, getStatusColoredText(t, status), getStatusColoredText(t, string(w.VerbBuildStatus)), getStatusColoredText(t, getShellDisplayStatus(w)), w.ID, instanceString, gpu}}
ta.AppendRows(workspaceRow)
}
ta.Render()
}
func getShellDisplayStatus(w entity.Workspace) string {
status := entity.NotReady
if w.Status == entity.Running && w.VerbBuildStatus == entity.Completed {
status = entity.Ready
}
return status
}
func getWorkspaceDisplayStatus(w entity.Workspace) string {
status := w.Status
if w.Status == entity.Running && w.HealthStatus == entity.Unhealthy {
status = w.HealthStatus
}
return status
}
// TODO: use displayOrgTablePlain and displayWorkspacesTablePlain for piped output
// once Workbench stops depending on the colored output format.
// displayWorkspacesTablePlain outputs a clean table without colors for piping
// Enables: brev ls | grep RUNNING | awk '{print $1}' | brev stop
func displayWorkspacesTablePlain(workspaces []entity.Workspace, gpuLookup map[string]string) { //nolint:unused // see TODO above
ta := table.NewWriter()
ta.SetOutputMirror(os.Stdout)
ta.Style().Options = getBrevTableOptions()
header := table.Row{"NAME", "STATUS", "BUILD", "SHELL", "ID", "MACHINE", "GPU"}
ta.AppendHeader(header)
for _, w := range workspaces {
status := getWorkspaceDisplayStatus(w)
instanceString := cmdutil.GetInstanceString(w)
gpu := getGPUForInstance(w, gpuLookup)
workspaceRow := []table.Row{{w.Name, status, string(w.VerbBuildStatus), getShellDisplayStatus(w), w.ID, instanceString, gpu}}
ta.AppendRows(workspaceRow)
}
ta.Render()
}
// displayOrgTablePlain outputs a clean table without colors for piping
// Enables: brev ls orgs | grep myorg | awk '{print $1}'
func displayOrgTablePlain(orgs []entity.Organization, currentOrg *entity.Organization) { //nolint:unused // see TODO above
ta := table.NewWriter()
ta.SetOutputMirror(os.Stdout)
ta.Style().Options = getBrevTableOptions()
header := table.Row{"NAME", "ID"}
ta.AppendHeader(header)
for _, o := range orgs {
activeMarker := ""
if currentOrg != nil && o.ID == currentOrg.ID {
activeMarker = "* "
}
ta.AppendRows([]table.Row{{activeMarker + o.Name, o.ID}})
}
ta.Render()
}
func displayOrgTable(t *terminal.Terminal, orgs []entity.Organization, currentOrg *entity.Organization) {
ta := table.NewWriter()
ta.SetOutputMirror(os.Stdout)
ta.Style().Options = getBrevTableOptions()
header := table.Row{"NAME", "ID"}
ta.AppendHeader(header)
for _, o := range orgs {
workspaceRow := []table.Row{{o.Name, o.ID}}
if o.ID == currentOrg.ID {
workspaceRow = []table.Row{{t.Green("* " + o.Name), t.Green(o.ID)}}
}
ta.AppendRows(workspaceRow)
}
ta.Render()
}
func getStatusColoredText(t *terminal.Terminal, status string) string {
switch status {
case entity.Running, entity.Ready, string(entity.Completed):
return t.Green(status)
case entity.Starting, entity.Deploying, entity.Stopping, string(entity.Building), string(entity.Pending):
return t.Yellow(status)
case entity.Failure, entity.Deleting, entity.Unhealthy, string(entity.CreateFailed):
return t.Red(status)
default:
return status
}
}
// NodeInfo represents external node data for JSON output.
type NodeInfo struct {
Name string `json:"name"`
ExternalNodeID string `json:"external_node_id"`
OrgID string `json:"org_id"`
Status string `json:"status"`
}
func (ls Ls) listNodes(org *entity.Organization) ([]*nodev1.ExternalNode, error) {
client := register.NewNodeServiceClient(ls.lsStore, config.GlobalConfig.GetBrevPublicAPIURL())
resp, err := client.ListNodes(context.Background(), connect.NewRequest(&nodev1.ListNodesRequest{
OrganizationId: org.ID,
}))
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
return resp.Msg.GetItems(), nil
}
// RunNodes lists external nodes for the given org.
func (ls Ls) RunNodes(org *entity.Organization) error {
nodes, err := ls.listNodes(org)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if len(nodes) == 0 {
if ls.jsonOutput {
fmt.Println("[]")
return nil
}
if ls.piped {
return nil
}
ls.terminal.Vprint(ls.terminal.Yellow("No external nodes in this org."))
return nil
}
if ls.jsonOutput {
return ls.outputNodesJSON(nodes)
}
if ls.piped {
displayNodesTablePlain(nodes)
return nil
}
ls.terminal.Vprintf("\nYou have %d external node(s) in Org %s\n", len(nodes), ls.terminal.Yellow(org.Name))
displayNodesTable(ls.terminal, nodes)
return nil
}
func (ls Ls) outputNodesJSON(nodes []*nodev1.ExternalNode) error {
var infos []NodeInfo
for _, n := range nodes {
infos = append(infos, NodeInfo{
Name: n.GetName(),
ExternalNodeID: n.GetExternalNodeId(),
OrgID: n.GetOrganizationId(),
Status: nodeConnectionStatus(n),
})
}
output, err := json.MarshalIndent(infos, "", " ")
if err != nil {
return breverrors.WrapAndTrace(err)
}
fmt.Println(string(output))
return nil
}
func displayNodesTable(t *terminal.Terminal, nodes []*nodev1.ExternalNode) {
ta := table.NewWriter()
ta.SetOutputMirror(os.Stdout)
ta.Style().Options = getBrevTableOptions()
ta.AppendHeader(table.Row{"NAME", "NODE ID", "DEVICE ID", "STATUS"})
for _, n := range nodes {
status := nodeConnectionStatus(n)
ta.AppendRows([]table.Row{{n.GetName(), n.GetExternalNodeId(), n.GetDeviceId(), getStatusColoredText(t, status)}})
}
ta.Render()
}
func displayNodesTablePlain(nodes []*nodev1.ExternalNode) {
ta := table.NewWriter()
ta.SetOutputMirror(os.Stdout)
ta.Style().Options = getBrevTableOptions()
ta.AppendHeader(table.Row{"NAME", "NODE ID", "DEVICE ID", "STATUS"})
for _, n := range nodes {
ta.AppendRows([]table.Row{{n.GetName(), n.GetExternalNodeId(), n.GetDeviceId(), nodeConnectionStatus(n)}})
}
ta.Render()
}
func nodeConnectionStatus(n *nodev1.ExternalNode) string {
ci := n.GetConnectivityInfo()
if ci == nil {
return "Unknown"
}
return externalnode.FriendlyNetworkStatus(ci.GetStatus())
}