feat(cli): add display of open ports in coder show (#16464)

Relates to https://github.com/coder/coder/issues/16418 -- devcontainers
will be shown in a similar manner.

Without ports (status quo):
![Screenshot 2025-02-10 at 12 50
46](https://github.com/user-attachments/assets/c25fd532-2e35-469c-bb28-26e59ded3eb4)

With ports:
![Screenshot 2025-02-10 at 12 50
06](https://github.com/user-attachments/assets/a4671349-5866-4e1e-848e-a6e819479793)
This commit is contained in:
Cian Johnston
2025-02-10 13:25:35 +00:00
committed by GitHub
parent e9b3561677
commit 695d552cd0
2 changed files with 100 additions and 26 deletions
+39 -2
View File
@@ -1,8 +1,13 @@
package cli
import (
"sort"
"sync"
"golang.org/x/xerrors"
"github.com/google/uuid"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
@@ -26,10 +31,42 @@ func (r *RootCmd) show() *serpent.Command {
if err != nil {
return xerrors.Errorf("get workspace: %w", err)
}
return cliui.WorkspaceResources(inv.Stdout, workspace.LatestBuild.Resources, cliui.WorkspaceResourcesOptions{
options := cliui.WorkspaceResourcesOptions{
WorkspaceName: workspace.Name,
ServerVersion: buildInfo.Version,
})
}
if workspace.LatestBuild.Status == codersdk.WorkspaceStatusRunning {
// Get listening ports for each agent.
options.ListeningPorts = fetchListeningPorts(inv, client, workspace.LatestBuild.Resources...)
}
return cliui.WorkspaceResources(inv.Stdout, workspace.LatestBuild.Resources, options)
},
}
}
func fetchListeningPorts(inv *serpent.Invocation, client *codersdk.Client, resources ...codersdk.WorkspaceResource) map[uuid.UUID]codersdk.WorkspaceAgentListeningPortsResponse {
ports := make(map[uuid.UUID]codersdk.WorkspaceAgentListeningPortsResponse)
var wg sync.WaitGroup
var mu sync.Mutex
for _, res := range resources {
for _, agent := range res.Agents {
wg.Add(1)
go func() {
defer wg.Done()
lp, err := client.WorkspaceAgentListeningPorts(inv.Context(), agent.ID)
if err != nil {
cliui.Warnf(inv.Stderr, "Failed to get listening ports for agent %s: %v", agent.Name, err)
}
sort.Slice(lp.Ports, func(i, j int) bool {
return lp.Ports[i].Port < lp.Ports[j].Port
})
mu.Lock()
ports[agent.ID] = lp
mu.Unlock()
}()
}
}
wg.Wait()
return ports
}