Skip to content
Merged
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
206 changes: 206 additions & 0 deletions agent/agent_test.go
Original file line number Diff line number Diff 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
21 changes: 13 additions & 8 deletions agent/agentcontainers/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,8 @@ func WithContainerCLI(ccli ContainerCLI) Option {

// WithContainerLabelIncludeFilter sets a label filter for containers.
// This option can be given multiple times to filter by multiple labels.
// The behavior is such that only containers matching one or more of the
// provided labels will be included.
// The behavior is such that only containers matching all of the provided
// labels will be included.
func WithContainerLabelIncludeFilter(label, value string) Option {
return func(api *API) {
api.containerLabelIncludeFilter[label] = value
Expand Down Expand Up @@ -927,17 +927,22 @@ func (api *API) processUpdatedContainersLocked(ctx context.Context, updated code
slog.F("config_file", configFile),
)

// If we haven't set any include filters, we should explicitly ignore test devcontainers.
if len(api.containerLabelIncludeFilter) == 0 && container.Labels[DevcontainerIsTestRunLabel] == "true" {
continue
}

// Filter out devcontainer tests, unless explicitly set in include filters.
if len(api.containerLabelIncludeFilter) > 0 || container.Labels[DevcontainerIsTestRunLabel] == "true" {
var ok bool
if len(api.containerLabelIncludeFilter) > 0 {
includeContainer := true
for label, value := range api.containerLabelIncludeFilter {
if v, found := container.Labels[label]; found && v == value {
ok = true
}
v, found := container.Labels[label]

includeContainer = includeContainer && (found && v == value)
}
// Verbose debug logging is fine here since typically filters
// are only used in development or testing environments.
if !ok {
if !includeContainer {
logger.Debug(ctx, "container does not match include filter, ignoring devcontainer", slog.F("container_labels", container.Labels), slog.F("include_filter", api.containerLabelIncludeFilter))
continue
}
Expand Down
Loading
Loading