1. 简介
概览
Cloud Run 沙盒提供快速、安全且隔离的环境,用于在现有服务中执行不受信任的代码或运行工具,例如 AI 智能体编写的代码。
此 Codelab 演示了如何在 Cloud Run 沙盒中执行 nodejs 和 Python。您还将了解如何使用 --allow-egress 标志在沙盒中安装依赖项。
如需详细了解沙盒,请参阅 Cloud Run 文档中的沙盒、在沙盒中运行代码以及博文。
学习内容
- 如何在 Cloud Run 沙盒中运行代码(Node.js 和 Python)
- 如何在 Cloud Run 沙盒中安装依赖项
- 如何将 FastAPI 与 Cloud Run 搭配使用
2. 设置和要求
前提条件
- 您已登录 Cloud 控制台。
- 您之前已部署过 Cloud Run 服务。例如,您可以按照此快速入门指南部署 Cloud Run 服务,以便开始使用。
设置环境变量
首先,请确保您已配置项目 ID。
gcloud config set project <YOUR_PROJECT_ID>
您可以通过运行以下命令来验证当前项目 ID
gcloud config get project
接下来,配置您的首选地区。
export REGION=<YOUR_REGION>
3. 创建服务
虽然此 Codelab 在沙盒中运行 Node.js 和 Python 代码,但您可以使用任何语言运行代码。确保您运行的任何命令或工具都已安装在容器映像中,您将在下文中了解如何做到这一点。
首先,创建一个用于存放源代码的目录,然后通过 cd 命令进入该目录。
mkdir sandbox-codelab && cd $_
接下来,创建一个 Dockerfile。
FROM python:3.11-slim
# Install Node.js to run both python and nodejs in sandbox
RUN apt-get update && apt-get install -y curl \
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y nodejs \
&& rm -rf /var/lib/apt/lists/*
# Set working directory
WORKDIR /app
# Copy requirements and install them
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the application code
COPY main.py .
# Run the FastAPI application using python
CMD ["python", "main.py"]
接下来,创建一个包含以下内容的 requirements.txt 文件:
fastapi
uvicorn
创建一个包含以下内容的 main.py 文件:
import os
import sys
import subprocess
import shlex
from fastapi import FastAPI
from fastapi.responses import JSONResponse
import uvicorn
app = FastAPI()
def run_in_sandbox(language: str, code: str, dependency: str = None):
# Setup commands
if language == "python":
run_cmd = f"python3 -c {shlex.quote(code)}"
install_cmd = f"pip install --no-cache-dir {dependency} >&2" if dependency else ""
elif language in ("node", "nodejs"):
run_cmd = f"node -e {shlex.quote(code)}"
install_cmd = f"npm install --cache /tmp/.npm-cache {dependency} >&2" if dependency else ""
else:
raise ValueError(f"Unsupported language: {language}")
# Combine install and execution commands if dependency exists
full_inner_cmd = f"{install_cmd} && {run_cmd}" if dependency else run_cmd
# Build sandbox command
# This binary is automatically injected into the container via the --sandbox-launcher deployment flag
sandbox_cmd = [
"/usr/local/gcp/bin/sandbox",
"do",
]
if dependency:
sandbox_cmd.extend(["--write", "--allow-egress"])
sandbox_cmd.extend(["--", "/bin/bash", "-c", full_inner_cmd])
return subprocess.run(
sandbox_cmd,
capture_output=True,
text=True,
timeout=15, # Increased timeout to allow for package downloads
)
@app.get("/python")
async def execute_python():
sandbox_code = "print(20 + 45)"
try:
result = run_in_sandbox("python", sandbox_code)
return {
"stdout": result.stdout,
"stderr": result.stderr,
"exit_code": result.returncode,
}
except subprocess.TimeoutExpired:
return JSONResponse(status_code=408, content={"error": "Execution timed out"})
except Exception as e:
return JSONResponse(status_code=500, content={"error": str(e)})
@app.get("/nodejs")
async def execute_nodejs():
sandbox_code = "const isOdd = require('is-odd'); console.log('Is 13 odd?', isOdd(13));"
dependency = "is-odd"
try:
result = run_in_sandbox("nodejs", sandbox_code, dependency)
return {
"stdout": result.stdout,
"stderr": result.stderr,
"exit_code": result.returncode,
}
except subprocess.CalledProcessError as e:
return JSONResponse(status_code=400, content={"error": f"Failed to install dependency: {e.stderr}"})
except subprocess.TimeoutExpired:
return JSONResponse(status_code=408, content={"error": "Execution timed out"})
except Exception as e:
return JSONResponse(status_code=500, content={"error": str(e)})
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
4. 部署和测试
现在,部署到 Cloud Run。请注意 --sandbox-launcher 标志和 beta 发布级别。
gcloud beta run deploy sandbox-executor \
--source . \
--region $REGION \
--no-allow-unauthenticated \
--sandbox-launcher
部署完成后,将服务网址记录在环境变量中。
SERVICE_URL=$(gcloud run services describe sandbox-executor --region $REGION --format 'value(status.url)')
首先,尝试调用 python 端点,该端点会在沙盒中添加两个数字。
curl -X GET $SERVICE_URL/python \
-H "Authorization: Bearer $(gcloud auth print-identity-token)"
您应该会看到 Python 代码返回以下内容:
{"stdout":"65\n","stderr":"","exit_code":0}
现在,尝试使用 nodejs 端点,该端点会安装依赖项 (is-odd) 并在沙盒中使用它。
curl -X GET $SERVICE_URL/nodejs \
-H "Authorization: Bearer $(gcloud auth print-identity-token)"
您应该会在响应中看到以下内容(以及 stderr 中的一些 npm 日志):
{"stdout":"Is 13 odd? true\n","stderr":"...","exit_code":0}
5. 恭喜!
恭喜您完成此 Codelab!
建议您查看 Cloud Run 文档,了解沙盒以及如何在沙盒中运行代码。
所学内容
- 如何在 Cloud Run 沙盒中运行代码
- 如何在 Cloud Run 沙盒中安装依赖项
- 如何将 FastAPI 与 Cloud Run 搭配使用
6. 清理
为避免产生意外费用(例如,如果 Cloud Run 服务 sandbox-executor 的调用次数意外超过免费层级中每月 Cloud Run 调用分配的次数),您可以删除 Cloud Run 服务或删除您在第 2 步中创建的项目。
如需删除 Cloud Run 服务,请前往 Cloud Console 中的 Cloud Run 页面 (https://console.cloud.google.com/run/),然后删除您在本 Codelab 中创建的服务。
如果您选择删除整个项目,可以前往 https://console.cloud.google.com/cloud-resource-manager,选择您在第 2 步中创建的项目,然后选择“删除”。如果您删除项目,则需要在 Cloud SDK 中更改项目。您可以运行 gcloud projects list 查看所有可用项目的列表。