Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

chore(agent/agentcontainers): test current prebuilds integration#19074

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes fromall 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
206 changes: 206 additions & 0 deletionsagent/agent_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2458,6 +2458,212 @@ func TestAgent_DevcontainersDisabledForSubAgent(t *testing.T) {
require.Contains(t, err.Error(), "Dev Container integration inside other Dev Containers is explicitly not supported.")
}

// TestAgent_DevcontainerPrebuildClaim tests that we correctly handle
// the claiming process for running devcontainers.
//
// You can run it manually as follows:
//
// CODER_TEST_USE_DOCKER=1 go test -count=1 ./agent -run TestAgent_DevcontainerPrebuildClaim
//
//nolint:paralleltest // This test sets an environment variable.
func TestAgent_DevcontainerPrebuildClaim(t *testing.T) {
if os.Getenv("CODER_TEST_USE_DOCKER") != "1" {
t.Skip("Set CODER_TEST_USE_DOCKER=1 to run this test")
}
if _, err := exec.LookPath("devcontainer"); err != nil {
t.Skip("This test requires the devcontainer CLI: npm install -g @devcontainers/cli")
}

pool, err := dockertest.NewPool("")
require.NoError(t, err, "Could not connect to docker")

var (
ctx = testutil.Context(t, testutil.WaitShort)

devcontainerID = uuid.New()
devcontainerLogSourceID = uuid.New()

workspaceFolder = filepath.Join(t.TempDir(), "project")
devcontainerPath = filepath.Join(workspaceFolder, ".devcontainer")
devcontainerConfig = filepath.Join(devcontainerPath, "devcontainer.json")
)

// Given: A devcontainer project.
t.Logf("Workspace folder: %s", workspaceFolder)

err = os.MkdirAll(devcontainerPath, 0o755)
require.NoError(t, err, "create dev container directory")

// Given: This devcontainer project specifies an app that uses the owner name and workspace name.
err = os.WriteFile(devcontainerConfig, []byte(`{
"name": "project",
"image": "busybox:latest",
"cmd": ["sleep", "infinity"],
"runArgs": ["--label=`+agentcontainers.DevcontainerIsTestRunLabel+`=true"],
"customizations": {
"coder": {
"apps": [{
"slug": "zed",
"url": "zed://ssh/${localEnv:CODER_WORKSPACE_AGENT_NAME}.${localEnv:CODER_WORKSPACE_NAME}.${localEnv:CODER_WORKSPACE_OWNER_NAME}.coder${containerWorkspaceFolder}"
}]
}
}
}`), 0o600)
require.NoError(t, err, "write devcontainer config")

// Given: A manifest with a prebuild username and workspace name.
manifest := agentsdk.Manifest{
OwnerName: "prebuilds",
WorkspaceName: "prebuilds-xyz-123",

Devcontainers: []codersdk.WorkspaceAgentDevcontainer{
{ID: devcontainerID, Name: "test", WorkspaceFolder: workspaceFolder},
},
Scripts: []codersdk.WorkspaceAgentScript{
{ID: devcontainerID, LogSourceID: devcontainerLogSourceID},
},
}

// When: We create an agent with devcontainers enabled.
//nolint:dogsled
conn, client, _, _, _ := setupAgent(t, manifest, 0, func(_ *agenttest.Client, o *agent.Options) {
o.Devcontainers = true
o.DevcontainerAPIOptions = append(o.DevcontainerAPIOptions,
agentcontainers.WithContainerLabelIncludeFilter(agentcontainers.DevcontainerLocalFolderLabel, workspaceFolder),
agentcontainers.WithContainerLabelIncludeFilter(agentcontainers.DevcontainerIsTestRunLabel, "true"),
)
})

testutil.Eventually(ctx, t, func(ctx context.Context) bool {
return slices.Contains(client.GetLifecycleStates(), codersdk.WorkspaceAgentLifecycleReady)
}, testutil.IntervalMedium, "agent not ready")

var dcPrebuild codersdk.WorkspaceAgentDevcontainer
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
resp, err := conn.ListContainers(ctx)
require.NoError(t, err)

for _, dc := range resp.Devcontainers {
if dc.Container == nil {
continue
}

v, ok := dc.Container.Labels[agentcontainers.DevcontainerLocalFolderLabel]
if ok && v == workspaceFolder {
dcPrebuild = dc
return true
}
}

return false
}, testutil.IntervalMedium, "devcontainer not found")
defer func() {
pool.Client.RemoveContainer(docker.RemoveContainerOptions{
ID: dcPrebuild.Container.ID,
RemoveVolumes: true,
Force: true,
})
}()

