Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
9c42f62
feat(sandbox): pre-pause guest reclaim via envd
ValentaTomas May 4, 2026
c041b7d
fix(sandbox): forward access token on reclaim envd call
ValentaTomas May 4, 2026
2a02232
feat(sandbox): per-step timeouts for pre-pause reclaim chain
ValentaTomas May 4, 2026
8698667
fix(sandbox): correct reclaim chain — drop master flag, fix timeout s…
ValentaTomas May 4, 2026
13ca893
refactor(sandbox): extract StartEnvdProcess helper; reuse from resume…
ValentaTomas May 4, 2026
db30f55
fix(sandbox): add missing envd_process.go helper
ValentaTomas May 4, 2026
e4a31de
fix(sandbox): silence reclaim step output and surface failures
ValentaTomas May 4, 2026
40a1e24
refactor(sandbox): inline envd reclaim call; drop --foreground
ValentaTomas May 6, 2026
294c7e4
Merge branch 'main' into feat/sandbox-pause-reclaim
ValentaTomas May 6, 2026
a7e6b75
chore(featureflags): isolate reclaim flags in own var block
ValentaTomas May 6, 2026
ec3db39
refactor(sandbox): extract StartEnvdBash; reuse from reclaim + resume…
ValentaTomas May 6, 2026
801a37f
refactor(reclaim): use DurationFlag and run via /bin/sh
ValentaTomas May 7, 2026
d03b564
fix(reclaim): skip sub-ms step durations to avoid no-timeout
ValentaTomas May 7, 2026
2760098
fix(sandbox): parameterize StartEnvdShell binary; keep bash for resum…
ValentaTomas May 7, 2026
c3f843b
refactor(reclaim): collapse 4 flags into one targeted JSON flag
ValentaTomas May 7, 2026
eecb55b
chore(reclaim): drop NewOfflineClient, trim docstrings
ValentaTomas May 8, 2026
e23ee08
chore(reclaim): use int ms directly, drop string parsing
ValentaTomas May 8, 2026
76f3b04
chore(reclaim): rename LD flag to guest-pause-reclaim
ValentaTomas May 8, 2026
1a742bf
perf(sandbox): reorder reclaim chain to fstrim → sync → drop_caches →…
ValentaTomas May 8, 2026
1b451c2
fix(resume-build): restore 10-minute upper bound on runCommandInSandbox
ValentaTomas May 8, 2026
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
47 changes: 16 additions & 31 deletions packages/orchestrator/cmd/resume-build/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"fmt"
"log"
"math"
"net/http"
"os"
"os/signal"
"path/filepath"
Expand All @@ -16,7 +15,6 @@ import (
"syscall"
"time"

"connectrpc.com/connect"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/coreos/go-iptables/iptables"
"github.com/google/uuid"
Expand All @@ -39,11 +37,8 @@ import (
"github.com/e2b-dev/infra/packages/orchestrator/pkg/tcpfirewall"
"github.com/e2b-dev/infra/packages/orchestrator/pkg/template/build/core/rootfs"
"github.com/e2b-dev/infra/packages/orchestrator/pkg/template/metadata"
"github.com/e2b-dev/infra/packages/shared/pkg/consts"
"github.com/e2b-dev/infra/packages/shared/pkg/featureflags"
"github.com/e2b-dev/infra/packages/shared/pkg/grpc"
"github.com/e2b-dev/infra/packages/shared/pkg/grpc/envd/process"
"github.com/e2b-dev/infra/packages/shared/pkg/grpc/envd/process/processconnect"
"github.com/e2b-dev/infra/packages/shared/pkg/logger"
sbxlogger "github.com/e2b-dev/infra/packages/shared/pkg/logger/sandbox"
"github.com/e2b-dev/infra/packages/shared/pkg/storage"
Expand Down Expand Up @@ -73,8 +68,18 @@ func main() {
optimize := flag.Bool("optimize", false, "collect fresh prefetch mapping after pause (resumes snapshot to record page faults)")
shell := flag.Bool("shell", false, "attach an interactive PTY shell via envd (no sshd required in the sandbox)")

// Enables the pre-pause reclaim chain with sensible per-step caps.
reclaim := flag.Bool("reclaim", false, "enable pre-pause reclaim chain (sync 500ms, drop_caches 200ms, compact 1s, fstrim 500ms)")

flag.Parse()

if *reclaim {
featureflags.NewDurationFlag("reclaim-sync-timeout", 500*time.Millisecond)
featureflags.NewDurationFlag("reclaim-drop-caches-timeout", 200*time.Millisecond)
featureflags.NewDurationFlag("reclaim-compact-memory-timeout", time.Second)
featureflags.NewDurationFlag("reclaim-fstrim-timeout", 500*time.Millisecond)
}
Comment thread
ValentaTomas marked this conversation as resolved.

if *fromBuild == "" {
log.Fatal("-from-build required")
}
Expand Down Expand Up @@ -1026,7 +1031,9 @@ func run(ctx context.Context, buildID string, iterations int, coldStart, noPrefe
if verbose {
logLevel = ldlog.Info
}
flags, _ := featureflags.NewClientWithLogLevel(logLevel)
// Always use the offline data source so per-run flag overrides (e.g. set
// from -reclaim) take effect regardless of LAUNCH_DARKLY_API_KEY.
flags, _ := featureflags.NewOfflineClient(logLevel)

sandboxes := sandbox.NewSandboxesMap()

Expand Down Expand Up @@ -1184,32 +1191,10 @@ func printTemplateInfo(ctx context.Context, tmpl template.Template, meta metadat
}
}

// runCommandInSandbox runs a command inside the sandbox via envd
// runCommandInSandbox runs a command inside the sandbox via envd as a
// login shell so /etc/profile is sourced.
func runCommandInSandbox(ctx context.Context, sbx *sandbox.Sandbox, command string) error {
// Connect directly to envd on the sandbox
envdURL := fmt.Sprintf("http://%s:%d", sbx.Slot.HostIPString(), consts.DefaultEnvdServerPort)

hc := http.Client{
Timeout: 10 * time.Minute,
Transport: sandbox.SandboxHttpTransport,
}

processC := processconnect.NewProcessClient(&hc, envdURL)

req := connect.NewRequest(&process.StartRequest{
Process: &process.ProcessConfig{
Cmd: "/bin/bash",
Args: []string{"-l", "-c", command},
},
})
grpc.SetUserHeader(req.Header(), "root")

// Set access token if available
if sbx.Config.Envd.AccessToken != nil {
req.Header().Set("X-Access-Token", *sbx.Config.Envd.AccessToken)
}

stream, err := processC.Start(ctx, req)
stream, err := sbx.StartEnvdShell(ctx, []string{"-l", "-c", command}, "root", 0)
if err != nil {
return fmt.Errorf("failed to start process: %w", err)
}
Expand Down
46 changes: 46 additions & 0 deletions packages/orchestrator/pkg/sandbox/envd_process.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package sandbox

import (
"context"
"fmt"
"net/http"
"strconv"
"time"

"connectrpc.com/connect"

"github.com/e2b-dev/infra/packages/shared/pkg/consts"
"github.com/e2b-dev/infra/packages/shared/pkg/grpc"
"github.com/e2b-dev/infra/packages/shared/pkg/grpc/envd/process"
"github.com/e2b-dev/infra/packages/shared/pkg/grpc/envd/process/processconnect"
)

// StartEnvdShell opens a streaming Process.Start call against this
// sandbox's envd, running `/bin/sh` with the given args as `user`.
// `/bin/sh` is used (not bash) so minimal guests without bash still
// work. Caller chooses login-shell vs. plain (e.g. []{"-l","-c",cmd}
// vs. []{"-c",script}). When timeout > 0 it sets `Connect-Timeout-Ms`
// so envd kills the process at the deadline. Auth/user headers are
// wired from sandbox config. Caller owns the returned stream.
func (s *Sandbox) StartEnvdShell(
ctx context.Context,
shellArgs []string,
user string,
timeout time.Duration,
) (*connect.ServerStreamForClient[process.StartResponse], error) {
addr := fmt.Sprintf("http://%s:%d", s.Slot.HostIPString(), consts.DefaultEnvdServerPort)
pc := processconnect.NewProcessClient(&http.Client{Transport: sandboxHttpClient.Transport}, addr)

req := connect.NewRequest(&process.StartRequest{
Process: &process.ProcessConfig{Cmd: "/bin/sh", Args: shellArgs},
Comment thread
ValentaTomas marked this conversation as resolved.
Outdated
})
if timeout > 0 {
req.Header().Set("Connect-Timeout-Ms", strconv.FormatInt(timeout.Milliseconds(), 10))
}
if s.Config.Envd.AccessToken != nil {
req.Header().Set("X-Access-Token", *s.Config.Envd.AccessToken)
}
grpc.SetUserHeader(req.Header(), user)

return pc.Start(ctx, req)
}
96 changes: 96 additions & 0 deletions packages/orchestrator/pkg/sandbox/reclaim.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package sandbox

import (
"context"
"fmt"
"strings"
"time"

"go.uber.org/zap"

"github.com/e2b-dev/infra/packages/shared/pkg/featureflags"
"github.com/e2b-dev/infra/packages/shared/pkg/logger"
)

type reclaimStep struct {
flag featureflags.DurationFlag
cmd string
}

// Order matters: sync makes drop_caches more effective; drop_caches gives
// compact_memory more headroom; fstrim wants a stable FS view.
var reclaimSteps = []reclaimStep{
{featureflags.ReclaimSyncTimeout, "sync"},
{featureflags.ReclaimDropCachesTimeout, "echo 3 > /proc/sys/vm/drop_caches"},
{featureflags.ReclaimCompactMemoryTimeout, "echo 1 > /proc/sys/vm/compact_memory"},
{featureflags.ReclaimFstrimTimeout, "fstrim -av"},
}

// Slack added to the sum of per-step caps to absorb shell start /
// envd round-trip overhead.
const reclaimOuterSlack = 500 * time.Millisecond

// buildReclaimScript composes a chain where each step has its own
// `timeout -s KILL` ceiling. Steps with cap=0 are skipped. Returns
// ("", 0) when every step is disabled.
func (s *Sandbox) buildReclaimScript(ctx context.Context) (string, time.Duration) {
var (
parts []string
sum time.Duration
)
for _, st := range reclaimSteps {
d := s.featureFlags.DurationFlag(ctx, st.flag)
if d <= 0 {
continue
}
// `timeout` accepts fractional seconds (s/m/h/d), not `ms`. Output
// is dropped; non-zero status is captured into `rc` so the final
// exit code surfaces failures without short-circuiting later steps.
parts = append(parts, fmt.Sprintf("timeout -s KILL %.3f sh -c %q >/dev/null 2>&1 || rc=$?", d.Seconds(), st.cmd))
Comment thread
ValentaTomas marked this conversation as resolved.
Outdated
sum += d
}
if len(parts) == 0 {
return "", 0
}

return "rc=0; " + strings.Join(parts, "; ") + "; exit $rc", sum + reclaimOuterSlack
}

// bestEffortReclaim asks envd to reclaim guest memory + disk before pause.
// Per-step output is silenced inside the guest; we only log when envd
// itself errors or the script reports a non-zero exit code.
func (s *Sandbox) bestEffortReclaim(ctx context.Context) {
script, timeout := s.buildReclaimScript(ctx)
if script == "" {
return
}

ctx, span := tracer.Start(ctx, "envd-reclaim")
defer span.End()

rcCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()

stream, err := s.StartEnvdShell(rcCtx, []string{"-c", script}, "root", timeout)
if err != nil {
logger.L().Warn(ctx, "envd reclaim failed", logger.WithSandboxID(s.Runtime.SandboxID), zap.Error(err))

return
}
defer stream.Close()

var exitCode int32
for stream.Receive() {
if end := stream.Msg().GetEvent().GetEnd(); end != nil {
exitCode = end.GetExitCode()
}
}
if err := stream.Err(); err != nil {
logger.L().Warn(ctx, "envd reclaim stream error", logger.WithSandboxID(s.Runtime.SandboxID), zap.Error(err))

return
}
if exitCode != 0 {
logger.L().Warn(ctx, "envd reclaim non-zero exit", logger.WithSandboxID(s.Runtime.SandboxID), zap.Int32("exit_code", exitCode))
}
}
13 changes: 11 additions & 2 deletions packages/orchestrator/pkg/sandbox/sandbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,8 @@ type Sandbox struct {
files *storage.SandboxFiles
cleanup *Cleanup

featureFlags *featureflags.Client

process *fc.Process
cgroupHandle *cgroup.CgroupHandle

Expand Down Expand Up @@ -457,7 +459,8 @@ func (f *Factory) CreateSandbox(
files: sandboxFiles,
process: fcHandle,

cleanup: cleanup,
cleanup: cleanup,
featureFlags: f.featureFlags,

APIStoredConfig: apiConfigToStore,

Expand Down Expand Up @@ -797,7 +800,8 @@ func (f *Factory) ResumeSandbox(
files: sandboxFiles,
process: fcHandle,

cleanup: cleanup,
cleanup: cleanup,
featureFlags: f.featureFlags,

APIStoredConfig: apiConfigToStore,
CABundle: f.egressProxy.CABundle(),
Expand Down Expand Up @@ -1051,6 +1055,11 @@ func (s *Sandbox) Pause(
// Stop the health check before pausing the VM
s.Checks.Stop()

// Best-effort pre-pause guest reclaim (sync, drop_caches, compact_memory,
// fstrim) on the live VM via envd. Per-step caps are LD-flag-driven; all
// default to 0 which disables the chain entirely. Non-fatal.
s.bestEffortReclaim(ctx)

if err := s.process.Pause(ctx); err != nil {
return nil, fmt.Errorf("failed to pause VM: %w", err)
}
Expand Down
49 changes: 49 additions & 0 deletions packages/shared/pkg/featureflags/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,25 @@ func NewClientWithLogLevel(logLevel ldlog.LogLevel) (*Client, error) {
return &Client{ld: ldClient}, nil
}

// NewOfflineClient creates a client that always reads from the in-process
// offline data source, ignoring LAUNCH_DARKLY_API_KEY. Use this in CLI/dev
// tools (e.g. resume-build) so flag overrides set via NewIntFlag/NewDurationFlag
// at startup take effect deterministically.
func NewOfflineClient(logLevel ldlog.LogLevel) (*Client, error) {
cfg := ldclient.Config{
Logging: ldcomponents.Logging().MinLevel(logLevel),
DataSource: launchDarklyOfflineStore,
Events: ldcomponents.NoEvents(),
DiagnosticOptOut: true,
}
ldClient, err := ldclient.MakeCustomClient("", cfg, 0)
if err != nil {
return nil, err
}

return &Client{ld: ldClient}, nil
}

func (c *Client) SetDeploymentName(deploymentName string) {
c.deploymentName = deploymentName
}
Expand All @@ -113,6 +132,36 @@ func (c *Client) StringFlag(ctx context.Context, flag StringFlag, contexts ...ld
return getFlag(ctx, c.ld, c.ld.StringVariationCtx, flag, c.allContexts(contexts))
}

// DurationFlag reads a duration-valued flag. The underlying flag is stored as a
// string (e.g. "500ms") and parsed via time.ParseDuration. Empty/invalid values
// fall back to the configured default.
func (c *Client) DurationFlag(ctx context.Context, flag DurationFlag, contexts ...ldcontext.Context) time.Duration {
if c.ld == nil {
logger.L().Info(ctx, "LaunchDarkly client is not initialized, returning fallback")

return flag.Fallback()
}

raw, err := c.ld.StringVariationCtx(ctx, flag.Key(), mergeContexts(ctx, c.allContexts(contexts)), "")
if err != nil {
logger.L().Warn(ctx, "error evaluating flag", zap.Error(err), zap.String("flag", flag.Key()))

return flag.Fallback()
}
if raw == "" {
return flag.Fallback()
}
d, err := time.ParseDuration(raw)
if err != nil {
logger.L().Warn(ctx, "invalid duration flag value, using fallback",
zap.String("flag", flag.Key()), zap.String("value", raw), zap.Error(err))

return flag.Fallback()
}

return d
}

type typedFlag[T any] interface {
Key() string
Fallback() T
Expand Down
Loading
Loading