Sandbox environment for code execution
Project description
沙箱环境
一个用于安全运行代码和命令的隔离环境。
目录结构
.
├── README.md # 项目说明文档
├── Dockerfile # Docker镜像构建文件
├── requirements.txt # Python依赖包列表
├── pyproject.toml # Python项目配置文件
├── azure-pipelines.yml # Azure DevOps CI/CD流水线配置
├── load_env.sh # 环境变量加载脚本
├── src/ # 源代码目录
│ ├── sandbox_runtime/ # 主要源代码目录
│ │ ├── __init__.py # Python包初始化文件
│ │ ├── errors.py # 全局错误定义
│ │ ├── main.py # 程序入口点
│ │ ├── python_runner/ # Python运行器相关代码
│ │ ├── sandbox/ # 沙箱核心实现
│ │ │ ├── README.md # 沙箱模块说明
│ │ │ ├── config/ # 配置相关
│ │ │ ├── core/ # 核心执行逻辑
│ │ │ │ ├── context.py # 执行上下文
│ │ │ │ ├── errors.py # 核心错误定义
│ │ │ │ ├── executor.py # 执行器实现
│ │ │ │ ├── result.py # 结果处理
│ │ │ ├── sandbox/ # 沙箱实例管理
│ │ │ │ ├── daemon.py # 沙箱守护进程
│ │ │ │ ├── instance.py # 沙箱实例
│ │ │ │ ├── pool.py # 沙箱池管理
│ │ │ ├── shared_env/ # 共享环境实现
│ │ │ │ ├── shared_env.py # 共享环境主模块
│ │ │ │ ├── run_isolated.sh # 隔离环境运行脚本
│ │ │ │ ├── cleanup.sh # 清理脚本
│ │ │ │ ├── api_doc.yaml # API文档
│ │ │ │ ├── app/ # 应用工厂和生命周期管理
│ │ │ │ │ ├── factory.py # FastAPI应用工厂
│ │ │ │ │ ├── lifespan.py # 生命周期管理
│ │ │ │ │ ├── config.py # 配置定义
│ │ │ │ ├── models/ # 数据模型
│ │ │ │ ├── routes/ # API路由
│ │ │ │ │ ├── execution.py # 代码执行相关路由
│ │ │ │ │ ├── file_operations.py # 文件操作路由
│ │ │ │ │ ├── management.py # 管理相关路由
│ │ │ │ │ ├── session.py # 会话管理路由
│ │ │ │ ├── utils/ # 工具函数
│ │ │ │ │ ├── session_utils.py # 会话工具
│ │ │ ├── ssh/ # SSH相关实现
│ │ │ ├── utils/ # 沙箱工具函数
│ │ ├── sdk/ # SDK客户端
│ │ │ ├── base.py # SDK基类
│ │ │ ├── shared_env.py # 共享环境SDK
│ │ │ ├── utils/ # SDK工具函数
│ │ ├── settings.py # 全局设置
│ │ ├── utils/ # 通用工具函数
│ │ │ ├── clean_task.py # 清理任务
│ │ │ ├── common.py # 通用工具
│ │ │ ├── efast_downloader.py # EFAST下载器
│ │ │ ├── http_api.py # HTTP API工具
│ │ │ ├── loggers.py # 日志工具
├── examples/ # 使用示例
│ ├── download_example.py # 下载示例
│ ├── efast_download_example.py # EFAST下载示例
│ ├── jupyter_gateway_example.py # Jupyter网关示例
│ ├── jupyter_gateway_ws_example.py # Jupyter网关WebSocket示例
│ ├── shared_env_example.py # 共享环境使用示例
├── test/ # 测试代码
│ ├── test_sdk.py # SDK测试
│ ├── test_shared_env_server.py # 共享环境服务测试
├── sandbox_runtime/ # Helm Chart相关
│ ├── Chart.yaml # Helm Chart元数据
│ ├── values.yaml # Helm Chart默认配置
│ ├── _componentMeta.json # 组件元数据
│ ├── templates/ # Helm模板
│ │ ├── deployment.yaml # Deployment模板
│ │ ├── service.yaml # Service模板
特性
- 在隔离环境中安全执行代码
- 文件系统操作与权限管理
- 命令执行与资源限制
- 会话管理
- 文件上传/下载功能
- 健康监控
- Kubernetes 和 Docker 支持
架构
系统包含两个主要组件:
-
SDK(客户端库)
- 用于与沙箱环境交互的 Python 客户端库
- 处理会话管理、文件操作和命令执行
- 为开发者提供简单的接口
-
服务器(FastAPI 应用)
- 基于 FastAPI 的服务器,管理沙箱环境
- 处理来自 SDK 的 HTTP 请求
- 管理文件系统操作和命令执行
- 提供健康监控端点
配置
环境变量配置
沙箱支持通过环境变量进行配置,可以在部署时灵活调整沙箱参数:
| 环境变量 | 类型 | 默认值 | 说明 |
|---|---|---|---|
SANDBOX_CPU_QUOTA |
int | 2 | CPU 配额 |
SANDBOX_MEMORY_LIMIT |
int | 131072 | 内存限制(KB),默认 128MB |
SANDBOX_ALLOW_NETWORK |
bool | true | 是否允许网络访问 |
SANDBOX_TIMEOUT_SECONDS |
int | 300 | 执行超时时间(秒) |
SANDBOX_MAX_USER_PROGRESS |
int | 10 | 最大用户进程数 |
SANDBOX_POOL_SIZE |
int | 2 | 沙箱池大小 |
Kubernetes 部署配置
在 values.yaml 中配置沙箱参数:
# 沙箱配置
sandbox:
cpuQuota: 2
memoryLimit: 131072 # 128 * 1024 in KB
allowNetwork: true
timeoutSeconds: 300
maxUserProgress: 10
poolSize: 2
安装
环境要求
- Python 3.8+
- Docker
- Kubernetes 集群(用于生产环境部署)
Python 包
服务器端
pip install sandbox_runtime
客户端
pip install sandbox_runtime[sdk]
Docker
构建 Docker 镜像:
docker build -t sandbox-runtime .
运行容器:
docker run -d -p 9101:9101 --name sandbox-runtime sandbox-runtime
Kubernetes
- 添加 Helm 仓库:
helm repo add sandbox-runtime https://your-helm-repo-url
helm repo update
- 安装 Chart:
helm install sandbox-runtime sandbox-runtime/sandbox_runtime
- 在
values.yaml中配置:
# 服务配置
service:
type: ClusterIP # 或 LoadBalancer、NodePort
port: 8000
headless: true # 启用 headless 服务以直接访问 Pod
# 部署配置
deployment:
replicas: 3
resources:
requests:
memory: "256Mi"
cpu: "200m"
limits:
memory: "512Mi"
cpu: "500m"
# 会话配置
session:
size: "50M" # 默认会话大小
timeout: 3600 # 会话超时时间(秒)
使用
基本用法
from sdk.shared_env import SharedEnvSandbox
# 初始化
sandbox = SharedEnvSandbox(session_id="test-session", servers=["http://localhost:9101"])
# 执行代码
result = await sandbox.execute_code("print('Hello, World!')", filename="test.py")
print(result["stdout"]) # 输出: Hello, World!
# 执行命令
result = await sandbox.execute("ls", "-l")
print(result["stdout"])
# 清理
await sandbox.close()
文件操作
# 上传文件
with open("local_file.txt", "rb") as f:
env.upload_file(session_id, f, "remote_file.txt")
# 下载文件
content = env.download_file(session_id, "remote_file.txt")
# 列出文件
files = env.list_files(session_id)
API 参考
SDK 方法
create_session(size: str) -> str- 创建会话delete_session(session_id: str) -> None- 删除会话create_file(session_id: str, content: str, filename: str, mode: int) -> dict- 创建文件list_files(session_id: str) -> list- 列出文件upload_file(session_id: str, file: BinaryIO, filename: str) -> dict- 上传文件download_file(session_id: str, filename: str) -> bytes- 下载文件execute_command(session_id: str, command: str, args: list) -> dict- 执行命令execute_code(session_id: str, code: str, filename: str, script_type: str) -> dict- 执行代码get_status(session_id: str) -> dict- 获取状态cleanup_all(force: bool = False) -> dict- 清理所有环境
服务器端点
GET /workspace/se/healthy- 健康检查POST /workspace/se/session/{session_id}- 创建会话DELETE /workspace/se/session/{session_id}- 删除会话POST /workspace/se/create/{session_id}- 创建文件GET /workspace/se/files/{session_id}- 列出文件POST /workspace/se/upload/{session_id}- 上传文件GET /workspace/se/download/{session_id}/{filename}- 下载文件POST /workspace/se/execute/{session_id}- 执行命令POST /workspace/se/execute_code/{session_id}- 执行代码GET /workspace/se/status/{session_id}- 获取会话状态POST /workspace/se/cleanup-all- 清理所有会话
开发
本地开发
- 克隆仓库:
git clone https://github.com/your-org/sandbox_runtime.git
cd sandbox_runtime
- 安装开发依赖:
pip install -e ".[dev]"
- 运行测试:
pytest
Docker 开发
- 构建开发镜像:
docker build -t sandbox-runtime-dev -f Dockerfile.dev .
- 运行开发容器:
docker run -it --rm -v $(pwd):/app sandbox-runtime-dev
Kubernetes 开发
- 安装开发 Chart:
helm install sandbox-runtime-dev ./helm/sandbox-runtime --set environment=dev
- 端口转发访问服务:
kubectl port-forward svc/sandbox-runtime 8000:8000
安全特性
- 每个会话在隔离环境中运行
- 文件系统操作限制在会话目录内
- 命令执行限制在允许的命令范围内
- 每个会话的资源使用限制
- 输入验证和净化
- 适当的错误处理和日志记录
贡献
- Fork 仓库
- 创建特性分支
- 提交更改
- 推送到分支
- 创建 Pull Request
许可证
本项目采用 MIT 许可证 - 详见 LICENSE 文件。
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file kweaver_sandbox_runtime-0.1.1.tar.gz.
File metadata
- Download URL: kweaver_sandbox_runtime-0.1.1.tar.gz
- Upload date:
- Size: 91.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.19
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5d42a53b9ea3d4f5cbd08a617537553a130979b1aa59db9decbd47e787d71e45
|
|
| MD5 |
ae8f3304db07e3c8be6db7a5c0dff024
|
|
| BLAKE2b-256 |
8d660bba8f1ce17886ca0a51f4e7e072cba9e6a2907469bd84631d970b22ccee
|
File details
Details for the file kweaver_sandbox_runtime-0.1.1-py3-none-any.whl.
File metadata
- Download URL: kweaver_sandbox_runtime-0.1.1-py3-none-any.whl
- Upload date:
- Size: 107.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.19
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4c425749c8457907e92b0c19a34705e514003fb40c9588d093bdd4230bf3c8e7
|
|
| MD5 |
18ef05a843885fc309d3f5b915c82d4c
|
|
| BLAKE2b-256 |
00c200509aa3e408f4570372df3ff39a25141b36ea1f1581138a0d7cd62314b1
|