// Then: We expect a sub agent to have been created.
subAgents := client.GetSubAgents()
require.Len(t, subAgents, 1)

subAgent := subAgents[0]
subAgentID, err := uuid.FromBytes(subAgent.GetId())
require.NoError(t, err)

// And: We expect there to be 1 app.
subAgentApps, err := client.GetSubAgentApps(subAgentID)
require.NoError(t, err)
require.Len(t, subAgentApps, 1)

// And: This app should contain the prebuild workspace name and owner name.
subAgentApp := subAgentApps[0]
require.Equal(t, "zed://ssh/project.prebuilds-xyz-123.prebuilds.coder/workspaces/project", subAgentApp.GetUrl())

// Given: We close the client and connection
client.Close()
conn.Close()

// Given: A new manifest with a regular user owner name and workspace name.
manifest = agentsdk.Manifest{
OwnerName: "user",
WorkspaceName: "user-workspace",

Devcontainers: []codersdk.WorkspaceAgentDevcontainer{
{ID: devcontainerID, Name: "test", WorkspaceFolder: workspaceFolder},
},
Scripts: []codersdk.WorkspaceAgentScript{
{ID: devcontainerID, LogSourceID: devcontainerLogSourceID},
},
}

// When: We create an agent with devcontainers enabled.
//nolint:dogsled
conn, client, _, _, _ = setupAgent(t, manifest, 0, func(_ *agenttest.Client, o *agent.Options) {
o.Devcontainers = true
o.DevcontainerAPIOptions = append(o.DevcontainerAPIOptions,
agentcontainers.WithContainerLabelIncludeFilter(agentcontainers.DevcontainerLocalFolderLabel, workspaceFolder),
agentcontainers.WithContainerLabelIncludeFilter(agentcontainers.DevcontainerIsTestRunLabel, "true"),
)
})

testutil.Eventually(ctx, t, func(ctx context.Context) bool {
return slices.Contains(client.GetLifecycleStates(), codersdk.WorkspaceAgentLifecycleReady)
}, testutil.IntervalMedium, "agent not ready")

var dcClaimed codersdk.WorkspaceAgentDevcontainer
testutil.Eventually(ctx, t, func(ctx context.Context) bool {
resp, err := conn.ListContainers(ctx)
require.NoError(t, err)

for _, dc := range resp.Devcontainers {
if dc.Container == nil {
continue
}

v, ok := dc.Container.Labels[agentcontainers.DevcontainerLocalFolderLabel]
if ok && v == workspaceFolder {
dcClaimed = dc
return true
}
}

return false
}, testutil.IntervalMedium, "devcontainer not found")
defer func() {
if dcClaimed.Container.ID != dcPrebuild.Container.ID {
pool.Client.RemoveContainer(docker.RemoveContainerOptions{
ID: dcClaimed.Container.ID,
RemoveVolumes: true,
Force: true,
})
}
}()

// Then: We expect the claimed devcontainer and prebuild devcontainer
// to be using the same underlying container.
require.Equal(t, dcPrebuild.Container.ID, dcClaimed.Container.ID)

// And: We expect there to be a sub agent created.
subAgents = client.GetSubAgents()
require.Len(t, subAgents, 1)

