sandbox/sandbox.go
Star f9dcf07ba4 first version
supported macOS、linux
2026-03-23 00:35:27 +08:00

102 lines
3.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// sandbox.go v1.6
package sandbox
import (
"os"
"os/exec"
"sync"
)
var pluginConfig = struct {
Root string // 沙盒临时根目录物理路径
Runtime map[string]*RuntimeConfig // 运行时配置
}{}
var sandboxList = map[string]*Sandbox{}
var sandboxLock = sync.RWMutex{}
// Volume 挂载配置
type Volume struct {
Source string // 宿主机路径或类型(如 tmpfs)
Target string // 沙盒内路径
ReadOnly bool // 是否只读
}
// Limits 资源限制
type Limits struct {
Cpu float64 // CPU 核心限制 (如 0.5)
Mem float64 // 内存限制 (单位: GB)
Swap float64 // SWAP 限制 (单位: GB)
Shm uint // /dev/shm 大小 (单位: MB)
Tmp uint // /tmp 大小 (单位: MB)
}
// Config 沙盒启动配置
type Config struct {
Name string // 沙盒名称
ProjectDir string // 宿主机的工作目录自动映射到SandboxWorkDir
WorkDir string // 沙盒内的工作目录
Envs map[string]string // 环境变量
Volumes []Volume // 挂载列表
Limits Limits // 资源限制
Network struct {
AllowInternet bool // 是否允许出站网络连接,默认关闭,配置后只开放非本地网络访问
AllowLocalNetwork bool // 是否允许访问本地网络默认关闭配置后只开放10.0.0.0/8、172.16.0.0/12、192.168.0.0/16
AllowListen []int // 允许监听端口列表,默认关闭所有监听端口和进站连接
AllowList []string // 允许出站访问的 IP/端口 列表同时放开TCP&UDP在拒绝的基础上允许访问白名单
BlockList []string // 拒绝访问的 IP/端口 列表同时拒绝TCP&UDP在允许的基础上拒绝黑名单
}
Gpu struct {
Driver string // 驱动或厂商,如 "nvidia", "amd", "apple"
Devices []string // 设备 ID如 ["0", "1"] 或 ["all"]
}
ExtraOptions []string // 额外参数
AutoStart bool // 是否自动启动沙盒进程
StartCmd string
StartArgs []string
Runtime struct {
Language string
Version string
Venv string
}
NoLog bool // 是否不显示沙盒运行日志
}
// Status 沙盒实时状态信息
type Status struct {
Id string // 沙盒唯一标识 (用于目录名、Cgroup 名)
Pid int // 宿主机上的进程 PID
Alive bool // 物理进程是否正在运行
Status string // 状态
StartTime int64 // 启动时间 (Unix 时间戳)
Uptime int64 // 运行耗时 (单位: 秒)
MemoryUsage uint // 当前内存使用 (单位: MB)
CpuUsage float64 // 当前 CPU 使用率 (百分比)
}
type State struct {
Id string
Pid int
StartTime int64
WorkDir string
MountedList []string
}
type Sandbox struct {
id string
pid int
uid int
gid int
root string
workDir string
config *Config
cmd *exec.Cmd
mountedList []string
startTime int64
lastLogFd *os.File
errorLogFd *os.File
status string
lock sync.Mutex
extra map[string]any
}