Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
c09c9b9
WIP: agent reinitialization
SasSwart Apr 21, 2025
476fe71
fix assignment to nil map
SasSwart Apr 21, 2025
8c8bca6
fix: ensure prebuilt workspace agent tokens are reused when a prebuil…
SasSwart Apr 23, 2025
7ce4eea
test agent reinitialization
SasSwart Apr 24, 2025
52ac64e
remove defunct metric
SasSwart Apr 24, 2025
362db7c
Remove todo
SasSwart Apr 25, 2025
dcc7379
test that we trigger workspace agent reinitialization under the right…
SasSwart Apr 28, 2025
ff66b3f
slight improvements to a test
SasSwart Apr 28, 2025
efff5d9
review notes to improve legibility
SasSwart Apr 28, 2025
cebd5db
add an integration test for prebuilt workspace agent reinitialization
SasSwart Apr 29, 2025
2679138
Merge remote-tracking branch 'origin/main' into jjs/prebuilds-agent-r…
SasSwart Apr 29, 2025
9feebef
enable the premium license in a prebuilds integration test
SasSwart Apr 29, 2025
b117b5c
encapsulate WaitForReinitLoop for easier testing
SasSwart Apr 30, 2025
a22b414
introduce unit testable abstraction layers
SasSwart Apr 30, 2025
9bbd2c7
test workspace claim pubsub
SasSwart May 1, 2025
5804201
add tests for agent reinitialization
SasSwart May 1, 2025
7e8dcee
review notes
SasSwart May 1, 2025
725f97b
Merge remote-tracking branch 'origin/main' into jjs/prebuilds-agent-r…
SasSwart May 1, 2025
a9b1567
make fmt lint
SasSwart May 1, 2025
21ee970
remove go mod replace
SasSwart May 1, 2025
e54d7e7
remove defunct logging
SasSwart May 1, 2025
2799858
update dependency on terraform-provider-coder
SasSwart May 2, 2025
1d93003
update dependency on terraform-provider-coder
SasSwart May 2, 2025
763fc12
go mod tidy
SasSwart May 2, 2025
0f879c7
make -B gen
SasSwart May 2, 2025
61784c9
dont require ids to InsertPresetParameters
SasSwart May 2, 2025
604eb27
dont require ids to InsertPresetParameters
SasSwart May 2, 2025
bf4d2cf
fix: set the running agent token
dannykopping May 2, 2025
38b4f0d
fix: use http client without timeout like we do in connectRPCVersion
dannykopping May 5, 2025
20df538
review notes
SasSwart May 6, 2025
4bb3b68
Merge remote-tracking branch 'origin/main' into jjs/prebuilds-agent-r…
SasSwart May 7, 2025
83972db
bump provisionerd proto version
SasSwart May 7, 2025
146b158
fix: fetch the previous agent when we need its token for prebuilt wor…
SasSwart May 12, 2025
5eb16cd
Merge remote-tracking branch 'origin/main' into jjs/prebuilds-agent-r…
SasSwart May 12, 2025
730d803
make -B lint
SasSwart May 12, 2025
150adc0
Test GetWorkspaceAgentsByBuildID
SasSwart May 12, 2025
b4ecf10
Rename GetWorkspaceAgentsByWorkspaceAndBuildNumber
SasSwart May 12, 2025
3fa3edf
make gen
SasSwart May 12, 2025
7e45919
fix a race condition
SasSwart May 12, 2025
a632508
Merge remote-tracking branch 'origin/main' into jjs/prebuilds-agent-r…
SasSwart May 12, 2025
72125ec
Merge remote-tracking branch 'origin/main' into jjs/prebuilds-agent-r…
SasSwart May 13, 2025
b65eea7
fix provisionerdserver test for prebuild claims
SasSwart May 13, 2025
e1339f3
fix race conditions
SasSwart May 13, 2025
c1a8ba6
Merge remote-tracking branch 'origin/main' into jjs/prebuilds-agent-r…
SasSwart May 13, 2025
5363dcc
Make TestReinitializeAgent more robust
SasSwart May 13, 2025
7ad9b6d
fix tests
SasSwart May 14, 2025
394571d
make -B gen
SasSwart May 14, 2025
890747b
remove a potential race in reinitialization testing in TestCompleteJob
SasSwart May 14, 2025
b3870db
fix a potential race in TestReinit
SasSwart May 14, 2025
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
Prev Previous commit
Next Next commit
test agent reinitialization
  • Loading branch information
SasSwart committed Apr 25, 2025
commit 7ce4eea2af98c805bd61ade3be14086c2e684f4a
2 changes: 1 addition & 1 deletion cli/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
break
}

logger.Info(ctx, "reinitializing...")
logger.Info(ctx, "agent reinitializing")
}
return lastErr
},
Expand Down
52 changes: 52 additions & 0 deletions cli/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import (
"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/coderd/database/dbtestutil"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
"github.com/coder/coder/v2/provisionersdk/proto"
"github.com/coder/coder/v2/testutil"
Expand Down Expand Up @@ -321,6 +323,56 @@ func TestWorkspaceAgent(t *testing.T) {
})
}

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

db, pubsub := dbtestutil.NewDB(t)
client := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: pubsub,
})
user := coderdtest.CreateFirstUser(t, client)
r := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OrganizationID: user.OrganizationID,
OwnerID: user.UserID,
}).WithAgent(func(a []*proto.Agent) []*proto.Agent {
a[0].Scripts = []*proto.Script{
{
DisplayName: "Prebuild Test Script",
Script: "sleep 5", // Make reinitiazation take long enough to assert that it happened
RunOnStart: true,
},
}
return a
}).Do()

