diff --git a/pkg/config/reserved_labels.go b/pkg/config/reserved_labels.go index b266b4775..45af7d94c 100644 --- a/pkg/config/reserved_labels.go +++ b/pkg/config/reserved_labels.go @@ -48,3 +48,22 @@ func ValidateUserLabels(labels []string) error { } return nil } + +func ValidateCreatedLabels(expected []string, actual map[string]string) error { + values := make(map[string]string, len(expected)) + for _, label := range expected { + key, value, _ := strings.Cut(label, "=") + values[key] = value + } + for key := range reservedLabels { + want, expectedPresent := values[key] + got, actualPresent := actual[key] + if expectedPresent != actualPresent || expectedPresent && want != got { + return fmt.Errorf( + "label %q does not match the value Devsy set; runArgs must not set Devsy reserved labels", + key, + ) + } + } + return nil +} diff --git a/pkg/config/reserved_labels_test.go b/pkg/config/reserved_labels_test.go index 83888c6e1..94d8da4f7 100644 --- a/pkg/config/reserved_labels_test.go +++ b/pkg/config/reserved_labels_test.go @@ -60,3 +60,28 @@ func (s *ReservedLabelsSuite) TestPreservesOrdinaryLabelsAndSupportedMetadata() s.Equal(original, labels) s.NoError(ValidateUserLabels(nil)) } + +func (s *ReservedLabelsSuite) TestCreatedLabels() { + for _, tc := range []struct { + name string + expected []string + actual map[string]string + key string + }{ + {"match", []string{"devsy.user=root"}, map[string]string{"devsy.user": "root"}, ""}, + {"ordinary", nil, map[string]string{"team": "a"}, ""}, + {"override", []string{"devsy.user=root"}, map[string]string{"devsy.user": "private-value"}, "devsy.user"}, + {"missing", []string{"devsy.user=private-value"}, nil, "devsy.user"}, + {"extra", nil, map[string]string{"sh.devsy.recovery": "private-value"}, "sh.devsy.recovery"}, + } { + s.Run(tc.name, func() { + err := ValidateCreatedLabels(tc.expected, tc.actual) + if tc.key == "" { + s.NoError(err) + return + } + s.Require().ErrorContains(err, tc.key) + s.NotContains(err.Error(), "private-value") + }) + } +} diff --git a/pkg/docker/helper.go b/pkg/docker/helper.go index a2df3403a..5a43fe534 100644 --- a/pkg/docker/helper.go +++ b/pkg/docker/helper.go @@ -19,6 +19,8 @@ import ( "github.com/devsy-org/devsy/pkg/image" "github.com/devsy-org/devsy/pkg/log" "github.com/devsy-org/devsy/pkg/scanner" + "github.com/devsy-org/devsy/pkg/secrets" + "github.com/devsy-org/devsy/pkg/subprocess" "k8s.io/apimachinery/pkg/util/wait" ) @@ -487,17 +489,40 @@ func (r *DockerHelper) RunWithEnv( } func (r *DockerHelper) StartContainer(ctx context.Context, containerId string) error { - out, err := r.buildCmd(ctx, "start", containerId).CombinedOutput() + return r.StartContainerWithEnvironment(ctx, containerId, nil) +} + +func (r *DockerHelper) StartContainerWithEnvironment( + ctx context.Context, + containerId string, + environment []string, +) error { + redactor := secrets.Combine( + secrets.NewEnvironmentRedactor(append(os.Environ(), r.Environment...)), + secrets.NewRedactor(environment), + ) + run := func(args ...string) (string, error) { + output := subprocess.NewBuffer(redactor) + cmd := r.buildCmd(ctx, args...) + cmd.Stdout = output + cmd.Stderr = output + err := cmd.Run() + return output.String(), err + } + out, err := run("start", containerId) if err != nil { - stateErr, _ := r.buildCmd(ctx, "inspect", containerId, "--format", - "{{.State.Error}} (exit code: {{.State.ExitCode}})"). - CombinedOutput() - logs, _ := r.buildCmd(ctx, "logs", containerId, "--tail", "50").CombinedOutput() - details := strings.TrimSpace(string(stateErr) + "\n" + string(logs)) + stateErr, _ := run( + "inspect", + containerId, + "--format", + "{{.State.Error}} (exit code: {{.State.ExitCode}})", + ) + logs, _ := run("logs", containerId, "--tail", "50") + details := strings.TrimSpace(stateErr + "\n" + logs) if details != "" { log.Errorf("container failed to start: %s", details) } - return fmt.Errorf("failed to start container: %s: %w", string(out), err) + return fmt.Errorf("failed to start container: %s: %w", out, err) } container, err := r.FindContainerByID(ctx, []string{containerId}) @@ -664,6 +689,30 @@ func (r *DockerHelper) InspectContainers( return details, nil } +type createdContainerConfig struct { + Labels map[string]string `json:"Labels"` + Env []string `json:"Env"` +} + +type createdContainerDetails struct { + ID string `json:"Id"` + Config createdContainerConfig `json:"Config"` +} + +func (r *DockerHelper) InspectCreatedContainer( + ctx context.Context, + id string, +) (map[string]string, []string, error) { + var details []createdContainerDetails + if err := r.Inspect(ctx, []string{id}, "container", &details); err != nil { + return nil, nil, err + } + if len(details) != 1 || details[0].ID != id { + return nil, nil, fmt.Errorf("created container inspection returned an unexpected result") + } + return details[0].Config.Labels, details[0].Config.Env, nil +} + func (r *DockerHelper) IsPodman() bool { return r.GetRuntime().Name() == RuntimePodman } diff --git a/pkg/docker/start_redaction_test.go b/pkg/docker/start_redaction_test.go new file mode 100644 index 000000000..1ae4909c2 --- /dev/null +++ b/pkg/docker/start_redaction_test.go @@ -0,0 +1,49 @@ +package docker + +import ( + "context" + "testing" + + "github.com/devsy-org/devsy/pkg/log" + "github.com/stretchr/testify/suite" + "go.uber.org/zap/zapcore" +) + +type StartRedactionSuite struct{ suite.Suite } + +func TestStartRedactionSuite(t *testing.T) { suite.Run(t, new(StartRedactionSuite)) } + +func (s *StartRedactionSuite) TestStartFailure() { + observed := log.InitTestObserved(s.T(), zapcore.ErrorLevel) + path := writeScript(s.T(), s.T().TempDir(), "engine", `#!/bin/sh +printf '%s\n' "$FIXTURE_TOKEN" "$ORDINARY" +if [ "$1" = start ]; then exit 1; fi +`) + h := &DockerHelper{DockerCommand: path, Environment: []string{ + "FIXTURE_TOKEN=fixture-private-value", "ORDINARY=container-private-value", + }} + err := h.StartContainerWithEnvironment( + context.Background(), + "container", + []string{"ORDINARY=container-private-value"}, + ) + s.Require().Error(err) + s.NotContains(err.Error(), "fixture-private-value") + s.Require().NotEmpty(observed.All()) + s.NotContains(observed.All()[0].Message, "fixture-private-value") + s.NotContains(err.Error(), "container-private-value") + s.NotContains(observed.All()[0].Message, "container-private-value") + s.Contains(err.Error(), "***") + s.Contains(observed.All()[0].Message, "***") +} + +func (s *StartRedactionSuite) TestInspectCreatedContainer() { + path := writeScript(s.T(), s.T().TempDir(), "engine", `#!/bin/sh +printf '%s\n' '[{"Id":"created-id","Config":{"Labels":{"team":"a"},"Env":["TOKEN=fixture-private-value"]}}]' +`) + h := &DockerHelper{DockerCommand: path} + labels, environment, err := h.InspectCreatedContainer(context.Background(), "created-id") + s.Require().NoError(err) + s.Equal(map[string]string{"team": "a"}, labels) + s.Equal([]string{"TOKEN=fixture-private-value"}, environment) +} diff --git a/pkg/driver/apple/lifecycle.go b/pkg/driver/apple/lifecycle.go index 10d850721..e3e570e6e 100644 --- a/pkg/driver/apple/lifecycle.go +++ b/pkg/driver/apple/lifecycle.go @@ -1,11 +1,16 @@ package apple import ( + "bytes" "context" + "errors" "fmt" "io" + "strings" + "time" "github.com/devsy-org/devsy/pkg/apple" + pkgconfig "github.com/devsy-org/devsy/pkg/config" "github.com/devsy-org/devsy/pkg/devcontainer/config" "github.com/devsy-org/devsy/pkg/driver" "github.com/devsy-org/devsy/pkg/log" @@ -163,9 +168,39 @@ func (d *appleDriver) RunImageDevContainer( "running apple container command: command=%s, args=%s", d.command, redactArgs(args), ) + var output bytes.Buffer err := d.Apple.RunWithDir(ctx, params.LocalWorkspaceFolder, args, - apple.Streams{Stdout: writer, Stderr: writer}) + apple.Streams{Stdout: io.MultiWriter(writer, &output), Stderr: writer}) if err != nil { + return fmt.Errorf( + "failed to start dev container: %w; %s", + err, + "runArgs must be valid for container create; options that only apply to run are not supported", + ) + } + ids := strings.Fields(output.String()) + if len(ids) != 1 { + return fmt.Errorf( + "failed to identify created container; inspect the runtime for an unstarted container", + ) + } + id := ids[0] + details, err := d.Apple.FindContainerByID(ctx, []string{id}) + if err == nil && (details == nil || details.ID != id) { + err = fmt.Errorf("created container inspection returned an unexpected result") + } + if err == nil { + labels := append( + config.GetIDLabels(params.WorkspaceID, d.IDLabels), + params.Options.Labels...) + err = pkgconfig.ValidateCreatedLabels(labels, details.Config.Labels) + } + if err != nil { + cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + return errors.Join(err, d.Apple.Remove(cleanupCtx, id)) + } + if err := d.Apple.StartContainer(ctx, id); err != nil { return fmt.Errorf("failed to start dev container: %w", err) } diff --git a/pkg/driver/apple/lifecycle_test.go b/pkg/driver/apple/lifecycle_test.go index 9dd8619a3..a018ab8e9 100644 --- a/pkg/driver/apple/lifecycle_test.go +++ b/pkg/driver/apple/lifecycle_test.go @@ -13,7 +13,9 @@ import ( ) const ( - stopC1 = "stop:c1" + stopC1 = "stop:c1" + testCreateCommand = "create" + testRunCall = "run" ) // Test image references shared across driver tests. @@ -39,6 +41,8 @@ type mockClient struct { runWithDir string // dir passed to the last RunWithDir call systemDown bool // SystemRunning reports false ensureErr error // error returned by EnsureSystemRunning + + createOutput string } func (m *mockClient) EnsureSystemRunning(context.Context) error { return m.ensureErr } @@ -78,11 +82,21 @@ func (m *mockClient) RunWithDir( _ context.Context, dir string, args []string, - _ apple.Streams, + streams apple.Streams, ) error { - m.calls = append(m.calls, "run") + m.calls = append(m.calls, testRunCall) m.runWithDir = dir m.ranArgs = append(m.ranArgs, args) + if args[0] == testCreateCommand { + output := m.createOutput + if output == "" { + output = "created-id\n" + } + _, _ = io.WriteString(streams.Stdout, output) + if m.found == nil { + m.found = &config.ContainerDetails{ID: "created-id"} + } + } return nil } @@ -198,7 +212,7 @@ func TestRunImageDevContainer_PullsRunsThenUID(t *testing.T) { t.Fatalf("RunImageDevContainer: %v", err) } // Image must be ensured (pulled) before the container is run. - if want := []string{"pull", "run"}; !slices.Equal(m.calls, want) { + if want := []string{"pull", testRunCall, "start:created-id"}; !slices.Equal(m.calls, want) { t.Errorf("call order = %v, want %v (ensure image before run)", m.calls, want) } if m.runWithDir != "/local/ws" { diff --git a/pkg/driver/apple/reserved_labels_test.go b/pkg/driver/apple/reserved_labels_test.go new file mode 100644 index 000000000..353a4d178 --- /dev/null +++ b/pkg/driver/apple/reserved_labels_test.go @@ -0,0 +1,78 @@ +package apple + +import ( + "context" + "testing" + + "github.com/devsy-org/devsy/pkg/devcontainer/config" + "github.com/devsy-org/devsy/pkg/driver" + "github.com/stretchr/testify/suite" +) + +type CreatedLabelsSuite struct{ suite.Suite } + +const ( + testUserLabel = "devsy.user" + testPrivateLabelValue = "private-value" + testRemoveCreated = "remove:created-id" +) + +func TestCreatedLabelsSuite(t *testing.T) { suite.Run(t, new(CreatedLabelsSuite)) } + +func (s *CreatedLabelsSuite) TestAmbiguousCreateOutputNeverStartsOrDeletes() { + m := &mockClient{createOutput: "private-value\ncreated-id\n"} + d := &appleDriver{Apple: m} + err := d.RunImageDevContainer(context.Background(), &driver.RunImageDevContainerParams{ + WorkspaceID: "ws", ParsedConfig: &config.DevContainerConfig{}, + Options: &driver.RunOptions{Image: testImageRef}, + }) + s.Require().ErrorContains(err, "inspect the runtime for an unstarted container") + s.NotContains(err.Error(), testPrivateLabelValue) + s.Equal([]string{testRunCall}, m.calls) +} + +func (s *CreatedLabelsSuite) TestCreateInspectsBeforeStarting() { + for _, tc := range []struct { + name string + labels map[string]string + wantCalls []string + wantKey string + }{ + {"match", map[string]string{testUserLabel: execUser, "team": "a"}, []string{testRunCall, "start:created-id"}, ""}, + { + "override", + map[string]string{testUserLabel: testPrivateLabelValue}, + []string{testRunCall, testRemoveCreated}, + testUserLabel, + }, + {"missing", nil, []string{testRunCall, testRemoveCreated}, testUserLabel}, + { + "extra", + map[string]string{testUserLabel: execUser, "sh.devsy.recovery": testPrivateLabelValue}, + []string{testRunCall, testRemoveCreated}, + "sh.devsy.recovery", + }, + } { + s.Run(tc.name, func() { + m := &mockClient{found: &config.ContainerDetails{ + ID: "created-id", Config: config.ContainerDetailsConfig{Labels: tc.labels}, + }} + d := &appleDriver{Apple: m} + err := d.RunImageDevContainer(context.Background(), &driver.RunImageDevContainerParams{ + WorkspaceID: "ws", + ParsedConfig: &config.DevContainerConfig{}, + Options: &driver.RunOptions{ + Image: testImageRef, + Labels: []string{"devsy.user=root"}, + }, + }) + if tc.wantKey != "" { + s.Require().ErrorContains(err, tc.wantKey) + s.NotContains(err.Error(), testPrivateLabelValue) + } else { + s.NoError(err) + } + s.Equal(tc.wantCalls, m.calls) + }) + } +} diff --git a/pkg/driver/apple/runargs.go b/pkg/driver/apple/runargs.go index 102b79174..db0c9c50a 100644 --- a/pkg/driver/apple/runargs.go +++ b/pkg/driver/apple/runargs.go @@ -14,7 +14,7 @@ import ( // buildRunArgs assembles `container run` args, emitting only flags Apple supports // (Docker/Podman-only flags like --security-opt/--gpus/--userns are omitted). func (d *appleDriver) buildRunArgs(params *driver.RunImageDevContainerParams) []string { - args := []string{"run", "-d"} + args := []string{"create"} if d.Rosetta { args = append(args, "--rosetta") diff --git a/pkg/driver/apple/runargs_test.go b/pkg/driver/apple/runargs_test.go index a1765b66f..daa1b4af2 100644 --- a/pkg/driver/apple/runargs_test.go +++ b/pkg/driver/apple/runargs_test.go @@ -37,7 +37,7 @@ func TestBuildRunArgs(t *testing.T) { joined := strings.Join(args, " ") for _, want := range []string{ - "run -d", + testCreateCommand, "-p 8080:8080", "-u vscode", "-e FOO=bar", @@ -253,7 +253,10 @@ func TestBuildRunArgsPreservesRunArgs(t *testing.T) { args := (&appleDriver{}).buildRunArgs(params) require.Equal( t, - append(append([]string{"run", "-d", "-l", "dev.containers.id="}, raw...), testImageRef), + append( + append([]string{testCreateCommand, "-l", "dev.containers.id="}, raw...), + testImageRef, + ), args, ) } diff --git a/pkg/driver/docker/lifecycle.go b/pkg/driver/docker/lifecycle.go index 981f6110e..0e1e15e90 100644 --- a/pkg/driver/docker/lifecycle.go +++ b/pkg/driver/docker/lifecycle.go @@ -1,6 +1,7 @@ package docker import ( + "bytes" "context" "errors" "fmt" @@ -9,6 +10,7 @@ import ( "strings" "time" + pkgconfig "github.com/devsy-org/devsy/pkg/config" "github.com/devsy-org/devsy/pkg/devcontainer/config" "github.com/devsy-org/devsy/pkg/docker" "github.com/devsy-org/devsy/pkg/driver" @@ -334,8 +336,45 @@ func (d *dockerDriver) RunImageDevContainer( writer := log.Writer(log.LevelInfo) defer func() { _ = writer.Close() }() - if err := d.startContainer(ctx, params.LocalWorkspaceFolder, args, writer); err != nil { - return err + var output bytes.Buffer + if err := d.startContainer( + ctx, params.LocalWorkspaceFolder, args, writer, &output, + ); err != nil { + return fmt.Errorf( + "%w; runArgs must be valid for container create; options that only apply to run are not supported", + err, + ) + } + ids := strings.Fields(output.String()) + if len(ids) != 1 || len(ids[0]) != 64 || strings.Trim(ids[0], "0123456789abcdef") != "" { + return fmt.Errorf( + "failed to identify created container; inspect the runtime for an unstarted container", + ) + } + id := ids[0] + actualLabels, actualEnv, err := d.Docker.InspectCreatedContainer(ctx, id) + if err == nil { + labels := append( + config.GetIDLabels(params.WorkspaceID, d.IDLabels), + params.Options.Labels...) + err = pkgconfig.ValidateCreatedLabels(labels, actualLabels) + } + if err != nil { + cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + removeErr := d.Docker.Run( + cleanupCtx, + []string{"rm", "-f", id}, + docker.Streams{Stderr: writer}, + ) + return errors.Join(err, removeErr) + } + environment := append([]string(nil), actualEnv...) + for key, value := range params.Options.Env { + environment = append(environment, key+"="+value) + } + if err := d.Docker.StartContainerWithEnvironment(ctx, id, environment); err != nil { + return fmt.Errorf("failed to start dev container: %w", err) } return d.UpdateContainerUserUID(ctx, params.WorkspaceID, params.ParsedConfig, writer) @@ -421,6 +460,7 @@ func (d *dockerDriver) startContainer( dir string, args []string, writer io.Writer, + stdout io.Writer, ) error { log.Debugf( "running docker command: command=%s, args=%s, cwd=%s", @@ -439,7 +479,10 @@ func (d *dockerDriver) startContainer( ctx, dir, args, - docker.Streams{Stdout: writer, Stderr: io.MultiWriter(writer, stderr)}, + docker.Streams{ + Stdout: io.MultiWriter(writer, stdout), + Stderr: io.MultiWriter(writer, stderr), + }, ) if err != nil { log.Errorf( diff --git a/pkg/driver/docker/lifecycle_test.go b/pkg/driver/docker/lifecycle_test.go index 8eef4eba3..21e140592 100644 --- a/pkg/driver/docker/lifecycle_test.go +++ b/pkg/driver/docker/lifecycle_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "io" "os" "os/exec" "path/filepath" @@ -591,6 +592,7 @@ fi t.TempDir(), []string{testRunArg, source}, &streamed, + io.Discard, ) require.Error(t, err) assert.Contains(t, err.Error(), "failed to start dev container") @@ -622,7 +624,13 @@ fi require.NoError(t, os.Chmod(bin, 0o700)) d := &dockerDriver{Docker: &docker.DockerHelper{DockerCommand: bin}} var streamed engineOutputBuffer - err := d.startContainer(context.Background(), t.TempDir(), []string{testRunArg}, &streamed) + err := d.startContainer( + context.Background(), + t.TempDir(), + []string{testRunArg}, + &streamed, + io.Discard, + ) require.Error(t, err) assert.Len(t, streamed.String(), 2048*1024+len("tail-marker")) assert.True(t, strings.HasSuffix(err.Error(), "tail-marker")) diff --git a/pkg/driver/docker/reserved_labels_integration_test.go b/pkg/driver/docker/reserved_labels_integration_test.go new file mode 100644 index 000000000..b343f823c --- /dev/null +++ b/pkg/driver/docker/reserved_labels_integration_test.go @@ -0,0 +1,81 @@ +package docker + +import ( + "context" + "fmt" + "os" + "os/exec" + "strings" + "testing" + "time" + + "github.com/devsy-org/devsy/pkg/devcontainer/config" + "github.com/devsy-org/devsy/pkg/docker" + "github.com/devsy-org/devsy/pkg/driver" + "github.com/stretchr/testify/suite" +) + +type NativeReservedLabelsSuite struct{ suite.Suite } + +const ( + testLabelFlag = "--label" + testAlpineImage = "alpine:3.22" +) + +func TestNativeReservedLabelsSuite(t *testing.T) { suite.Run(t, new(NativeReservedLabelsSuite)) } + +func (s *NativeReservedLabelsSuite) TestPositionalImage() { + if os.Getenv("DEVSY_REAL_DOCKER_TEST") != "1" { + s.T().Skip("requires an explicitly enabled Docker runtime") + } + name := fmt.Sprintf("devsy-label-proof-%d", time.Now().UnixNano()) + d := &dockerDriver{Docker: &docker.DockerHelper{DockerCommand: testDockerCmd}} + s.T(). + Cleanup(func() { _ = d.Docker.Run(context.Background(), []string{"rm", "-f", name}, docker.Streams{}) }) + err := d.RunImageDevContainer(context.Background(), &driver.RunImageDevContainerParams{ + WorkspaceID: "label-proof", + ParsedConfig: &config.DevContainerConfig{ + NonComposeBase: config.NonComposeBase{RunArgs: []string{ + "--name", name, testLabelFlag, "sh.devsy.recovery=fixture-private-value", + "--entrypoint", testShellPath, testAlpineImage, "-c", "sleep 120", + }}, + }, + Options: &driver.RunOptions{Image: testAlpineImage, Labels: []string{"devsy.user=root"}}, + }) + s.Require().ErrorContains(err, `label "sh.devsy.recovery" does not match the value Devsy set`) + s.NotContains(err.Error(), "fixture-private-value") + s.T().Logf("after: %s", err) + out, err := exec.Command(testDockerCmd, "ps", "-a", "--format", "{{.Names}}").Output() + s.Require().NoError(err) + s.NotContains(strings.Split(strings.TrimSpace(string(out)), "\n"), name) + s.T().Log("docker ps -a: no container") +} + +func (s *NativeReservedLabelsSuite) TestOrdinaryLabelStarts() { + if os.Getenv("DEVSY_REAL_DOCKER_TEST") != "1" { + s.T().Skip("requires an explicitly enabled Docker runtime") + } + name := fmt.Sprintf("devsy-label-control-%d", time.Now().UnixNano()) + d := &dockerDriver{ + Docker: &docker.DockerHelper{DockerCommand: testDockerCmd}, + UpdateRemoteUserUIDDefault: "off", + } + s.T(). + Cleanup(func() { _ = d.Docker.Run(context.Background(), []string{"rm", "-f", name}, docker.Streams{}) }) + err := d.RunImageDevContainer(context.Background(), &driver.RunImageDevContainerParams{ + WorkspaceID: "label-control", + ParsedConfig: &config.DevContainerConfig{NonComposeBase: config.NonComposeBase{ + RunArgs: []string{"--name", name, testLabelFlag, "team=a"}, + }}, + Options: &driver.RunOptions{ + Image: testAlpineImage, Labels: []string{"devsy.user=root"}, + Entrypoint: testShellPath, Cmd: []string{"-c", "sleep 120"}, + }, + }) + s.Require().NoError(err) + details, err := d.Docker.InspectContainers(context.Background(), []string{name}) + s.Require().NoError(err) + s.Require().Len(details, 1) + s.Equal(config.ContainerStatusRunning, details[0].State.Status) + s.Equal("a", details[0].Config.Labels["team"]) +} diff --git a/pkg/driver/docker/runargs.go b/pkg/driver/docker/runargs.go index cb8896f9f..f2f23dde8 100644 --- a/pkg/driver/docker/runargs.go +++ b/pkg/driver/docker/runargs.go @@ -32,16 +32,12 @@ func (d *dockerDriver) buildRunArgs( helper *docker.DockerHelper, ) ([]string, error) { b := &runArgsBuilder{ - args: []string{"run"}, + args: []string{"create"}, driver: d, params: params, helper: helper, } - if helper.GetRuntime().SupportsSignalProxy() { - b.args = append(b.args, "--sig-proxy=false") - } - steps := []func() error{ b.addPorts, b.addWorkspaceMount, @@ -58,7 +54,6 @@ func (d *dockerDriver) buildRunArgs( b.addGPU, b.addRunArgs, b.addRunPlatform, - b.addDetached, b.addEntrypoint, b.addImage, } @@ -154,11 +149,6 @@ func (b *runArgsBuilder) addRunPlatform() error { return nil } -func (b *runArgsBuilder) addDetached() error { - b.args = append(b.args, "-d") - return nil -} - func (b *runArgsBuilder) addEntrypoint() error { b.args = b.driver.addEntrypointArgs(b.args, b.params.Options) return nil diff --git a/pkg/driver/docker/runargs_test.go b/pkg/driver/docker/runargs_test.go index 9241f81e6..73c69efd3 100644 --- a/pkg/driver/docker/runargs_test.go +++ b/pkg/driver/docker/runargs_test.go @@ -1,6 +1,8 @@ package docker import ( + "bytes" + "context" "os" "path/filepath" @@ -9,9 +11,24 @@ import ( "github.com/devsy-org/devsy/pkg/driver" ) +func (s *DockerDriverTestSuite) TestCreateSeparatesWarningsFromContainerID() { + if os.PathSeparator == '\\' { + s.T().Skip("requires a POSIX shell") + } + d := &dockerDriver{Docker: &docker.DockerHelper{DockerCommand: testShellPath}} + var logs engineOutputBuffer + var id bytes.Buffer + s.Require().NoError(d.startContainer(context.Background(), "", []string{ + "-c", "printf 'warning\\n' >&2; printf 'container-id\\n'", + }, &logs, &id)) + s.Equal("container-id\n", id.String()) + s.Contains(logs.String(), "warning\n") +} + const ( testBindMountType = "bind" testReadonly = "readonly" + testShellPath = "/bin/sh" ) func (s *DockerDriverTestSuite) TestAddCapabilityArgs_SingleSecurityOpt() { diff --git a/sites/docs-devsy-sh/content/docs/developing-in-workspaces/devcontainer-json.mdx b/sites/docs-devsy-sh/content/docs/developing-in-workspaces/devcontainer-json.mdx index 01303c9cd..9d8396337 100644 --- a/sites/docs-devsy-sh/content/docs/developing-in-workspaces/devcontainer-json.mdx +++ b/sites/docs-devsy-sh/content/docs/developing-in-workspaces/devcontainer-json.mdx @@ -167,4 +167,6 @@ Do not supply these keys through `--id-label`, Kubernetes provider labels, or Ku Custom identification labels, including `dev.containers.id`, remain configurable. The `devcontainer.metadata` image label remains a supported configuration source and can contain private values. Reserving a label does not make every value stored under it public. -The top-level `containerLabels` and `labels` fields in devcontainer.json are ignored. External providers reject `runArgs` rather than translate them into request labels. Native Docker, Podman, nerdctl, Apple and Compose arguments and inherited image labels are outside this explicit map reservation. Avoid using reserved keys there. Native argument validation is a separate follow-up. +The top-level `containerLabels` and `labels` fields in devcontainer.json are ignored. External providers reject `runArgs` rather than translate them into request labels. For Docker, Podman, nerdctl, and Apple, Devsy checks the created container before starting it. Reserved labels must match the values Devsy set, including when they come from `runArgs` or an image. Devsy removes the container if they do not match. Compose arguments and inherited Compose image labels are outside this check. + +Native `runArgs` must be valid for the runtime's `create` command. Options supported only by `run` are no longer supported.