fix(sandbox): wait until Docker containers are running before exec

ContainerStart returning success does not mean State.Running, so the first
skill-install ExecCreate can 409. Wait for running after start, and retry
once if exec still races.
main
wizardchen 2026-08-27 15:32:11 +08:00 committed by lyingbug
parent 1f86e3e369
commit 46faca4619
2 changed files with 262 additions and 8 deletions

View File

@ -295,6 +295,15 @@ func (c *DockerRemoteClient) Create(
c.removeQuietly(ctx, created.ID)
return nil, dockerError("Create", err)
}
// ContainerStart returning is not the same as State.Running: the daemon
// accepts the start, then PID 1 still has to replace sh. ExecCreate on a
// container that is still "created" comes back as 409 Conflict
// ("container is not running"), which used to fail skill install on
// the first attempt and succeed on retry.
if err := c.waitUntilRunning(ctx, created.ID, "Create"); err != nil {
c.removeQuietly(ctx, created.ID)
return nil, err
}
c.sweepInBackground(ctx)
return &dockerSandboxHandle{id: created.ID, metadata: dockerSandboxMetadata(labels)}, nil
}
@ -387,7 +396,10 @@ func (c *DockerRemoteClient) Connect(
Message: "container is dead",
}
case RemoteStatePaused:
if err := c.resume(ctx, inspected.Container.ID, string(state.Status)); err != nil {
if err := c.resume(ctx, inspected.Container.ID, string(state.Status), "Connect"); err != nil {
return nil, err
}
if err := c.waitUntilRunning(ctx, inspected.Container.ID, "Connect"); err != nil {
return nil, err
}
}
@ -403,20 +415,131 @@ func (c *DockerRemoteClient) Connect(
}, nil
}
// dockerStartReadyTimeout bounds how long Create/Connect/Exec wait for PID 1
// after the daemon has accepted a start. The window is milliseconds on a
// healthy daemon; this is only the ceiling for a wedged one.
var dockerStartReadyTimeout = 15 * time.Second
// dockerStartReadyPoll is the inspect interval inside waitUntilRunning.
var dockerStartReadyPoll = 50 * time.Millisecond
// resume brings a paused or stopped container back to running.
func (c *DockerRemoteClient) resume(ctx context.Context, id, status string) error {
func (c *DockerRemoteClient) resume(ctx context.Context, id, status, op string) error {
if op == "" {
op = "Connect"
}
if strings.EqualFold(status, "paused") {
if _, err := c.api.ContainerUnpause(ctx, id, client.ContainerUnpauseOptions{}); err != nil {
return dockerError("Connect", err)
return dockerError(op, err)
}
return nil
}
if _, err := c.api.ContainerStart(ctx, id, client.ContainerStartOptions{}); err != nil {
return dockerError("Connect", err)
return dockerError(op, err)
}
return nil
}
// dockerContainerNotRunning reports the Engine 409 that ExecCreate returns
// when the target is not in State.Running. The message is the signal: Kind
// Conflict also covers "already exists" and is not replaceable, so callers
// that want to resume have to look here rather than at CanReplaceRemoteBinding.
func dockerContainerNotRunning(err error) bool {
if err == nil {
return false
}
return strings.Contains(strings.ToLower(err.Error()), "is not running")
}
// waitUntilRunning polls inspect until the container is running, or until it
// is clear waiting will not help (exited, paused, dead).
func (c *DockerRemoteClient) waitUntilRunning(ctx context.Context, id, op string) error {
deadline := time.Now().Add(dockerStartReadyTimeout)
var lastStatus string
for {
if err := ctx.Err(); err != nil {
return dockerError(op, err)
}
inspected, err := c.api.ContainerInspect(ctx, id, client.ContainerInspectOptions{})
if err != nil {
return dockerError(op, err)
}
state := inspected.Container.State
if state == nil {
return dockerError(op, errors.New("daemon returned no container state"))
}
lastStatus = strings.TrimSpace(string(state.Status))
switch dockerStateOf(state.Status) {
case RemoteStateRunning:
return nil
case RemoteStateTerminal:
return &RemoteError{
Kind: RemoteErrorKindTerminal,
Provider: SandboxTypeDocker,
Op: op,
Message: "container is dead",
}
}
switch strings.ToLower(lastStatus) {
case "exited", "paused":
return &RemoteError{
Kind: RemoteErrorKindConflict,
Provider: SandboxTypeDocker,
Op: op,
Message: "container is not running: " + lastStatus,
}
}
if !time.Now().Before(deadline) {
return &RemoteError{
Kind: RemoteErrorKindTimeout,
Provider: SandboxTypeDocker,
Op: op,
Message: fmt.Sprintf("container did not reach running (last state %q)", lastStatus),
}
}
timer := time.NewTimer(dockerStartReadyPoll)
select {
case <-ctx.Done():
timer.Stop()
return dockerError(op, ctx.Err())
case <-timer.C:
}
}
}
// ensureRunning resumes a stopped/paused container and waits until exec can
// succeed. It is the Exec counterpart of Connect: the first command of a
// newly created sandbox used to race PID 1, and a later command can hit a
// container the host or the idle sweep stopped.
func (c *DockerRemoteClient) ensureRunning(ctx context.Context, id, op string) error {
inspected, err := c.api.ContainerInspect(ctx, id, client.ContainerInspectOptions{})
if err != nil {
return dockerError(op, err)
}
state := inspected.Container.State
if state == nil {
return dockerError(op, errors.New("daemon returned no container state"))
}
switch dockerStateOf(state.Status) {
case RemoteStateRunning:
return nil
case RemoteStateTerminal:
return &RemoteError{
Kind: RemoteErrorKindTerminal,
Provider: SandboxTypeDocker,
Op: op,
Message: "container is dead",
}
case RemoteStatePaused:
if err := c.resume(ctx, inspected.Container.ID, string(state.Status), op); err != nil {
return err
}
return c.waitUntilRunning(ctx, id, op)
default:
return c.waitUntilRunning(ctx, id, op)
}
}
// Get returns one sandbox summary.
func (c *DockerRemoteClient) Get(
ctx context.Context,
@ -544,7 +667,7 @@ func (c *DockerRemoteClient) Exec(
execCtx, cancel := context.WithTimeout(ctx, timeout+dockerExecGrace)
defer cancel()
created, err := c.api.ExecCreate(execCtx, id, client.ExecCreateOptions{
execOpts := client.ExecCreateOptions{
Cmd: dockerExecCommand(req, timeout),
User: dockerExecUser(req.User),
WorkingDir: req.WorkDir,
@ -552,7 +675,14 @@ func (c *DockerRemoteClient) Exec(
AttachStdin: req.Stdin != "",
AttachStdout: true,
AttachStderr: true,
})
}
created, err := c.api.ExecCreate(execCtx, id, execOpts)
if err != nil && dockerContainerNotRunning(err) {
if readyErr := c.ensureRunning(execCtx, id, "Exec"); readyErr != nil {
return nil, readyErr
}
created, err = c.api.ExecCreate(execCtx, id, execOpts)
}
if err != nil {
return nil, dockerError("Exec", err)
}

View File

@ -40,16 +40,24 @@ type fakeDockerEngine struct {
removeErr error
inspect map[string]container.InspectResponse
inspectErr error
inspectHook func(id string) (container.InspectResponse, error)
list []container.Summary
listFilters []client.Filters
listErr error
// startLeavesState skips the default "start → running" inspect update so
// a test can drive waitUntilRunning itself.
startLeavesState bool
execOptions []client.ExecCreateOptions
execStdout string
execStderr string
execExit int
execErr error
execStdin bytes.Buffer
// execNotRunningOnce makes the first ExecCreate fail the way the daemon
// does when the container has not reached State.Running yet.
execNotRunningOnce bool
execStdin bytes.Buffer
// execStreamStalls hands back an output stream that never ends on its
// own, which is what a long-running exec looks like to a client that
// gives up on it. execStream is the stream handed to the last attach.
@ -104,13 +112,39 @@ func (f *fakeDockerEngine) ContainerStart(
_ context.Context, id string, _ client.ContainerStartOptions,
) (client.ContainerStartResult, error) {
f.started = append(f.started, id)
return client.ContainerStartResult{}, f.startErr
if f.startErr != nil {
return client.ContainerStartResult{}, f.startErr
}
if !f.startLeavesState {
found := f.inspect[id]
if found.ID == "" {
found.ID = id
}
if found.State == nil {
found.State = &container.State{}
}
found.State.Status = "running"
if f.inspect == nil {
f.inspect = map[string]container.InspectResponse{}
}
f.inspect[id] = found
}
return client.ContainerStartResult{}, nil
}
func (f *fakeDockerEngine) ContainerUnpause(
_ context.Context, id string, _ client.ContainerUnpauseOptions,
) (client.ContainerUnpauseResult, error) {
f.unpaused = append(f.unpaused, id)
found := f.inspect[id]
if found.State == nil {
found.State = &container.State{}
}
found.State.Status = "running"
if f.inspect == nil {
f.inspect = map[string]container.InspectResponse{}
}
f.inspect[id] = found
return client.ContainerUnpauseResult{}, nil
}
@ -120,6 +154,13 @@ func (f *fakeDockerEngine) ContainerInspect(
if f.inspectErr != nil {
return client.ContainerInspectResult{}, f.inspectErr
}
if f.inspectHook != nil {
found, err := f.inspectHook(id)
if err != nil {
return client.ContainerInspectResult{}, err
}
return client.ContainerInspectResult{Container: found}, nil
}
found, ok := f.inspect[id]
if !ok {
return client.ContainerInspectResult{}, cerrdefs.ErrNotFound.WithMessage("no such container")
@ -148,6 +189,10 @@ func (f *fakeDockerEngine) ExecCreate(
_ context.Context, _ string, options client.ExecCreateOptions,
) (client.ExecCreateResult, error) {
f.execOptions = append(f.execOptions, options)
if f.execNotRunningOnce && len(f.execOptions) == 1 {
return client.ExecCreateResult{}, cerrdefs.ErrConflict.WithMessage(
"container is not running")
}
if f.execErr != nil {
return client.ExecCreateResult{}, f.execErr
}
@ -470,6 +515,55 @@ func TestDockerClientCreateRemovesContainerThatCannotStart(t *testing.T) {
require.Equal(t, []string{"container-1"}, engine.removed)
}
// ContainerStart returning is not Running. A skill install used to exec
// immediately and fail with 409 "container is not running"; waiting here is
// what makes the first attempt succeed.
func TestDockerClientCreateWaitsUntilTheContainerIsRunning(t *testing.T) {
engine := newFakeDockerEngine()
engine.imagePresent["weknora/sandbox:test"] = true
engine.startLeavesState = true
var inspects int
engine.inspectHook = func(id string) (container.InspectResponse, error) {
inspects++
status := "created"
if inspects >= 2 {
status = "running"
}
return container.InspectResponse{
ID: id,
State: &container.State{Status: container.ContainerState(status)},
}, nil
}
docker := newTestDockerClient(t, engine)
handle, err := docker.Create(context.Background(), RemoteCreateRequest{
TemplateID: "weknora/sandbox:test",
})
require.NoError(t, err)
require.Equal(t, "container-1", handle.ID())
require.GreaterOrEqual(t, inspects, 2)
}
// PID 1 dying right after start is not a race: waiting will never help, and
// the container has to be removed the same way a failed Start is.
func TestDockerClientCreateRemovesContainerThatExitsImmediately(t *testing.T) {
engine := newFakeDockerEngine()
engine.imagePresent["weknora/sandbox:test"] = true
engine.startLeavesState = true
engine.inspect["container-1"] = container.InspectResponse{
ID: "container-1",
State: &container.State{Status: "exited"},
}
docker := newTestDockerClient(t, engine)
_, err := docker.Create(context.Background(), RemoteCreateRequest{
TemplateID: "weknora/sandbox:test",
})
require.Error(t, err)
require.Equal(t, []string{"container-1"}, engine.removed)
require.Contains(t, err.Error(), "not running")
}
func TestDockerClientCreateRefusesVolumeMounts(t *testing.T) {
docker := newTestDockerClient(t, newFakeDockerEngine())
_, err := docker.Create(context.Background(), RemoteCreateRequest{
@ -738,6 +832,36 @@ func TestDockerClientExecWritesStdin(t *testing.T) {
require.True(t, engine.execOptions[0].AttachStdin)
}
func TestDockerContainerNotRunning(t *testing.T) {
require.False(t, dockerContainerNotRunning(nil))
require.False(t, dockerContainerNotRunning(errors.New("already exists")))
require.True(t, dockerContainerNotRunning(
cerrdefs.ErrConflict.WithMessage("container abc is not running")))
}
// ExecCreate 409 "container is not running" is not a failed command: Connect
// already resumes an exited container, and the first exec of a new sandbox
// used to hit this before PID 1 was up. Resume once, then retry.
func TestDockerClientExecResumesAStoppedContainerAndRetries(t *testing.T) {
engine := newFakeDockerEngine()
engine.inspect["container-1"] = container.InspectResponse{
ID: "container-1",
State: &container.State{Status: "exited"},
}
engine.execNotRunningOnce = true
engine.execStdout = "ok\n"
docker := newTestDockerClient(t, engine)
result, err := docker.Exec(context.Background(), testHandle("container-1"), RemoteExecRequest{
Command: "true",
Timeout: time.Second,
})
require.NoError(t, err)
require.Equal(t, "ok\n", result.Stdout)
require.Equal(t, []string{"container-1"}, engine.started)
require.Len(t, engine.execOptions, 2)
}
// The archive endpoint would apply this write as root and resolve symlinks on
// the way, so a link planted under the writable workspace could redirect an
// upload onto a file the sandbox account cannot touch. Writing through exec