Skip to content

feat(cli): add functionality to retrieve workspace build logs to CLI #19008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions cli/builds.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package cli

import (
"fmt"
"strconv"
"time"

"golang.org/x/xerrors"

"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)

type workspaceBuildListRow struct {
codersdk.WorkspaceBuild `table:"-"`

BuildNumber string `json:"-" table:"build,default_sort"`
BuildID string `json:"-" table:"build id"`
Status string `json:"-" table:"status"`
Reason string `json:"-" table:"reason"`
CreatedAt string `json:"-" table:"created"`
Duration string `json:"-" table:"duration"`
}

func workspaceBuildListRowFromBuild(build codersdk.WorkspaceBuild) workspaceBuildListRow {
status := codersdk.WorkspaceDisplayStatus(build.Job.Status, build.Transition)
createdAt := build.CreatedAt.Format("2006-01-02 15:04:05")

duration := ""
if build.Job.CompletedAt != nil {
duration = build.Job.CompletedAt.Sub(build.CreatedAt).Truncate(time.Second).String()
}

return workspaceBuildListRow{
WorkspaceBuild: build,
BuildNumber: strconv.Itoa(int(build.BuildNumber)),
BuildID: build.ID.String(),
Status: status,
Reason: string(build.Reason),
CreatedAt: createdAt,
Duration: duration,
}
}

func (r *RootCmd) builds() *serpent.Command {
return &serpent.Command{
Use: "builds",
Short: "Manage workspace builds",
Children: []*serpent.Command{
r.buildsList(),
},
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
},
}
}

func (r *RootCmd) buildsList() *serpent.Command {
formatter := cliui.NewOutputFormatter(
cliui.TableFormat(
[]workspaceBuildListRow{},
[]string{"build", "build id", "status", "reason", "created", "duration"},
),
cliui.JSONFormat(),
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Annotations: workspaceCommand,
Use: "list <workspace>",
Short: "List builds for a workspace",
Aliases: []string{"ls"},
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
workspace, err := namedWorkspace(inv.Context(), client, inv.Args[0])
if err != nil {
return xerrors.Errorf("get workspace: %w", err)
}

builds, err := client.WorkspaceBuildsByWorkspaceID(inv.Context(), workspace.ID)
if err != nil {
return xerrors.Errorf("get workspace builds: %w", err)
}

rows := make([]workspaceBuildListRow, len(builds))
for i, build := range builds {
rows[i] = workspaceBuildListRowFromBuild(build)
}

out, err := formatter.Format(inv.Context(), rows)
if err != nil {
return err
}

_, err = fmt.Fprintln(inv.Stdout, out)
return err
},
}
formatter.AttachOptions(&cmd.Options)
return cmd
}
101 changes: 101 additions & 0 deletions cli/builds_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package cli_test

import (
"bytes"
"context"
"encoding/json"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbfake"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/pty/ptytest"
"github.com/coder/coder/v2/testutil"
)

func TestBuildsList(t *testing.T) {
t.Parallel()

t.Run("Table", func(t *testing.T) {
t.Parallel()
client, db := coderdtest.NewWithDatabase(t, nil)
owner := coderdtest.CreateFirstUser(t, client)
member, memberUser := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)

// Create a workspace with a build
r := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OrganizationID: owner.OrganizationID,
OwnerID: memberUser.ID,
}).WithAgent().Do()

inv, root := clitest.New(t, "builds", "list", r.Workspace.Name)
clitest.SetupConfig(t, member, root)
pty := ptytest.New(t).Attach(inv)

ctx, cancelFunc := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancelFunc()

done := make(chan any)
go func() {
errC := inv.WithContext(ctx).Run()
assert.NoError(t, errC)
close(done)
}()

pty.ExpectMatch("1") // Build number
pty.ExpectMatch(r.Build.ID.String()) // Build ID
cancelFunc()
<-done
})

t.Run("JSON", func(t *testing.T) {
t.Parallel()
client, db := coderdtest.NewWithDatabase(t, nil)
owner := coderdtest.CreateFirstUser(t, client)
member, memberUser := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)

// Create a workspace with a build
r := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OrganizationID: owner.OrganizationID,
OwnerID: memberUser.ID,
}).WithAgent().Do()

inv, root := clitest.New(t, "builds", "list", r.Workspace.Name, "--output=json")
clitest.SetupConfig(t, member, root)

ctx, cancelFunc := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancelFunc()

out := bytes.NewBuffer(nil)
inv.Stdout = out
err := inv.WithContext(ctx).Run()
require.NoError(t, err)

var builds []codersdk.WorkspaceBuild
require.NoError(t, json.Unmarshal(out.Bytes(), &builds))
require.Len(t, builds, 1)
assert.Equal(t, r.Build.ID, builds[0].ID)
})

