| @@ -422,6 +422,24 @@ build_fc_netns_exec() { | |||
| 422 | log_info "✓ ${BIN_DIR}/fc-netns-exec 构建完成" | 422 | log_info "✓ ${BIN_DIR}/fc-netns-exec 构建完成" |
| 423 | } | 423 | } |
| 424 | 424 | ||
| 425 | +# 构建 stratovirt-netns-exec(不需要 CGO) | ||
| 426 | +build_stratovirt_netns_exec() { | ||
| 427 | + local orch_dir="packages/orchestrator" | ||
| 428 | + local exec_dir="$orch_dir/cmd/stratovirt-netns-exec" | ||
| 429 | + | ||
| 430 | + if [ ! -d "$exec_dir" ]; then | ||
| 431 | + log_error "✗ 目录不存在: $exec_dir" | ||
| 432 | + return | ||
| 433 | + fi | ||
| 434 | + | ||
| 435 | + log_warn "→ 构建 $orch_dir 的 stratovirt-netns-exec" | ||
| 436 | + ( | ||
| 437 | + cd "$orch_dir" | ||
| 438 | + CGO_ENABLED=0 GOOS=linux go build -o "../../${BIN_DIR}/stratovirt-netns-exec" ./cmd/stratovirt-netns-exec | ||
| 439 | + ) | ||
| 440 | + log_info "✓ ${BIN_DIR}/stratovirt-netns-exec 构建完成" | ||
| 441 | +} | ||
| 442 | + | ||
| 425 | # 构建 CRI 多路复用器 | 443 | # 构建 CRI 多路复用器 |
| 426 | build_cri_multiplex() { | 444 | build_cri_multiplex() { |
| 427 | if ! $ENABLE_CRI_MUX; then | 445 | if ! $ENABLE_CRI_MUX; then |
| @@ -475,7 +493,7 @@ build_docker_images() { | |||
| 475 | # 定义镜像构建任务:镜像名|Dockerfile|构建上下文|需要的二进制 | 493 | # 定义镜像构建任务:镜像名|Dockerfile|构建上下文|需要的二进制 |
| 476 | local image_tasks=( | 494 | local image_tasks=( |
| 477 | "${API_IMAGE_NAME}|packages/api/Dockerfile|packages/api|api" | 495 | "${API_IMAGE_NAME}|packages/api/Dockerfile|packages/api|api" |
| 478 | - "${ORCHESTRATOR_IMAGE_NAME}|packages/orchestrator/Dockerfile|packages/orchestrator|orchestrator,fc-netns-exec" | 496 | + "${ORCHESTRATOR_IMAGE_NAME}|packages/orchestrator/Dockerfile|packages/orchestrator|orchestrator,fc-netns-exec,stratovirt-netns-exec" |
| 479 | "${CLIENT_PROXY_IMAGE_NAME}|packages/client-proxy/Dockerfile|packages/client-proxy|client-proxy" | 497 | "${CLIENT_PROXY_IMAGE_NAME}|packages/client-proxy/Dockerfile|packages/client-proxy|client-proxy" |
| 480 | "${WEBHOOK_IMAGE_NAME}|e2b-webhook/Dockerfile.scratch|e2b-webhook|e2b-webhook" | 498 | "${WEBHOOK_IMAGE_NAME}|e2b-webhook/Dockerfile.scratch|e2b-webhook|e2b-webhook" |
| 481 | ) | 499 | ) |
| @@ -944,6 +962,7 @@ else | |||
| 944 | build_main_binaries | 962 | build_main_binaries |
| 945 | build_db_tools | 963 | build_db_tools |
| 946 | build_fc_netns_exec | 964 | build_fc_netns_exec |
| 965 | + build_stratovirt_netns_exec | ||
| 947 | fi | 966 | fi |
| 948 | 967 | ||
| 949 | # ============================================================================ | 968 | # ============================================================================ |
| @@ -160,7 +160,10 @@ export ENVD_TIMEOUT=60s | |||
| 160 | export ALLOW_SANDBOX_INTERNET=true | 160 | export ALLOW_SANDBOX_INTERNET=true |
| 161 | export SHARED_CHUNK_CACHE_PATH= | 161 | export SHARED_CHUNK_CACHE_PATH= |
| 162 | export E2B_FC_NETNS_EXEC_HELPER=/opt/e2b-infra/bin/fc-netns-exec | 162 | export E2B_FC_NETNS_EXEC_HELPER=/opt/e2b-infra/bin/fc-netns-exec |
| 163 | +export E2B_STRATOVIRT_NETNS_EXEC_HELPER=/opt/e2b-infra/bin/stratovirt-netns-exec | ||
| 163 | export E2B_USE_FC_NETNS_EXEC_HELPER=true | 164 | export E2B_USE_FC_NETNS_EXEC_HELPER=true |
| 165 | +# 是否为每个沙箱创建统计 cgroup;VMM 目前未放入该 cgroup,默认关闭 | ||
| 166 | +export E2B_SANDBOX_CGROUP_ENABLED=false | ||
| 164 | 167 | ||
| 165 | # ============================================================================= | 168 | # ============================================================================= |
| 166 | # 9. Mooncake 存储后端 | 169 | # 9. Mooncake 存储后端 |
| @@ -495,7 +495,7 @@ $TEMPLATE_MANAGER_PORT $DOCKER_REVERSE_PROXY_PORT $LOKI_SERVICE_PORT $OTEL_COLLE | |||
| 495 | $LOGS_PROXY_PORT $LOGS_HEALTH_PROXY_PORT $STORAGE_PROVIDER $ARTIFACTS_REGISTRY_PROVIDER $API_NODE_POOL $BUILD_NODE_POOL $LOGS_COLLECTOR_VERSION $LOKI_VERSION $OTEL_COLLECTOR_VERSION $CLICKHOUSE_SERVER_PORT $CLICKHOUSE_METRICS_PORT $API_GRPC_PORT $EDGE_HEALTH_PORT $API_GRPC_ADDRESS $DOMAIN_NAME $SANDBOX_STORAGE_BACKEND $ORCHESTRATOR_TYPE $ORCHESTRATOR_STATIC_NODES | 495 | $LOGS_PROXY_PORT $LOGS_HEALTH_PROXY_PORT $STORAGE_PROVIDER $ARTIFACTS_REGISTRY_PROVIDER $API_NODE_POOL $BUILD_NODE_POOL $LOGS_COLLECTOR_VERSION $LOKI_VERSION $OTEL_COLLECTOR_VERSION $CLICKHOUSE_SERVER_PORT $CLICKHOUSE_METRICS_PORT $API_GRPC_PORT $EDGE_HEALTH_PORT $API_GRPC_ADDRESS $DOMAIN_NAME $SANDBOX_STORAGE_BACKEND $ORCHESTRATOR_TYPE $ORCHESTRATOR_STATIC_NODES |
| 496 | $HARBOR_CERTS_DIR $NODE_ID $GLOG_logtostderr $MOONCAKE_MASTER_ADDR $MOONCAKE_METADATA_SERVER $MOONCAKE_LOCAL_BUFFER_SIZE $MOONCAKE_GLOBAL_SEGMENT_SIZE $MOONCAKE_PROTOCOL $MC_URMA_TRANS_MODE $MOONCAKE_DEVICE_NAME $MC_LOG_ENABLE $MC_LOG_DIR $MC_LOG_LEVEL $MC_STORE_LOCAL_HOT_CACHE_USE_SHM $MC_STORE_LOCAL_HOT_BLOCK_SIZE $MC_STORE_LOCAL_HOT_ADMISSION_THRESHOLD $MC_SLICE_SIZE $MC_WORKERS_PER_CTX $MC_MAX_WR $MC_URMA_BONDING_MULTIPATH_ENABLE $MC_UB_NUMA_AFFINITY_ENABLE | 496 | $HARBOR_CERTS_DIR $NODE_ID $GLOG_logtostderr $MOONCAKE_MASTER_ADDR $MOONCAKE_METADATA_SERVER $MOONCAKE_LOCAL_BUFFER_SIZE $MOONCAKE_GLOBAL_SEGMENT_SIZE $MOONCAKE_PROTOCOL $MC_URMA_TRANS_MODE $MOONCAKE_DEVICE_NAME $MC_LOG_ENABLE $MC_LOG_DIR $MC_LOG_LEVEL $MC_STORE_LOCAL_HOT_CACHE_USE_SHM $MC_STORE_LOCAL_HOT_BLOCK_SIZE $MC_STORE_LOCAL_HOT_ADMISSION_THRESHOLD $MC_SLICE_SIZE $MC_WORKERS_PER_CTX $MC_MAX_WR $MC_URMA_BONDING_MULTIPATH_ENABLE $MC_UB_NUMA_AFFINITY_ENABLE |
| 497 | $MOONCAKE_UPLOAD_SIGNING_SECRET $MOONCAKE_UPLOAD_MAX_BYTES | 497 | $MOONCAKE_UPLOAD_SIGNING_SECRET $MOONCAKE_UPLOAD_MAX_BYTES |
| 498 | -$E2B_FC_NETNS_EXEC_HELPER $E2B_USE_FC_NETNS_EXEC_HELPER | 498 | +$E2B_FC_NETNS_EXEC_HELPER $E2B_USE_FC_NETNS_EXEC_HELPER $E2B_STRATOVIRT_NETNS_EXEC_HELPER $E2B_SANDBOX_CGROUP_ENABLED |
| 499 | $API_RESOURCES_CPU_COUNT $API_RESOURCES_MEMORY_MB $API_LIMITS_CPU_COUNT $API_LIMITS_MEMORY_MB | 499 | $API_RESOURCES_CPU_COUNT $API_RESOURCES_MEMORY_MB $API_LIMITS_CPU_COUNT $API_LIMITS_MEMORY_MB |
| 500 | $TEMPLATE_MANAGER_RESOURCES_CPU_COUNT $TEMPLATE_MANAGER_RESOURCES_MEMORY_MB $TEMPLATE_MANAGER_LIMITS_CPU_COUNT $TEMPLATE_MANAGER_LIMITS_MEMORY_MB | 500 | $TEMPLATE_MANAGER_RESOURCES_CPU_COUNT $TEMPLATE_MANAGER_RESOURCES_MEMORY_MB $TEMPLATE_MANAGER_LIMITS_CPU_COUNT $TEMPLATE_MANAGER_LIMITS_MEMORY_MB |
| 501 | $COMPRESS_ENABLED $COMPRESS_TYPE $COMPRESS_LEVEL' | 501 | $COMPRESS_ENABLED $COMPRESS_TYPE $COMPRESS_LEVEL' |
| @@ -23,8 +23,8 @@ RUN update-alternatives --set iptables /usr/sbin/iptables-nft || true | |||
| 23 | COPY orchestrator /usr/bin/orchestrator | 23 | COPY orchestrator /usr/bin/orchestrator |
| 24 | RUN chmod +x /usr/bin/orchestrator | 24 | RUN chmod +x /usr/bin/orchestrator |
| 25 | RUN mkdir -p /opt/e2b-infra/bin/ | 25 | RUN mkdir -p /opt/e2b-infra/bin/ |
| 26 | -COPY fc-netns-exec /opt/e2b-infra/bin/ | 26 | +COPY fc-netns-exec stratovirt-netns-exec /opt/e2b-infra/bin/ |
| 27 | -RUN chmod +x /opt/e2b-infra/bin/fc-netns-exec | 27 | +RUN chmod +x /opt/e2b-infra/bin/fc-netns-exec /opt/e2b-infra/bin/stratovirt-netns-exec |
| 28 | 28 | ||
| 29 | #将/opt/e2b-infra/bin下mooncake相关安装到系统路径下 | 29 | #将/opt/e2b-infra/bin下mooncake相关安装到系统路径下 |
| 30 | COPY *.rpm /opt/e2b-infra/bin/ | 30 | COPY *.rpm /opt/e2b-infra/bin/ |
| @@ -54,7 +54,9 @@ job "template-manager" { | |||
| 54 | COMPRESS_TYPE = "${COMPRESS_TYPE}" | 54 | COMPRESS_TYPE = "${COMPRESS_TYPE}" |
| 55 | COMPRESS_LEVEL = "${COMPRESS_LEVEL}" | 55 | COMPRESS_LEVEL = "${COMPRESS_LEVEL}" |
| 56 | E2B_FC_NETNS_EXEC_HELPER = "${E2B_FC_NETNS_EXEC_HELPER}" | 56 | E2B_FC_NETNS_EXEC_HELPER = "${E2B_FC_NETNS_EXEC_HELPER}" |
| 57 | + E2B_STRATOVIRT_NETNS_EXEC_HELPER = "${E2B_STRATOVIRT_NETNS_EXEC_HELPER}" | ||
| 57 | E2B_USE_FC_NETNS_EXEC_HELPER = "${E2B_USE_FC_NETNS_EXEC_HELPER}" | 58 | E2B_USE_FC_NETNS_EXEC_HELPER = "${E2B_USE_FC_NETNS_EXEC_HELPER}" |
| 59 | + E2B_SANDBOX_CGROUP_ENABLED = "${E2B_SANDBOX_CGROUP_ENABLED}" | ||
| 58 | GRPC_PORT = "${TEMPLATE_MANAGER_PORT}" | 60 | GRPC_PORT = "${TEMPLATE_MANAGER_PORT}" |
| 59 | GIN_MODE = "release" | 61 | GIN_MODE = "release" |
| 60 | STORAGE_PROVIDER = "${STORAGE_PROVIDER}" | 62 | STORAGE_PROVIDER = "${STORAGE_PROVIDER}" |
| @@ -152,7 +152,7 @@ func (tm *TemplateManager) CreateTemplate( | |||
| 152 | DiskSizeMB: int32(diskSizeMB), | 152 | DiskSizeMB: int32(diskSizeMB), |
| 153 | KernelVersion: kernelVersion, | 153 | KernelVersion: kernelVersion, |
| 154 | FirecrackerVersion: firecrackerVersion, | 154 | FirecrackerVersion: firecrackerVersion, |
| 155 | - HugePages: resolvedOsType != api.Android && features.HasHugePages(), | 155 | + HugePages: features.HasHugePages(), |
| 156 | StartCommand: startCmd, | 156 | StartCommand: startCmd, |
| 157 | ReadyCommand: readyCmd, | 157 | ReadyCommand: readyCmd, |
| 158 | Force: force, | 158 | Force: force, |
| @@ -2,7 +2,8 @@ FROM ubuntu:24.04 | |||
| 2 | RUN apt-get update && apt-get install -y iptables iproute2 rsync && rm -rf /var/lib/apt/lists/* | 2 | RUN apt-get update && apt-get install -y iptables iproute2 rsync && rm -rf /var/lib/apt/lists/* |
| 3 | COPY orchestrator /usr/bin/orchestrator | 3 | COPY orchestrator /usr/bin/orchestrator |
| 4 | COPY fc-netns-exec /opt/e2b-infra/bin/fc-netns-exec | 4 | COPY fc-netns-exec /opt/e2b-infra/bin/fc-netns-exec |
| 5 | -RUN chmod +x /usr/bin/orchestrator /opt/e2b-infra/bin/fc-netns-exec | 5 | +COPY stratovirt-netns-exec /opt/e2b-infra/bin/stratovirt-netns-exec |
| 6 | +RUN chmod +x /usr/bin/orchestrator /opt/e2b-infra/bin/fc-netns-exec /opt/e2b-infra/bin/stratovirt-netns-exec | ||
| 6 | 7 | ||
| 7 | ENTRYPOINT [ "/usr/bin/orchestrator"] | 8 | ENTRYPOINT [ "/usr/bin/orchestrator"] |
| 8 | 9 | ||
| @@ -22,6 +22,7 @@ build: | |||
| 22 | CGO_ENABLED=1 GOOS=linux go build -o bin/orchestrator -ldflags "-X=main.commitSHA=$(COMMIT_SHA)" . | 22 | CGO_ENABLED=1 GOOS=linux go build -o bin/orchestrator -ldflags "-X=main.commitSHA=$(COMMIT_SHA)" . |
| 23 | CGO_ENABLED=1 GOOS=linux go build -o bin/clean-nfs-cache -ldflags "-X=main.commitSHA=$(COMMIT_SHA)" ./cmd/clean-nfs-cache | 23 | CGO_ENABLED=1 GOOS=linux go build -o bin/clean-nfs-cache -ldflags "-X=main.commitSHA=$(COMMIT_SHA)" ./cmd/clean-nfs-cache |
| 24 | CGO_ENABLED=0 GOOS=linux go build -o bin/fc-netns-exec ./cmd/fc-netns-exec | 24 | CGO_ENABLED=0 GOOS=linux go build -o bin/fc-netns-exec ./cmd/fc-netns-exec |
| 25 | + CGO_ENABLED=0 GOOS=linux go build -o bin/stratovirt-netns-exec ./cmd/stratovirt-netns-exec | ||
| 25 | 26 | ||
| 26 | .PHONY: build-local | 27 | .PHONY: build-local |
| 27 | build-local: | 28 | build-local: |
| @@ -30,6 +31,7 @@ build-local: | |||
| 30 | CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o bin/orchestrator -ldflags "-X=main.commitSHA=$(COMMIT_SHA)" . | 31 | CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o bin/orchestrator -ldflags "-X=main.commitSHA=$(COMMIT_SHA)" . |
| 31 | CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o bin/clean-nfs-cache -ldflags "-X=main.commitSHA=$(COMMIT_SHA)" ./cmd/clean-nfs-cache | 32 | CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o bin/clean-nfs-cache -ldflags "-X=main.commitSHA=$(COMMIT_SHA)" ./cmd/clean-nfs-cache |
| 32 | CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o bin/fc-netns-exec ./cmd/fc-netns-exec | 33 | CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o bin/fc-netns-exec ./cmd/fc-netns-exec |
| 34 | + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o bin/stratovirt-netns-exec ./cmd/stratovirt-netns-exec | ||
| 33 | 35 | ||
| 34 | .PHONY: build-debug | 36 | .PHONY: build-debug |
| 35 | build-debug: | 37 | build-debug: |
| @@ -0,0 +1,107 @@ | |||
| 1 | +//go:build linux | ||
| 2 | + | ||
| 3 | +package main | ||
| 4 | + | ||
| 5 | +import ( | ||
| 6 | + "errors" | ||
| 7 | + "flag" | ||
| 8 | + "fmt" | ||
| 9 | + "io" | ||
| 10 | + "os" | ||
| 11 | + "path/filepath" | ||
| 12 | + | ||
| 13 | + "golang.org/x/sys/unix" | ||
| 14 | +) | ||
| 15 | + | ||
| 16 | +// Android restore preparation creates a private tmpfs, three disk links, | ||
| 17 | +// and host-visible FIFOs before entering the network namespace. | ||
| 18 | +type prepareAndroidArgs struct { | ||
| 19 | + sandboxDir string | ||
| 20 | + rootfsSrc string | ||
| 21 | + persistentSrc string | ||
| 22 | + sdcardSrc string | ||
| 23 | + pipeDir string | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +func prepareAndroidMain(args []string) { | ||
后面StratoVirt也要支持linux沙箱,而且这快代码和fc版本重复度太高,所以建议要和fc-netns-exec合并一下。 交流一下咋合并 ![]() ![]() | |||
| 27 | + fs := flag.NewFlagSet("prepare-android", flag.ContinueOnError) | ||
| 28 | + fs.SetOutput(io.Discard) | ||
| 29 | + var prep prepareAndroidArgs | ||
| 30 | + var probe bool | ||
| 31 | + fs.StringVar(&prep.sandboxDir, "sandbox-dir", "", "sandbox tmpfs directory") | ||
| 32 | + fs.StringVar(&prep.rootfsSrc, "rootfs-src", "", "rootfs link source") | ||
| 33 | + fs.StringVar(&prep.persistentSrc, "persistent-src", "", "persistent disk link source") | ||
| 34 | + fs.StringVar(&prep.sdcardSrc, "sdcard-src", "", "sdcard link source") | ||
| 35 | + fs.StringVar(&prep.pipeDir, "pipe-dir", "", "host-visible Android FIFO directory") | ||
| 36 | + fs.BoolVar(&probe, "probe", false, "probe prepare-android capability and exit") | ||
| 37 | + if err := fs.Parse(args); err != nil { | ||
| 38 | + fmt.Fprintf(os.Stderr, "stratovirt-netns-exec: prepare-android: %v\n", err) | ||
| 39 | + os.Exit(2) | ||
| 40 | + } | ||
| 41 | + if probe { | ||
| 42 | + fmt.Println("prepare-android ok") | ||
| 43 | + return | ||
| 44 | + } | ||
| 45 | + rest := fs.Args() | ||
| 46 | + if len(rest) < 2 { | ||
| 47 | + fmt.Fprintln(os.Stderr, "usage: stratovirt-netns-exec --prepare-android <flags> <netns-name-or-path> <command> [args...]") | ||
| 48 | + os.Exit(2) | ||
| 49 | + } | ||
| 50 | + if err := prep.validate(); err != nil { | ||
| 51 | + fmt.Fprintf(os.Stderr, "stratovirt-netns-exec: prepare-android: %v\n", err) | ||
| 52 | + os.Exit(2) | ||
| 53 | + } | ||
| 54 | + if err := prep.run(); err != nil { | ||
| 55 | + fmt.Fprintf(os.Stderr, "stratovirt-netns-exec: prepare-android: %v\n", err) | ||
| 56 | + os.Exit(1) | ||
| 57 | + } | ||
| 58 | + joinNetns(rest[0]) | ||
| 59 | + execCommand(rest[1], rest[1:]) | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +func (p *prepareAndroidArgs) validate() error { | ||
| 63 | + for name, value := range map[string]string{ | ||
| 64 | + "sandbox-dir": p.sandboxDir, "rootfs-src": p.rootfsSrc, | ||
| 65 | + "persistent-src": p.persistentSrc, "sdcard-src": p.sdcardSrc, | ||
| 66 | + "pipe-dir": p.pipeDir, | ||
| 67 | + } { | ||
| 68 | + if value == "" { | ||
| 69 | + return fmt.Errorf("missing required flag -%s", name) | ||
| 70 | + } | ||
| 71 | + } | ||
| 72 | + return nil | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +func (p *prepareAndroidArgs) run() error { | ||
| 76 | + if err := unix.Mount("", "/", "", unix.MS_REC|unix.MS_PRIVATE, ""); err != nil { | ||
| 77 | + return fmt.Errorf("mount --make-rprivate /: %w", err) | ||
| 78 | + } | ||
| 79 | + if err := os.MkdirAll(p.sandboxDir, 0o755); err != nil { | ||
| 80 | + return fmt.Errorf("mkdir sandbox: %w", err) | ||
| 81 | + } | ||
| 82 | + if err := unix.Mount("tmpfs", p.sandboxDir, "tmpfs", 0, ""); err != nil { | ||
| 83 | + return fmt.Errorf("mount sandbox tmpfs: %w", err) | ||
| 84 | + } | ||
| 85 | + for i, src := range []string{p.rootfsSrc, p.persistentSrc, p.sdcardSrc} { | ||
| 86 | + if err := os.Symlink(src, filepath.Join(p.sandboxDir, fmt.Sprintf("android-disk-%d.raw", i))); err != nil { | ||
| 87 | + return fmt.Errorf("symlink Android disk %d: %w", i, err) | ||
| 88 | + } | ||
| 89 | + } | ||
| 90 | + if err := os.MkdirAll(p.pipeDir, 0o755); err != nil { | ||
| 91 | + return fmt.Errorf("mkdir Android pipes: %w", err) | ||
| 92 | + } | ||
| 93 | + for _, name := range []string{"keymaster_fifo_vm", "gatekeeper_fifo_vm", "oemlock_fifo_vm", "keymint_fifo_vm"} { | ||
| 94 | + for _, suffix := range []string{".in", ".out"} { | ||
| 95 | + path := filepath.Join(p.pipeDir, name+suffix) | ||
| 96 | + if err := unix.Mkfifo(path, 0o600); err != nil { | ||
| 97 | + // Host services may have already created the shared FIFO. | ||
| 98 | + info, statErr := os.Lstat(path) | ||
| 99 | + if errors.Is(err, unix.EEXIST) && statErr == nil && info.Mode()&os.ModeNamedPipe != 0 { | ||
| 100 | + continue | ||
| 101 | + } | ||
| 102 | + return fmt.Errorf("mkfifo %s: %w", path, err) | ||
| 103 | + } | ||
| 104 | + } | ||
| 105 | + } | ||
| 106 | + return nil | ||
| 107 | +} | ||
| @@ -0,0 +1,81 @@ | |||
| 1 | +//go:build linux | ||
| 2 | + | ||
| 3 | +package main | ||
| 4 | + | ||
| 5 | +import ( | ||
| 6 | + "fmt" | ||
| 7 | + "os" | ||
| 8 | + "path/filepath" | ||
| 9 | + "runtime" | ||
| 10 | + "strconv" | ||
| 11 | + | ||
| 12 | + "golang.org/x/sys/unix" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +const netnsDir = "/run/netns" | ||
| 16 | + | ||
| 17 | +// The orchestrator passes an open netns FD because the pinned mount namespace | ||
| 18 | +// does not contain the network pool's namespace mounts. | ||
| 19 | +const netnsFDEnv = "E2B_STRATOVIRT_NETNS_FD" | ||
| 20 | + | ||
| 21 | +func main() { | ||
| 22 | + runtime.LockOSThread() | ||
| 23 | + | ||
| 24 | + if len(os.Args) > 1 && os.Args[1] == "--prepare-android" { | ||
| 25 | + prepareAndroidMain(os.Args[2:]) | ||
| 26 | + return | ||
| 27 | + } | ||
| 28 | + | ||
| 29 | + if len(os.Args) < 3 { | ||
| 30 | + fmt.Fprintf(os.Stderr, "usage: %s [--prepare-android <flags>] <netns-name-or-path> <command> [args...]\n", os.Args[0]) | ||
| 31 | + os.Exit(2) | ||
| 32 | + } | ||
| 33 | + | ||
| 34 | + joinNetns(os.Args[1]) | ||
| 35 | + execCommand(os.Args[2], os.Args[2:]) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +func joinNetns(namespace string) { | ||
| 39 | + if fdEnv := os.Getenv(netnsFDEnv); fdEnv != "" { | ||
| 40 | + fd, err := strconv.Atoi(fdEnv) | ||
| 41 | + if err != nil { | ||
| 42 | + fmt.Fprintf(os.Stderr, "stratovirt-netns-exec: invalid %s %q: %v\n", netnsFDEnv, fdEnv, err) | ||
| 43 | + os.Exit(1) | ||
| 44 | + } | ||
| 45 | + if err := unix.Setns(fd, unix.CLONE_NEWNET); err != nil { | ||
| 46 | + fmt.Fprintf(os.Stderr, "stratovirt-netns-exec: setns(fd %d, CLONE_NEWNET): %v\n", fd, err) | ||
| 47 | + os.Exit(1) | ||
| 48 | + } | ||
| 49 | + unix.Close(fd) | ||
| 50 | + os.Unsetenv(netnsFDEnv) | ||
| 51 | + return | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + nsPath := namespacePath(namespace) | ||
| 55 | + fd, err := unix.Open(nsPath, unix.O_RDONLY|unix.O_CLOEXEC, 0) | ||
| 56 | + if err != nil { | ||
| 57 | + fmt.Fprintf(os.Stderr, "stratovirt-netns-exec: open network namespace %q: %v\n", nsPath, err) | ||
| 58 | + os.Exit(1) | ||
| 59 | + } | ||
| 60 | + defer unix.Close(fd) | ||
| 61 | + | ||
| 62 | + if err := unix.Setns(fd, unix.CLONE_NEWNET); err != nil { | ||
| 63 | + fmt.Fprintf(os.Stderr, "stratovirt-netns-exec: setns(%q, CLONE_NEWNET): %v\n", nsPath, err) | ||
| 64 | + os.Exit(1) | ||
| 65 | + } | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +func execCommand(command string, commandArgs []string) { | ||
| 69 | + if err := unix.Exec(command, commandArgs, os.Environ()); err != nil { | ||
| 70 | + fmt.Fprintf(os.Stderr, "stratovirt-netns-exec: exec %q: %v\n", command, err) | ||
| 71 | + os.Exit(1) | ||
| 72 | + } | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +func namespacePath(namespace string) string { | ||
| 76 | + if filepath.IsAbs(namespace) { | ||
| 77 | + return filepath.Clean(namespace) | ||
| 78 | + } | ||
| 79 | + | ||
| 80 | + return filepath.Join(netnsDir, namespace) | ||
| 81 | +} | ||
| @@ -17,6 +17,7 @@ type BuilderConfig struct { | |||
| 17 | DomainName string `env:"DOMAIN_NAME" envDefault:""` | 17 | DomainName string `env:"DOMAIN_NAME" envDefault:""` |
| 18 | EnvdTimeout time.Duration `env:"ENVD_TIMEOUT" envDefault:"10s"` | 18 | EnvdTimeout time.Duration `env:"ENVD_TIMEOUT" envDefault:"10s"` |
| 19 | FirecrackerNetnsExecHelper string `env:"E2B_FC_NETNS_EXEC_HELPER" envDefault:"/opt/e2b-infra/bin/fc-netns-exec"` | 19 | FirecrackerNetnsExecHelper string `env:"E2B_FC_NETNS_EXEC_HELPER" envDefault:"/opt/e2b-infra/bin/fc-netns-exec"` |
| 20 | + StratoVirtNetnsExecHelper string `env:"E2B_STRATOVIRT_NETNS_EXEC_HELPER" envDefault:"/opt/e2b-infra/bin/stratovirt-netns-exec"` | ||
| 20 | FirecrackerVersionsDir string `env:"FIRECRACKER_VERSIONS_DIR" envDefault:"/fc-versions"` | 21 | FirecrackerVersionsDir string `env:"FIRECRACKER_VERSIONS_DIR" envDefault:"/fc-versions"` |
| 21 | StratoVirtVersionsDir string `env:"STRATOVIRT_VERSIONS_DIR" envDefault:"/stratovirt-versions"` | 22 | StratoVirtVersionsDir string `env:"STRATOVIRT_VERSIONS_DIR" envDefault:"/stratovirt-versions"` |
| 22 | HostEnvdPath string `env:"HOST_ENVD_PATH" envDefault:"/fc-envd/envd"` | 23 | HostEnvdPath string `env:"HOST_ENVD_PATH" envDefault:"/fc-envd/envd"` |
| @@ -32,6 +33,10 @@ type BuilderConfig struct { | |||
| 32 | ReadyCheckTimeout time.Duration `env:"READY_CHECK_TIMEOUT" envDefault:"30s"` | 33 | ReadyCheckTimeout time.Duration `env:"READY_CHECK_TIMEOUT" envDefault:"30s"` |
| 33 | ADBVsockPort uint32 `env:"ADB_VSOCK_PORT" envDefault:"5555"` | 34 | ADBVsockPort uint32 `env:"ADB_VSOCK_PORT" envDefault:"5555"` |
| 34 | 35 | ||
| 36 | + // SandboxCgroupEnabled creates a per-sandbox accounting cgroup. It stays off | ||
| 37 | + // until the VMM launchers place their process into that cgroup (UseCgroupFD). | ||
| 38 | + SandboxCgroupEnabled bool `env:"E2B_SANDBOX_CGROUP_ENABLED" envDefault:"false"` | ||
| 39 | + | ||
| 35 | StorageConfig storage.Config | 40 | StorageConfig storage.Config |
| 36 | NetworkConfig network.Config | 41 | NetworkConfig network.Config |
| 37 | } | 42 | } |
| @@ -55,6 +60,7 @@ func makePathsAbsolute(c *BuilderConfig) error { | |||
| 55 | for _, item := range []*string{ | 60 | for _, item := range []*string{ |
| 56 | &c.DefaultCacheDir, | 61 | &c.DefaultCacheDir, |
| 57 | &c.FirecrackerNetnsExecHelper, | 62 | &c.FirecrackerNetnsExecHelper, |
| 63 | + &c.StratoVirtNetnsExecHelper, | ||
| 58 | &c.FirecrackerVersionsDir, | 64 | &c.FirecrackerVersionsDir, |
| 59 | &c.StratoVirtVersionsDir, | 65 | &c.StratoVirtVersionsDir, |
| 60 | &c.HostEnvdPath, | 66 | &c.HostEnvdPath, |
| @@ -102,9 +102,9 @@ func (b *File) Slice(ctx context.Context, off, _ int64) ([]byte, error) { | |||
| 102 | return nil, fmt.Errorf("failed to get mapping: %w", err) | 102 | return nil, fmt.Errorf("failed to get mapping: %w", err) |
| 103 | } | 103 | } |
| 104 | 104 | ||
| 105 | - // Pass empty huge page when the build id is nil. | 105 | + // Match the template block size, as required by UFFD prefetch. |
| 106 | if *buildID == uuid.Nil { | 106 | if *buildID == uuid.Nil { |
| 107 | - return header.EmptyHugePage, nil | 107 | + return header.EmptyHugePage[:b.header.Metadata.BlockSize], nil |
| 108 | } | 108 | } |
| 109 | 109 | ||
| 110 | build, err := b.getBuild(ctx, buildID) | 110 | build, err := b.getBuild(ctx, buildID) |
| @@ -171,6 +171,8 @@ func (p *Process) configure( | |||
| 171 | //// Set up cgroup FD for atomic placement via CLONE_INTO_CGROUP. | 171 | //// Set up cgroup FD for atomic placement via CLONE_INTO_CGROUP. |
| 172 | //// The cgroup is created and owned by the caller (Sandbox); Process only | 172 | //// The cgroup is created and owned by the caller (Sandbox); Process only |
| 173 | //// uses the FD during clone. | 173 | //// uses the FD during clone. |
| 174 | + //// Placement is not enabled yet, so E2B_SANDBOX_CGROUP_ENABLED defaults to | ||
| 175 | + //// false; drop that switch once this is restored. | ||
| 174 | //if cgroupFD != cgroup.NoCgroupFD { | 176 | //if cgroupFD != cgroup.NoCgroupFD { |
| 175 | // p.cmd.SysProcAttr.UseCgroupFD = true | 177 | // p.cmd.SysProcAttr.UseCgroupFD = true |
| 176 | // p.cmd.SysProcAttr.CgroupFD = cgroupFD | 178 | // p.cmd.SysProcAttr.CgroupFD = cgroupFD |
| @@ -22,9 +22,8 @@ type Provider interface { | |||
| 22 | } | 22 | } |
| 23 | 23 | ||
| 24 | const ( | 24 | const ( |
| 25 | - // TODO: Look into optimizing the buffer reads by increasing the buffer size by 28 bytes, | 25 | + // DefaultReceiveBufferSize is the standard NBD request receive buffer size. |
| 26 | - // to account for a request that is 28 bytes of header + 4MB of data (this seems to be preferred kernel buffer size). | 26 | + DefaultReceiveBufferSize = 4 * 1024 * 1024 |
| 27 | - dispatchBufferSize = 4 * 1024 * 1024 | ||
| 28 | // https://sourceforge.net/p/nbd/mailman/message/35081223/ | 27 | // https://sourceforge.net/p/nbd/mailman/message/35081223/ |
| 29 | // 32MB is the maximum buffer size for a single request that should be universally supported. | 28 | // 32MB is the maximum buffer size for a single request that should be universally supported. |
| 30 | dispatchMaxWriteBufferSize = 32 * 1024 * 1024 | 29 | dispatchMaxWriteBufferSize = 32 * 1024 * 1024 |
| @@ -122,8 +121,8 @@ func (d *Dispatch) writeResponse(respError uint32, respHandle uint64, chunk []by | |||
| 122 | * This dispatches incoming NBD requests sequentially to the provider. | 121 | * This dispatches incoming NBD requests sequentially to the provider. |
| 123 | * | 122 | * |
| 124 | */ | 123 | */ |
| 125 | -func (d *Dispatch) Handle(ctx context.Context) error { | 124 | +func (d *Dispatch) Handle(ctx context.Context, receiveBufferSize int) error { |
| 126 | - buffer := make([]byte, dispatchBufferSize) | 125 | + buffer := make([]byte, receiveBufferSize) |
| 127 | wp := 0 | 126 | wp := 0 |
| 128 | 127 | ||
| 129 | request := Request{} | 128 | request := Request{} |
| @@ -62,8 +62,9 @@ type DirectPathMount struct { | |||
| 62 | devicePool *DevicePool | 62 | devicePool *DevicePool |
| 63 | featureFlags *featureflags.Client | 63 | featureFlags *featureflags.Client |
| 64 | 64 | ||
| 65 | - Backend block.Device | 65 | + Backend block.Device |
| 66 | - blockSize uint64 | 66 | + blockSize uint64 |
| 67 | + receiveBufferSize int | ||
| 67 | 68 | ||
| 68 | mu sync.Mutex | 69 | mu sync.Mutex |
| 69 | deviceIndex uint32 | 70 | deviceIndex uint32 |
| @@ -75,15 +76,16 @@ type DirectPathMount struct { | |||
| 75 | handlersWg sync.WaitGroup | 76 | handlersWg sync.WaitGroup |
| 76 | } | 77 | } |
| 77 | 78 | ||
| 78 | -func NewDirectPathMount(b block.Device, devicePool *DevicePool, featureFlags *featureflags.Client) *DirectPathMount { | 79 | +func NewDirectPathMount(b block.Device, devicePool *DevicePool, featureFlags *featureflags.Client, receiveBufferSize int) *DirectPathMount { |
| 79 | return &DirectPathMount{ | 80 | return &DirectPathMount{ |
| 80 | - Backend: b, | 81 | + Backend: b, |
| 81 | - blockSize: 4096, | 82 | + blockSize: 4096, |
| 82 | - devicePool: devicePool, | 83 | + receiveBufferSize: receiveBufferSize, |
| 83 | - featureFlags: featureFlags, | 84 | + devicePool: devicePool, |
| 84 | - socksClient: make([]*os.File, 0), | 85 | + featureFlags: featureFlags, |
| 85 | - socksServer: make([]io.Closer, 0), | 86 | + socksClient: make([]*os.File, 0), |
| 86 | - deviceIndex: math.MaxUint32, | 87 | + socksServer: make([]io.Closer, 0), |
| 88 | + deviceIndex: math.MaxUint32, | ||
| 87 | } | 89 | } |
| 88 | } | 90 | } |
| 89 | 91 | ||
| @@ -182,7 +184,7 @@ func (d *DirectPathMount) Open(ctx context.Context) (retDeviceIndex uint32, err | |||
| 182 | dispatch := NewDispatch(serverc, d.Backend) | 184 | dispatch := NewDispatch(serverc, d.Backend) |
| 183 | // Start reading commands on the socket and dispatching them to our provider | 185 | // Start reading commands on the socket and dispatching them to our provider |
| 184 | d.handlersWg.Go(func() { | 186 | d.handlersWg.Go(func() { |
| 185 | - handleErr := dispatch.Handle(ctx) | 187 | + handleErr := dispatch.Handle(ctx, d.receiveBufferSize) |
| 186 | // The error is expected to happen if the nbd (socket connection) is closed | 188 | // The error is expected to happen if the nbd (socket connection) is closed |
| 187 | logger.L().Info(ctx, "closing handler for NBD commands", | 189 | logger.L().Info(ctx, "closing handler for NBD commands", |
| 188 | zap.Error(handleErr), | 190 | zap.Error(handleErr), |
| @@ -44,7 +44,7 @@ func GetNBDDevice(ctx context.Context, backend block.Device, featureFlags *featu | |||
| 44 | close(poolClosed) | 44 | close(poolClosed) |
| 45 | }() | 45 | }() |
| 46 | 46 | ||
| 47 | - mnt := nbd.NewDirectPathMount(backend, devicePool, featureFlags) | 47 | + mnt := nbd.NewDirectPathMount(backend, devicePool, featureFlags, nbd.DefaultReceiveBufferSize) |
| 48 | 48 | ||
| 49 | mntIndex, err := mnt.Open(ctx) | 49 | mntIndex, err := mnt.Open(ctx) |
| 50 | if err != nil { | 50 | if err != nil { |
| @@ -32,7 +32,7 @@ type NBDProvider struct { | |||
| 32 | devicePool *nbd.DevicePool | 32 | devicePool *nbd.DevicePool |
| 33 | } | 33 | } |
| 34 | 34 | ||
| 35 | -func NewNBDProvider(ctx context.Context, rootfs block.ReadonlyDevice, cachePath string, devicePool *nbd.DevicePool, featureFlags *featureflags.Client) (Provider, error) { | 35 | +func NewNBDProvider(ctx context.Context, rootfs block.ReadonlyDevice, cachePath string, devicePool *nbd.DevicePool, featureFlags *featureflags.Client, receiveBufferSize int) (Provider, error) { |
| 36 | size, err := rootfs.Size(ctx) | 36 | size, err := rootfs.Size(ctx) |
| 37 | if err != nil { | 37 | if err != nil { |
| 38 | return nil, fmt.Errorf("error getting device size: %w", err) | 38 | return nil, fmt.Errorf("error getting device size: %w", err) |
| @@ -47,7 +47,7 @@ func NewNBDProvider(ctx context.Context, rootfs block.ReadonlyDevice, cachePath | |||
| 47 | 47 | ||
| 48 | overlay := block.NewOverlay(rootfs, cache) | 48 | overlay := block.NewOverlay(rootfs, cache) |
| 49 | 49 | ||
| 50 | - mnt := nbd.NewDirectPathMount(overlay, devicePool, featureFlags) | 50 | + mnt := nbd.NewDirectPathMount(overlay, devicePool, featureFlags, receiveBufferSize) |
| 51 | 51 | ||
| 52 | return &NBDProvider{ | 52 | return &NBDProvider{ |
| 53 | mnt: mnt, | 53 | mnt: mnt, |
| @@ -63,6 +63,15 @@ var sandboxHttpClient = http.Client{ | |||
| 63 | Transport: SandboxHttpTransport, | 63 | Transport: SandboxHttpTransport, |
| 64 | } | 64 | } |
| 65 | 65 | ||
| 66 | +func nbdReceiveBufferSize(osType vmm.OsType) int { | ||
| 67 | + if osType == vmm.OsAndroid { | ||
| 68 | + // Android opens multiple NBD disks, each with a buffer per connection. | ||
| 69 | + return 64 * 1024 | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + return nbd.DefaultReceiveBufferSize | ||
| 73 | +} | ||
| 74 | + | ||
| 66 | type Config struct { | 75 | type Config struct { |
| 67 | // TODO: Remove when the rootfs path is constant. | 76 | // TODO: Remove when the rootfs path is constant. |
| 68 | // Only used for v1 rootfs paths format. | 77 | // Only used for v1 rootfs paths format. |
| @@ -338,13 +347,21 @@ func (f *Factory) CreateSandbox( | |||
| 338 | return nil, fmt.Errorf("failed to get template disks: %w", err) | 347 | return nil, fmt.Errorf("failed to get template disks: %w", err) |
| 339 | } | 348 | } |
| 340 | 349 | ||
| 350 | + receiveBufferSize := nbdReceiveBufferSize(config.VMMConfig.OsType.OrDefault()) | ||
| 341 | rootfsProviders := make([]rootfs.Provider, 0, len(disks)) | 351 | rootfsProviders := make([]rootfs.Provider, 0, len(disks)) |
| 342 | for _, disk := range disks { | 352 | for _, disk := range disks { |
| 343 | var provider rootfs.Provider | 353 | var provider rootfs.Provider |
| 344 | if directPath := directDiskPaths[disk.Name]; directPath != "" { | 354 | if directPath := directDiskPaths[disk.Name]; directPath != "" { |
| 345 | provider, err = rootfs.NewDirectProvider(ctx, disk.Device, directPath) | 355 | provider, err = rootfs.NewDirectProvider(ctx, disk.Device, directPath) |
| 346 | } else { | 356 | } else { |
| 347 | - provider, err = rootfs.NewNBDProvider(ctx, disk.Device, sandboxFiles.SandboxCacheDiskPath(f.config.StorageConfig, disk.Name), f.devicePool, f.featureFlags) | 357 | + provider, err = rootfs.NewNBDProvider( |
| 358 | + ctx, | ||
| 359 | + disk.Device, | ||
| 360 | + sandboxFiles.SandboxCacheDiskPath(f.config.StorageConfig, disk.Name), | ||
| 361 | + f.devicePool, | ||
| 362 | + f.featureFlags, | ||
| 363 | + receiveBufferSize, | ||
| 364 | + ) | ||
| 348 | } | 365 | } |
| 349 | if err != nil { | 366 | if err != nil { |
| 350 | return nil, fmt.Errorf("failed to create %s disk provider: %w", disk.Name, err) | 367 | return nil, fmt.Errorf("failed to create %s disk provider: %w", disk.Name, err) |
| @@ -711,6 +728,7 @@ func (f *Factory) ResumeSandbox( | |||
| 711 | zap.L().Sugar().Infof("[ResumeSandbox] t.Disks cost: %.3f ms, traceID=%s", time.Since(tDisks).Seconds()*1000, traceID) | 728 | zap.L().Sugar().Infof("[ResumeSandbox] t.Disks cost: %.3f ms, traceID=%s", time.Since(tDisks).Seconds()*1000, traceID) |
| 712 | 729 | ||
| 713 | tNBD := time.Now() | 730 | tNBD := time.Now() |
| 731 | + receiveBufferSize := nbdReceiveBufferSize(config.VMMConfig.OsType.OrDefault()) | ||
| 714 | rootfsProviders := make([]rootfs.Provider, 0, len(disks)) | 732 | rootfsProviders := make([]rootfs.Provider, 0, len(disks)) |
| 715 | for _, disk := range disks { | 733 | for _, disk := range disks { |
| 716 | provider, providerErr := rootfs.NewNBDProvider( | 734 | provider, providerErr := rootfs.NewNBDProvider( |
| @@ -719,6 +737,7 @@ func (f *Factory) ResumeSandbox( | |||
| 719 | sandboxFiles.SandboxCacheDiskPath(f.config.StorageConfig, disk.Name), | 737 | sandboxFiles.SandboxCacheDiskPath(f.config.StorageConfig, disk.Name), |
| 720 | f.devicePool, | 738 | f.devicePool, |
| 721 | f.featureFlags, | 739 | f.featureFlags, |
| 740 | + receiveBufferSize, | ||
| 722 | ) | 741 | ) |
| 723 | if providerErr != nil { | 742 | if providerErr != nil { |
| 724 | return nil, fmt.Errorf("failed to create %s disk overlay: %w", disk.Name, providerErr) | 743 | return nil, fmt.Errorf("failed to create %s disk overlay: %w", disk.Name, providerErr) |
| @@ -1047,9 +1066,23 @@ func (f *Factory) ResumeSandbox( | |||
| 1047 | } | 1066 | } |
| 1048 | 1067 | ||
| 1049 | if config.VMMConfig.OsType.OrDefault() == vmm.OsAndroid { | 1068 | if config.VMMConfig.OsType.OrDefault() == vmm.OsAndroid { |
| 1050 | - if err := hostservice.RestartGuestRild(ctx, sbx.Slot.HostIPString(), config.Envd.AccessToken, runtime.SandboxID, f.config.ReadyCheckTimeout); err != nil { | 1069 | + rilCtx, cancelRIL := context.WithCancel(execCtx) |
| 1051 | - return nil, fmt.Errorf("failed to restart guest RIL: %w", err) | 1070 | + rilDone := make(chan struct{}) |
| 1052 | - } | 1071 | + go func() { |
| 1072 | + defer close(rilDone) | ||
| 1073 | + defer cancelRIL() | ||
| 1074 | + if err := hostservice.RestartGuestRild(rilCtx, sbx.Slot.HostIPString(), config.Envd.AccessToken, runtime.SandboxID, f.config.ReadyCheckTimeout); err != nil && rilCtx.Err() == nil { | ||
| 1075 | + logger.L().Warn(rilCtx, "failed to restart guest RIL", | ||
改为异步是不是丢失了失败中断恢复的路径 ![]() ![]() | |||
| 1076 | + logger.WithSandboxID(runtime.SandboxID), | ||
| 1077 | + zap.Error(err)) | ||
| 1078 | + } | ||
| 1079 | + }() | ||
| 1080 | + // Finish the background request before stopping the VM and recycling its IP. | ||
| 1081 | + cleanup.AddPriority(ctx, func(context.Context) error { | ||
| 1082 | + cancelRIL() | ||
| 1083 | + <-rilDone | ||
| 1084 | + return nil | ||
| 1085 | + }) | ||
🟡 Medium Priority 改动前 失败模式:guest rild 重启失败(例如 guest 内部 hostservice 尚未就绪、连接被拒、ReadyCheckTimeout 超时等)时, 建议:不要把 RIL 重启失败完全吞掉:至少用一个可控的错误通道(如记录到 sbx 的健康检查结果/上报指标),或在后台任务失败后用 ![]() ![]() Incorrect? | |||
| 1053 | } | 1086 | } |
| 1054 | 1087 | ||
| 1055 | if f.featureFlags.BoolFlag(execCtx, featureflags.HostStatsEnabled) { | 1088 | if f.featureFlags.BoolFlag(execCtx, featureflags.HostStatsEnabled) { |
| @@ -25,6 +25,12 @@ func Wait(ctx context.Context, socketPath string) error { | |||
| 25 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds)*time.Second) | 25 | ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds)*time.Second) |
| 26 | defer cancel() | 26 | defer cancel() |
| 27 | 27 | ||
| 28 | + // The socket is usually created before the caller starts waiting | ||
| 29 | + // (e.g. the UFFD listener), so check once before the first tick. | ||
| 30 | + if _, err := os.Stat(socketPath); err == nil { | ||
| 31 | + return nil | ||
| 32 | + } | ||
| 33 | + | ||
| 28 | ticker := time.NewTicker(waitInterval) | 34 | ticker := time.NewTicker(waitInterval) |
| 29 | defer ticker.Stop() | 35 | defer ticker.Stop() |
| 30 | 36 | ||
| @@ -23,10 +23,11 @@ func NewCommandBuilder(config cfg.BuilderConfig) *CommandBuilder { | |||
| 23 | } | 23 | } |
| 24 | 24 | ||
| 25 | type CommandResult struct { | 25 | type CommandResult struct { |
| 26 | - Value string | 26 | + Value string |
| 27 | - RootfsPath string | 27 | + RootfsPath string |
| 28 | - KernelPath string | 28 | + KernelPath string |
| 29 | - QmpSocket string | 29 | + QmpSocket string |
| 30 | + PrepareArgv []string | ||
| 30 | } | 31 | } |
| 31 | 32 | ||
| 32 | func (b *CommandBuilder) Build( | 33 | func (b *CommandBuilder) Build( |
| @@ -37,7 +38,7 @@ func (b *CommandBuilder) Build( | |||
| 37 | guestConsoleLogs bool, | 38 | guestConsoleLogs bool, |
| 38 | memoryMB int64, | 39 | memoryMB int64, |
| 39 | vcpuCount int64, | 40 | vcpuCount int64, |
| 40 | - _ bool, | 41 | + hugePages bool, |
| 41 | incomingURI string, | 42 | incomingURI string, |
| 42 | vsockGuestCID int64, | 43 | vsockGuestCID int64, |
| 43 | ) *CommandResult { | 44 | ) *CommandResult { |
| @@ -72,7 +73,7 @@ func (b *CommandBuilder) Build( | |||
| 72 | ) | 73 | ) |
| 73 | } | 74 | } |
| 74 | if versions.OsType.OrDefault() == vmm.OsAndroid { | 75 | if versions.OsType.OrDefault() == vmm.OsAndroid { |
| 75 | - return b.buildAndroidCommand(versions, files, slot, qmpSocket, guestConsoleLogs, memoryMB, vcpuCount, incomingArg, vsockGuestCID) | 76 | + return b.buildAndroidCommand(versions, files, slot, qmpSocket, guestConsoleLogs, memoryMB, vcpuCount, incomingURI, vsockGuestCID, hugePages) |
| 76 | } | 77 | } |
| 77 | 78 | ||
| 78 | machineType = "microvm" | 79 | machineType = "microvm" |
| @@ -148,7 +149,11 @@ func (b *CommandBuilder) Build( | |||
| 148 | } | 149 | } |
| 149 | } | 150 | } |
| 150 | 151 | ||
| 151 | -func (b *CommandBuilder) buildAndroidCommand(versions Config, files *storage.SandboxFiles, slot *network.Slot, qmpSocket string, guestConsoleLogs bool, memoryMB, vcpuCount int64, incomingArg string, vsockGuestCID int64) *CommandResult { | 152 | +func (b *CommandBuilder) buildAndroidCommand(versions Config, files *storage.SandboxFiles, slot *network.Slot, qmpSocket string, guestConsoleLogs bool, memoryMB, vcpuCount int64, incomingURI string, vsockGuestCID int64, hugePages bool) *CommandResult { |
| 153 | + memoryMode := "" | ||
| 154 | + if hugePages { | ||
| 155 | + memoryMode = ",hugepages=2M" | ||
| 156 | + } | ||
| 152 | diskNames := []string{storage.RootfsName, storage.PersistentName, storage.SDCardName} | 157 | diskNames := []string{storage.RootfsName, storage.PersistentName, storage.SDCardName} |
| 153 | guestDiskPaths := make([]string, len(diskNames)) | 158 | guestDiskPaths := make([]string, len(diskNames)) |
| 154 | var preamble strings.Builder | 159 | var preamble strings.Builder |
| @@ -179,83 +184,80 @@ func (b *CommandBuilder) buildAndroidCommand(versions Config, files *storage.San | |||
| 179 | } | 184 | } |
| 180 | preamble.WriteString("} &&\n\n") | 185 | preamble.WriteString("} &&\n\n") |
| 181 | 186 | ||
| 182 | - diskArgs := buildAndroidDiskArgs(guestDiskPaths) | ||
| 183 | - virtconsoleArgs := buildAndroidVirtconsoleArgs(pipeDir, guestConsoleLogs) | ||
| 184 | serialBackend := "null" | 187 | serialBackend := "null" |
| 185 | if guestConsoleLogs { | 188 | if guestConsoleLogs { |
| 186 | serialBackend = "redirect-to-log" | 189 | serialBackend = "redirect-to-log" |
| 187 | } | 190 | } |
| 188 | 191 | ||
| 189 | - vsockArg := "" | 192 | + argv := []string{ |
| 190 | - if vsockGuestCID > 0 { | ||
| 191 | - vsockArg = fmt.Sprintf("-device vhost-vsock-pci,id=vsock0,guest-cid=%d,bus=pcie.0,addr=0x6 ", vsockGuestCID) | ||
| 192 | - } | ||
| 193 | - | ||
| 194 | - cmd := fmt.Sprintf( | ||
| 195 | - "ip netns exec %s %s "+ | ||
| 196 | - "-disable-seccomp "+ | ||
| 197 | - "-machine virt,gic-version=3,dump-guest-core=off,mem-share=on "+ | ||
| 198 | - "-accel kvm "+ | ||
| 199 | - "-smp %d,cores=%d,threads=1 "+ | ||
| 200 | - "-m size=%dM,maxmem=%dM "+ | ||
| 201 | - "-uuid 699acfc4-c8c4-11e7-882b-%012x "+ | ||
| 202 | - "-cpu host "+ | ||
| 203 | - "-drive file=%s,if=pflash,unit=0,readonly=true "+ | ||
| 204 | - "%s"+ | ||
| 205 | - "-boot strict=on -msg timestamp=on -rtc base=utc "+ | ||
| 206 | - "-device virtio-serial-pci,id=virtio-serial0,bus=pcie.0,addr=0x11,max-ports=31 "+ | ||
| 207 | - "%s"+ | ||
| 208 | - "%s"+ | ||
| 209 | - "-netdev tap,id=netdev0,ifname=%s -device virtio-net-pci,netdev=netdev0,id=%s,bus=pcie.0,addr=0x8,mac=00:1a:11:e0:cf:00 "+ | ||
| 210 | - "-netdev tap,id=netdev1,ifname=%s -device virtio-net-pci,netdev=netdev1,id=%s,bus=pcie.0,addr=0x9,mac=00:1a:11:e1:cf:00 "+ | ||
| 211 | - "-device virtio-gpu-pci,id=gpu0,bus=pcie.0,addr=0x10,xres=720,yres=1280 "+ | ||
| 212 | - "-object rng-random,id=objrng0,filename=/dev/urandom -device virtio-rng-pci,id=rng0,rng=objrng0,bus=pcie.0,addr=0x5,max-bytes=1024,period=2000 "+ | ||
| 213 | - "-device virtio-balloon-pci,id=balloon0,bus=pcie.0,addr=0x7,free-page-reporting=true "+ | ||
| 214 | - "-qmp unix:%s,server,nowait "+ | ||
| 215 | - "-serial %s "+ | ||
| 216 | - "%s", | ||
| 217 | - slot.NamespaceID(), | ||
| 218 | versions.StratoVirtPath(b.config), | 193 | versions.StratoVirtPath(b.config), |
| 219 | - vcpuCount, | 194 | + "-disable-seccomp", |
| 220 | - vcpuCount, | 195 | + "-machine", "virt,gic-version=3,dump-guest-core=off" + memoryMode, |
| 221 | - memoryMB, | 196 | + "-accel", "kvm", |
| 222 | - memoryMB+4, | 197 | + "-smp", fmt.Sprintf("%d,cores=%d,threads=1", vcpuCount, vcpuCount), |
| 223 | - slot.Idx, | 198 | + "-m", fmt.Sprintf("size=%dM,maxmem=%dM", memoryMB, memoryMB+4), |
| 224 | - filepath.Join(b.config.FirmwareDirForVersion(string(versions.AndroidVersion)), androidBootloaderFile), | 199 | + "-uuid", fmt.Sprintf("699acfc4-c8c4-11e7-882b-%012x", slot.Idx), |
| 225 | - diskArgs, | 200 | + "-cpu", "host", |
| 226 | - virtconsoleArgs, | 201 | + "-drive", fmt.Sprintf("file=%s,if=pflash,unit=0,readonly=true", filepath.Join(b.config.FirmwareDirForVersion(string(versions.AndroidVersion)), androidBootloaderFile)), |
| 227 | - vsockArg, | 202 | + } |
| 228 | - slot.ExtraTapName(), // netdev0 ifname = cvd-mtap | 203 | + argv = append(argv, buildAndroidDiskArgs(guestDiskPaths)...) |
改动量比较大,要确保参数没出差错 ![]() ![]() | |||
| 229 | - androidMobileNetdevID, | 204 | + argv = append(argv, "-boot", "strict=on", "-msg", "timestamp=on", "-rtc", "base=utc", |
| 230 | - slot.TapName(), // netdev1 ifname = tap0 | 205 | + "-device", "virtio-serial-pci,id=virtio-serial0,bus=pcie.0,addr=0x11,max-ports=31") |
| 231 | - slot.VpeerName(), // netdev1 id = eth0 (MMDS) | 206 | + argv = append(argv, buildAndroidVirtconsoleArgs(pipeDir, guestConsoleLogs)...) |
| 232 | - qmpSocket, | 207 | + if vsockGuestCID > 0 { |
| 233 | - serialBackend, | 208 | + argv = append(argv, "-device", fmt.Sprintf("vhost-vsock-pci,id=vsock0,guest-cid=%d,bus=pcie.0,addr=0x6", vsockGuestCID)) |
| 234 | - incomingArg, | 209 | + } |
| 210 | + argv = append(argv, | ||
| 211 | + "-netdev", fmt.Sprintf("tap,id=netdev0,ifname=%s", slot.ExtraTapName()), | ||
| 212 | + "-device", fmt.Sprintf("virtio-net-pci,netdev=netdev0,id=%s,bus=pcie.0,addr=0x8,mac=00:1a:11:e0:cf:00", androidMobileNetdevID), | ||
| 213 | + "-netdev", fmt.Sprintf("tap,id=netdev1,ifname=%s", slot.TapName()), | ||
| 214 | + "-device", fmt.Sprintf("virtio-net-pci,netdev=netdev1,id=%s,bus=pcie.0,addr=0x9,mac=00:1a:11:e1:cf:00", slot.VpeerName()), | ||
| 215 | + "-device", "virtio-gpu-pci,id=gpu0,bus=pcie.0,addr=0x10,xres=720,yres=1280", | ||
| 216 | + "-object", "rng-random,id=objrng0,filename=/dev/urandom", | ||
| 217 | + "-device", "virtio-rng-pci,id=rng0,rng=objrng0,bus=pcie.0,addr=0x5,max-bytes=1024,period=2000", | ||
| 218 | + "-device", "virtio-balloon-pci,id=balloon0,bus=pcie.0,addr=0x7,free-page-reporting=true", | ||
| 219 | + "-qmp", "unix:"+qmpSocket+",server,nowait", | ||
| 220 | + "-serial", serialBackend, | ||
| 235 | ) | 221 | ) |
| 222 | + if incomingURI != "" { | ||
| 223 | + argv = append(argv, "-incoming", incomingURI) | ||
| 224 | + } | ||
| 225 | + quoted := make([]string, len(argv)) | ||
| 226 | + for i, arg := range argv { | ||
| 227 | + quoted[i] = "'" + strings.ReplaceAll(arg, "'", "'\"'\"'") + "'" | ||
| 228 | + } | ||
| 229 | + cmd := fmt.Sprintf("ip netns exec %s %s", slot.NamespaceID(), strings.Join(quoted, " ")) | ||
| 230 | + prepArgv := []string{b.config.StratoVirtNetnsExecHelper, "--prepare-android", | ||
| 231 | + "-sandbox-dir", b.config.SandboxDir, | ||
| 232 | + "-rootfs-src", files.SandboxCacheDiskLinkPath(b.config.StorageConfig, storage.RootfsName), | ||
| 233 | + "-persistent-src", files.SandboxCacheDiskLinkPath(b.config.StorageConfig, storage.PersistentName), | ||
| 234 | + "-sdcard-src", files.SandboxCacheDiskLinkPath(b.config.StorageConfig, storage.SDCardName), | ||
| 235 | + "-pipe-dir", pipeDir, slot.NamespaceID(), | ||
| 236 | + } | ||
| 237 | + prepArgv = append(prepArgv, argv...) | ||
| 236 | 238 | ||
| 237 | rootfsPath := guestDiskPaths[0] | 239 | rootfsPath := guestDiskPaths[0] |
| 238 | - return &CommandResult{Value: preamble.String() + cmd, RootfsPath: rootfsPath, QmpSocket: qmpSocket} | 240 | + return &CommandResult{Value: preamble.String() + cmd, RootfsPath: rootfsPath, QmpSocket: qmpSocket, PrepareArgv: prepArgv} |
| 239 | } | 241 | } |
| 240 | 242 | ||
| 241 | // buildAndroidDiskArgs renders the Android data disks (os/persistent/sdcard) | 243 | // buildAndroidDiskArgs renders the Android data disks (os/persistent/sdcard) |
| 242 | // as virtio-blk-pci devices. Disk 0 gets bootindex=1 so the guest boots from it. | 244 | // as virtio-blk-pci devices. Disk 0 gets bootindex=1 so the guest boots from it. |
| 243 | -func buildAndroidDiskArgs(guestDiskPaths []string) string { | 245 | +func buildAndroidDiskArgs(guestDiskPaths []string) []string { |
| 244 | - var args strings.Builder | 246 | + var args []string |
| 245 | for i, path := range guestDiskPaths { | 247 | for i, path := range guestDiskPaths { |
| 246 | bootIndex := "" | 248 | bootIndex := "" |
| 247 | if i == 0 { | 249 | if i == 0 { |
| 248 | bootIndex = ",bootindex=1" | 250 | bootIndex = ",bootindex=1" |
| 249 | } | 251 | } |
| 250 | - fmt.Fprintf(&args, "-drive file=%s,format=raw,if=none,id=drive-virtio-disk%d,aio=threads -device virtio-blk-pci,drive=drive-virtio-disk%d,id=virtio-disk%d,bus=pcie.0,addr=0x%x%s ", | 252 | + args = append(args, "-drive", fmt.Sprintf("file=%s,format=raw,if=none,id=drive-virtio-disk%d,aio=threads", path, i), |
| 251 | - path, i, i, i, i+2, bootIndex) | 253 | + "-device", fmt.Sprintf("virtio-blk-pci,drive=drive-virtio-disk%d,id=virtio-disk%d,bus=pcie.0,addr=0x%x%s", i, i, i+2, bootIndex)) |
| 252 | } | 254 | } |
| 253 | - return args.String() | 255 | + return args |
| 254 | } | 256 | } |
| 255 | 257 | ||
| 256 | // buildAndroidVirtconsoleArgs renders the 31 virtio-serial ports for the Android HALs | 258 | // buildAndroidVirtconsoleArgs renders the 31 virtio-serial ports for the Android HALs |
| 257 | -func buildAndroidVirtconsoleArgs(pipeDir string, guestConsoleLogs bool) string { | 259 | +func buildAndroidVirtconsoleArgs(pipeDir string, guestConsoleLogs bool) []string { |
| 258 | - var args strings.Builder | 260 | + var args []string |
| 259 | pipeByPort := map[int]string{ | 261 | pipeByPort := map[int]string{ |
| 260 | 3: "keymaster_fifo_vm", | 262 | 3: "keymaster_fifo_vm", |
| 261 | 4: "gatekeeper_fifo_vm", | 263 | 4: "gatekeeper_fifo_vm", |
| @@ -269,16 +271,16 @@ func buildAndroidVirtconsoleArgs(pipeDir string, guestConsoleLogs bool) string { | |||
| 269 | if guestConsoleLogs { | 271 | if guestConsoleLogs { |
| 270 | backend = "redirect-to-log" | 272 | backend = "redirect-to-log" |
| 271 | } | 273 | } |
| 272 | - fmt.Fprintf(&args, "-chardev %s,id=hvc0 -device virtconsole,id=hvc0,chardev=hvc0,nr=0 ", backend) | 274 | + args = append(args, "-chardev", backend+",id=hvc0", "-device", "virtconsole,id=hvc0,chardev=hvc0,nr=0") |
| 273 | default: | 275 | default: |
| 274 | if name, ok := pipeByPort[port]; ok { | 276 | if name, ok := pipeByPort[port]; ok { |
| 275 | - fmt.Fprintf(&args, "-chardev pipe,id=hvc%d,path=%s -device virtconsole,id=hvc%d,chardev=hvc%d,nr=%d ", port, filepath.Join(pipeDir, name), port, port, port) | 277 | + args = append(args, "-chardev", fmt.Sprintf("pipe,id=hvc%d,path=%s", port, filepath.Join(pipeDir, name)), "-device", fmt.Sprintf("virtconsole,id=hvc%d,chardev=hvc%d,nr=%d", port, port, port)) |
| 276 | } else { | 278 | } else { |
| 277 | - fmt.Fprintf(&args, "-chardev null,id=hvc%d -device virtconsole,id=hvc%d,chardev=hvc%d,nr=%d ", port, port, port, port) | 279 | + args = append(args, "-chardev", fmt.Sprintf("null,id=hvc%d", port), "-device", fmt.Sprintf("virtconsole,id=hvc%d,chardev=hvc%d,nr=%d", port, port, port)) |
| 278 | } | 280 | } |
| 279 | } | 281 | } |
| 280 | } | 282 | } |
| 281 | - return args.String() | 283 | + return args |
| 282 | } | 284 | } |
| 283 | 285 | ||
| 284 | // buildWindowsCommand builds the StratoVirt invocation for a Windows guest. | 286 | // buildWindowsCommand builds the StratoVirt invocation for a Windows guest. |
| @@ -8,6 +8,7 @@ import ( | |||
| 8 | "github.com/bits-and-blooms/bitset" | 8 | "github.com/bits-and-blooms/bitset" |
| 9 | 9 | ||
| 10 | "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/block" | 10 | "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/block" |
| 11 | + "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/vmm" | ||
| 11 | "github.com/e2b-dev/infra/packages/shared/pkg/storage/header" | 12 | "github.com/e2b-dev/infra/packages/shared/pkg/storage/header" |
| 12 | ) | 13 | ) |
| 13 | 14 | ||
| @@ -61,8 +62,25 @@ func memorySize(mappings []memoryMapping) (int64, error) { | |||
| 61 | return int64(totalSize), nil | 62 | return int64(totalSize), nil |
| 62 | } | 63 | } |
| 63 | 64 | ||
| 64 | -// MemoryInfo returns all blocks dirty, for the fresh-start path (NoopMemory). | 65 | +type memoryPageState struct { |
| 66 | + Resident []uint64 `json:"resident"` | ||
| 67 | + Empty []uint64 `json:"empty"` | ||
| 68 | + PageSize uint64 `json:"page-size"` | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +// MemoryInfo reports which blocks to export on a fresh start (NoopMemory). | ||
| 65 | func (p *Process) MemoryInfo(ctx context.Context, blockSize int64) (*header.DiffMetadata, error) { | 72 | func (p *Process) MemoryInfo(ctx context.Context, blockSize int64) (*header.DiffMetadata, error) { |
| 73 | + if p.Versions.OsType.OrDefault() == vmm.OsAndroid { | ||
| 74 | + var state memoryPageState | ||
| 75 | + if err := p.qmpClient.executeCommandWithReturn(ctx, "query-mem-page-state", nil, &state); err != nil { | ||
| 76 | + return nil, fmt.Errorf("query stratovirt memory page state: %w", err) | ||
| 77 | + } | ||
| 78 | + if blockSize <= 0 || state.PageSize != uint64(blockSize) { | ||
| 79 | + return nil, fmt.Errorf("memory page size %d does not match block size %d", state.PageSize, blockSize) | ||
| 80 | + } | ||
| 81 | + return &header.DiffMetadata{Dirty: bitset.From(state.Resident), Empty: bitset.From(state.Empty), BlockSize: blockSize}, nil | ||
| 82 | + } | ||
| 83 | + | ||
| 66 | mappings, err := p.queryMemoryMappings(ctx) | 84 | mappings, err := p.queryMemoryMappings(ctx) |
| 67 | if err != nil { | 85 | if err != nil { |
| 68 | return nil, err | 86 | return nil, err |
| @@ -93,6 +111,13 @@ func (p *Process) DirtyMemory(ctx context.Context, blockSize int64) (*header.Dif | |||
| 93 | return nil, fmt.Errorf("query mem dirty bitmap: %w", err) | 111 | return nil, fmt.Errorf("query mem dirty bitmap: %w", err) |
| 94 | } | 112 | } |
| 95 | 113 | ||
| 114 | + if p.Versions.OsType.OrDefault() == vmm.OsAndroid { | ||
| 115 | + if blockSize <= 0 || res.PageSize != uint64(blockSize) { | ||
| 116 | + return nil, fmt.Errorf("memory page size %d does not match block size %d", res.PageSize, blockSize) | ||
| 117 | + } | ||
| 118 | + return &header.DiffMetadata{Dirty: bitset.From(res.Bitmap), Empty: bitset.New(0), BlockSize: blockSize}, nil | ||
| 119 | + } | ||
| 120 | + | ||
| 96 | pageSize := int64(res.PageSize) | 121 | pageSize := int64(res.PageSize) |
| 97 | if pageSize == 0 { | 122 | if pageSize == 0 { |
| 98 | pageSize = 4096 | 123 | pageSize = 4096 |
| @@ -119,9 +144,9 @@ func (p *Process) DirtyMemory(ctx context.Context, blockSize int64) (*header.Dif | |||
| 119 | 144 | ||
| 120 | // denseBitmapToBlockBitset converts a page-granularity bitmap (each bit = one | 145 | // denseBitmapToBlockBitset converts a page-granularity bitmap (each bit = one |
| 121 | // pageSize) to a block-granularity BitSet (each bit = one blockSize). | 146 | // pageSize) to a block-granularity BitSet (each bit = one blockSize). |
| 122 | -// - blockSize == pageSize: 1:1 | 147 | +// - blockSize == pageSize: 1:1 |
| 123 | -// - blockSize > pageSize: block dirty if any spanning page is dirty | 148 | +// - blockSize > pageSize: block dirty if any spanning page is dirty |
| 124 | -// - blockSize < pageSize: all blocks a dirty page spans are marked dirty | 149 | +// - blockSize < pageSize: all blocks a dirty page spans are marked dirty |
| 125 | func denseBitmapToBlockBitset(denseBitmap []uint64, pageSize, blockSize int64, totalBlocks uint) *bitset.BitSet { | 150 | func denseBitmapToBlockBitset(denseBitmap []uint64, pageSize, blockSize int64, totalBlocks uint) *bitset.BitSet { |
| 126 | dirty := bitset.New(totalBlocks) | 151 | dirty := bitset.New(totalBlocks) |
| 127 | 152 | ||
| @@ -0,0 +1,226 @@ | |||
| 1 | +package stratovirt | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "fmt" | ||
| 6 | + "os" | ||
| 7 | + "os/exec" | ||
| 8 | + "path/filepath" | ||
| 9 | + "strings" | ||
| 10 | + "sync" | ||
| 11 | + "syscall" | ||
| 12 | + "time" | ||
| 13 | + | ||
| 14 | + "go.uber.org/zap" | ||
| 15 | + | ||
| 16 | + "github.com/e2b-dev/infra/packages/orchestrator/internal/cfg" | ||
| 17 | + "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/network" | ||
| 18 | +) | ||
| 19 | + | ||
| 20 | +const stratoVirtNetnsFDEnv = "E2B_STRATOVIRT_NETNS_FD" | ||
| 21 | + | ||
| 22 | +var pinnedMountNS struct { | ||
| 23 | + once sync.Once | ||
| 24 | + path string // /proc/<holder pid>/ns/mnt | ||
| 25 | + err error | ||
| 26 | + cmd *exec.Cmd | ||
| 27 | + keepOpen *os.File // 管道写端,编排器存活期间保持打开 | ||
| 28 | + prepareVMOK bool // helper --prepare-android 探测结果 | ||
| 29 | + warnOnce sync.Once | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +// Mirrors fc.buildStartCommand: Android pinned mount namespace, inherited netns FD, | ||
| 33 | +// native preparation, and a legacy fallback. Template builds retain their launcher. | ||
| 34 | +func buildStartCommand( | ||
| 35 | + ctx context.Context, | ||
| 36 | + execCtx context.Context, | ||
| 37 | + config cfg.BuilderConfig, | ||
| 38 | + startScript string, | ||
| 39 | + slot *network.Slot, | ||
| 40 | + restoredSandbox bool, | ||
| 41 | + prepArgv []string, | ||
| 42 | +) (*exec.Cmd, func()) { | ||
| 43 | + fallback := func() (*exec.Cmd, func()) { | ||
| 44 | + return exec.CommandContext(execCtx, | ||
| 45 | + "unshare", | ||
| 46 | + "-m", | ||
| 47 | + "--", | ||
| 48 | + "bash", | ||
| 49 | + "-c", | ||
| 50 | + startScript, | ||
| 51 | + ), func() {} | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + helper := strings.TrimSpace(config.StratoVirtNetnsExecHelper) | ||
| 55 | + if helper == "" || helper == "disabled" || helper == "ip-netns-exec" || !restoredSandbox || len(prepArgv) == 0 { | ||
| 56 | + return fallback() | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + pinPath, err := pinnedMountNSPath(ctx, helper) | ||
| 60 | + if err != nil { | ||
| 61 | + pinnedMountNS.warnOnce.Do(func() { | ||
| 62 | + zap.L().Warn("Android pinned mount namespace unavailable, falling back to plain unshare for all sandboxes", zap.Error(err)) | ||
| 63 | + }) | ||
| 64 | + | ||
| 65 | + return fallback() | ||
| 66 | + } | ||
| 67 | + | ||
| 68 | + // Same as FC: if the holder is gone, its /proc path disappears and we fall back. | ||
| 69 | + if _, err := os.Stat(pinPath); err != nil { | ||
| 70 | + pinnedMountNS.warnOnce.Do(func() { | ||
| 71 | + zap.L().Warn("Android pinned mount namespace holder is gone, falling back to plain unshare for all sandboxes", zap.String("path", pinPath), zap.Error(err)) | ||
| 72 | + }) | ||
| 73 | + | ||
| 74 | + return fallback() | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + if !pinnedMountNS.prepareVMOK { | ||
| 78 | + return fallback() | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + netnsFile, err := os.Open(netnsHostPath(slot)) | ||
| 82 | + if err != nil { | ||
| 83 | + zap.L().Error("open sandbox netns failed, falling back to plain unshare", zap.String("netns", slot.NamespaceID()), zap.Error(err)) | ||
| 84 | + | ||
| 85 | + return fallback() | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + inner := append([]string{"unshare", "-m", "--"}, prepArgv...) | ||
| 89 | + cmd := exec.CommandContext(execCtx, | ||
| 90 | + "nsenter", append([]string{"--mount=" + pinPath}, inner...)..., | ||
| 91 | + ) | ||
| 92 | + // The netns FD is fd 3 in the child (ExtraFiles[0]). | ||
| 93 | + cmd.ExtraFiles = []*os.File{netnsFile} | ||
| 94 | + cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%d", stratoVirtNetnsFDEnv, 3)) | ||
| 95 | + | ||
| 96 | + return cmd, func() { netnsFile.Close() } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +func netnsHostPath(slot *network.Slot) string { | ||
| 100 | + if slot.ExternalNetNS && slot.NetNSPath != "" { | ||
| 101 | + return slot.NetNSPath | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + return filepath.Join("/run/netns", slot.NamespaceID()) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +// WarmupPinnedMountNS must run before the network pool starts filling. | ||
| 108 | +func WarmupPinnedMountNS(ctx context.Context, builderConfig cfg.BuilderConfig) { | ||
| 109 | + helper := strings.TrimSpace(builderConfig.StratoVirtNetnsExecHelper) | ||
| 110 | + if helper == "" || helper == "disabled" || helper == "ip-netns-exec" { | ||
| 111 | + return | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + if _, err := pinnedMountNSPath(ctx, helper); err != nil { | ||
| 115 | + zap.L().Error("warmup Android pinned mount namespace failed", zap.Error(err)) | ||
| 116 | + } | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +func pinnedMountNSPath(ctx context.Context, helper string) (string, error) { | ||
| 120 | + pinnedMountNS.once.Do(func() { | ||
| 121 | + pinnedMountNS.path, pinnedMountNS.err = setupPinnedMountNS(ctx, helper) | ||
| 122 | + }) | ||
| 123 | + | ||
| 124 | + return pinnedMountNS.path, pinnedMountNS.err | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +// The holder exits on pipe EOF when orchestrator exits, including SIGKILL. | ||
| 128 | +// Keep mount namespace operations in subprocesses, as in the FC launcher. | ||
| 129 | +func setupPinnedMountNS(ctx context.Context, helper string) (string, error) { | ||
| 130 | + pipeR, pipeW, err := os.Pipe() | ||
| 131 | + if err != nil { | ||
| 132 | + return "", fmt.Errorf("create holder lifetime pipe: %w", err) | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + cmd := exec.CommandContext(context.Background(), | ||
| 136 | + "unshare", "-m", "--propagation", "private", "--", | ||
| 137 | + "sh", "-c", "umount -l /run/netns 2>/dev/null; read _ || true", | ||
| 138 | + ) | ||
| 139 | + cmd.Stdin = pipeR | ||
| 140 | + | ||
| 141 | + if err := cmd.Start(); err != nil { | ||
| 142 | + pipeR.Close() | ||
| 143 | + pipeW.Close() | ||
| 144 | + | ||
| 145 | + return "", fmt.Errorf("start mount ns holder: %w", err) | ||
| 146 | + } | ||
| 147 | + pipeR.Close() | ||
| 148 | + | ||
| 149 | + teardown := func() { | ||
| 150 | + pipeW.Close() | ||
| 151 | + _ = cmd.Process.Kill() | ||
| 152 | + _ = cmd.Wait() | ||
| 153 | + } | ||
| 154 | + | ||
| 155 | + nsPath := fmt.Sprintf("/proc/%d/ns/mnt", cmd.Process.Pid) | ||
| 156 | + | ||
| 157 | + selfNS, err := os.Stat("/proc/self/ns/mnt") | ||
| 158 | + if err != nil { | ||
| 159 | + teardown() | ||
| 160 | + | ||
| 161 | + return "", fmt.Errorf("stat self mount ns: %w", err) | ||
| 162 | + } | ||
| 163 | + selfStat := selfNS.Sys().(*syscall.Stat_t) | ||
| 164 | + | ||
| 165 | + deadline := time.Now().Add(5 * time.Second) | ||
| 166 | + unshared := false | ||
| 167 | + for time.Now().Before(deadline) { | ||
| 168 | + if childNS, err := os.Stat(nsPath); err == nil { | ||
| 169 | + childStat := childNS.Sys().(*syscall.Stat_t) | ||
| 170 | + if childStat.Ino != selfStat.Ino || childStat.Dev != selfStat.Dev { | ||
| 171 | + unshared = true | ||
| 172 | + | ||
| 173 | + break | ||
| 174 | + } | ||
| 175 | + } | ||
| 176 | + time.Sleep(10 * time.Millisecond) | ||
| 177 | + } | ||
| 178 | + if !unshared { | ||
| 179 | + teardown() | ||
| 180 | + | ||
| 181 | + return "", fmt.Errorf("wait for mount ns holder unshare: timeout") | ||
| 182 | + } | ||
| 183 | + | ||
| 184 | + if out, err := exec.CommandContext(ctx, "nsenter", "--mount="+nsPath, "/bin/true").CombinedOutput(); err != nil { | ||
| 185 | + teardown() | ||
| 186 | + | ||
| 187 | + return "", fmt.Errorf("nsenter pinned mount ns failed: %w (%s)", err, strings.TrimSpace(string(out))) | ||
| 188 | + } | ||
| 189 | + | ||
| 190 | + selfNetNS, err := os.Open("/proc/self/ns/net") | ||
| 191 | + if err != nil { | ||
| 192 | + teardown() | ||
| 193 | + | ||
| 194 | + return "", fmt.Errorf("open self netns for helper probe: %w", err) | ||
| 195 | + } | ||
| 196 | + probe := exec.CommandContext(ctx, helper, "self", "/bin/true") | ||
| 197 | + probe.ExtraFiles = []*os.File{selfNetNS} | ||
| 198 | + probe.Env = append(os.Environ(), fmt.Sprintf("%s=%d", stratoVirtNetnsFDEnv, 3)) | ||
| 199 | + out, probeErr := probe.CombinedOutput() | ||
| 200 | + selfNetNS.Close() | ||
| 201 | + if probeErr != nil { | ||
| 202 | + teardown() | ||
| 203 | + | ||
| 204 | + return "", fmt.Errorf("helper %s does not support %s mode: %w (%s)", helper, stratoVirtNetnsFDEnv, probeErr, strings.TrimSpace(string(out))) | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + prepProbe := exec.CommandContext(ctx, helper, "--prepare-android", "--probe") | ||
🟡 Medium Priority mountns.go:202-213(以及 188、213 的 enterProbe/prepProbe)用调用方传入的 影响链路: 失败模式:① 启动阶段直接把编排器启动卡死(warmup 是同步调用);② 若首次调用来自某个沙箱恢复的 ctx(warmup 因 helper 未就绪失败以外的分支未消费 once 时),该 ctx 被取消(恢复超时)会让 setup 以 ctx canceled 失败并被永久缓存,此后整进程所有 Android 恢复静默回退到 建议:在 setupPinnedMountNS 内使用独立的 ![]() ![]() Incorrect? | |||
| 208 | + if out, err := prepProbe.CombinedOutput(); err != nil { | ||
| 209 | + zap.L().Warn("helper does not support --prepare-android, falling back to bash start script", zap.String("helper", helper), zap.Error(err), zap.String("output", strings.TrimSpace(string(out)))) | ||
| 210 | + } else { | ||
| 211 | + pinnedMountNS.prepareVMOK = true | ||
| 212 | + zap.L().Info("Android native launcher --prepare-android probe passed", zap.String("helper", helper)) | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + pinnedMountNS.cmd = cmd | ||
| 216 | + pinnedMountNS.keepOpen = pipeW | ||
| 217 | + | ||
| 218 | + go func() { | ||
| 219 | + err := cmd.Wait() | ||
| 220 | + zap.L().Warn("Android mount namespace holder exited; new sandboxes will fall back to plain unshare", zap.Int("pid", cmd.Process.Pid), zap.Error(err)) | ||
| 221 | + }() | ||
| 222 | + | ||
| 223 | + zap.L().Sugar().Infof("pinned minimal mount namespace via holder pid %d (%s)", cmd.Process.Pid, nsPath) | ||
| 224 | + | ||
| 225 | + return nsPath, nil | ||
| 226 | +} | ||
| @@ -187,7 +187,7 @@ func (p *Process) Create( | |||
| 187 | Setsid: true, | 187 | Setsid: true, |
| 188 | } | 188 | } |
| 189 | 189 | ||
| 190 | - err = p.startProcess(ctx, metadata, options.Stdout, options.Stderr, cmd) | 190 | + err = p.startProcess(ctx, metadata, options.Stdout, options.Stderr, cmd, func() {}) |
| 191 | if err != nil { | 191 | if err != nil { |
| 192 | stopErr := p.Stop(ctx) | 192 | stopErr := p.Stop(ctx) |
| 193 | return errors.Join(fmt.Errorf("error starting stratovirt process: %w", err), stopErr) | 193 | return errors.Join(fmt.Errorf("error starting stratovirt process: %w", err), stopErr) |
| @@ -236,7 +236,7 @@ func (p *Process) Resume( | |||
| 236 | cleanup := func() { _ = os.RemoveAll(restoreDir) } | 236 | cleanup := func() { _ = os.RemoveAll(restoreDir) } |
| 237 | defer cleanup() | 237 | defer cleanup() |
| 238 | 238 | ||
| 239 | - if err := unpackSnapshot(snapfile.Path(), restoreDir); err != nil { | 239 | + if err := restoreSnapshotFiles(snapfile, restoreDir, p.Versions.OsType.OrDefault() == vmm.OsAndroid); err != nil { |
| 240 | return fmt.Errorf("unpack stratovirt snapshot: %w", err) | 240 | return fmt.Errorf("unpack stratovirt snapshot: %w", err) |
| 241 | } | 241 | } |
| 242 | telemetry.ReportEvent(ctx, "unpacked stratovirt snapshot") | 242 | telemetry.ReportEvent(ctx, "unpacked stratovirt snapshot") |
| @@ -268,8 +268,11 @@ func (p *Process) Resume( | |||
| 268 | p.vsockGuestCID, | 268 | p.vsockGuestCID, |
| 269 | ) | 269 | ) |
| 270 | 270 | ||
| 271 | - cmd := exec.CommandContext(p.execCtx, "unshare", "-m", "--", "bash", "-c", cmdResult.Value) | 271 | + cmd, closeNetnsFD := buildStartCommand(ctx, p.execCtx, p.config, cmdResult.Value, p.slot, |
| 272 | + p.Versions.OsType.OrDefault() == vmm.OsAndroid, cmdResult.PrepareArgv) | ||
| 272 | sysProcAttr := &syscall.SysProcAttr{Setsid: true} | 273 | sysProcAttr := &syscall.SysProcAttr{Setsid: true} |
| 274 | + // Placement is not enabled yet, so E2B_SANDBOX_CGROUP_ENABLED defaults to | ||
| 275 | + // false; drop that switch once this is restored. | ||
| 273 | // if cgroupFD >= 0 { | 276 | // if cgroupFD >= 0 { |
| 274 | // sysProcAttr.UseCgroupFD = true | 277 | // sysProcAttr.UseCgroupFD = true |
| 275 | // sysProcAttr.CgroupFD = cgroupFD | 278 | // sysProcAttr.CgroupFD = cgroupFD |
| @@ -277,7 +280,7 @@ func (p *Process) Resume( | |||
| 277 | cmd.SysProcAttr = sysProcAttr | 280 | cmd.SysProcAttr = sysProcAttr |
| 278 | 281 | ||
| 279 | phaseStart = time.Now() | 282 | phaseStart = time.Now() |
| 280 | - if err := p.startProcess(ctx, metadata.LoggerMetadata(), nil, nil, cmd); err != nil { | 283 | + if err := p.startProcess(ctx, metadata.LoggerMetadata(), nil, nil, cmd, closeNetnsFD); err != nil { |
| 281 | _ = p.Stop(ctx) | 284 | _ = p.Stop(ctx) |
| 282 | return fmt.Errorf("error starting stratovirt: %w", err) | 285 | return fmt.Errorf("error starting stratovirt: %w", err) |
| 283 | } | 286 | } |
| @@ -318,6 +321,7 @@ func (p *Process) startProcess( | |||
| 318 | stdoutExternal io.Writer, | 321 | stdoutExternal io.Writer, |
| 319 | stderrExternal io.Writer, | 322 | stderrExternal io.Writer, |
| 320 | cmd *exec.Cmd, | 323 | cmd *exec.Cmd, |
| 324 | + closeNetnsFD func(), | ||
| 321 | ) error { | 325 | ) error { |
| 322 | ctx, childSpan := tracer.Start(ctx, "start-stratovirt-process") | 326 | ctx, childSpan := tracer.Start(ctx, "start-stratovirt-process") |
| 323 | defer childSpan.End() | 327 | defer childSpan.End() |
| @@ -339,6 +343,7 @@ func (p *Process) startProcess( | |||
| 339 | p.cmd = cmd | 343 | p.cmd = cmd |
| 340 | 344 | ||
| 341 | err := cmd.Start() | 345 | err := cmd.Start() |
| 346 | + closeNetnsFD() | ||
| 342 | if err != nil { | 347 | if err != nil { |
| 343 | return fmt.Errorf("error starting stratovirt process: %w", err) | 348 | return fmt.Errorf("error starting stratovirt process: %w", err) |
| 344 | } | 349 | } |
| @@ -7,6 +7,10 @@ import ( | |||
| 7 | "os" | 7 | "os" |
| 8 | "path/filepath" | 8 | "path/filepath" |
| 9 | "strings" | 9 | "strings" |
| 10 | + | ||
| 11 | + "go.uber.org/zap" | ||
| 12 | + | ||
| 13 | + "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/template" | ||
| 10 | ) | 14 | ) |
| 11 | 15 | ||
| 12 | const ( | 16 | const ( |
| @@ -137,3 +141,29 @@ func isSnapshotFile(name string) bool { | |||
| 137 | // Archive entries become paths below the restore directory. | 141 | // Archive entries become paths below the restore directory. |
| 138 | return strings.HasPrefix(name, gpuImagesFilePrefix) && filepath.Base(name) == name | 142 | return strings.HasPrefix(name, gpuImagesFilePrefix) && filepath.Base(name) == name |
| 139 | } | 143 | } |
| 144 | + | ||
| 145 | +func restoreSnapshotFiles(file template.File, dir string, cached bool) error { | ||
| 146 | + if cached { | ||
| 147 | + if prepared, ok := file.(*template.PreparedFile); ok { | ||
| 148 | + err := prepared.LinkPreparedDir(dir, unpackSnapshot) | ||
| 149 | + if err == nil { | ||
| 150 | + return nil | ||
| 151 | + } | ||
| 152 | + // The cache is only an optimization; fall back to a private unpack. | ||
| 153 | + zap.L().Warn("prepared snapshot unavailable, unpacking snapshot archive", zap.String("dir", dir), zap.Error(err)) | ||
| 154 | + if err := removeSnapshotFiles(dir); err != nil { | ||
| 155 | + return fmt.Errorf("clean partial prepared snapshot: %w", err) | ||
| 156 | + } | ||
| 157 | + } | ||
| 158 | + } | ||
| 159 | + return unpackSnapshot(file.Path(), dir) | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +func removeSnapshotFiles(dir string) error { | ||
| 163 | + for _, name := range snapshotFiles(dir) { | ||
| 164 | + if err := os.Remove(filepath.Join(dir, name)); err != nil && !os.IsNotExist(err) { | ||
| 165 | + return err | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + return nil | ||
| 169 | +} | ||
| @@ -80,6 +80,10 @@ func NewCache( | |||
| 80 | return nil, fmt.Errorf("failed to remove old build cache directory: %w", err) | 80 | return nil, fmt.Errorf("failed to remove old build cache directory: %w", err) |
| 81 | } | 81 | } |
| 82 | 82 | ||
| 83 | + if err := cleanupPreparedSnapshots(config.StorageConfig.SandboxCacheDir); err != nil { | ||
| 84 | + logger.L().Warn(context.Background(), "failed to cleanup abandoned prepared snapshots", zap.Error(err)) | ||
| 85 | + } | ||
| 86 | + | ||
| 83 | buildStore, err := build.NewDiffStore( | 87 | buildStore, err := build.NewDiffStore( |
| 84 | config, | 88 | config, |
| 85 | flags, | 89 | flags, |
| @@ -111,6 +115,25 @@ func (c *Cache) Start(ctx context.Context) { | |||
| 111 | func (c *Cache) Stop() { | 115 | func (c *Cache) Stop() { |
| 112 | c.buildStore.Close() | 116 | c.buildStore.Close() |
| 113 | c.cache.Stop() | 117 | c.cache.Stop() |
| 118 | + c.closePreparedSnapshots() | ||
| 119 | +} | ||
这两处清理,分别在什么时候发生 ![]() ![]() | |||
| 120 | + | ||
| 121 | +func (c *Cache) closePreparedSnapshots() { | ||
| 122 | + for _, item := range c.cache.Items() { | ||
| 123 | + t, ok := item.Value().(*storageTemplate) | ||
| 124 | + if !ok { | ||
| 125 | + continue | ||
| 126 | + } | ||
| 127 | + file, err := t.snapfile.Result() | ||
| 128 | + if err != nil { | ||
| 129 | + continue | ||
| 130 | + } | ||
| 131 | + if prepared, ok := file.(*PreparedFile); ok { | ||
| 132 | + if err := prepared.Close(); err != nil { | ||
| 133 | + logger.L().Warn(context.Background(), "failed to close prepared snapshot cache", zap.Error(err)) | ||
| 134 | + } | ||
| 135 | + } | ||
| 136 | + } | ||
| 114 | } | 137 | } |
| 115 | 138 | ||
| 116 | func (c *Cache) Items() map[string]*ttlcache.Item[string, Template] { | 139 | func (c *Cache) Items() map[string]*ttlcache.Item[string, Template] { |
| @@ -0,0 +1,163 @@ | |||
| 1 | +package template | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "errors" | ||
| 5 | + "fmt" | ||
| 6 | + "os" | ||
| 7 | + "path/filepath" | ||
| 8 | + "strings" | ||
| 9 | + "sync" | ||
| 10 | + | ||
| 11 | + "golang.org/x/sys/unix" | ||
| 12 | +) | ||
| 13 | + | ||
| 14 | +const preparedSnapshotPrefix = ".stratovirt-snapshot-" | ||
| 15 | +const preparedSnapshotOwner = ".owner.lock" | ||
| 16 | + | ||
| 17 | +// PreparedFile keeps an immutable expanded snapshot for the template lifetime. | ||
| 18 | +// Each restore takes hard links, so template eviction cannot remove its files. | ||
| 19 | +// Consumers must only read the snapshot or map it privately; never modify or truncate it. | ||
| 20 | +type PreparedFile struct { | ||
| 21 | + File | ||
| 22 | + mu sync.Mutex | ||
| 23 | + dir string | ||
| 24 | + files []string // prepared entries, fixed when the cache is published | ||
| 25 | + owner *os.File | ||
| 26 | + closed bool | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +func (f *PreparedFile) LinkPreparedDir(target string, prepare func(string, string) error) error { | ||
| 30 | + f.mu.Lock() | ||
| 31 | + defer f.mu.Unlock() | ||
| 32 | + if f.closed { | ||
| 33 | + return os.ErrClosed | ||
| 34 | + } | ||
| 35 | + if f.dir == "" { | ||
| 36 | + // Publish the cache only after holding its owner lock. Startup cleanup | ||
| 37 | + // must never mistake an in-progress preparation for an abandoned cache. | ||
| 38 | + staging, err := os.MkdirTemp(filepath.Dir(target), ".stratovirt-prepare-") | ||
fc的vmstate快照是放在什么地方的。 我们现在放在temp目录,可能会占用过多内存 ![]() ![]() | |||
| 39 | + if err != nil { | ||
| 40 | + return err | ||
| 41 | + } | ||
| 42 | + owner, err := os.OpenFile(filepath.Join(staging, preparedSnapshotOwner), os.O_CREATE|os.O_RDWR, 0o600) | ||
| 43 | + if err != nil { | ||
| 44 | + return errors.Join(err, os.RemoveAll(staging)) | ||
| 45 | + } | ||
| 46 | + defer func() { | ||
| 47 | + if f.owner != owner { | ||
| 48 | + _ = owner.Close() | ||
| 49 | + _ = os.RemoveAll(staging) | ||
| 50 | + } | ||
| 51 | + }() | ||
| 52 | + if err := unix.Flock(int(owner.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { | ||
| 53 | + return err | ||
| 54 | + } | ||
| 55 | + dir := filepath.Join(filepath.Dir(target), preparedSnapshotPrefix+strings.TrimPrefix(filepath.Base(staging), ".stratovirt-prepare-")) | ||
| 56 | + if err := os.Rename(staging, dir); err != nil { | ||
| 57 | + return err | ||
| 58 | + } | ||
| 59 | + if err := prepare(f.Path(), dir); err != nil { | ||
| 60 | + return errors.Join(err, os.RemoveAll(dir)) | ||
| 61 | + } | ||
| 62 | + entries, err := os.ReadDir(dir) | ||
| 63 | + if err != nil { | ||
| 64 | + return errors.Join(err, os.RemoveAll(dir)) | ||
| 65 | + } | ||
| 66 | + var files []string | ||
| 67 | + for _, entry := range entries { | ||
| 68 | + if entry.Name() == preparedSnapshotOwner { | ||
| 69 | + continue | ||
| 70 | + } | ||
| 71 | + if !entry.Type().IsRegular() { | ||
| 72 | + return errors.Join(fmt.Errorf("non-regular prepared snapshot entry %q", entry.Name()), os.RemoveAll(dir)) | ||
| 73 | + } | ||
| 74 | + if err := os.Chmod(filepath.Join(dir, entry.Name()), 0o400); err != nil { | ||
| 75 | + return errors.Join(err, os.RemoveAll(dir)) | ||
| 76 | + } | ||
| 77 | + files = append(files, entry.Name()) | ||
| 78 | + } | ||
| 79 | + f.dir = dir | ||
| 80 | + f.files = files | ||
| 81 | + f.owner = owner | ||
| 82 | + } | ||
| 83 | + for _, name := range f.files { | ||
| 84 | + source := filepath.Join(f.dir, name) | ||
| 85 | + if err := os.Link(source, filepath.Join(target, name)); err != nil { | ||
| 86 | + err = fmt.Errorf("link prepared snapshot %s: %w", name, err) | ||
| 87 | + // A missing source means the cache was damaged externally; drop it so | ||
| 88 | + // the next restore prepares it again. Target-side errors keep the cache. | ||
| 89 | + if _, statErr := os.Lstat(source); statErr != nil { | ||
| 90 | + err = errors.Join(err, f.resetLocked()) | ||
| 91 | + } | ||
| 92 | + return err | ||
| 93 | + } | ||
| 94 | + } | ||
| 95 | + return nil | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +// resetLocked drops a damaged cache. Existing restore links remain valid. | ||
| 99 | +func (f *PreparedFile) resetLocked() error { | ||
| 100 | + var err error | ||
| 101 | + if f.dir != "" { | ||
| 102 | + err = os.RemoveAll(f.dir) | ||
| 103 | + f.dir = "" | ||
| 104 | + } | ||
| 105 | + f.files = nil | ||
| 106 | + if f.owner != nil { | ||
| 107 | + err = errors.Join(err, f.owner.Close()) | ||
| 108 | + f.owner = nil | ||
| 109 | + } | ||
| 110 | + return err | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +func (f *PreparedFile) Close() error { | ||
| 114 | + f.mu.Lock() | ||
| 115 | + defer f.mu.Unlock() | ||
| 116 | + if f.closed { | ||
| 117 | + return nil | ||
| 118 | + } | ||
| 119 | + f.closed = true | ||
| 120 | + return errors.Join(f.resetLocked(), f.File.Close()) | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +// A process exit releases flock even when the normal shutdown callback did not run. | ||
| 124 | +// Existing restore links and VMM mappings remain valid after an orphan is removed. | ||
| 125 | +func cleanupPreparedSnapshots(parent string) error { | ||
| 126 | + entries, err := os.ReadDir(parent) | ||
| 127 | + if os.IsNotExist(err) { | ||
| 128 | + return nil | ||
| 129 | + } | ||
| 130 | + if err != nil { | ||
| 131 | + return err | ||
| 132 | + } | ||
| 133 | + var cleanupErr error | ||
| 134 | + for _, entry := range entries { | ||
| 135 | + if !entry.IsDir() || !strings.HasPrefix(entry.Name(), preparedSnapshotPrefix) { | ||
| 136 | + continue | ||
| 137 | + } | ||
🟡 Medium Priority prepared_file.go:122-125 的清理循环只匹配 影响链路: 失败模式:编排器在 prepare 过程中被 SIGKILL / OOM kill / 重启, 建议:让清理逻辑同时识别 staging 前缀(如 ".stratovirt-prepare-"),对两类目录都用 owner flock 探测持有者是否存活,拿到锁即 RemoveAll,避免崩溃后残留数 GB 的中间目录。 ![]() ![]() Incorrect? | |||
| 138 | + dir := filepath.Join(parent, entry.Name()) | ||
| 139 | + owner, err := os.OpenFile(filepath.Join(dir, preparedSnapshotOwner), os.O_RDWR|unix.O_NOFOLLOW, 0) | ||
| 140 | + if os.IsNotExist(err) { | ||
| 141 | + continue | ||
| 142 | + } | ||
| 143 | + if err != nil { | ||
| 144 | + cleanupErr = errors.Join(cleanupErr, fmt.Errorf("open prepared snapshot owner %s: %w", dir, err)) | ||
| 145 | + continue | ||
| 146 | + } | ||
| 147 | + err = unix.Flock(int(owner.Fd()), unix.LOCK_EX|unix.LOCK_NB) | ||
| 148 | + if errors.Is(err, unix.EWOULDBLOCK) { | ||
| 149 | + _ = owner.Close() | ||
| 150 | + continue | ||
| 151 | + } | ||
| 152 | + if err != nil { | ||
| 153 | + cleanupErr = errors.Join(cleanupErr, fmt.Errorf("lock prepared snapshot %s: %w", dir, errors.Join(err, owner.Close()))) | ||
| 154 | + continue | ||
| 155 | + } | ||
| 156 | + removeErr := os.RemoveAll(dir) | ||
| 157 | + closeErr := owner.Close() | ||
| 158 | + if err := errors.Join(removeErr, closeErr); err != nil { | ||
| 159 | + cleanupErr = errors.Join(cleanupErr, fmt.Errorf("remove prepared snapshot %s: %w", dir, err)) | ||
| 160 | + } | ||
| 161 | + } | ||
| 162 | + return cleanupErr | ||
| 163 | +} | ||
| @@ -95,7 +95,7 @@ func (t *storageTemplate) Fetch(ctx context.Context, buildStore *build.DiffStore | |||
| 95 | wg.Go(func() error { | 95 | wg.Go(func() error { |
| 96 | if t.localSnapfile != nil { | 96 | if t.localSnapfile != nil { |
| 97 | t1 := time.Now() | 97 | t1 := time.Now() |
| 98 | - if err := t.snapfile.SetValue(t.localSnapfile); err != nil { | 98 | + if err := t.setSnapfile(t.localSnapfile); err != nil { |
| 99 | return fmt.Errorf("failed to set local snapfile: %w", err) | 99 | return fmt.Errorf("failed to set local snapfile: %w", err) |
| 100 | } | 100 | } |
| 101 | zap.L().Sugar().Infof("[ResumeSandbox] storageTemplate.Fetch set local snapfile cost: %.3f ms, buildID=%s", | 101 | zap.L().Sugar().Infof("[ResumeSandbox] storageTemplate.Fetch set local snapfile cost: %.3f ms, buildID=%s", |
| @@ -124,7 +124,7 @@ func (t *storageTemplate) Fetch(ctx context.Context, buildStore *build.DiffStore | |||
| 124 | zap.L().Sugar().Infof("[ResumeSandbox] storageTemplate.Fetch newStorageFile(snapfile) cost: %.3f ms, buildID=%s, cache=%s", | 124 | zap.L().Sugar().Infof("[ResumeSandbox] storageTemplate.Fetch newStorageFile(snapfile) cost: %.3f ms, buildID=%s, cache=%s", |
| 125 | time.Since(tSnap).Seconds()*1000, t.files.BuildID, t.files.CacheSnapfilePath()) | 125 | time.Since(tSnap).Seconds()*1000, t.files.BuildID, t.files.CacheSnapfilePath()) |
| 126 | 126 | ||
| 127 | - if err := t.snapfile.SetValue(snapfile); err != nil { | 127 | + if err := t.setSnapfile(snapfile); err != nil { |
| 128 | return fmt.Errorf("failed to set snapfile: %w", err) | 128 | return fmt.Errorf("failed to set snapfile: %w", err) |
| 129 | } | 129 | } |
| 130 | 130 | ||
| @@ -347,3 +347,8 @@ func (t *storageTemplate) Metadata() (metadata.Template, error) { | |||
| 347 | 347 | ||
| 348 | return metadata.FromFile(metafile.Path()) | 348 | return metadata.FromFile(metafile.Path()) |
| 349 | } | 349 | } |
| 350 | + | ||
| 351 | +func (t *storageTemplate) setSnapfile(file File) error { | ||
| 352 | + // Expansion is lazy: only Android restore requests a prepared directory. | ||
Linux沙箱应该也需要这个优化把? ![]() ![]() | |||
| 353 | + return t.snapfile.SetValue(&PreparedFile{File: file}) | ||
| 354 | +} | ||
| @@ -136,7 +136,7 @@ func (s *Server) Create(ctx context.Context, req *orchestrator.SandboxCreateRequ | |||
| 136 | return nil, status.Errorf(codes.FailedPrecondition, "invalid template OS/VMM metadata: %s", err) | 136 | return nil, status.Errorf(codes.FailedPrecondition, "invalid template OS/VMM metadata: %s", err) |
| 137 | } | 137 | } |
| 138 | 138 | ||
| 139 | - if templateVMM == vmm.BackendStratoVirt && sandboxConfig.GetHugePages() { | 139 | + if templateVMM == vmm.BackendStratoVirt && templateOS != vmm.OsAndroid && sandboxConfig.GetHugePages() { |
| 140 | logger.L().Warn(ctx, "HugePages are not supported by StratoVirt; disabling HugePages", | 140 | logger.L().Warn(ctx, "HugePages are not supported by StratoVirt; disabling HugePages", |
| 141 | logger.WithSandboxID(sandboxConfig.GetSandboxId()), | 141 | logger.WithSandboxID(sandboxConfig.GetSandboxId()), |
| 142 | logger.WithTemplateID(sandboxConfig.GetTemplateId()), | 142 | logger.WithTemplateID(sandboxConfig.GetTemplateId()), |
| @@ -42,7 +42,7 @@ func (s *ServerStore) TemplateCreate(ctx context.Context, templateRequest *templ | |||
| 42 | } | 42 | } |
| 43 | 43 | ||
| 44 | hugePages := cfg.GetHugePages() | 44 | hugePages := cfg.GetHugePages() |
| 45 | - if vmmType == vmm.BackendStratoVirt && hugePages { | 45 | + if vmmType == vmm.BackendStratoVirt && osType != vmm.OsAndroid && hugePages { |
| 46 | s.buildLogger.Warn(ctx, "HugePages are not supported by StratoVirt; disabling HugePages", | 46 | s.buildLogger.Warn(ctx, "HugePages are not supported by StratoVirt; disabling HugePages", |
| 47 | logger.WithTemplateID(cfg.GetTemplateID()), | 47 | logger.WithTemplateID(cfg.GetTemplateID()), |
| 48 | logger.WithBuildID(cfg.GetBuildID()), | 48 | logger.WithBuildID(cfg.GetBuildID()), |
| @@ -356,17 +356,24 @@ func run(config cfg.Config) (success bool) { | |||
| 356 | closers = append(closers, closer{"sandbox host stats delivery", hostStatsDeliveryClickhouse.Close}) | 356 | closers = append(closers, closer{"sandbox host stats delivery", hostStatsDeliveryClickhouse.Close}) |
| 357 | } | 357 | } |
| 358 | 358 | ||
| 359 | - // cgroup manager for resource accounting | 359 | + // cgroup manager for resource accounting. A nil manager disables per-sandbox |
| 360 | - cgroupManager, err := cgroup.NewManager() | 360 | + // cgroups; keep the interface type so the nil check in the sandbox factory holds. |
| 361 | - if err != nil { | 361 | + var cgroupManager cgroup.Manager |
| 362 | - logger.L().Fatal(ctx, "failed to initialize cgroup manager", zap.Error(err)) | 362 | + if config.BuilderConfig.SandboxCgroupEnabled { |
| 363 | - } | 363 | + manager, err := cgroup.NewManager() |
| 364 | + if err != nil { | ||
| 365 | + logger.L().Fatal(ctx, "failed to initialize cgroup manager", zap.Error(err)) | ||
| 366 | + } | ||
| 364 | 367 | ||
| 365 | - if err := cgroupManager.Initialize(ctx); err != nil { | 368 | + if err := manager.Initialize(ctx); err != nil { |
| 366 | - logger.L().Fatal(ctx, "failed to initialize root cgroup", zap.Error(err)) | 369 | + logger.L().Fatal(ctx, "failed to initialize root cgroup", zap.Error(err)) |
| 367 | - } | 370 | + } |
| 368 | 371 | ||
| 369 | - logger.L().Info(ctx, "cgroup accounting enabled", zap.String("root", cgroup.RootCgroupPath)) | 372 | + cgroupManager = manager |
| 373 | + logger.L().Info(ctx, "cgroup accounting enabled", zap.String("root", cgroup.RootCgroupPath)) | ||
| 374 | + } else { | ||
| 375 | + logger.L().Info(ctx, "cgroup accounting disabled") | ||
| 376 | + } | ||
| 370 | 377 | ||
| 371 | // redis | 378 | // redis |
| 372 | redisClient, err := sharedFactories.NewRedisClient(ctx, sharedFactories.RedisConfig{ | 379 | redisClient, err := sharedFactories.NewRedisClient(ctx, sharedFactories.RedisConfig{ |
| @@ -450,6 +457,7 @@ func run(config cfg.Config) (success bool) { | |||
| 450 | // 已清理(newStorage)之后、网络池开始填充之前创建,这样其冻结的挂载表 | 457 | // 已清理(newStorage)之后、网络池开始填充之前创建,这样其冻结的挂载表 |
| 451 | // 最小且不引用任何 netns;失败仅记录日志并回退原 unshare -m 路径 | 458 | // 最小且不引用任何 netns;失败仅记录日志并回退原 unshare -m 路径 |
| 452 | fc.WarmupPinnedMountNS(ctx, config.BuilderConfig) | 459 | fc.WarmupPinnedMountNS(ctx, config.BuilderConfig) |
| 460 | + stratovirt.WarmupPinnedMountNS(ctx, config.BuilderConfig) | ||
| 453 | 461 | ||
| 454 | startService("network pool", func() error { | 462 | startService("network pool", func() error { |
| 455 | networkPool.Populate(ctx) | 463 | networkPool.Populate(ctx) |
| @@ -67,7 +67,7 @@ case "%{_target_cpu}" in | |||
| 67 | *) echo "Unsupported architecture: %{_target_cpu}" >&2; exit 1 ;; | 67 | *) echo "Unsupported architecture: %{_target_cpu}" >&2; exit 1 ;; |
| 68 | esac | 68 | esac |
| 69 | for binary in api client-proxy envd orchestrator e2b-webhook \ | 69 | for binary in api client-proxy envd orchestrator e2b-webhook \ |
| 70 | - migrator seed-db fc-netns-exec cri-multiplex; do | 70 | + migrator seed-db fc-netns-exec stratovirt-netns-exec cri-multiplex; do |
| 71 | binary_path="bin/${binary_arch}/${binary}" | 71 | binary_path="bin/${binary_arch}/${binary}" |
| 72 | [ -x "$binary_path" ] || { | 72 | [ -x "$binary_path" ] || { |
| 73 | echo "Missing built binary: $binary_path" >&2 | 73 | echo "Missing built binary: $binary_path" >&2 |


🟡 Medium Priority
证据链:
stratovirt-netns-exec加进了 orchestrator 镜像任务("${ORCHESTRATOR_IMAGE_NAME}|packages/orchestrator/Dockerfile|packages/orchestrator|orchestrator,fc-netns-exec,stratovirt-netns-exec")。该任务的 Dockerfile 是packages/orchestrator/Dockerfile,构建上下文是packages/orchestrator。deploy/dockerfiles/orchestrator-mooncake.Dockerfile:26-27,在那里加了COPY fc-netns-exec stratovirt-netns-exec。deploy/build.sh的build_and_push_dockerfiles只遍历$BIN_DIR/*.Dockerfile,而deploy/dockerfiles/目录当前只有 orchestrator-mooncake 这一个变体,说明 mooncake 变体与 build.sh 主流程用的packages/orchestrator/Dockerfile是两条独立路径。packages/orchestrator/Dockerfile未 COPY 该文件,则默认(非 mooncake)orchestrator 镜像内/opt/e2b-infra/bin/stratovirt-netns-exec不存在,而 deploy/.env 已把E2B_STRATOVIRT_NETNS_EXEC_HELPER指向该绝对路径(deploy/.env:163),一旦 orchestrator 走到需要该 helper 的分支就会以 ENOENT 失败;反之若该 Dockerfile 也未更新却又不允许缺文件,则镜像构建直接失败。建议:核对并同步更新
packages/orchestrator/Dockerfile(build.sh 实际使用的 Dockerfile),在其中COPY fc-netns-exec stratovirt-netns-exec /opt/e2b-infra/bin/并 chmod;同时确认 deploy/build.sh 把 stratovirt-netns-exec 一并 stage 到 BIN_DIR,避免只有 mooncake 变体镜像包含该 helper。