Isolate Integration
这个 crate 提供了一个 Rust 接口来使用 ioi/isolate 沙箱程序。
使用 tokio 异步运行时来管理沙箱的生命周期和执行命令。
前提条件
首先,确保系统已安装 isolate。请参考 ioi/isolate。
关于 isolate 的配置,参阅 isolate document 的 INSTALLATION 部分。
如果需要使用 cgroup 相关特性(推荐,如 --cg-mem 选项),请确保系统支持 cgroup v2。
基本用法
isolate 用法、选项含义等请参考 isolate document。
下面是一个示例:
use ;
async
高级配置
目录绑定
use DirectoryRule;
let sandbox = new
// 绑定外部目录到沙箱内部
.with_directory_rule
// 创建临时目录
.with_directory_rule
// 绑定系统目录(只读,禁止执行)
.with_directory_rule
// 挂载文件系统
.with_directory_rule;
环境变量
use EnvRule;
let sandbox = new
// 继承环境变量
.with_env_rule
// 设置环境变量
.with_env_rule
// 继承所有环境变量
.with_env_rule;
资源限制
let limits = new
.with_time_limit // CPU 时间限制
.with_wall_time_limit // 墙钟时间限制
.with_memory_limit // 内存限制
.with_cg_memory_limit // 控制组内存限制
.with_open_files_limit // 打开文件数限制
.with_file_size_limit // 单文件大小限制
.with_process_limit; // 进程数限制
特殊选项
let sandbox = new
.use_cgroups // 启用控制组(默认已启用)
.disable_cgroups // 禁用控制组
.share_network // 共享网络命名空间
.no_default_dirs // 不绑定默认目录
.verbose; // 详细输出
编译和运行示例
参见 examples/sandbox_usage.rs 中的完整示例,
运行示例:
API 简要参考
IsolateSandbox
主要的沙箱类,提供以下方法:
new(box_id: u32)- 创建新的沙箱实例init(&self, limits: &ResourceLimits)- 初始化沙箱run<I, S>(&self, program: &str, args: I, limits: &ResourceLimits)- 运行命令cleanup(&self)- 清理沙箱disable_cgroups(self)- 禁用控制组(如果不需要)
ResourceLimits
资源限制配置:
with_time_limit(seconds: f64)- 设置 CPU 时间限制with_memory_limit(kb: u32)- 设置内存限制with_wall_time_limit(seconds: f64)- 设置墙上时间限制with_process_limit(count: u32)- 设置进程数限制。与isolate的--processes选项不同,不给出该限制时允许无限制的进程数。
DirectoryRule
目录绑定规则:
bind(inside, outside)- 绑定外部目录bind_same(path)- 绑定到相同路径tmp(path)- 创建临时目录filesystem(name)- 挂载文件系统
ExecutionResult
执行结果包含:
exit_code: Option<i32>- 退出码signal: Option<i32>- 信号time_used: f64- CPU 时间wall_time_used: f64- 墙上时间memory_used: u32- 内存使用killed: bool- 是否被杀死stdout: String- 标准输出stderr: String- 标准错误