// Spin up an agent
logDir := t.TempDir()
inv, _ := clitest.New(t,
"agent",
"--auth", "token",
"--agent-token", r.AgentToken,
"--agent-url", client.URL.String(),
"--log-dir", logDir,
)
clitest.Start(t, inv)

// Check that the agent is in a happy steady state
waiter := coderdtest.NewWorkspaceAgentWaiter(t, client, r.Workspace.ID)
waiter.WaitFor(coderdtest.AgentReady)

// Trigger reinitialization
channel := agentsdk.PrebuildClaimedChannel(r.Workspace.ID)
err := pubsub.Publish(channel, []byte(user.UserID.String()))
require.NoError(t, err)

// Check that the agent reinitializes
waiter.WaitFor(coderdtest.AgentNotReady)

// Check that reinitialization completed
waiter.WaitFor(coderdtest.AgentReady)
}

func matchAgentWithVersion(rs []codersdk.WorkspaceResource) bool {
if len(rs) < 1 {
return false
Expand Down
53 changes: 53 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,59 @@ func (w WorkspaceAgentWaiter) MatchResources(m func([]codersdk.WorkspaceResource
return w
}

type WaitForCriterium func(agent codersdk.WorkspaceAgent) bool

func AgentReady(agent codersdk.WorkspaceAgent) bool {
return agent.LifecycleState == codersdk.WorkspaceAgentLifecycleReady
}

func AgentNotReady(agent codersdk.WorkspaceAgent) bool {
return !AgentReady(agent)
}

func (w WorkspaceAgentWaiter) WaitFor(criteria ...WaitForCriterium) {
w.t.Helper()

agentNamesMap := make(map[string]struct{}, len(w.agentNames))
for _, name := range w.agentNames {
agentNamesMap[name] = struct{}{}
}

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

w.t.Logf("waiting for workspace agents (workspace %s)", w.workspaceID)
require.Eventually(w.t, func() bool {
var err error
workspace, err := w.client.Workspace(ctx, w.workspaceID)
if err != nil {
return false
}
if workspace.LatestBuild.Job.CompletedAt == nil {
return false
}
if workspace.LatestBuild.Job.CompletedAt.IsZero() {
return false
}

for _, resource := range workspace.LatestBuild.Resources {
for _, agent := range resource.Agents {
if len(w.agentNames) > 0 {
if _, ok := agentNamesMap[agent.Name]; !ok {
continue
}
}
for _, criterium := range criteria {
if !criterium(agent) {
return false
}
}
}
}
return true
}, testutil.WaitLong, testutil.IntervalMedium)
}

// Wait waits for the agent(s) to connect and fails the test if they do not within testutil.WaitLong
func (w WorkspaceAgentWaiter) Wait() []codersdk.WorkspaceResource {
w.t.Helper()
Expand Down
9 changes: 6 additions & 3 deletions coderd/workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -689,10 +689,13 @@ func createWorkspace(
api.Logger.Error(ctx, "failed to retrieve running agents of claimed prebuilt workspace",
slog.F("workspace_id", claimedWorkspace.ID), slog.Error(err))
}
agentTokensByAgentID = make(map[uuid.UUID]string, len(agents))
for _, agent := range agents {
agentTokensByAgentID[agent.ID] = agent.AuthToken.String()
if len(agents) > 1 {
return xerrors.Errorf("multiple agents are not yet supported in prebuilt workspaces")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It feels wrong to error here. While we don't support multiple agents, we shouldn't fail the call to createWorkspace, but rather prevent the ability to claim prebuilds. Right now I think this would be unrecoverable until the template is changed.

Can you please add a test for this scenario to validate this behaviour?

We could hard-fail this, though, on the template import side when an admin tries to use prebuilds with multiple agents (in a follow-up PR).

}
// agentTokensByAgentID = make(map[uuid.UUID]string, len(agents))
// for _, agent := range agents {
// agentTokensByAgentID[agent.ID] = agent.AuthToken.String()
// }
}

// We have to refetch the workspace for the joined in fields.
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -921,8 +921,6 @@ github.com/coder/tailscale v1.1.1-0.20250422090654-5090e715905e h1:nope/SZfoLB9M
github.com/coder/tailscale v1.1.1-0.20250422090654-5090e715905e/go.mod h1:1ggFFdHTRjPRu9Yc1yA7nVHBYB50w9Ce7VIXNqcW6Ko=
github.com/coder/terraform-config-inspect v0.0.0-20250107175719-6d06d90c630e h1:JNLPDi2P73laR1oAclY6jWzAbucf70ASAvf5mh2cME0=
github.com/coder/terraform-config-inspect v0.0.0-20250107175719-6d06d90c630e/go.mod h1:Gz/z9Hbn+4KSp8A2FBtNszfLSdT2Tn/uAKGuVqqWmDI=
github.com/coder/terraform-provider-coder/v2 v2.4.0-pre1.0.20250417100258-c86bb5c3ddcd h1:FsIG6Fd0YOEK7D0Hl/CJywRA+Y6Gd5RQbSIa2L+/BmE=
github.com/coder/terraform-provider-coder/v2 v2.4.0-pre1.0.20250417100258-c86bb5c3ddcd/go.mod h1:56/KdGYaA+VbwXJbTI8CA57XPfnuTxN8rjxbR34PbZw=
github.com/coder/trivy v0.0.0-20250409153844-e6b004bc465a h1:yryP7e+IQUAArlycH4hQrjXQ64eRNbxsV5/wuVXHgME=
github.com/coder/trivy v0.0.0-20250409153844-e6b004bc465a/go.mod h1:dDvq9axp3kZsT63gY2Znd1iwzfqDq3kXbQnccIrjRYY=
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
Expand Down