t.Run("WorkspaceNotFound", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
owner := coderdtest.CreateFirstUser(t, client)
member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)

inv, root := clitest.New(t, "builds", "list", "non-existent-workspace")
clitest.SetupConfig(t, member, root)

ctx, cancelFunc := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancelFunc()

err := inv.WithContext(ctx).Run()
require.Error(t, err)
assert.Contains(t, err.Error(), "get workspace")
})
}
67 changes: 67 additions & 0 deletions cli/logs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package cli

import (
"fmt"

"github.com/google/uuid"
"golang.org/x/xerrors"

"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)

func (r *RootCmd) logs() *serpent.Command {
var follow bool
client := new(codersdk.Client)
cmd := &serpent.Command{
Annotations: workspaceCommand,
Use: "logs <build-id>",
Short: "Show logs for a workspace build",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
buildIDStr := inv.Args[0]
buildID, err := uuid.Parse(buildIDStr)
if err != nil {
return xerrors.Errorf("invalid build ID %q: %w", buildIDStr, err)
}

logs, closer, err := client.WorkspaceBuildLogsAfter(inv.Context(), buildID, 0)
if err != nil {
return xerrors.Errorf("get build logs: %w", err)
}
defer closer.Close()

for {
log, ok := <-logs
if !ok {
break
}

// Simple format with timestamp and stage
timestamp := log.CreatedAt.Format("15:04:05")
if log.Stage != "" {
_, _ = fmt.Fprintf(inv.Stdout, "[%s] %s: %s\n",
timestamp, log.Stage, log.Output)
} else {
_, _ = fmt.Fprintf(inv.Stdout, "[%s] %s\n",
timestamp, log.Output)
}
}
return nil
},
}

cmd.Options = serpent.OptionSet{
{
Flag: "follow",
FlagShorthand: "f",
Description: "Follow log output (stream real-time logs).",
Value: serpent.BoolOf(&follow),
},
}

return cmd
}
53 changes: 53 additions & 0 deletions cli/logs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package cli_test

import (
"context"
"strings"
"testing"

"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/testutil"
)

func TestLogs(t *testing.T) {
t.Parallel()

t.Run("LogsInvalidBuildID", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)

inv, root := clitest.New(t, "logs", "invalid-uuid")
clitest.SetupConfig(t, client, root)

ctx, cancelFunc := context.WithTimeout(context.Background(), testutil.WaitMedium)
defer cancelFunc()

err := inv.WithContext(ctx).Run()
require.Error(t, err)
assert.True(t, strings.Contains(err.Error(), "invalid build ID"))
})

t.Run("LogsNonexistentBuild", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)

inv, root := clitest.New(t, "logs", uuid.New().String())
clitest.SetupConfig(t, client, root)

ctx, cancelFunc := context.WithTimeout(context.Background(), testutil.WaitMedium)
defer cancelFunc()

err := inv.WithContext(ctx).Run()
require.Error(t, err)
assert.True(t, strings.Contains(err.Error(), "get build logs"))
})
}
2 changes: 2 additions & 0 deletions cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,13 @@ func (r *RootCmd) CoreSubcommands() []*serpent.Command {

// Workspace Commands
r.autoupdate(),
r.builds(),
r.configSSH(),
r.create(),
r.deleteWorkspace(),
r.favorite(),
r.list(),
r.logs(),
r.open(),
r.ping(),
r.rename(),
Expand Down
2 changes: 2 additions & 0 deletions cli/testdata/coder_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ USAGE:

SUBCOMMANDS:
autoupdate Toggle auto-update policy for a workspace
builds Manage workspace builds
completion Install or update shell completion scripts for the
detected or chosen shell.
config-ssh Add an SSH Host entry for your workspaces "ssh
Expand All @@ -28,6 +29,7 @@ SUBCOMMANDS:
list List workspaces
login Authenticate with Coder deployment
logout Unauthenticate your local session
logs Show logs for a workspace build
netcheck Print network debug information for DERP and STUN
notifications Manage Coder notifications
open Open a workspace
Expand Down
12 changes: 12 additions & 0 deletions cli/testdata/coder_builds_--help.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
coder v0.0.0-devel

USAGE:
coder builds

Manage workspace builds

SUBCOMMANDS:
list List builds for a workspace

———
Run `coder --help` for a list of global options.
18 changes: 18 additions & 0 deletions cli/testdata/coder_builds_list_--help.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
coder v0.0.0-devel

USAGE:
coder builds list [flags] <workspace>

List builds for a workspace

Aliases: ls

OPTIONS:
-c, --column [build|build id|status|reason|created|duration] (default: build,build id,status,reason,created,duration)
Columns to display in table output.

-o, --output table|json (default: table)
Output format.

———
Run `coder --help` for a list of global options.
Loading
Loading