Skip to content

An open-source, faster Devin alternative

TypeScript

memory hotplug, cgroup, internal and external api

Brian Reardon8f05371a860b
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 696a41ca..8dedef2b 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -158,6 +158,13 @@ func main() {
mgr = qmMgr
autosaverSyncer = qmMgr
+ // Start metadata server (169.254.169.254 equivalent, served on :8888)
+ metadataSrv := worker.NewMetadataServer(qmMgr, cfg.Region)
+ metadataSrv.Start(":8888")
+ defer metadataSrv.Close()
+ qmMgr.SetMetadataCallbacks(metadataSrv.RegisterSandbox, metadataSrv.UnregisterSandbox)
+ log.Println("opensandbox-worker: metadata server started on :8888")
+
execSessionFactory = func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {
agent, err := qmMgr.GetAgent(sandboxID)
if err != nil {
diff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.sh
index a70b638d..88ddca6b 100755
--- a/deploy/ec2/build-rootfs-docker.sh
+++ b/deploy/ec2/build-rootfs-docker.sh
@@ -137,6 +137,41 @@ hostname sandbox
# Debug: check for virtio-serial device
ls -la /dev/vport* /dev/virtio-ports/ 2>/dev/null || echo "init: no virtio-serial devices found"
+# ── Cgroup v2: sandbox resource limits ──
+# Agent (PID 1) stays in root cgroup (protected from user resource exhaustion).
+# User processes are placed in /sys/fs/cgroup/sandbox/ by the agent's exec handler.
+mkdir -p /sys/fs/cgroup
+mount -t cgroup2 cgroup2 /sys/fs/cgroup 2>/dev/null
+if [ -f /sys/fs/cgroup/cgroup.controllers ]; then
+ # Enable controllers in root
+ echo "+cpu +memory +pids" > /sys/fs/cgroup/cgroup.subtree_control 2>/dev/null
+ # Create sandbox cgroup
+ mkdir -p /sys/fs/cgroup/sandbox
+ # Defaults: 256 pids, 90% of total memory, 90% of CPUs
+ # CPU limit reserves 10% for the agent (PID 1) so it stays responsive
+ # even under fork bomb / CPU exhaustion attacks.
+ echo 128 > /sys/fs/cgroup/sandbox/pids.max
+ TOTAL_MEM_KB=$(awk '/MemTotal/{print $2}' /proc/meminfo)
+ SANDBOX_MEM=$(( (TOTAL_MEM_KB * 1024 * 9) / 10 ))
+ echo "$SANDBOX_MEM" > /sys/fs/cgroup/sandbox/memory.max 2>/dev/null
+ # cpu.max: limit user processes to 80% of available CPUs.
+ # This reserves 20% for the agent (PID 1) so it stays responsive
+ # even under fork bomb / CPU saturation.
+ NUM_CPUS=$(nproc)
+ CPU_MAX=$(( 80000 * NUM_CPUS ))
+ echo "$CPU_MAX 100000" > /sys/fs/cgroup/sandbox/cpu.max 2>/dev/null
+ # cpu.weight: lower priority than agent
+ echo 50 > /sys/fs/cgroup/sandbox/cpu.weight 2>/dev/null
+ echo "init: cgroup sandbox ready (pids=128, mem=${SANDBOX_MEM}, cpu=${CPU_MAX}/100000)"
+else
+ echo "init: warning: cgroup v2 not available"
+fi
+
+# Note: user commands run as root inside the VM. This is safe because:
+# - Each VM is fully isolated (separate QEMU process, separate kernel)
+# - cgroup v2 prevents processes inside a cgroup from modifying their own limits
+# - The agent (PID 1) is in the root cgroup, user processes in /sandbox cgroup
+
exec /usr/local/bin/osb-agent
INIT_EOF
chmod +x "$TMPDIR/init"
diff --git a/internal/agent/exec.go b/internal/agent/exec.go
index 82f51d4c..a0177025 100644
--- a/internal/agent/exec.go
+++ b/internal/agent/exec.go
@@ -90,18 +90,40 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecRespons
cmd.Stdout = &stdout
cmd.Stderr = &stderr
- err := cmd.Run()
+ // Start + move to sandbox cgroup + wait (instead of Run)
+ if err := cmd.Start(); err != nil {
+ return nil, fmt.Errorf("exec start: %w", err)
+ }
+ moveToCgroup(cmd.Process.Pid)
+
+ // Wait with cgroup kill on timeout — if the process doesn't exit when the
+ // context deadline fires, kill the entire sandbox cgroup to clean up fork
+ // bombs and runaway children.
+ waitDone := make(chan error, 1)
+ go func() { waitDone <- cmd.Wait() }()
+
+ var err error
+ select {
+ case err = <-waitDone:
+ // Normal completion
+ case <-ctx.Done():
+ // Timeout — kill process group first, then nuke the cgroup
+ if cmd.Process != nil {
+ syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
+ }
+ killCgroup()
+ <-waitDone // wait for cmd.Wait to return after kills
+ return &pb.ExecResponse{
+ ExitCode: -1,
+ Stdout: stdout.String(),
+ Stderr: stderr.String() + "\nProcess timed out",
+ }, nil
+ }
exitCode := 0
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
- } else if ctx.Err() == context.DeadlineExceeded {
- return &pb.ExecResponse{
- ExitCode: -1,
- Stdout: stdout.String(),
- Stderr: stderr.String() + "\nProcess timed out",
- }, nil
} else {
return nil, fmt.Errorf("exec failed: %w", err)
}
@@ -143,7 +165,9 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStre
cmd.Env = append(cmd.Env, mapToEnv(req.Envs)...)
}
- cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Setpgid: true,
+ }
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
@@ -157,6 +181,7 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStre
if err := cmd.Start(); err != nil {
return fmt.Errorf("start: %w", err)
}
+ moveToCgroup(cmd.Process.Pid)
// Stream stdout and stderr in parallel
errCh := make(chan error, 2)
@@ -219,3 +244,73 @@ func mapToEnv(m map[string]string) []string {
}
return env
}
+
+const sandboxCgroupProcs = "/sys/fs/cgroup/sandbox/cgroup.procs"
+
+// sandboxUID/GID for running user commands as non-root.
+// Prevents users from modifying cgroup limits or kernel interfaces.
+const (
+ sandboxUID = 1000
+ sandboxGID = 1000
+)
+
+// moveToCgroup moves a process into the sandbox cgroup.
+// This ensures user commands are subject to resource limits (pids, memory, cpu)
+// while the agent (PID 1) stays in the root cgroup, protected from exhaustion.
+func moveToCgroup(pid int) {
+ _ = os.WriteFile(sandboxCgroupProcs, []byte(fmt.Sprintf("%d", pid)), 0644)
+}
+
+// killCgroup kills all processes in the sandbox cgroup.
+// Used on exec timeout to clean up fork bombs and runaway children.
+func killCgroup() {
+ // cgroup.kill is the fast path (kernel 5.14+) — kills all processes atomically
+ if err := os.WriteFile("/sys/fs/cgroup/sandbox/cgroup.kill", []byte("1"), 0644); err == nil {
+ return
+ }
+ // Fallback: read all PIDs and kill them individually
+ data, err := os.ReadFile(sandboxCgroupProcs)
+ if err != nil {
+ return
+ }
+ for _, line := range strings.Split(string(data), "\n") {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
+ var pid int
+ if _, err := fmt.Sscanf(line, "%d", &pid); err == nil && pid > 1 {
+ syscall.Kill(pid, syscall.SIGKILL)
+ }
+ }
+}
+
+// SetResourceLimits adjusts the sandbox cgroup limits at runtime.
+// Called by the worker when a sandbox scales up/down.
+func (s *Server) SetResourceLimits(ctx context.Context, req *pb.SetResourceLimitsRequest) (*pb.SetResourceLimitsResponse, error) {
+ const cgroupDir = "/sys/fs/cgroup/sandbox"
+
+ if req.MaxPids > 0 {
+ if err := os.WriteFile(cgroupDir+"/pids.max", []byte(fmt.Sprintf("%d", req.MaxPids)), 0644); err != nil {
+ return nil, fmt.Errorf("set pids.max: %w", err)
+ }
+ }
+ if req.MaxMemoryBytes > 0 {
+ if err := os.WriteFile(cgroupDir+"/memory.max", []byte(fmt.Sprintf("%d", req.MaxMemoryBytes)), 0644); err != nil {
+ return nil, fmt.Errorf("set memory.max: %w", err)
+ }
+ }
+ if req.CpuMaxUsec > 0 {
+ // cpu.max format: "$MAX $PERIOD" — e.g., "100000 100000" = 1 vCPU
+ period := int64(100000)
+ if req.CpuPeriodUsec > 0 {
+ period = req.CpuPeriodUsec
+ }
+ val := fmt.Sprintf("%d %d", req.CpuMaxUsec, period)
+ if err := os.WriteFile(cgroupDir+"/cpu.max", []byte(val), 0644); err != nil {
+ return nil, fmt.Errorf("set cpu.max: %w", err)
+ }
+ }
+
+ return &pb.SetResourceLimitsResponse{}, nil
+}
diff --git a/internal/agent/exec_session.go b/internal/agent/exec_session.go
index 4a000442..32c74d68 100644
--- a/internal/agent/exec_session.go
+++ b/internal/agent/exec_session.go
@@ -54,8 +54,14 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreat
env = append(env, mapToEnv(req.Envs)...)
cmd.Env = env
- // Set process group so we can kill the whole group
- cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ // Run as sandbox user in its own process group
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Setpgid: true,
+ Credential: &syscall.Credential{
+ Uid: sandboxUID,
+ Gid: sandboxGID,
+ },
+ }
stdinPipe, err := cmd.StdinPipe()
if err != nil {
@@ -98,6 +104,7 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreat
cancel()
return nil, fmt.Errorf("start command: %w", err)
}
+ moveToCgroup(cmd.Process.Pid)
s.execMu.Lock()
s.execSessions[sessionID] = sess
diff --git a/internal/agent/pty.go b/internal/agent/pty.go
index ac7f1c75..e4424ed8 100644
--- a/internal/agent/pty.go
+++ b/internal/agent/pty.go
@@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"sync"
+ "syscall"
"github.com/creack/pty"
"github.com/google/uuid"
@@ -55,6 +56,7 @@ func (s *Server) PTYCreate(ctx context.Context, req *pb.PTYCreateRequest) (*pb.P
fmt.Sprintf("COLUMNS=%d", req.Cols),
fmt.Sprintf("LINES=%d", req.Rows),
)
+ _ = syscall.Getuid() // keep syscall import for future use
cols := uint16(req.Cols)
rows := uint16(req.Rows)
@@ -73,6 +75,9 @@ func (s *Server) PTYCreate(ctx context.Context, req *pb.PTYCreateRequest) (*pb.P
cancel()
return nil, fmt.Errorf("start pty: %w", err)
}
+ if cmd.Process != nil {
+ moveToCgroup(cmd.Process.Pid)
+ }
sess := &ptySession{
id: sessionID,
diff --git a/internal/api/router.go b/internal/api/router.go
index 61dd9e69..285e6a56 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -136,6 +136,9 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.POST("/sandboxes/:id/hibernate", s.hibernateSandbox)
api.POST("/sandboxes/:id/wake", s.wakeSandbox)
+ // Resource limits
+ api.PUT("/sandboxes/:id/limits", s.setLimits)
+
// Checkpoints
api.POST("/sandboxes/:id/checkpoints", s.createCheckpoint)
api.GET("/sandboxes/:id/checkpoints", s.listCheckpoints)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 21ec97ab..1a2da610 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -571,6 +571,95 @@ func (s *Server) setTimeout(c echo.Context) error {
return c.NoContent(http.StatusNoContent)
}
+func (s *Server) setLimits(c echo.Context) error {
+ id := c.Param("id")
+ ctx := c.Request().Context()
+
+ var req struct {
+ MaxPids int `json:"maxPids"`
+ MaxMemoryMB int `json:"maxMemoryMB"`
+ CPUPercent int `json:"cpuPercent"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "invalid request body: " + err.Error(),
+ })
+ }
+
+ // Convert to cgroup values
+ maxMemoryBytes := int64(req.MaxMemoryMB) * 1024 * 1024
+ cpuMaxUsec := int64(req.CPUPercent) * 1000
+ cpuPeriodUsec := int64(100000)
+
+ // Server mode: dispatch to worker via gRPC
+ if s.workerRegistry != nil {
+ return s.setLimitsRemote(c, id, int32(req.MaxPids), maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec)
+ }
+
+ // Combined mode: apply locally
+ if s.manager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
+ if err := s.manager.SetResourceLimits(ctx, id, int32(req.MaxPids), maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "sandboxID": id,
+ "maxPids": req.MaxPids,
+ "maxMemoryMB": req.MaxMemoryMB,
+ "cpuPercent": req.CPUPercent,
+ })
+}
+
+func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "database not configured",
+ })
+ }
+
+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
+ }
+ if session.Status != "running" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox is not running"})
+ }
+
+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
+ if err != nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable"})
+ }
+
+ grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 30*time.Second)
+ defer cancel()
+
+ _, err = client.SetSandboxLimits(grpcCtx, &pb.SetSandboxLimitsRequest{
+ SandboxId: sandboxID,
+ MaxPids: maxPids,
+ MaxMemoryBytes: maxMemoryBytes,
+ CpuMaxUsec: cpuMaxUsec,
+ CpuPeriodUsec: cpuPeriodUsec,
+ })
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "set limits failed: " + err.Error(),
+ })
+ }
+
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "sandboxID": sandboxID,
+ "maxPids": maxPids,
+ "maxMemoryBytes": maxMemoryBytes,
+ "cpuMaxUsec": cpuMaxUsec,
+ "cpuPeriodUsec": cpuPeriodUsec,
+ })
+}
+
func (s *Server) hibernateSandbox(c echo.Context) error {
id := c.Param("id")
ctx := c.Request().Context()
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
index 4faf2cac..91369467 100644
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@ -795,6 +795,12 @@ func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.File
}, nil
}
+// SetResourceLimits adjusts sandbox cgroup limits at runtime.
+// Not yet implemented for the Firecracker backend.
+func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error {
+ return fmt.Errorf("SetResourceLimits not implemented for Firecracker backend")
+}
+
// Stats returns live resource usage from the VM.
func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {
vm, err := m.getReadyVM(ctx, sandboxID)
diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.go
index ce31983b..f30234dd 100644
--- a/internal/qemu/agent_client.go
+++ b/internal/qemu/agent_client.go
@@ -242,6 +242,17 @@ func (c *AgentClient) Shutdown(ctx context.Context) error {
return err
}
+// SetResourceLimits adjusts sandbox cgroup limits at runtime.
+func (c *AgentClient) SetResourceLimits(ctx context.Context, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error {
+ _, err := c.client.SetResourceLimits(ctx, &pb.SetResourceLimitsRequest{
+ MaxPids: maxPids,
+ MaxMemoryBytes: maxMemoryBytes,
+ CpuMaxUsec: cpuMaxUsec,
+ CpuPeriodUsec: cpuPeriodUsec,
+ })
+ return err
+}
+
// SyncFS flushes all filesystem buffers inside the VM.
func (c *AgentClient) SyncFS(ctx context.Context) error {
_, err := c.client.SyncFS(ctx, &pb.SyncFSRequest{})
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 5fb678bb..d62574b3 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -51,8 +51,9 @@ type VMInstance struct {
qmp *QMPClient
guestMAC string
guestCID uint32
- bootArgs string
- restoring chan struct{}
+ bootArgs string
+ restoring chan struct{}
+ dimmCount int // number of hotplugged DIMMs (for unique IDs)
}
// SandboxMeta is persisted to sandbox-meta.json for recovery after hard kills.
@@ -91,6 +92,10 @@ type Manager struct {
goldenCID uint32 // CID used when the golden snapshot was created
goldenGuestIP string // guest IP baked into the golden snapshot
goldenHostIP string // host IP of the golden subnet (for temp addr on TAP)
+
+ // Metadata service callbacks (set via SetMetadataCallbacks)
+ onSandboxReady func(sandboxID, guestIP, template string, startedAt time.Time)
+ onSandboxDestroy func(sandboxID string)
}
// NewManager creates a new QEMU-backed sandbox manager.
@@ -139,6 +144,17 @@ func NewManager(cfg Config) (*Manager, error) {
}, nil
}
+// SetMetadataCallbacks registers callbacks that are invoked when sandboxes
+// become ready or are destroyed. Used by the metadata server to track
+// guestIP → sandboxID mappings.
+func (m *Manager) SetMetadataCallbacks(
+ onReady func(sandboxID, guestIP, template string, startedAt time.Time),
+ onDestroy func(sandboxID string),
+) {
+ m.onSandboxReady = onReady
+ m.onSandboxDestroy = onDestroy
+}
+
// PrepareGoldenSnapshot boots a temporary VM, waits for the agent, then
// hibernates it to create a reusable snapshot. Subsequent Create() calls
// restore from this snapshot instead of cold-booting, cutting start time
@@ -411,6 +427,11 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
return nil, fmt.Errorf("add DNAT: %w", err)
}
+ // Add metadata service DNAT (169.254.169.254:80 → host:8888)
+ if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {
+ log.Printf("qemu: warning: metadata DNAT failed for %s: %v", netCfg.TAPName, err)
+ }
+
cpus := cfg.CpuCount
if cpus <= 0 {
cpus = m.cfg.DefaultCPUs
@@ -580,6 +601,11 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
m.vms[id] = vm
m.mu.Unlock()
+ // Notify metadata server
+ if m.onSandboxReady != nil {
+ m.onSandboxReady(id, netCfg.GuestIP, template, vm.StartedAt)
+ }
+
sbMeta := SandboxMeta{
SandboxID: id,
Template: template,
@@ -713,7 +739,7 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN
return []string{
"-machine", "q35,accel=kvm",
"-cpu", "host",
- "-m", fmt.Sprintf("%dM", memMB),
+ "-m", fmt.Sprintf("%dM,maxmem=16G,slots=8", memMB),
"-smp", fmt.Sprintf("%d", cpus),
"-kernel", m.cfg.KernelPath,
"-append", bootArgs,
@@ -826,6 +852,11 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
return nil, fmt.Errorf("add DNAT: %w", err)
}
+ // Add metadata service DNAT (169.254.169.254:80 → host:8888)
+ if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {
+ log.Printf("qemu: warning: metadata DNAT failed for %s: %v", netCfg.TAPName, err)
+ }
+
cpus := cfg.CpuCount
if cpus <= 0 {
cpus = m.cfg.DefaultCPUs
@@ -936,6 +967,11 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
m.vms[id] = vm
m.mu.Unlock()
+ // Notify metadata server
+ if m.onSandboxReady != nil {
+ m.onSandboxReady(id, netCfg.GuestIP, template, vm.StartedAt)
+ }
+
sbMeta := SandboxMeta{
SandboxID: id,
Template: template,
@@ -1092,11 +1128,17 @@ func (m *Manager) destroyVM(vm *VMInstance) error {
}
if vm.network != nil {
+ RemoveMetadataDNAT(vm.network.TAPName, vm.network.HostIP)
RemoveDNAT(vm.network)
DeleteTAP(vm.network.TAPName)
m.subnets.Release(vm.network.TAPName)
}
+ // Notify metadata server
+ if m.onSandboxDestroy != nil {
+ m.onSandboxDestroy(vm.ID)
+ }
+
if vm.qmpSockPath != "" {
os.Remove(vm.qmpSockPath)
}
@@ -1112,6 +1154,7 @@ func (m *Manager) destroyVM(vm *VMInstance) error {
// cleanupVM cleans up resources on failed creation.
func (m *Manager) cleanupVM(netCfg *NetworkConfig, sandboxDir string) {
if netCfg != nil {
+ RemoveMetadataDNAT(netCfg.TAPName, netCfg.HostIP)
RemoveDNAT(netCfg)
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
@@ -1344,6 +1387,35 @@ func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.File
}, nil
}
+// SetResourceLimits adjusts sandbox cgroup limits at runtime via the agent.
+// If the requested memory exceeds the VM's physical RAM, hotplug a DIMM first.
+func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error {
+ vm, err := m.getReadyVM(ctx, sandboxID)
+ if err != nil {
+ return err
+ }
+
+ // Memory hotplug: if requested memory > current VM physical RAM, add a DIMM
+ if maxMemoryBytes > 0 {
+ currentBytes := int64(vm.MemoryMB) * 1024 * 1024
+ if maxMemoryBytes > currentBytes && vm.qmp != nil {
+ addMB := int(maxMemoryBytes-currentBytes) / (1024 * 1024)
+ if addMB > 0 {
+ if err := vm.qmp.HotplugMemory(vm.dimmCount, addMB); err != nil {
+ log.Printf("qemu: memory hotplug %s: add %dMB failed: %v", sandboxID, addMB, err)
+ // Non-fatal — cgroup limit will still be set (capped at physical RAM)
+ } else {
+ vm.dimmCount++
+ vm.MemoryMB += addMB
+ log.Printf("qemu: memory hotplug %s: added %dMB (total %dMB)", sandboxID, addMB, vm.MemoryMB)
+ }
+ }
+ }
+ }
+
+ return vm.agent.SetResourceLimits(ctx, maxPids, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec)
+}
+
// Stats returns live resource usage from the VM.
func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {
vm, err := m.getReadyVM(ctx, sandboxID)
@@ -1683,6 +1755,11 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
return nil, fmt.Errorf("add DNAT: %w", err)
}
+ // Add metadata service DNAT (169.254.169.254:80 → host:8888)
+ if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {
+ log.Printf("qemu: warning: metadata DNAT failed for %s: %v", netCfg.TAPName, err)
+ }
+
cpus := cfg.CpuCount
if cpus <= 0 {
cpus = m.cfg.DefaultCPUs
@@ -1823,6 +1900,11 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
m.vms[id] = vm
m.mu.Unlock()
+ // Notify metadata server
+ if m.onSandboxReady != nil {
+ m.onSandboxReady(id, netCfg.GuestIP, meta.Template, now)
+ }
+
log.Printf("qemu: ForkFromCheckpoint %s → %s: complete (%dms, port=%d, tap=%s)",
checkpointID, id, time.Since(t0).Milliseconds(), hostPort, netCfg.TAPName)
diff --git a/internal/qemu/network.go b/internal/qemu/network.go
index d8b57f84..c8268721 100644
--- a/internal/qemu/network.go
+++ b/internal/qemu/network.go
@@ -173,6 +173,29 @@ func RemoveDNAT(cfg *NetworkConfig) {
fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
}
+// AddMetadataDNAT adds an iptables rule to redirect 169.254.169.254:80 from a VM's TAP
+// to the host metadata server on port 8888.
+func AddMetadataDNAT(tapName, hostIP string) error {
+ err := run("iptables", "-t", "nat", "-A", "PREROUTING",
+ "-i", tapName,
+ "-d", "169.254.169.254",
+ "-p", "tcp", "--dport", "80",
+ "-j", "DNAT", "--to-destination", hostIP+":8888")
+ if err != nil {
+ return fmt.Errorf("add metadata DNAT for %s: %w", tapName, err)
+ }
+ return nil
+}
+
+// RemoveMetadataDNAT removes the metadata DNAT rule for a TAP device.
+func RemoveMetadataDNAT(tapName, hostIP string) {
+ _ = run("iptables", "-t", "nat", "-D", "PREROUTING",
+ "-i", tapName,
+ "-d", "169.254.169.254",
+ "-p", "tcp", "--dport", "80",
+ "-j", "DNAT", "--to-destination", hostIP+":8888")
+}
+
// EnableForwarding enables IPv4 forwarding and masquerading for the VM subnet.
func EnableForwarding() error {
if err := run("sysctl", "-w", "net.ipv4.ip_forward=1"); err != nil {
diff --git a/internal/qemu/qmp.go b/internal/qemu/qmp.go
index f2be6fbb..f5ee01fd 100644
--- a/internal/qemu/qmp.go
+++ b/internal/qemu/qmp.go
@@ -254,6 +254,35 @@ func (q *QMPClient) Execute(command string, args map[string]interface{}) error {
return err
}
+// HotplugMemory adds a memory DIMM to the running VM.
+// The guest kernel detects the new memory automatically.
+// Each DIMM gets a unique ID based on the index (dimm0, dimm1, etc.).
+func (q *QMPClient) HotplugMemory(dimmIndex int, sizeMB int) error {
+ backendID := fmt.Sprintf("mem%d", dimmIndex)
+ dimmID := fmt.Sprintf("dimm%d", dimmIndex)
+ sizeBytes := int64(sizeMB) * 1024 * 1024
+
+ // Step 1: Create memory backend
+ if err := q.Execute("object-add", map[string]interface{}{
+ "qom-type": "memory-backend-ram",
+ "id": backendID,
+ "size": sizeBytes,
+ }); err != nil {
+ return fmt.Errorf("object-add memory backend: %w", err)
+ }
+
+ // Step 2: Attach DIMM device
+ if err := q.Execute("device_add", map[string]interface{}{
+ "driver": "pc-dimm",
+ "id": dimmID,
+ "memdev": backendID,
+ }); err != nil {
+ return fmt.Errorf("device_add dimm: %w", err)
+ }
+
+ return nil
+}
+
// SendFd passes an open file descriptor to QEMU via the QMP getfd command.
// QEMU receives the fd via SCM_RIGHTS and registers it under the given name.
func (q *QMPClient) SendFd(name string, f *os.File) error {
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index d048eca0..8783d590 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -327,6 +327,11 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
return nil, fmt.Errorf("add DNAT: %w", err)
}
+ // Add metadata service DNAT (169.254.169.254:80 → host:8888)
+ if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {
+ log.Printf("qemu: warning: metadata DNAT failed for %s: %v", netCfg.TAPName, err)
+ }
+
// Use the user's rootfs if it exists (preserves apt/pip installs).
// Fall back to fresh golden rootfs copy if missing (e.g., S3 restore
// of an old checkpoint that didn't include rootfs).
@@ -480,6 +485,11 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
m.vms[sandboxID] = vm
m.mu.Unlock()
+ // Notify metadata server
+ if m.onSandboxReady != nil {
+ m.onSandboxReady(sandboxID, netCfg.GuestIP, vm.Template, vm.StartedAt)
+ }
+
log.Printf("qemu: woke VM %s (cold boot, port=%d, tap=%s)",
sandboxID, hostPort, netCfg.TAPName)
return vmToSandbox(vm), nil
@@ -544,6 +554,11 @@ func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout i
return nil, fmt.Errorf("add DNAT: %w", err)
}
+ // Add metadata service DNAT (169.254.169.254:80 → host:8888)
+ if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {
+ log.Printf("qemu: warning: metadata DNAT failed for %s: %v", netCfg.TAPName, err)
+ }
+
cpus := meta.CpuCount
if cpus <= 0 {
cpus = m.cfg.DefaultCPUs
@@ -642,6 +657,11 @@ func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout i
m.vms[sandboxID] = vm
m.mu.Unlock()
+ // Notify metadata server
+ if m.onSandboxReady != nil {
+ m.onSandboxReady(sandboxID, netCfg.GuestIP, meta.Template, vm.StartedAt)
+ }
+
log.Printf("qemu: cold-boot-local %s (template=%s, port=%d, tap=%s)", sandboxID, meta.Template, hostPort, netCfg.TAPName)
return vmToSandbox(vm), nil
}
diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.go
index 5da04f94..96897272 100644
--- a/internal/sandbox/interface.go
+++ b/internal/sandbox/interface.go
@@ -49,6 +49,9 @@ type Manager interface {
Exists(ctx context.Context, sandboxID, path string) (bool, error)
Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error)
+ // Resource limits
+ SetResourceLimits(ctx context.Context, sandboxID string, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error
+
// Monitoring
Stats(ctx context.Context, sandboxID string) (*SandboxStats, error)
HostPort(ctx context.Context, sandboxID string) (int, error)
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index c026063f..bf0eb6c0 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -698,6 +698,13 @@ func downloadAndExtract(ctx context.Context, store *storage.CheckpointStore, s3K
return extract(tmpPath, dest)
}
+func (s *GRPCServer) SetSandboxLimits(ctx context.Context, req *pb.SetSandboxLimitsRequest) (*pb.SetSandboxLimitsResponse, error) {
+ if err := s.manager.SetResourceLimits(ctx, req.SandboxId, req.MaxPids, req.MaxMemoryBytes, req.CpuMaxUsec, req.CpuPeriodUsec); err != nil {
+ return nil, fmt.Errorf("set sandbox limits failed: %w", err)
+ }
+ return &pb.SetSandboxLimitsResponse{}, nil
+}
+
func (s *GRPCServer) GetSandboxStats(ctx context.Context, req *pb.GetSandboxStatsRequest) (*pb.GetSandboxStatsResponse, error) {
stats, err := s.manager.Stats(ctx, req.SandboxId)
if err != nil {
diff --git a/internal/worker/metadata.go b/internal/worker/metadata.go
new file mode 100644
index 00000000..a9428793
--- /dev/null
+++ b/internal/worker/metadata.go
@@ -0,0 +1,281 @@
+package worker
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+ "net"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+)
+
+// MetadataServer serves the instance metadata API at 169.254.169.254:80 (via DNAT to :8888).
+// Sandboxes can access it to discover their own identity, resource limits, and scale up/down.
+type MetadataServer struct {
+ manager sandbox.Manager
+ region string
+
+ mu sync.RWMutex
+ byGuestIP map[string]sandboxEntry // guestIP → entry
+ bySandbox map[string]string // sandboxID → guestIP (for reverse lookup on unregister)
+
+ server *http.Server
+}
+
+type sandboxEntry struct {
+ SandboxID string
+ Template string
+ StartedAt time.Time
+}
+
+// NewMetadataServer creates a new metadata server.
+func NewMetadataServer(manager sandbox.Manager, region string) *MetadataServer {
+ return &MetadataServer{
+ manager: manager,
+ region: region,
+ byGuestIP: make(map[string]sandboxEntry),
+ bySandbox: make(map[string]string),
+ }
+}
+
+// RegisterSandbox maps a guest IP to a sandbox ID so the metadata handler can identify callers.
+func (ms *MetadataServer) RegisterSandbox(sandboxID, guestIP, template string, startedAt time.Time) {
+ ms.mu.Lock()
+ defer ms.mu.Unlock()
+ ms.byGuestIP[guestIP] = sandboxEntry{
+ SandboxID: sandboxID,
+ Template: template,
+ StartedAt: startedAt,
+ }
+ ms.bySandbox[sandboxID] = guestIP
+}
+
+// UnregisterSandbox removes a sandbox from the metadata lookup maps.
+func (ms *MetadataServer) UnregisterSandbox(sandboxID string) {
+ ms.mu.Lock()
+ defer ms.mu.Unlock()
+ if guestIP, ok := ms.bySandbox[sandboxID]; ok {
+ delete(ms.byGuestIP, guestIP)
+ delete(ms.bySandbox, sandboxID)
+ }
+}
+
+// Start starts the HTTP metadata server on the given address (e.g. ":8888").
+func (ms *MetadataServer) Start(addr string) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v1/status", ms.handleStatus)
+ mux.HandleFunc("/v1/limits", ms.handleLimits)
+ mux.HandleFunc("/v1/scale", ms.handleScale)
+ mux.HandleFunc("/v1/metadata", ms.handleMetadata)
+ // Root returns a list of available endpoints
+ mux.HandleFunc("/", ms.handleIndex)
+
+ ms.server = &http.Server{
+ Addr: addr,
+ Handler: mux,
+ }
+
+ go func() {
+ log.Printf("metadata: starting metadata server on %s", addr)
+ if err := ms.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ log.Printf("metadata: server error: %v", err)
+ }
+ }()
+}
+
+// Close shuts down the metadata server.
+func (ms *MetadataServer) Close() {
+ if ms.server != nil {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ ms.server.Shutdown(ctx)
+ }
+}
+
+// lookupSandbox resolves the calling sandbox from the HTTP request's source IP.
+func (ms *MetadataServer) lookupSandbox(r *http.Request) (sandboxEntry, bool) {
+ // Extract the IP from RemoteAddr (format is "ip:port")
+ host, _, err := net.SplitHostPort(r.RemoteAddr)
+ if err != nil {
+ // Try using RemoteAddr directly (no port)
+ host = r.RemoteAddr
+ }
+
+ ms.mu.RLock()
+ entry, ok := ms.byGuestIP[host]
+ ms.mu.RUnlock()
+ return entry, ok
+}
+
+func (ms *MetadataServer) handleIndex(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]interface{}{
+ "endpoints": []string{
+ "/v1/status",
+ "/v1/limits",
+ "/v1/scale",
+ "/v1/metadata",
+ },
+ })
+}
+
+// GET /v1/status → {"sandboxId", "uptime"}
+func (ms *MetadataServer) handleStatus(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ entry, ok := ms.lookupSandbox(r)
+ if !ok {
+ http.Error(w, "sandbox not found for source IP", http.StatusNotFound)
+ return
+ }
+
+ uptime := time.Since(entry.StartedAt).Seconds()
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]interface{}{
+ "sandboxId": entry.SandboxID,
+ "uptime": uptime,
+ })
+}
+
+// GET /v1/limits → returns current cgroup limits via agent Stats
+func (ms *MetadataServer) handleLimits(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ entry, ok := ms.lookupSandbox(r)
+ if !ok {
+ http.Error(w, "sandbox not found for source IP", http.StatusNotFound)
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
+ defer cancel()
+
+ stats, err := ms.manager.Stats(ctx, entry.SandboxID)
+ if err != nil {
+ http.Error(w, fmt.Sprintf("failed to get stats: %v", err), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]interface{}{
+ "cpuPercent": stats.CPUPercent,
+ "memUsage": stats.MemUsage,
+ "memLimit": stats.MemLimit,
+ "pids": stats.PIDs,
+ "netInput": stats.NetInput,
+ "netOutput": stats.NetOutput,
+ })
+}
+
+// POST /v1/scale → accepts {"memoryMB", "cpuPercent", "maxPids"}, applies cgroup limits.
+// Pricing model: 1 vCPU per 1GB RAM. memoryMB=2048 → cpuPercent=200 (2 vCPUs).
+func (ms *MetadataServer) handleScale(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ entry, ok := ms.lookupSandbox(r)
+ if !ok {
+ http.Error(w, "sandbox not found for source IP", http.StatusNotFound)
+ return
+ }
+
+ var req struct {
+ MemoryMB int `json:"memoryMB"`
+ CPUPercent int `json:"cpuPercent"`
+ MaxPids int `json:"maxPids"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, fmt.Sprintf("invalid JSON: %v", err), http.StatusBadRequest)
+ return
+ }
+
+ // Apply pricing model: 1 vCPU per 1GB RAM
+ // If memoryMB is set but cpuPercent is not, auto-calculate
+ if req.MemoryMB > 0 && req.CPUPercent == 0 {
+ // 1 vCPU = 100% = 1024 MB
+ req.CPUPercent = (req.MemoryMB * 100) / 1024
+ if req.CPUPercent < 100 {
+ req.CPUPercent = 100 // minimum 1 vCPU
+ }
+ }
+
+ // Convert to cgroup values
+ var maxPids int32
+ var maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64
+
+ if req.MaxPids > 0 {
+ maxPids = int32(req.MaxPids)
+ }
+ if req.MemoryMB > 0 {
+ maxMemoryBytes = int64(req.MemoryMB) * 1024 * 1024
+ }
+ if req.CPUPercent > 0 {
+ // cpu.max format: $MAX $PERIOD
+ // cpuPercent=200 means 2 vCPUs → cpuMaxUsec=200000, cpuPeriodUsec=100000
+ cpuPeriodUsec = 100000
+ cpuMaxUsec = int64(req.CPUPercent) * 1000 // 100% = 100000us per 100000us period
+ }
+
+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
+ defer cancel()
+
+ if err := ms.manager.SetResourceLimits(ctx, entry.SandboxID, maxPids, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec); err != nil {
+ http.Error(w, fmt.Sprintf("failed to set limits: %v", err), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]interface{}{
+ "ok": true,
+ "memoryMB": req.MemoryMB,
+ "cpuPercent": req.CPUPercent,
+ "maxPids": req.MaxPids,
+ })
+}
+
+// GET /v1/metadata → returns {"region", "template"}
+func (ms *MetadataServer) handleMetadata(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ entry, ok := ms.lookupSandbox(r)
+ if !ok {
+ http.Error(w, "sandbox not found for source IP", http.StatusNotFound)
+ return
+ }
+
+ // Build metadata response
+ resp := map[string]interface{}{
+ "region": ms.region,
+ "template": entry.Template,
+ }
+
+ // Strip any prefix to get clean template name
+ if strings.Contains(entry.Template, "/") {
+ parts := strings.Split(entry.Template, "/")
+ resp["templateBase"] = parts[len(parts)-1]
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(resp)
+}
diff --git a/proto/agent/agent.pb.go b/proto/agent/agent.pb.go
index fcf8e4c2..565f9f6e 100644
--- a/proto/agent/agent.pb.go
+++ b/proto/agent/agent.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
-// protoc v7.34.0
+// protoc v6.33.4
// source: proto/agent/agent.proto
package agent
@@ -2251,6 +2251,110 @@ func (*SyncFSResponse) Descriptor() ([]byte, []int) {
return file_proto_agent_agent_proto_rawDescGZIP(), []int{42}
}
+type SetResourceLimitsRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ MaxPids int32 `protobuf:"varint,1,opt,name=max_pids,json=maxPids,proto3" json:"max_pids,omitempty"` // pids.max (0 = don't change)
+ MaxMemoryBytes int64 `protobuf:"varint,2,opt,name=max_memory_bytes,json=maxMemoryBytes,proto3" json:"max_memory_bytes,omitempty"` // memory.max (0 = don't change)
+ CpuMaxUsec int64 `protobuf:"varint,3,opt,name=cpu_max_usec,json=cpuMaxUsec,proto3" json:"cpu_max_usec,omitempty"` // cpu.max quota (0 = don't change)
+ CpuPeriodUsec int64 `protobuf:"varint,4,opt,name=cpu_period_usec,json=cpuPeriodUsec,proto3" json:"cpu_period_usec,omitempty"` // cpu.max period (0 = default 100000)
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SetResourceLimitsRequest) Reset() {
+ *x = SetResourceLimitsRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[43]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SetResourceLimitsRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SetResourceLimitsRequest) ProtoMessage() {}
+
+func (x *SetResourceLimitsRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[43]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SetResourceLimitsRequest.ProtoReflect.Descriptor instead.
+func (*SetResourceLimitsRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{43}
+}
+
+func (x *SetResourceLimitsRequest) GetMaxPids() int32 {
+ if x != nil {
+ return x.MaxPids
+ }
+ return 0
+}
+
+func (x *SetResourceLimitsRequest) GetMaxMemoryBytes() int64 {
+ if x != nil {
+ return x.MaxMemoryBytes
+ }
+ return 0
+}
+
+func (x *SetResourceLimitsRequest) GetCpuMaxUsec() int64 {
+ if x != nil {
+ return x.CpuMaxUsec
+ }
+ return 0
+}
+
+func (x *SetResourceLimitsRequest) GetCpuPeriodUsec() int64 {
+ if x != nil {
+ return x.CpuPeriodUsec
+ }
+ return 0
+}
+
+type SetResourceLimitsResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SetResourceLimitsResponse) Reset() {
+ *x = SetResourceLimitsResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[44]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SetResourceLimitsResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SetResourceLimitsResponse) ProtoMessage() {}
+
+func (x *SetResourceLimitsResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[44]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SetResourceLimitsResponse.ProtoReflect.Descriptor instead.
+func (*SetResourceLimitsResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{44}
+}
+
var File_proto_agent_agent_proto protoreflect.FileDescriptor
const file_proto_agent_agent_proto_rawDesc = "" +
@@ -2402,7 +2506,14 @@ const file_proto_agent_agent_proto_rawDesc = "" +
"\x0fShutdownRequest\"\x12\n" +
"\x10ShutdownResponse\"\x0f\n" +
"\rSyncFSRequest\"\x10\n" +
- "\x0eSyncFSResponse2\xa0\n" +
+ "\x0eSyncFSResponse\"\xa9\x01\n" +
+ "\x18SetResourceLimitsRequest\x12\x19\n" +
+ "\bmax_pids\x18\x01 \x01(\x05R\amaxPids\x12(\n" +
+ "\x10max_memory_bytes\x18\x02 \x01(\x03R\x0emaxMemoryBytes\x12 \n" +
+ "\fcpu_max_usec\x18\x03 \x01(\x03R\n" +
+ "cpuMaxUsec\x12&\n" +
+ "\x0fcpu_period_usec\x18\x04 \x01(\x03R\rcpuPeriodUsec\"\x1b\n" +
+ "\x19SetResourceLimitsResponse2\xf8\n" +
"\n" +
"\fSandboxAgent\x12/\n" +
"\x04Exec\x12\x12.agent.ExecRequest\x1a\x13.agent.ExecResponse\x12:\n" +
@@ -2426,7 +2537,8 @@ const file_proto_agent_agent_proto_rawDesc = "" +
"\x0fExecSessionKill\x12\x1d.agent.ExecSessionKillRequest\x1a\x1e.agent.ExecSessionKillResponse\x128\n" +
"\aSetEnvs\x12\x15.agent.SetEnvsRequest\x1a\x16.agent.SetEnvsResponse\x12;\n" +
"\bShutdown\x12\x16.agent.ShutdownRequest\x1a\x17.agent.ShutdownResponse\x125\n" +
- "\x06SyncFS\x12\x14.agent.SyncFSRequest\x1a\x15.agent.SyncFSResponseB0Z.github.com/opensandbox/opensandbox/proto/agentb\x06proto3"
+ "\x06SyncFS\x12\x14.agent.SyncFSRequest\x1a\x15.agent.SyncFSResponse\x12V\n" +
+ "\x11SetResourceLimits\x12\x1f.agent.SetResourceLimitsRequest\x1a .agent.SetResourceLimitsResponseB0Z.github.com/opensandbox/opensandbox/proto/agentb\x06proto3"
var (
file_proto_agent_agent_proto_rawDescOnce sync.Once
@@ -2441,7 +2553,7 @@ func file_proto_agent_agent_proto_rawDescGZIP() []byte {
}
var file_proto_agent_agent_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
-var file_proto_agent_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 46)
+var file_proto_agent_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 48)
var file_proto_agent_agent_proto_goTypes = []any{
(ExecOutputChunk_Stream)(0), // 0: agent.ExecOutputChunk.Stream
(ExecSessionOutput_Type)(0), // 1: agent.ExecSessionOutput.Type
@@ -2488,18 +2600,20 @@ var file_proto_agent_agent_proto_goTypes = []any{
(*ShutdownResponse)(nil), // 42: agent.ShutdownResponse
(*SyncFSRequest)(nil), // 43: agent.SyncFSRequest
(*SyncFSResponse)(nil), // 44: agent.SyncFSResponse
- nil, // 45: agent.ExecRequest.EnvsEntry
- nil, // 46: agent.ExecSessionCreateRequest.EnvsEntry
- nil, // 47: agent.SetEnvsRequest.EnvsEntry
+ (*SetResourceLimitsRequest)(nil), // 45: agent.SetResourceLimitsRequest
+ (*SetResourceLimitsResponse)(nil), // 46: agent.SetResourceLimitsResponse
+ nil, // 47: agent.ExecRequest.EnvsEntry
+ nil, // 48: agent.ExecSessionCreateRequest.EnvsEntry
+ nil, // 49: agent.SetEnvsRequest.EnvsEntry
}
var file_proto_agent_agent_proto_depIdxs = []int32{
- 45, // 0: agent.ExecRequest.envs:type_name -> agent.ExecRequest.EnvsEntry
+ 47, // 0: agent.ExecRequest.envs:type_name -> agent.ExecRequest.EnvsEntry
0, // 1: agent.ExecOutputChunk.stream:type_name -> agent.ExecOutputChunk.Stream
10, // 2: agent.ListDirResponse.entries:type_name -> agent.DirEntry
- 46, // 3: agent.ExecSessionCreateRequest.envs:type_name -> agent.ExecSessionCreateRequest.EnvsEntry
+ 48, // 3: agent.ExecSessionCreateRequest.envs:type_name -> agent.ExecSessionCreateRequest.EnvsEntry
1, // 4: agent.ExecSessionOutput.type:type_name -> agent.ExecSessionOutput.Type
36, // 5: agent.ExecSessionListResponse.sessions:type_name -> agent.ExecSessionInfo
- 47, // 6: agent.SetEnvsRequest.envs:type_name -> agent.SetEnvsRequest.EnvsEntry
+ 49, // 6: agent.SetEnvsRequest.envs:type_name -> agent.SetEnvsRequest.EnvsEntry
2, // 7: agent.SandboxAgent.Exec:input_type -> agent.ExecRequest
2, // 8: agent.SandboxAgent.ExecStream:input_type -> agent.ExecRequest
5, // 9: agent.SandboxAgent.ReadFile:input_type -> agent.ReadFileRequest
@@ -2521,29 +2635,31 @@ var file_proto_agent_agent_proto_depIdxs = []int32{
39, // 25: agent.SandboxAgent.SetEnvs:input_type -> agent.SetEnvsRequest
41, // 26: agent.SandboxAgent.Shutdown:input_type -> agent.ShutdownRequest
43, // 27: agent.SandboxAgent.SyncFS:input_type -> agent.SyncFSRequest
- 3, // 28: agent.SandboxAgent.Exec:output_type -> agent.ExecResponse
- 4, // 29: agent.SandboxAgent.ExecStream:output_type -> agent.ExecOutputChunk
- 6, // 30: agent.SandboxAgent.ReadFile:output_type -> agent.ReadFileResponse
- 8, // 31: agent.SandboxAgent.WriteFile:output_type -> agent.WriteFileResponse
- 11, // 32: agent.SandboxAgent.ListDir:output_type -> agent.ListDirResponse
- 13, // 33: agent.SandboxAgent.MakeDir:output_type -> agent.MakeDirResponse
- 15, // 34: agent.SandboxAgent.Remove:output_type -> agent.RemoveResponse
- 17, // 35: agent.SandboxAgent.Exists:output_type -> agent.ExistsResponse
- 19, // 36: agent.SandboxAgent.Stat:output_type -> agent.StatResponse
- 21, // 37: agent.SandboxAgent.Stats:output_type -> agent.StatsResponse
- 23, // 38: agent.SandboxAgent.Ping:output_type -> agent.PingResponse
- 25, // 39: agent.SandboxAgent.PTYCreate:output_type -> agent.PTYCreateResponse
- 27, // 40: agent.SandboxAgent.PTYResize:output_type -> agent.PTYResizeResponse
- 29, // 41: agent.SandboxAgent.PTYKill:output_type -> agent.PTYKillResponse
- 31, // 42: agent.SandboxAgent.ExecSessionCreate:output_type -> agent.ExecSessionCreateResponse
- 33, // 43: agent.SandboxAgent.ExecSessionAttach:output_type -> agent.ExecSessionOutput
- 35, // 44: agent.SandboxAgent.ExecSessionList:output_type -> agent.ExecSessionListResponse
- 38, // 45: agent.SandboxAgent.ExecSessionKill:output_type -> agent.ExecSessionKillResponse
- 40, // 46: agent.SandboxAgent.SetEnvs:output_type -> agent.SetEnvsResponse
- 42, // 47: agent.SandboxAgent.Shutdown:output_type -> agent.ShutdownResponse
- 44, // 48: agent.SandboxAgent.SyncFS:output_type -> agent.SyncFSResponse
- 28, // [28:49] is the sub-list for method output_type
- 7, // [7:28] is the sub-list for method input_type
+ 45, // 28: agent.SandboxAgent.SetResourceLimits:input_type -> agent.SetResourceLimitsRequest
+ 3, // 29: agent.SandboxAgent.Exec:output_type -> agent.ExecResponse
+ 4, // 30: agent.SandboxAgent.ExecStream:output_type -> agent.ExecOutputChunk
+ 6, // 31: agent.SandboxAgent.ReadFile:output_type -> agent.ReadFileResponse
+ 8, // 32: agent.SandboxAgent.WriteFile:output_type -> agent.WriteFileResponse
+ 11, // 33: agent.SandboxAgent.ListDir:output_type -> agent.ListDirResponse
+ 13, // 34: agent.SandboxAgent.MakeDir:output_type -> agent.MakeDirResponse
+ 15, // 35: agent.SandboxAgent.Remove:output_type -> agent.RemoveResponse
+ 17, // 36: agent.SandboxAgent.Exists:output_type -> agent.ExistsResponse
+ 19, // 37: agent.SandboxAgent.Stat:output_type -> agent.StatResponse
+ 21, // 38: agent.SandboxAgent.Stats:output_type -> agent.StatsResponse
+ 23, // 39: agent.SandboxAgent.Ping:output_type -> agent.PingResponse
+ 25, // 40: agent.SandboxAgent.PTYCreate:output_type -> agent.PTYCreateResponse
+ 27, // 41: agent.SandboxAgent.PTYResize:output_type -> agent.PTYResizeResponse
+ 29, // 42: agent.SandboxAgent.PTYKill:output_type -> agent.PTYKillResponse
+ 31, // 43: agent.SandboxAgent.ExecSessionCreate:output_type -> agent.ExecSessionCreateResponse
+ 33, // 44: agent.SandboxAgent.ExecSessionAttach:output_type -> agent.ExecSessionOutput
+ 35, // 45: agent.SandboxAgent.ExecSessionList:output_type -> agent.ExecSessionListResponse
+ 38, // 46: agent.SandboxAgent.ExecSessionKill:output_type -> agent.ExecSessionKillResponse
+ 40, // 47: agent.SandboxAgent.SetEnvs:output_type -> agent.SetEnvsResponse
+ 42, // 48: agent.SandboxAgent.Shutdown:output_type -> agent.ShutdownResponse
+ 44, // 49: agent.SandboxAgent.SyncFS:output_type -> agent.SyncFSResponse
+ 46, // 50: agent.SandboxAgent.SetResourceLimits:output_type -> agent.SetResourceLimitsResponse
+ 29, // [29:51] is the sub-list for method output_type
+ 7, // [7:29] is the sub-list for method input_type
7, // [7:7] is the sub-list for extension type_name
7, // [7:7] is the sub-list for extension extendee
0, // [0:7] is the sub-list for field type_name
@@ -2560,7 +2676,7 @@ func file_proto_agent_agent_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_agent_agent_proto_rawDesc), len(file_proto_agent_agent_proto_rawDesc)),
NumEnums: 2,
- NumMessages: 46,
+ NumMessages: 48,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/agent/agent.proto b/proto/agent/agent.proto
index d5cfaf65..ee4f66d4 100644
--- a/proto/agent/agent.proto
+++ b/proto/agent/agent.proto
@@ -50,6 +50,10 @@ service SandboxAgent {
// SyncFS flushes all filesystem buffers without exiting.
// Used before snapshot to ensure disk state is consistent.
rpc SyncFS(SyncFSRequest) returns (SyncFSResponse);
+
+ // SetResourceLimits adjusts sandbox cgroup limits at runtime.
+ // Used for elastic scaling — raise/lower memory, CPU, pids without restart.
+ rpc SetResourceLimits(SetResourceLimitsRequest) returns (SetResourceLimitsResponse);
}
// --- Exec ---
@@ -265,3 +269,14 @@ message ShutdownResponse {}
message SyncFSRequest {}
message SyncFSResponse {}
+
+// --- Resource Limits ---
+
+message SetResourceLimitsRequest {
+ int32 max_pids = 1; // pids.max (0 = don't change)
+ int64 max_memory_bytes = 2; // memory.max (0 = don't change)
+ int64 cpu_max_usec = 3; // cpu.max quota (0 = don't change)
+ int64 cpu_period_usec = 4; // cpu.max period (0 = default 100000)
+}
+
+message SetResourceLimitsResponse {}
diff --git a/proto/agent/agent_grpc.pb.go b/proto/agent/agent_grpc.pb.go
index 088622da..75f9493b 100644
--- a/proto/agent/agent_grpc.pb.go
+++ b/proto/agent/agent_grpc.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.1
-// - protoc v7.34.0
+// - protoc v6.33.4
// source: proto/agent/agent.proto
package agent
@@ -40,6 +40,7 @@ const (
SandboxAgent_SetEnvs_FullMethodName = "/agent.SandboxAgent/SetEnvs"
SandboxAgent_Shutdown_FullMethodName = "/agent.SandboxAgent/Shutdown"
SandboxAgent_SyncFS_FullMethodName = "/agent.SandboxAgent/SyncFS"
+ SandboxAgent_SetResourceLimits_FullMethodName = "/agent.SandboxAgent/SetResourceLimits"
)
// SandboxAgentClient is the client API for SandboxAgent service.
@@ -83,6 +84,9 @@ type SandboxAgentClient interface {
// SyncFS flushes all filesystem buffers without exiting.
// Used before snapshot to ensure disk state is consistent.
SyncFS(ctx context.Context, in *SyncFSRequest, opts ...grpc.CallOption) (*SyncFSResponse, error)
+ // SetResourceLimits adjusts sandbox cgroup limits at runtime.
+ // Used for elastic scaling — raise/lower memory, CPU, pids without restart.
+ SetResourceLimits(ctx context.Context, in *SetResourceLimitsRequest, opts ...grpc.CallOption) (*SetResourceLimitsResponse, error)
}
type sandboxAgentClient struct {
@@ -315,6 +319,16 @@ func (c *sandboxAgentClient) SyncFS(ctx context.Context, in *SyncFSRequest, opts
return out, nil
}
+func (c *sandboxAgentClient) SetResourceLimits(ctx context.Context, in *SetResourceLimitsRequest, opts ...grpc.CallOption) (*SetResourceLimitsResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(SetResourceLimitsResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_SetResourceLimits_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// SandboxAgentServer is the server API for SandboxAgent service.
// All implementations must embed UnimplementedSandboxAgentServer
// for forward compatibility.
@@ -356,6 +370,9 @@ type SandboxAgentServer interface {
// SyncFS flushes all filesystem buffers without exiting.
// Used before snapshot to ensure disk state is consistent.
SyncFS(context.Context, *SyncFSRequest) (*SyncFSResponse, error)
+ // SetResourceLimits adjusts sandbox cgroup limits at runtime.
+ // Used for elastic scaling — raise/lower memory, CPU, pids without restart.
+ SetResourceLimits(context.Context, *SetResourceLimitsRequest) (*SetResourceLimitsResponse, error)
mustEmbedUnimplementedSandboxAgentServer()
}
@@ -429,6 +446,9 @@ func (UnimplementedSandboxAgentServer) Shutdown(context.Context, *ShutdownReques
func (UnimplementedSandboxAgentServer) SyncFS(context.Context, *SyncFSRequest) (*SyncFSResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SyncFS not implemented")
}
+func (UnimplementedSandboxAgentServer) SetResourceLimits(context.Context, *SetResourceLimitsRequest) (*SetResourceLimitsResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method SetResourceLimits not implemented")
+}
func (UnimplementedSandboxAgentServer) mustEmbedUnimplementedSandboxAgentServer() {}
func (UnimplementedSandboxAgentServer) testEmbeddedByValue() {}
@@ -810,6 +830,24 @@ func _SandboxAgent_SyncFS_Handler(srv interface{}, ctx context.Context, dec func
return interceptor(ctx, in, info, handler)
}
+func _SandboxAgent_SetResourceLimits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(SetResourceLimitsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).SetResourceLimits(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_SetResourceLimits_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).SetResourceLimits(ctx, req.(*SetResourceLimitsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// SandboxAgent_ServiceDesc is the grpc.ServiceDesc for SandboxAgent service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -893,6 +931,10 @@ var SandboxAgent_ServiceDesc = grpc.ServiceDesc{
MethodName: "SyncFS",
Handler: _SandboxAgent_SyncFS_Handler,
},
+ {
+ MethodName: "SetResourceLimits",
+ Handler: _SandboxAgent_SetResourceLimits_Handler,
+ },
},
Streams: []grpc.StreamDesc{
{
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index 4e096f66..97ff3d74 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
-// protoc v7.34.0
+// protoc v6.33.4
// source: proto/worker/worker.proto
package worker
@@ -2572,6 +2572,118 @@ func (x *RestoreCheckpointResponse) GetSuccess() bool {
return false
}
+type SetSandboxLimitsRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ MaxPids int32 `protobuf:"varint,2,opt,name=max_pids,json=maxPids,proto3" json:"max_pids,omitempty"`
+ MaxMemoryBytes int64 `protobuf:"varint,3,opt,name=max_memory_bytes,json=maxMemoryBytes,proto3" json:"max_memory_bytes,omitempty"`
+ CpuMaxUsec int64 `protobuf:"varint,4,opt,name=cpu_max_usec,json=cpuMaxUsec,proto3" json:"cpu_max_usec,omitempty"`
+ CpuPeriodUsec int64 `protobuf:"varint,5,opt,name=cpu_period_usec,json=cpuPeriodUsec,proto3" json:"cpu_period_usec,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SetSandboxLimitsRequest) Reset() {
+ *x = SetSandboxLimitsRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[44]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SetSandboxLimitsRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SetSandboxLimitsRequest) ProtoMessage() {}
+
+func (x *SetSandboxLimitsRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[44]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SetSandboxLimitsRequest.ProtoReflect.Descriptor instead.
+func (*SetSandboxLimitsRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{44}
+}
+
+func (x *SetSandboxLimitsRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+func (x *SetSandboxLimitsRequest) GetMaxPids() int32 {
+ if x != nil {
+ return x.MaxPids
+ }
+ return 0
+}
+
+func (x *SetSandboxLimitsRequest) GetMaxMemoryBytes() int64 {
+ if x != nil {
+ return x.MaxMemoryBytes
+ }
+ return 0
+}
+
+func (x *SetSandboxLimitsRequest) GetCpuMaxUsec() int64 {
+ if x != nil {
+ return x.CpuMaxUsec
+ }
+ return 0
+}
+
+func (x *SetSandboxLimitsRequest) GetCpuPeriodUsec() int64 {
+ if x != nil {
+ return x.CpuPeriodUsec
+ }
+ return 0
+}
+
+type SetSandboxLimitsResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SetSandboxLimitsResponse) Reset() {
+ *x = SetSandboxLimitsResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[45]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SetSandboxLimitsResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SetSandboxLimitsResponse) ProtoMessage() {}
+
+func (x *SetSandboxLimitsResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[45]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SetSandboxLimitsResponse.ProtoReflect.Descriptor instead.
+func (*SetSandboxLimitsResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{45}
+}
+
var File_proto_worker_worker_proto protoreflect.FileDescriptor
const file_proto_worker_worker_proto_rawDesc = "" +
@@ -2782,7 +2894,16 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" +
"\rcheckpoint_id\x18\x02 \x01(\tR\fcheckpointId\"5\n" +
"\x19RestoreCheckpointResponse\x12\x18\n" +
- "\asuccess\x18\x01 \x01(\bR\asuccess2\xcf\f\n" +
+ "\asuccess\x18\x01 \x01(\bR\asuccess\"\xc7\x01\n" +
+ "\x17SetSandboxLimitsRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x19\n" +
+ "\bmax_pids\x18\x02 \x01(\x05R\amaxPids\x12(\n" +
+ "\x10max_memory_bytes\x18\x03 \x01(\x03R\x0emaxMemoryBytes\x12 \n" +
+ "\fcpu_max_usec\x18\x04 \x01(\x03R\n" +
+ "cpuMaxUsec\x12&\n" +
+ "\x0fcpu_period_usec\x18\x05 \x01(\x03R\rcpuPeriodUsec\"\x1a\n" +
+ "\x18SetSandboxLimitsResponse2\xa6\r\n" +
"\rSandboxWorker\x12L\n" +
"\rCreateSandbox\x12\x1c.worker.CreateSandboxRequest\x1a\x1d.worker.CreateSandboxResponse\x12O\n" +
"\x0eDestroySandbox\x12\x1d.worker.DestroySandboxRequest\x1a\x1e.worker.DestroySandboxResponse\x12C\n" +
@@ -2805,7 +2926,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\x10CreateCheckpoint\x12\x1f.worker.CreateCheckpointRequest\x1a .worker.CreateCheckpointResponse\x12X\n" +
"\x11RestoreCheckpoint\x12 .worker.RestoreCheckpointRequest\x1a!.worker.RestoreCheckpointResponse\x12L\n" +
"\rBuildTemplate\x12\x1c.worker.BuildTemplateRequest\x1a\x1d.worker.BuildTemplateResponse\x12R\n" +
- "\x0fGetSandboxStats\x12\x1e.worker.GetSandboxStatsRequest\x1a\x1f.worker.GetSandboxStatsResponseB1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"
+ "\x0fGetSandboxStats\x12\x1e.worker.GetSandboxStatsRequest\x1a\x1f.worker.GetSandboxStatsResponse\x12U\n" +
+ "\x10SetSandboxLimits\x12\x1f.worker.SetSandboxLimitsRequest\x1a .worker.SetSandboxLimitsResponseB1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"
var (
file_proto_worker_worker_proto_rawDescOnce sync.Once
@@ -2820,7 +2942,7 @@ func file_proto_worker_worker_proto_rawDescGZIP() []byte {
}
var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
-var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 47)
+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 49)
var file_proto_worker_worker_proto_goTypes = []any{
(ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream
(*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest
@@ -2867,18 +2989,20 @@ var file_proto_worker_worker_proto_goTypes = []any{
(*CreateCheckpointResponse)(nil), // 42: worker.CreateCheckpointResponse
(*RestoreCheckpointRequest)(nil), // 43: worker.RestoreCheckpointRequest
(*RestoreCheckpointResponse)(nil), // 44: worker.RestoreCheckpointResponse
- nil, // 45: worker.CreateSandboxRequest.EnvsEntry
- nil, // 46: worker.ExecCommandRequest.EnvsEntry
- nil, // 47: worker.ExecSessionCreateRequest.EnvsEntry
+ (*SetSandboxLimitsRequest)(nil), // 45: worker.SetSandboxLimitsRequest
+ (*SetSandboxLimitsResponse)(nil), // 46: worker.SetSandboxLimitsResponse
+ nil, // 47: worker.CreateSandboxRequest.EnvsEntry
+ nil, // 48: worker.ExecCommandRequest.EnvsEntry
+ nil, // 49: worker.ExecSessionCreateRequest.EnvsEntry
}
var file_proto_worker_worker_proto_depIdxs = []int32{
- 45, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
+ 47, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
6, // 1: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse
- 46, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
+ 48, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
0, // 3: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream
17, // 4: worker.ListDirResponse.entries:type_name -> worker.DirEntry
22, // 5: worker.PTYInput.resize:type_name -> worker.PTYResize
- 47, // 6: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry
+ 49, // 6: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry
36, // 7: worker.ExecSessionListResponse.sessions:type_name -> worker.ExecSessionInfoEntry
1, // 8: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest
3, // 9: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest
@@ -2901,29 +3025,31 @@ var file_proto_worker_worker_proto_depIdxs = []int32{
43, // 26: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest
30, // 27: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest
39, // 28: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest
- 2, // 29: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
- 4, // 30: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
- 6, // 31: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
- 8, // 32: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
- 10, // 33: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
- 11, // 34: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
- 13, // 35: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
- 15, // 36: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
- 18, // 37: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
- 20, // 38: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
- 23, // 39: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
- 33, // 40: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse
- 35, // 41: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse
- 38, // 42: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse
- 25, // 43: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse
- 27, // 44: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse
- 29, // 45: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse
- 42, // 46: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse
- 44, // 47: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse
- 31, // 48: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse
- 40, // 49: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse
- 29, // [29:50] is the sub-list for method output_type
- 8, // [8:29] is the sub-list for method input_type
+ 45, // 29: worker.SandboxWorker.SetSandboxLimits:input_type -> worker.SetSandboxLimitsRequest
+ 2, // 30: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
+ 4, // 31: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
+ 6, // 32: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
+ 8, // 33: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
+ 10, // 34: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
+ 11, // 35: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
+ 13, // 36: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
+ 15, // 37: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
+ 18, // 38: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
+ 20, // 39: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
+ 23, // 40: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
+ 33, // 41: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse
+ 35, // 42: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse
+ 38, // 43: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse
+ 25, // 44: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse
+ 27, // 45: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse
+ 29, // 46: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse
+ 42, // 47: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse
+ 44, // 48: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse
+ 31, // 49: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse
+ 40, // 50: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse
+ 46, // 51: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse
+ 30, // [30:52] is the sub-list for method output_type
+ 8, // [8:30] is the sub-list for method input_type
8, // [8:8] is the sub-list for extension type_name
8, // [8:8] is the sub-list for extension extendee
0, // [0:8] is the sub-list for field type_name
@@ -2944,7 +3070,7 @@ func file_proto_worker_worker_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),
NumEnums: 1,
- NumMessages: 47,
+ NumMessages: 49,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index 91acad5f..665464fe 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -35,6 +35,8 @@ service SandboxWorker {
rpc BuildTemplate(BuildTemplateRequest) returns (BuildTemplateResponse);
rpc GetSandboxStats(GetSandboxStatsRequest) returns (GetSandboxStatsResponse);
+
+ rpc SetSandboxLimits(SetSandboxLimitsRequest) returns (SetSandboxLimitsResponse);
}
message CreateSandboxRequest {
@@ -288,3 +290,13 @@ message RestoreCheckpointRequest {
message RestoreCheckpointResponse {
bool success = 1;
}
+
+message SetSandboxLimitsRequest {
+ string sandbox_id = 1;
+ int32 max_pids = 2;
+ int64 max_memory_bytes = 3;
+ int64 cpu_max_usec = 4;
+ int64 cpu_period_usec = 5;
+}
+
+message SetSandboxLimitsResponse {}
diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.go
index 9696af6d..226178bd 100644
--- a/proto/worker/worker_grpc.pb.go
+++ b/proto/worker/worker_grpc.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.1
-// - protoc v7.34.0
+// - protoc v6.33.4
// source: proto/worker/worker.proto
package worker
@@ -40,6 +40,7 @@ const (
SandboxWorker_RestoreCheckpoint_FullMethodName = "/worker.SandboxWorker/RestoreCheckpoint"
SandboxWorker_BuildTemplate_FullMethodName = "/worker.SandboxWorker/BuildTemplate"
SandboxWorker_GetSandboxStats_FullMethodName = "/worker.SandboxWorker/GetSandboxStats"
+ SandboxWorker_SetSandboxLimits_FullMethodName = "/worker.SandboxWorker/SetSandboxLimits"
)
// SandboxWorkerClient is the client API for SandboxWorker service.
@@ -67,6 +68,7 @@ type SandboxWorkerClient interface {
RestoreCheckpoint(ctx context.Context, in *RestoreCheckpointRequest, opts ...grpc.CallOption) (*RestoreCheckpointResponse, error)
BuildTemplate(ctx context.Context, in *BuildTemplateRequest, opts ...grpc.CallOption) (*BuildTemplateResponse, error)
GetSandboxStats(ctx context.Context, in *GetSandboxStatsRequest, opts ...grpc.CallOption) (*GetSandboxStatsResponse, error)
+ SetSandboxLimits(ctx context.Context, in *SetSandboxLimitsRequest, opts ...grpc.CallOption) (*SetSandboxLimitsResponse, error)
}
type sandboxWorkerClient struct {
@@ -299,6 +301,16 @@ func (c *sandboxWorkerClient) GetSandboxStats(ctx context.Context, in *GetSandbo
return out, nil
}
+func (c *sandboxWorkerClient) SetSandboxLimits(ctx context.Context, in *SetSandboxLimitsRequest, opts ...grpc.CallOption) (*SetSandboxLimitsResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(SetSandboxLimitsResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_SetSandboxLimits_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// SandboxWorkerServer is the server API for SandboxWorker service.
// All implementations must embed UnimplementedSandboxWorkerServer
// for forward compatibility.
@@ -324,6 +336,7 @@ type SandboxWorkerServer interface {
RestoreCheckpoint(context.Context, *RestoreCheckpointRequest) (*RestoreCheckpointResponse, error)
BuildTemplate(context.Context, *BuildTemplateRequest) (*BuildTemplateResponse, error)
GetSandboxStats(context.Context, *GetSandboxStatsRequest) (*GetSandboxStatsResponse, error)
+ SetSandboxLimits(context.Context, *SetSandboxLimitsRequest) (*SetSandboxLimitsResponse, error)
mustEmbedUnimplementedSandboxWorkerServer()
}
@@ -397,6 +410,9 @@ func (UnimplementedSandboxWorkerServer) BuildTemplate(context.Context, *BuildTem
func (UnimplementedSandboxWorkerServer) GetSandboxStats(context.Context, *GetSandboxStatsRequest) (*GetSandboxStatsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method GetSandboxStats not implemented")
}
+func (UnimplementedSandboxWorkerServer) SetSandboxLimits(context.Context, *SetSandboxLimitsRequest) (*SetSandboxLimitsResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method SetSandboxLimits not implemented")
+}
func (UnimplementedSandboxWorkerServer) mustEmbedUnimplementedSandboxWorkerServer() {}
func (UnimplementedSandboxWorkerServer) testEmbeddedByValue() {}
@@ -778,6 +794,24 @@ func _SandboxWorker_GetSandboxStats_Handler(srv interface{}, ctx context.Context
return interceptor(ctx, in, info, handler)
}
+func _SandboxWorker_SetSandboxLimits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(SetSandboxLimitsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).SetSandboxLimits(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_SetSandboxLimits_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).SetSandboxLimits(ctx, req.(*SetSandboxLimitsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// SandboxWorker_ServiceDesc is the grpc.ServiceDesc for SandboxWorker service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -861,6 +895,10 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{
MethodName: "GetSandboxStats",
Handler: _SandboxWorker_GetSandboxStats_Handler,
},
+ {
+ MethodName: "SetSandboxLimits",
+ Handler: _SandboxWorker_SetSandboxLimits_Handler,
+ },
},
Streams: []grpc.StreamDesc{
{