diff --git a/agent/agent.go b/agent/agent.go index e142f8662f641..0033e7750628a 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -1145,13 +1145,6 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context, scripts = manifest.Scripts scriptRunnerOpts []agentscripts.InitOption ) - if a.experimentalDevcontainersEnabled { - var dcScripts []codersdk.WorkspaceAgentScript - scripts, dcScripts = agentcontainers.ExtractAndInitializeDevcontainerScripts(manifest.Devcontainers, scripts) - // See ExtractAndInitializeDevcontainerScripts for motivation - // behind running dcScripts as post start scripts. - scriptRunnerOpts = append(scriptRunnerOpts, agentscripts.WithPostStartScripts(dcScripts...)) - } err = a.scriptRunner.Init(scripts, aAPI.ScriptCompleted, scriptRunnerOpts...) if err != nil { return xerrors.Errorf("init script runner: %w", err) @@ -1169,7 +1162,13 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context, // finished (both start and post start). For instance, an // autostarted devcontainer will be included in this time. err := a.scriptRunner.Execute(a.gracefulCtx, agentscripts.ExecuteStartScripts) - err = errors.Join(err, a.scriptRunner.Execute(a.gracefulCtx, agentscripts.ExecutePostStartScripts)) + + if cAPI := a.containerAPI.Load(); cAPI != nil { + for _, dc := range manifest.Devcontainers { + err = errors.Join(err, cAPI.CreateDevcontainer(dc)) + } + } + dur := time.Since(start).Seconds() if err != nil { a.logger.Warn(ctx, "startup script(s) failed", slog.Error(err)) diff --git a/agent/agentcontainers/api.go b/agent/agentcontainers/api.go index ddf98e38bdb48..3cc89dee76b49 100644 --- a/agent/agentcontainers/api.go +++ b/agent/agentcontainers/api.go @@ -784,7 +784,9 @@ func (api *API) handleDevcontainerRecreate(w http.ResponseWriter, r *http.Reques dc.Container = nil api.knownDevcontainers[dc.WorkspaceFolder] = dc api.asyncWg.Add(1) - go api.recreateDevcontainer(dc, configPath) + go func() { + _ = api.recreateDevcontainer(dc, configPath) + }() api.mu.Unlock() @@ -794,6 +796,17 @@ func (api *API) handleDevcontainerRecreate(w http.ResponseWriter, r *http.Reques }) } +func (api *API) CreateDevcontainer(dc codersdk.WorkspaceAgentDevcontainer) error { + api.mu.Lock() + dc.Status = codersdk.WorkspaceAgentDevcontainerStatusStarting + dc.Container = nil + api.knownDevcontainers[dc.WorkspaceFolder] = dc + api.asyncWg.Add(1) + api.mu.Unlock() + + return api.recreateDevcontainer(dc, dc.ConfigPath) +} + // recreateDevcontainer should run in its own goroutine and is responsible for // recreating a devcontainer based on the provided devcontainer configuration. // It updates the devcontainer status and logs the process. The configPath is @@ -801,7 +814,7 @@ func (api *API) handleDevcontainerRecreate(w http.ResponseWriter, r *http.Reques // has a different config file than the one stored in the devcontainer state. // The devcontainer state must be set to starting and the asyncWg must be // incremented before calling this function. -func (api *API) recreateDevcontainer(dc codersdk.WorkspaceAgentDevcontainer, configPath string) { +func (api *API) recreateDevcontainer(dc codersdk.WorkspaceAgentDevcontainer, configPath string) error { defer api.asyncWg.Done() var ( @@ -857,7 +870,7 @@ func (api *API) recreateDevcontainer(dc codersdk.WorkspaceAgentDevcontainer, con api.knownDevcontainers[dc.WorkspaceFolder] = dc api.recreateErrorTimes[dc.WorkspaceFolder] = api.clock.Now("agentcontainers", "recreate", "errorTimes") api.mu.Unlock() - return + return err } logger.Info(ctx, "devcontainer recreated successfully") @@ -884,7 +897,10 @@ func (api *API) recreateDevcontainer(dc codersdk.WorkspaceAgentDevcontainer, con // devcontainer state after recreation. if err := api.RefreshContainers(ctx); err != nil { logger.Error(ctx, "failed to trigger immediate refresh after devcontainer recreation", slog.Error(err)) + return err } + + return nil } // markDevcontainerDirty finds the devcontainer with the given config file path diff --git a/agent/agentcontainers/devcontainer.go b/agent/agentcontainers/devcontainer.go index f13963d7b63d7..9ba77e7121b9b 100644 --- a/agent/agentcontainers/devcontainer.go +++ b/agent/agentcontainers/devcontainer.go @@ -2,10 +2,8 @@ package agentcontainers import ( "context" - "fmt" "os" "path/filepath" - "strings" "cdr.dev/slog" "github.com/coder/coder/v2/codersdk" @@ -22,61 +20,6 @@ const ( DevcontainerDefaultContainerWorkspaceFolder = "/workspaces" ) -const devcontainerUpScriptTemplate = ` -if ! which devcontainer > /dev/null 2>&1; then - echo "ERROR: Unable to start devcontainer, @devcontainers/cli is not installed or not found in \$PATH." 1>&2 - echo "Please install @devcontainers/cli by running \"npm install -g @devcontainers/cli\" or by using the \"devcontainers-cli\" Coder module." 1>&2 - exit 1 -fi -devcontainer up %s -` - -// ExtractAndInitializeDevcontainerScripts extracts devcontainer scripts from -// the given scripts and devcontainers. The devcontainer scripts are removed -// from the returned scripts so that they can be run separately. -// -// Dev Containers have an inherent dependency on start scripts, since they -// initialize the workspace (e.g. git clone, npm install, etc). This is -// important if e.g. a Coder module to install @devcontainer/cli is used. -func ExtractAndInitializeDevcontainerScripts( - devcontainers []codersdk.WorkspaceAgentDevcontainer, - scripts []codersdk.WorkspaceAgentScript, -) (filteredScripts []codersdk.WorkspaceAgentScript, devcontainerScripts []codersdk.WorkspaceAgentScript) { -ScriptLoop: - for _, script := range scripts { - for _, dc := range devcontainers { - // The devcontainer scripts match the devcontainer ID for - // identification. - if script.ID == dc.ID { - devcontainerScripts = append(devcontainerScripts, devcontainerStartupScript(dc, script)) - continue ScriptLoop - } - } - - filteredScripts = append(filteredScripts, script) - } - - return filteredScripts, devcontainerScripts -} - -func devcontainerStartupScript(dc codersdk.WorkspaceAgentDevcontainer, script codersdk.WorkspaceAgentScript) codersdk.WorkspaceAgentScript { - args := []string{ - "--log-format json", - fmt.Sprintf("--workspace-folder %q", dc.WorkspaceFolder), - } - if dc.ConfigPath != "" { - args = append(args, fmt.Sprintf("--config %q", dc.ConfigPath)) - } - cmd := fmt.Sprintf(devcontainerUpScriptTemplate, strings.Join(args, " ")) - // Force the script to run in /bin/sh, since some shells (e.g. fish) - // don't support the script. - script.Script = fmt.Sprintf("/bin/sh -c '%s'", cmd) - // Disable RunOnStart, scripts have this set so that when devcontainers - // have not been enabled, a warning will be surfaced in the agent logs. - script.RunOnStart = false - return script -} - // ExpandAllDevcontainerPaths expands all devcontainer paths in the given // devcontainers. This is required by the devcontainer CLI, which requires // absolute paths for the workspace folder and config path. diff --git a/agent/agentcontainers/devcontainer_test.go b/agent/agentcontainers/devcontainer_test.go deleted file mode 100644 index b20c943175821..0000000000000 --- a/agent/agentcontainers/devcontainer_test.go +++ /dev/null @@ -1,274 +0,0 @@ -package agentcontainers_test - -import ( - "path/filepath" - "strings" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "github.com/google/uuid" - "github.com/stretchr/testify/require" - - "cdr.dev/slog/sloggers/slogtest" - "github.com/coder/coder/v2/agent/agentcontainers" - "github.com/coder/coder/v2/codersdk" -) - -func TestExtractAndInitializeDevcontainerScripts(t *testing.T) { - t.Parallel() - - scriptIDs := []uuid.UUID{uuid.New(), uuid.New()} - devcontainerIDs := []uuid.UUID{uuid.New(), uuid.New()} - - type args struct { - expandPath func(string) (string, error) - devcontainers []codersdk.WorkspaceAgentDevcontainer - scripts []codersdk.WorkspaceAgentScript - } - tests := []struct { - name string - args args - wantFilteredScripts []codersdk.WorkspaceAgentScript - wantDevcontainerScripts []codersdk.WorkspaceAgentScript - - skipOnWindowsDueToPathSeparator bool - }{ - { - name: "no scripts", - args: args{ - expandPath: nil, - devcontainers: nil, - scripts: nil, - }, - wantFilteredScripts: nil, - wantDevcontainerScripts: nil, - }, - { - name: "no devcontainers", - args: args{ - expandPath: nil, - devcontainers: nil, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0]}, - {ID: scriptIDs[1]}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0]}, - {ID: scriptIDs[1]}, - }, - wantDevcontainerScripts: nil, - }, - { - name: "no scripts match devcontainers", - args: args{ - expandPath: nil, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - {ID: devcontainerIDs[0]}, - {ID: devcontainerIDs[1]}, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0]}, - {ID: scriptIDs[1]}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0]}, - {ID: scriptIDs[1]}, - }, - wantDevcontainerScripts: nil, - }, - { - name: "scripts match devcontainers and sets RunOnStart=false", - args: args{ - expandPath: nil, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - {ID: devcontainerIDs[0], WorkspaceFolder: "workspace1"}, - {ID: devcontainerIDs[1], WorkspaceFolder: "workspace2"}, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0], RunOnStart: true}, - {ID: scriptIDs[1], RunOnStart: true}, - {ID: devcontainerIDs[0], RunOnStart: true}, - {ID: devcontainerIDs[1], RunOnStart: true}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0], RunOnStart: true}, - {ID: scriptIDs[1], RunOnStart: true}, - }, - wantDevcontainerScripts: []codersdk.WorkspaceAgentScript{ - { - ID: devcontainerIDs[0], - Script: "devcontainer up --log-format json --workspace-folder \"workspace1\"", - RunOnStart: false, - }, - { - ID: devcontainerIDs[1], - Script: "devcontainer up --log-format json --workspace-folder \"workspace2\"", - RunOnStart: false, - }, - }, - }, - { - name: "scripts match devcontainers with config path", - args: args{ - expandPath: nil, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - { - ID: devcontainerIDs[0], - WorkspaceFolder: "workspace1", - ConfigPath: "config1", - }, - { - ID: devcontainerIDs[1], - WorkspaceFolder: "workspace2", - ConfigPath: "config2", - }, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: devcontainerIDs[0]}, - {ID: devcontainerIDs[1]}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{}, - wantDevcontainerScripts: []codersdk.WorkspaceAgentScript{ - { - ID: devcontainerIDs[0], - Script: "devcontainer up --log-format json --workspace-folder \"workspace1\" --config \"workspace1/config1\"", - RunOnStart: false, - }, - { - ID: devcontainerIDs[1], - Script: "devcontainer up --log-format json --workspace-folder \"workspace2\" --config \"workspace2/config2\"", - RunOnStart: false, - }, - }, - skipOnWindowsDueToPathSeparator: true, - }, - { - name: "scripts match devcontainers with expand path", - args: args{ - expandPath: func(s string) (string, error) { - return "/home/" + s, nil - }, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - { - ID: devcontainerIDs[0], - WorkspaceFolder: "workspace1", - ConfigPath: "config1", - }, - { - ID: devcontainerIDs[1], - WorkspaceFolder: "workspace2", - ConfigPath: "config2", - }, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: devcontainerIDs[0], RunOnStart: true}, - {ID: devcontainerIDs[1], RunOnStart: true}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{}, - wantDevcontainerScripts: []codersdk.WorkspaceAgentScript{ - { - ID: devcontainerIDs[0], - Script: "devcontainer up --log-format json --workspace-folder \"/home/workspace1\" --config \"/home/workspace1/config1\"", - RunOnStart: false, - }, - { - ID: devcontainerIDs[1], - Script: "devcontainer up --log-format json --workspace-folder \"/home/workspace2\" --config \"/home/workspace2/config2\"", - RunOnStart: false, - }, - }, - skipOnWindowsDueToPathSeparator: true, - }, - { - name: "expand config path when ~", - args: args{ - expandPath: func(s string) (string, error) { - s = strings.Replace(s, "~/", "", 1) - if filepath.IsAbs(s) { - return s, nil - } - return "/home/" + s, nil - }, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - { - ID: devcontainerIDs[0], - WorkspaceFolder: "workspace1", - ConfigPath: "~/config1", - }, - { - ID: devcontainerIDs[1], - WorkspaceFolder: "workspace2", - ConfigPath: "/config2", - }, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: devcontainerIDs[0], RunOnStart: true}, - {ID: devcontainerIDs[1], RunOnStart: true}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{}, - wantDevcontainerScripts: []codersdk.WorkspaceAgentScript{ - { - ID: devcontainerIDs[0], - Script: "devcontainer up --log-format json --workspace-folder \"/home/workspace1\" --config \"/home/config1\"", - RunOnStart: false, - }, - { - ID: devcontainerIDs[1], - Script: "devcontainer up --log-format json --workspace-folder \"/home/workspace2\" --config \"/config2\"", - RunOnStart: false, - }, - }, - skipOnWindowsDueToPathSeparator: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - if tt.skipOnWindowsDueToPathSeparator && filepath.Separator == '\\' { - t.Skip("Skipping test on Windows due to path separator difference.") - } - - logger := slogtest.Make(t, nil) - if tt.args.expandPath == nil { - tt.args.expandPath = func(s string) (string, error) { - return s, nil - } - } - gotFilteredScripts, gotDevcontainerScripts := agentcontainers.ExtractAndInitializeDevcontainerScripts( - agentcontainers.ExpandAllDevcontainerPaths(logger, tt.args.expandPath, tt.args.devcontainers), - tt.args.scripts, - ) - - if diff := cmp.Diff(tt.wantFilteredScripts, gotFilteredScripts, cmpopts.EquateEmpty()); diff != "" { - t.Errorf("ExtractAndInitializeDevcontainerScripts() gotFilteredScripts mismatch (-want +got):\n%s", diff) - } - - // Preprocess the devcontainer scripts to remove scripting part. - for i := range gotDevcontainerScripts { - gotDevcontainerScripts[i].Script = textGrep("devcontainer up", gotDevcontainerScripts[i].Script) - require.NotEmpty(t, gotDevcontainerScripts[i].Script, "devcontainer up script not found") - } - if diff := cmp.Diff(tt.wantDevcontainerScripts, gotDevcontainerScripts); diff != "" { - t.Errorf("ExtractAndInitializeDevcontainerScripts() gotDevcontainerScripts mismatch (-want +got):\n%s", diff) - } - }) - } -} - -// textGrep returns matching lines from multiline string. -func textGrep(want, got string) (filtered string) { - var lines []string - for _, line := range strings.Split(got, "\n") { - if strings.Contains(line, want) { - lines = append(lines, line) - } - } - return strings.Join(lines, "\n") -} diff --git a/agent/agentcontainers/devcontainercli.go b/agent/agentcontainers/devcontainercli.go index e302ff07d6dd9..9673fd4c2d799 100644 --- a/agent/agentcontainers/devcontainercli.go +++ b/agent/agentcontainers/devcontainercli.go @@ -135,7 +135,7 @@ func WithReadConfigOutput(stdout, stderr io.Writer) DevcontainerCLIReadConfigOpt } func applyDevcontainerCLIUpOptions(opts []DevcontainerCLIUpOptions) devcontainerCLIUpConfig { - conf := devcontainerCLIUpConfig{} + conf := devcontainerCLIUpConfig{stdout: io.Discard, stderr: io.Discard} for _, opt := range opts { if opt != nil { opt(&conf) @@ -145,7 +145,7 @@ func applyDevcontainerCLIUpOptions(opts []DevcontainerCLIUpOptions) devcontainer } func applyDevcontainerCLIExecOptions(opts []DevcontainerCLIExecOptions) devcontainerCLIExecConfig { - conf := devcontainerCLIExecConfig{} + conf := devcontainerCLIExecConfig{stdout: io.Discard, stderr: io.Discard} for _, opt := range opts { if opt != nil { opt(&conf) @@ -155,7 +155,7 @@ func applyDevcontainerCLIExecOptions(opts []DevcontainerCLIExecOptions) devconta } func applyDevcontainerCLIReadConfigOptions(opts []DevcontainerCLIReadConfigOptions) devcontainerCLIReadConfigConfig { - conf := devcontainerCLIReadConfigConfig{} + conf := devcontainerCLIReadConfigConfig{stdout: io.Discard, stderr: io.Discard} for _, opt := range opts { if opt != nil { opt(&conf) @@ -195,17 +195,20 @@ func (d *devcontainerCLI) Up(ctx context.Context, workspaceFolder, configPath st // Capture stdout for parsing and stream logs for both default and provided writers. var stdoutBuf bytes.Buffer - stdoutWriters := []io.Writer{&stdoutBuf, &devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stdout", true))}} - if conf.stdout != nil { - stdoutWriters = append(stdoutWriters, conf.stdout) - } - cmd.Stdout = io.MultiWriter(stdoutWriters...) + cmd.Stdout = io.MultiWriter( + &stdoutBuf, + &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stdout", true)), + writer: conf.stdout, + }, + ) // Stream stderr logs and provided writer if any. - stderrWriters := []io.Writer{&devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stderr", true))}} - if conf.stderr != nil { - stderrWriters = append(stderrWriters, conf.stderr) + cmd.Stderr = &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stderr", true)), + writer: conf.stderr, } - cmd.Stderr = io.MultiWriter(stderrWriters...) if err := cmd.Run(); err != nil { _, err2 := parseDevcontainerCLILastLine[devcontainerCLIResult](ctx, logger, stdoutBuf.Bytes()) @@ -244,16 +247,16 @@ func (d *devcontainerCLI) Exec(ctx context.Context, workspaceFolder, configPath args = append(args, cmdArgs...) c := d.execer.CommandContext(ctx, "devcontainer", args...) - stdoutWriters := []io.Writer{&devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stdout", true))}} - if conf.stdout != nil { - stdoutWriters = append(stdoutWriters, conf.stdout) - } - c.Stdout = io.MultiWriter(stdoutWriters...) - stderrWriters := []io.Writer{&devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stderr", true))}} - if conf.stderr != nil { - stderrWriters = append(stderrWriters, conf.stderr) - } - c.Stderr = io.MultiWriter(stderrWriters...) + c.Stdout = io.MultiWriter(conf.stdout, &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stdout", true)), + writer: io.Discard, + }) + c.Stderr = io.MultiWriter(conf.stderr, &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stderr", true)), + writer: io.Discard, + }) if err := c.Run(); err != nil { return xerrors.Errorf("devcontainer exec failed: %w", err) @@ -279,16 +282,19 @@ func (d *devcontainerCLI) ReadConfig(ctx context.Context, workspaceFolder, confi c.Env = append(c.Env, env...) var stdoutBuf bytes.Buffer - stdoutWriters := []io.Writer{&stdoutBuf, &devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stdout", true))}} - if conf.stdout != nil { - stdoutWriters = append(stdoutWriters, conf.stdout) - } - c.Stdout = io.MultiWriter(stdoutWriters...) - stderrWriters := []io.Writer{&devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stderr", true))}} - if conf.stderr != nil { - stderrWriters = append(stderrWriters, conf.stderr) + c.Stdout = io.MultiWriter( + &stdoutBuf, + &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stdout", true)), + writer: conf.stdout, + }, + ) + c.Stderr = &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stderr", true)), + writer: conf.stderr, } - c.Stderr = io.MultiWriter(stderrWriters...) if err := c.Run(); err != nil { return DevcontainerConfig{}, xerrors.Errorf("devcontainer read-configuration failed: %w", err) @@ -381,6 +387,7 @@ type devcontainerCLIJSONLogLine struct { type devcontainerCLILogWriter struct { ctx context.Context logger slog.Logger + writer io.Writer } func (l *devcontainerCLILogWriter) Write(p []byte) (n int, err error) { @@ -401,6 +408,7 @@ func (l *devcontainerCLILogWriter) Write(p []byte) (n int, err error) { } if logLine.Level >= 3 { l.logger.Info(l.ctx, "@devcontainer/cli", slog.F("line", string(line))) + _, _ = l.writer.Write([]byte(logLine.Text + "\n")) continue } l.logger.Debug(l.ctx, "@devcontainer/cli", slog.F("line", string(line))) diff --git a/agent/agentcontainers/devcontainercli_test.go b/agent/agentcontainers/devcontainercli_test.go index 821e6e8f95e76..28a39a4b47ab9 100644 --- a/agent/agentcontainers/devcontainercli_test.go +++ b/agent/agentcontainers/devcontainercli_test.go @@ -363,7 +363,7 @@ func TestDevcontainerCLI_WithOutput(t *testing.T) { require.NotEmpty(t, containerID, "expected non-empty container ID") // Read expected log content. - expLog, err := os.ReadFile(filepath.Join("testdata", "devcontainercli", "parse", "up.log")) + expLog, err := os.ReadFile(filepath.Join("testdata", "devcontainercli", "parse", "up.expected")) require.NoError(t, err, "reading expected log file") // Verify stdout buffer contains the CLI logs and stderr is empty. diff --git a/agent/agentcontainers/testdata/devcontainercli/parse/up.expected b/agent/agentcontainers/testdata/devcontainercli/parse/up.expected new file mode 100644 index 0000000000000..83a2bdcc78f68 --- /dev/null +++ b/agent/agentcontainers/testdata/devcontainercli/parse/up.expected @@ -0,0 +1,76 @@ +@devcontainers/cli 0.75.0. Node.js v23.9.0. darwin 24.4.0 arm64. +Resolving Feature dependencies for 'ghcr.io/devcontainers/features/docker-in-docker:2'... +Soft-dependency 'ghcr.io/devcontainers/features/common-utils' is not required. Removing from installation order... +Files to omit: '' +Run: docker buildx build --load --build-context dev_containers_feature_content_source=/var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/container-features/0.75.0-1744102171193 --build-arg _DEV_CONTAINERS_BASE_IMAGE=mcr.microsoft.com/devcontainers/javascript-node:1-18-bullseye --build-arg _DEV_CONTAINERS_IMAGE_USER=root --build-arg _DEV_CONTAINERS_FEATURE_CONTENT_SOURCE=dev_container_feature_content_temp --target dev_containers_target_stage -f /var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/container-features/0.75.0-1744102171193/Dockerfile.extended -t vsc-devcontainers-template-starter-81d8f17e32abef6d434cbb5a37fe05e5c8a6f8ccede47a61197f002dcbf60566-features /var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/empty-folder +#0 building with "orbstack" instance using docker driver + +#1 [internal] load build definition from Dockerfile.extended + +#1 transferring dockerfile: 3.09kB done +#1 DONE 0.0s + +#2 resolve image config for docker-image://docker.io/docker/dockerfile:1.4 + +#2 DONE 1.3s + + +#3 docker-image://docker.io/docker/dockerfile:1.4@sha256:9ba7531bd80fb0a858632727cf7a112fbfd19b17e94c4e84ced81e24ef1a0dbc +#3 CACHED + + + +#4 [internal] load .dockerignore +#4 transferring context: 2B done +#4 DONE 0.0s + +#5 [internal] load metadata for mcr.microsoft.com/devcontainers/javascript-node:1-18-bullseye +#5 DONE 0.0s + +#6 [context dev_containers_feature_content_source] load .dockerignore +#6 transferring dev_containers_feature_content_source: 2B done +#6 DONE 0.0s + +#7 [dev_containers_feature_content_normalize 1/3] FROM mcr.microsoft.com/devcontainers/javascript-node:1-18-bullseye +#7 DONE 0.0s + +#8 [context dev_containers_feature_content_source] load from client +#8 transferring dev_containers_feature_content_source: 82.11kB 0.0s done +#8 DONE 0.0s + +#9 [dev_containers_feature_content_normalize 2/3] COPY --from=dev_containers_feature_content_source devcontainer-features.builtin.env /tmp/build-features/ +#9 CACHED + +#10 [dev_containers_target_stage 2/5] RUN mkdir -p /tmp/dev-container-features +#10 CACHED + +#11 [dev_containers_target_stage 3/5] COPY --from=dev_containers_feature_content_normalize /tmp/build-features/ /tmp/dev-container-features +#11 CACHED + +#12 [dev_containers_target_stage 4/5] RUN echo "_CONTAINER_USER_HOME=$( (command -v getent >/dev/null 2>&1 && getent passwd 'root' || grep -E '^root|^[^:]*:[^:]*:root:' /etc/passwd || true) | cut -d: -f6)" >> /tmp/dev-container-features/devcontainer-features.builtin.env && echo "_REMOTE_USER_HOME=$( (command -v getent >/dev/null 2>&1 && getent passwd 'node' || grep -E '^node|^[^:]*:[^:]*:node:' /etc/passwd || true) | cut -d: -f6)" >> /tmp/dev-container-features/devcontainer-features.builtin.env +#12 CACHED + +#13 [dev_containers_feature_content_normalize 3/3] RUN chmod -R 0755 /tmp/build-features/ +#13 CACHED + +#14 [dev_containers_target_stage 5/5] RUN --mount=type=bind,from=dev_containers_feature_content_source,source=docker-in-docker_0,target=/tmp/build-features-src/docker-in-docker_0 cp -ar /tmp/build-features-src/docker-in-docker_0 /tmp/dev-container-features && chmod -R 0755 /tmp/dev-container-features/docker-in-docker_0 && cd /tmp/dev-container-features/docker-in-docker_0 && chmod +x ./devcontainer-features-install.sh && ./devcontainer-features-install.sh && rm -rf /tmp/dev-container-features/docker-in-docker_0 +#14 CACHED + +#15 exporting to image +#15 exporting layers done +#15 writing image sha256:275dc193c905d448ef3945e3fc86220cc315fe0cb41013988d6ff9f8d6ef2357 done +#15 naming to docker.io/library/vsc-devcontainers-template-starter-81d8f17e32abef6d434cbb5a37fe05e5c8a6f8ccede47a61197f002dcbf60566-features done +#15 DONE 0.0s + +Run: docker buildx build --load --build-context dev_containers_feature_content_source=/var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/container-features/0.75.0-1744102171193 --build-arg _DEV_CONTAINERS_BASE_IMAGE=mcr.microsoft.com/devcontainers/javascript-node:1-18-bullseye --build-arg _DEV_CONTAINERS_IMAGE_USER=root --build-arg _DEV_CONTAINERS_FEATURE_CONTENT_SOURCE=dev_container_feature_content_temp --target dev_containers_target_stage -f /var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/container-features/0.75.0-1744102171193/Dockerfile.extended -t vsc-devcontainers-template-starter-81d8f17e32abef6d434cbb5a37fe05e5c8a6f8ccede47a61197f002dcbf60566-features /var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/empty-folder +Run: docker run --sig-proxy=false -a STDOUT -a STDERR --mount type=bind,source=/code/devcontainers-template-starter,target=/workspaces/devcontainers-template-starter,consistency=cached --mount type=volume,src=dind-var-lib-docker-0pctifo8bbg3pd06g3j5s9ae8j7lp5qfcd67m25kuahurel7v7jm,dst=/var/lib/docker -l devcontainer.local_folder=/code/devcontainers-template-starter -l devcontainer.config_file=/code/devcontainers-template-starter/.devcontainer/devcontainer.json --privileged --entrypoint /bin/sh vsc-devcontainers-template-starter-81d8f17e32abef6d434cbb5a37fe05e5c8a6f8ccede47a61197f002dcbf60566-features -c echo Container started +Container started + +Not setting dockerd DNS manually. + +Running the postCreateCommand from devcontainer.json... + + + +added 1 package in 784ms + diff --git a/agent/agentscripts/agentscripts.go b/agent/agentscripts/agentscripts.go index 79606a80233b9..ac6e3a30f44a1 100644 --- a/agent/agentscripts/agentscripts.go +++ b/agent/agentscripts/agentscripts.go @@ -79,21 +79,6 @@ func New(opts Options) *Runner { type ScriptCompletedFunc func(context.Context, *proto.WorkspaceAgentScriptCompletedRequest) (*proto.WorkspaceAgentScriptCompletedResponse, error) -type runnerScript struct { - runOnPostStart bool - codersdk.WorkspaceAgentScript -} - -func toRunnerScript(scripts ...codersdk.WorkspaceAgentScript) []runnerScript { - var rs []runnerScript - for _, s := range scripts { - rs = append(rs, runnerScript{ - WorkspaceAgentScript: s, - }) - } - return rs -} - type Runner struct { Options @@ -103,7 +88,7 @@ type Runner struct { closed chan struct{} closeMutex sync.Mutex cron *cron.Cron - scripts []runnerScript + scripts []codersdk.WorkspaceAgentScript dataDir string scriptCompleted ScriptCompletedFunc @@ -138,19 +123,6 @@ func (r *Runner) RegisterMetrics(reg prometheus.Registerer) { // InitOption describes an option for the runner initialization. type InitOption func(*Runner) -// WithPostStartScripts adds scripts that should be run after the workspace -// start scripts but before the workspace is marked as started. -func WithPostStartScripts(scripts ...codersdk.WorkspaceAgentScript) InitOption { - return func(r *Runner) { - for _, s := range scripts { - r.scripts = append(r.scripts, runnerScript{ - runOnPostStart: true, - WorkspaceAgentScript: s, - }) - } - } -} - // Init initializes the runner with the provided scripts. // It also schedules any scripts that have a schedule. // This function must be called before Execute. @@ -161,7 +133,7 @@ func (r *Runner) Init(scripts []codersdk.WorkspaceAgentScript, scriptCompleted S return xerrors.New("init: already initialized") } r.initialized = true - r.scripts = toRunnerScript(scripts...) + r.scripts = scripts r.scriptCompleted = scriptCompleted for _, opt := range opts { opt(r) @@ -179,7 +151,7 @@ func (r *Runner) Init(scripts []codersdk.WorkspaceAgentScript, scriptCompleted S } script := script _, err := r.cron.AddFunc(script.Cron, func() { - err := r.trackRun(r.cronCtx, script.WorkspaceAgentScript, ExecuteCronScripts) + err := r.trackRun(r.cronCtx, script, ExecuteCronScripts) if err != nil { r.Logger.Warn(context.Background(), "run agent script on schedule", slog.Error(err)) } @@ -223,7 +195,6 @@ type ExecuteOption int const ( ExecuteAllScripts ExecuteOption = iota ExecuteStartScripts - ExecutePostStartScripts ExecuteStopScripts ExecuteCronScripts ) @@ -246,7 +217,6 @@ func (r *Runner) Execute(ctx context.Context, option ExecuteOption) error { for _, script := range r.scripts { runScript := (option == ExecuteStartScripts && script.RunOnStart) || (option == ExecuteStopScripts && script.RunOnStop) || - (option == ExecutePostStartScripts && script.runOnPostStart) || (option == ExecuteCronScripts && script.Cron != "") || option == ExecuteAllScripts @@ -256,7 +226,7 @@ func (r *Runner) Execute(ctx context.Context, option ExecuteOption) error { script := script eg.Go(func() error { - err := r.trackRun(ctx, script.WorkspaceAgentScript, option) + err := r.trackRun(ctx, script, option) if err != nil { return xerrors.Errorf("run agent script %q: %w", script.LogSourceID, err) } diff --git a/agent/agentscripts/agentscripts_test.go b/agent/agentscripts/agentscripts_test.go index f50a0cc065138..c032ea1f83a1a 100644 --- a/agent/agentscripts/agentscripts_test.go +++ b/agent/agentscripts/agentscripts_test.go @@ -4,7 +4,6 @@ import ( "context" "path/filepath" "runtime" - "slices" "sync" "testing" "time" @@ -177,11 +176,6 @@ func TestExecuteOptions(t *testing.T) { Script: "echo stop", RunOnStop: true, } - postStartScript := codersdk.WorkspaceAgentScript{ - ID: uuid.New(), - LogSourceID: uuid.New(), - Script: "echo poststart", - } regularScript := codersdk.WorkspaceAgentScript{ ID: uuid.New(), LogSourceID: uuid.New(), @@ -193,10 +187,9 @@ func TestExecuteOptions(t *testing.T) { stopScript, regularScript, } - allScripts := append(slices.Clone(scripts), postStartScript) scriptByID := func(t *testing.T, id uuid.UUID) codersdk.WorkspaceAgentScript { - for _, script := range allScripts { + for _, script := range scripts { if script.ID == id { return script } @@ -206,10 +199,9 @@ func TestExecuteOptions(t *testing.T) { } wantOutput := map[uuid.UUID]string{ - startScript.ID: "start", - stopScript.ID: "stop", - postStartScript.ID: "poststart", - regularScript.ID: "regular", + startScript.ID: "start", + stopScript.ID: "stop", + regularScript.ID: "regular", } testCases := []struct { @@ -220,18 +212,13 @@ func TestExecuteOptions(t *testing.T) { { name: "ExecuteAllScripts", option: agentscripts.ExecuteAllScripts, - wantRun: []uuid.UUID{startScript.ID, stopScript.ID, regularScript.ID, postStartScript.ID}, + wantRun: []uuid.UUID{startScript.ID, stopScript.ID, regularScript.ID}, }, { name: "ExecuteStartScripts", option: agentscripts.ExecuteStartScripts, wantRun: []uuid.UUID{startScript.ID}, }, - { - name: "ExecutePostStartScripts", - option: agentscripts.ExecutePostStartScripts, - wantRun: []uuid.UUID{postStartScript.ID}, - }, { name: "ExecuteStopScripts", option: agentscripts.ExecuteStopScripts, @@ -260,7 +247,6 @@ func TestExecuteOptions(t *testing.T) { err := runner.Init( scripts, aAPI.ScriptCompleted, - agentscripts.WithPostStartScripts(postStartScript), ) require.NoError(t, err) @@ -274,7 +260,7 @@ func TestExecuteOptions(t *testing.T) { "script %s should have run when using filter %s", scriptByID(t, id).Script, tc.name) } - for _, script := range allScripts { + for _, script := range scripts { if _, ok := gotRun[script.ID]; ok { continue }