subAgent = subAgents[0]
subAgentID, err = uuid.FromBytes(subAgent.GetId())
require.NoError(t, err)

// And: We expect there to be an app.
subAgentApps, err = client.GetSubAgentApps(subAgentID)
require.NoError(t, err)
require.Len(t, subAgentApps, 1)

// And: We expect this app to have the user's owner name and workspace name.
subAgentApp = subAgentApps[0]
require.Equal(t, "zed://ssh/project.user-workspace.user.coder/workspaces/project", subAgentApp.GetUrl())
}

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

Expand Down
182 changes: 182 additions & 0 deletionsagent/agentcontainers/api_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3815,3 +3815,185 @@ func TestDevcontainerDiscovery(t *testing.T) {
}
})
}

// TestDevcontainerPrebuildSupport validates that devcontainers survive the transition
// from prebuild to claimed workspace, ensuring the existing container is reused
// with updated configuration rather than being recreated.
func TestDevcontainerPrebuildSupport(t *testing.T) {
t.Parallel()

if runtime.GOOS == "windows" {
t.Skip("Dev Container tests are not supported on Windows")
}

var (
ctx = testutil.Context(t, testutil.WaitShort)
logger = testutil.Logger(t)

fDCCLI = &fakeDevcontainerCLI{readConfigErrC: make(chan func(envs []string) error, 1)}
fCCLI = &fakeContainerCLI{arch: runtime.GOARCH}
fSAC = &fakeSubAgentClient{}

testDC = codersdk.WorkspaceAgentDevcontainer{
ID: uuid.New(),
WorkspaceFolder: "/home/coder/coder",
ConfigPath: "/home/coder/coder/.devcontainer/devcontainer.json",
}

testContainer = newFakeContainer("test-container-id", testDC.ConfigPath, testDC.WorkspaceFolder)

prebuildOwner = "prebuilds"
prebuildWorkspace = "prebuilds-xyz-123"
prebuildAppURL = "prebuilds.zed"

userOwner = "user"
userWorkspace = "user-workspace"
userAppURL = "user.zed"
)

// ==================================================
// PHASE 1: Prebuild workspace creates devcontainer
// ==================================================

// Given: There are no containers initially.
fCCLI.containers = codersdk.WorkspaceAgentListContainersResponse{}

api := agentcontainers.NewAPI(logger,
// We want this first `agentcontainers.API` to have a manifest info
// that is consistent with what a prebuild workspace would have.
agentcontainers.WithManifestInfo(prebuildOwner, prebuildWorkspace, "dev", "/home/coder"),
// Given: We start with a single dev container resource.
agentcontainers.WithDevcontainers(
[]codersdk.WorkspaceAgentDevcontainer{testDC},
[]codersdk.WorkspaceAgentScript{{ID: testDC.ID, LogSourceID: uuid.New()}},
),
agentcontainers.WithSubAgentClient(fSAC),
agentcontainers.WithContainerCLI(fCCLI),
agentcontainers.WithDevcontainerCLI(fDCCLI),
agentcontainers.WithWatcher(watcher.NewNoop()),
)
api.Start()

fCCLI.containers = codersdk.WorkspaceAgentListContainersResponse{
Containers: []codersdk.WorkspaceAgentContainer{testContainer},
}

// Given: We allow the dev container to be created.
fDCCLI.upID = testContainer.ID
fDCCLI.readConfig = agentcontainers.DevcontainerConfig{
MergedConfiguration: agentcontainers.DevcontainerMergedConfiguration{
Customizations: agentcontainers.DevcontainerMergedCustomizations{
Coder: []agentcontainers.CoderCustomization{{
Apps: []agentcontainers.SubAgentApp{
{Slug: "zed", URL: prebuildAppURL},
},
}},
},
},
}

var readConfigEnvVars []string
testutil.RequireSend(ctx, t, fDCCLI.readConfigErrC, func(env []string) error {
readConfigEnvVars = env
return nil
})

// When: We create the dev container resource
err := api.CreateDevcontainer(testDC.WorkspaceFolder, testDC.ConfigPath)
require.NoError(t, err)

require.Contains(t, readConfigEnvVars, "CODER_WORKSPACE_OWNER_NAME="+prebuildOwner)
require.Contains(t, readConfigEnvVars, "CODER_WORKSPACE_NAME="+prebuildWorkspace)

// Then: We there to be only 1 agent.
require.Len(t, fSAC.agents, 1)

// And: We expect only 1 agent to have been created.
require.Len(t, fSAC.created, 1)
firstAgent := fSAC.created[0]

// And: We expect this agent to be the current agent.
_, found := fSAC.agents[firstAgent.ID]
require.True(t, found, "first agent expected to be current agent")

// And: We expect there to be a single app.
require.Len(t, firstAgent.Apps, 1)
firstApp := firstAgent.Apps[0]

// And: We expect this app to have the pre-claim URL.
require.Equal(t, prebuildAppURL, firstApp.URL)

// Given: We now close the API
api.Close()

// =============================================================
// PHASE 2: User claims workspace, devcontainer should be reused
// =============================================================

// Given: We create a new claimed API
api = agentcontainers.NewAPI(logger,
// We want this second `agentcontainers.API` to have a manifest info
// that is consistent with what a claimed workspace would have.
agentcontainers.WithManifestInfo(userOwner, userWorkspace, "dev", "/home/coder"),
// Given: We start with a single dev container resource.
agentcontainers.WithDevcontainers(
[]codersdk.WorkspaceAgentDevcontainer{testDC},
[]codersdk.WorkspaceAgentScript{{ID: testDC.ID, LogSourceID: uuid.New()}},
),
agentcontainers.WithSubAgentClient(fSAC),
agentcontainers.WithContainerCLI(fCCLI),
agentcontainers.WithDevcontainerCLI(fDCCLI),
agentcontainers.WithWatcher(watcher.NewNoop()),
)
api.Start()
defer func() {
close(fDCCLI.readConfigErrC)

api.Close()
}()

// Given: We allow the dev container to be created.
fDCCLI.upID = testContainer.ID
fDCCLI.readConfig = agentcontainers.DevcontainerConfig{
MergedConfiguration: agentcontainers.DevcontainerMergedConfiguration{
Customizations: agentcontainers.DevcontainerMergedCustomizations{
Coder: []agentcontainers.CoderCustomization{{
Apps: []agentcontainers.SubAgentApp{
{Slug: "zed", URL: userAppURL},
},
}},
},
},
}

testutil.RequireSend(ctx, t, fDCCLI.readConfigErrC, func(env []string) error {
readConfigEnvVars = env
return nil
})

// When: We create the dev container resource.
err = api.CreateDevcontainer(testDC.WorkspaceFolder, testDC.ConfigPath)
require.NoError(t, err)

// Then: We expect the environment variables were passed correctly.
require.Contains(t, readConfigEnvVars, "CODER_WORKSPACE_OWNER_NAME="+userOwner)
require.Contains(t, readConfigEnvVars, "CODER_WORKSPACE_NAME="+userWorkspace)

// And: We expect there to be only 1 agent.
require.Len(t, fSAC.agents, 1)

// And: We expect _a separate agent_ to have been created.
require.Len(t, fSAC.created, 2)
secondAgent := fSAC.created[1]

// And: We expect this new agent to be the current agent.
_, found = fSAC.agents[secondAgent.ID]
require.True(t, found, "second agent expected to be current agent")

// And: We expect there to be a single app.
require.Len(t, secondAgent.Apps, 1)
secondApp := secondAgent.Apps[0]

// And: We expect this app to have the post-claim URL.
require.Equal(t, userAppURL, secondApp.URL)
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp