Skip to content
Closed
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
4 changes: 3 additions & 1 deletion packages/orchestrator/pkg/sandbox/sandbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -1161,7 +1161,9 @@ func (f *Factory) ResumeSandbox(
ctx, span := tracer.Start(execCtx, "sandbox-exit-wait")
defer span.End()

// Wait for either uffd or fc process to exit
// Wait for either uffd or fc process to exit.
// A UFFD handle() failure sets u.exit error and closes Exit().Done(),
// causing this goroutine to call sbx.Stop() — no explicit kill needed in uffd.go.
select {
case <-fcUffd.Exit().Done():
case <-fcHandle.Exit.Done():
Expand Down
5 changes: 4 additions & 1 deletion packages/orchestrator/pkg/sandbox/uffd/uffd.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,16 @@ func (u *Uffd) Start(ctx context.Context, sandboxId string) error {
ctx, span := tracer.Start(ctx, "serve uffd")
defer span.End()

// TODO: If the handle function fails, we should kill the sandbox
handleErr := u.handle(ctx, sandboxId, fdExit)

// If handle failed before setting the handler value, set an error to unblock
// any waiters (e.g., prefetcher goroutines waiting on Prefault).
if handleErr != nil {
u.handler.SetError(handleErr)
logger.L().Error(ctx, "uffd handle failed, sandbox will be terminated",
logger.WithSandboxID(sandboxId),
zap.String("socket_path", u.socketPath),
zap.Error(handleErr))
}

closeErr := u.lis.Close()
Expand Down
208 changes: 208 additions & 0 deletions packages/orchestrator/pkg/sandbox/uffd/uffd_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
//go:build linux

package uffd

import (
"context"
"os"
"path/filepath"
"testing"
"time"

"github.com/e2b-dev/infra/packages/shared/pkg/storage/header"
)

// mockMemfile is a minimal ReadonlyDevice for testing.
type mockMemfile struct{}

func (m *mockMemfile) ReadAt(_ context.Context, p []byte, _ int64) (int, error) {
return len(p), nil
}

func (m *mockMemfile) Size(_ context.Context) (int64, error) {
return 0, nil
}

func (m *mockMemfile) Close() error {
return nil
}

func (m *mockMemfile) Slice(_ context.Context, _, _ int64) ([]byte, error) {
return nil, nil
}

func (m *mockMemfile) BlockSize() int64 {
return 4096
}

func (m *mockMemfile) Header() *header.Header {
return nil
}

func (m *mockMemfile) SwapHeader(_ *header.Header) {}

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

dir := t.TempDir()
socketPath := filepath.Join(dir, "test.sock")

u := New(&mockMemfile{}, socketPath)

ctx := context.Background()
if err := u.Start(ctx, "test-sandbox"); err != nil {
t.Fatalf("Start() failed: %v", err)
}

// Close the listener to make handle()'s Accept() fail immediately.
u.lis.Close()

// Wait for the exit signal with a timeout.
select {
case <-u.Exit().Done():
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for exit signal after handle failure")
}

// exit should carry an error because handle() failed.
exitErr := u.Exit().Wait()
if exitErr == nil {
t.Fatal("expected exit error after handle failure, got nil")
}

t.Logf("exit error (expected): %v", exitErr)
}

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

dir := t.TempDir()
socketPath := filepath.Join(dir, "test.sock")

u := New(&mockMemfile{}, socketPath)

ctx := context.Background()
if err := u.Start(ctx, "test-sandbox"); err != nil {
t.Fatalf("Start() failed: %v", err)
}

// Close the listener to make handle() fail.
u.lis.Close()

// readyCh should be closed even on failure, to unblock waiters.
select {
case <-u.Ready():
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for readyCh to close after handle failure")
}
}

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

dir := t.TempDir()
socketPath := filepath.Join(dir, "test.sock")

u := New(&mockMemfile{}, socketPath)

ctx := context.Background()
if err := u.Start(ctx, "test-sandbox"); err != nil {
t.Fatalf("Start() failed: %v", err)
}

// Close the listener to make handle() fail.
u.lis.Close()

// Wait for exit to ensure the goroutine has finished.
select {
case <-u.Exit().Done():
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for exit")
}

// Prefault should fail because handler was never set (SetError was called).
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()

_, err := u.Prefault(ctx, 0, []byte{0})
if err == nil {
t.Fatal("expected Prefault to fail after handle failure, got nil")
}

t.Logf("Prefault error (expected): %v", err)
}

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

// Use a path that cannot be created.
socketPath := filepath.Join("/nonexistent-dir-xxx", "test.sock")

u := New(&mockMemfile{}, socketPath)

ctx := context.Background()
err := u.Start(ctx, "test-sandbox")
if err == nil {
t.Fatal("expected Start() to fail with invalid socket path")
}

t.Logf("Start error (expected): %v", err)
}

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

dir := t.TempDir()
socketPath := filepath.Join(dir, "test.sock")

u := New(&mockMemfile{}, socketPath)

// readyCh should not be closed initially.
select {
case <-u.Ready():
t.Fatal("readyCh should not be closed before Start()")
default:
}

// exit should not be done initially.
select {
case <-u.Exit().Done():
t.Fatal("exit should not be done before Start()")
default:
}
}

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

dir := t.TempDir()
socketPath := filepath.Join(dir, "test.sock")

u := New(&mockMemfile{}, socketPath)

ctx := context.Background()
if err := u.Start(ctx, "test-sandbox"); err != nil {
t.Fatalf("Start() failed: %v", err)
}

// Verify socket file exists.
info, err := os.Stat(socketPath)
if err != nil {
t.Fatalf("socket file not found: %v", err)
}

// Verify permissions are 0777.
perm := info.Mode().Perm()
if perm != 0o777 {
t.Errorf("expected socket permissions 0777, got %o", perm)
}

// Clean up: close listener to let goroutine exit.
u.lis.Close()

select {
case <-u.Exit().Done():
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for cleanup")
}
}