-
Notifications
You must be signed in to change notification settings - Fork 292
feat(sandbox): pre-pause guest reclaim via envd #2551
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
ValentaTomas
wants to merge
6
commits into
main
Choose a base branch
from
feat/sandbox-pause-reclaim
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9c42f62
feat(sandbox): pre-pause guest reclaim via envd
ValentaTomas c041b7d
fix(sandbox): forward access token on reclaim envd call
ValentaTomas 2a02232
feat(sandbox): per-step timeouts for pre-pause reclaim chain
ValentaTomas 8698667
fix(sandbox): correct reclaim chain — drop master flag, fix timeout s…
ValentaTomas 13ca893
refactor(sandbox): extract StartEnvdProcess helper; reuse from resume…
ValentaTomas db30f55
fix(sandbox): add missing envd_process.go helper
ValentaTomas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| 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" | ||
| ) | ||
|
|
||
| // StartEnvdProcess opens a streaming Process.Start call against this | ||
| // sandbox's envd, running `script` under `/bin/bash -c` as `user`. When | ||
| // timeout > 0 it sets `Connect-Timeout-Ms` so envd kills the process | ||
| // hard at the deadline. Auth/user headers are wired from sandbox config. | ||
| // Caller owns the returned stream (Close + Receive). | ||
| func (s *Sandbox) StartEnvdProcess( | ||
| ctx context.Context, | ||
| script, 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/bash", Args: []string{"-c", script}}, | ||
| }) | ||
| if timeout > 0 { | ||
| req.Header().Set("Connect-Timeout-Ms", strconv.FormatInt(int64(timeout/time.Millisecond), 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) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| 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.IntFlag | ||
| 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.ReclaimSyncTimeoutMs, "sync"}, | ||
| {featureflags.ReclaimDropCachesTimeoutMs, "echo 3 > /proc/sys/vm/drop_caches"}, | ||
| {featureflags.ReclaimCompactMemoryTimeoutMs, "echo 1 > /proc/sys/vm/compact_memory"}, | ||
| {featureflags.ReclaimFstrimTimeoutMs, "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 --foreground -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 { | ||
| ms := s.featureFlags.IntFlag(ctx, st.flag) | ||
| if ms <= 0 { | ||
| continue | ||
| } | ||
| // `timeout` accepts fractional seconds (s/m/h/d), not `ms`. | ||
| // `--foreground` ensures SIGKILL actually reaches the child when we | ||
| // run inside a non-interactive bash invoked from envd. | ||
| secs := float64(ms) / 1000.0 | ||
| parts = append(parts, fmt.Sprintf("timeout --foreground -s KILL %.3f sh -c %q 2>/dev/null", secs, st.cmd)) | ||
| sum += time.Duration(ms) * time.Millisecond | ||
| } | ||
| if len(parts) == 0 { | ||
| return "", 0 | ||
| } | ||
|
|
||
| // Trailing `true` keeps the script's exit code at 0 regardless of any | ||
| // individual step's outcome. | ||
| return strings.Join(parts, "; ") + "; true", sum + reclaimOuterSlack | ||
| } | ||
|
|
||
| // bestEffortReclaim asks envd to reclaim guest memory + disk before pause. | ||
| // All failures are swallowed. | ||
| func (s *Sandbox) bestEffortReclaim(ctx context.Context) { | ||
| ctx, span := tracer.Start(ctx, "envd-reclaim") | ||
| defer span.End() | ||
|
|
||
| script, timeout := s.buildReclaimScript(ctx) | ||
| if script == "" { | ||
| return | ||
| } | ||
|
|
||
| rcCtx, cancel := context.WithTimeout(ctx, timeout) | ||
| defer cancel() | ||
|
|
||
| stream, err := s.StartEnvdProcess(rcCtx, 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() | ||
|
|
||
| for stream.Receive() { | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Login shell flag dropped during refactor to shared helper
Medium Severity
The old
runCommandInSandboxusedArgs: []string{"-l", "-c", command}to invoke bash as a login shell, sourcing/etc/profileand user profile scripts. The new sharedStartEnvdProcessusesArgs: []string{"-c", script}, dropping the-lflag. This means user-provided commands via--cmd,--cmd-pause, or--cmd-signal-pausein theresume-buildCLI no longer get a login shell environment, potentially breaking commands that depend on PATH or environment variables set in profile scripts.Additional Locations (1)
packages/orchestrator/cmd/resume-build/main.go#L1172-L1173Reviewed by Cursor Bugbot for commit db30f55. Configure here.