如何在 Cloud Run Sandbox 中執行 Python 和 Node.js

1. 簡介

總覽

Cloud Run 沙箱提供快速、安全且隔離的環境,可在現有服務中執行不受信任的程式碼或工具,例如 AI 代理程式編寫的程式碼。

本程式碼實驗室說明如何在 Cloud Run 沙箱中執行 nodejs 和 python。您也會瞭解如何使用 --allow-egress 標記,在沙箱中安裝依附元件。

如要進一步瞭解沙箱,請參閱 Cloud Run 說明文件中的沙箱、如何在沙箱中執行程式碼,以及這篇網誌文章。

課程內容

  • 如何在 Cloud Run 沙箱中執行程式碼 (Node.js 和 Python)
  • 如何在 Cloud Run 沙箱中安裝依附元件
  • 如何搭配使用 FastAPI 與 Cloud Run

2. 設定和需求條件

必要條件

  • 您已登入 Cloud Console。
  • 您先前已部署 Cloud Run 服務。舉例來說,您可以按照這篇快速入門導覽課程部署 Cloud Run 服務,開始使用 Cloud Run。

設定環境變數

首先,請確認您已設定專案 ID。

gcloud config set project <YOUR_PROJECT_ID>

您可以執行下列指令,驗證目前的專案 ID:

gcloud config get project

接著設定偏好的區域。

export REGION=<YOUR_REGION>

3. 建立服務

雖然這個程式碼研究室會在沙箱中執行 nodejs 和 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. 恭喜!

恭喜您完成本程式碼研究室!

建議您參閱 Cloud Run 說明文件,瞭解沙箱和如何在沙箱中執行程式碼。

涵蓋內容

  • 如何在 Cloud Run 沙箱中執行程式碼
  • 如何在 Cloud Run 沙箱中安裝依附元件
  • 如何搭配使用 FastAPI 與 Cloud Run

6. 清理

為避免產生意外費用 (例如,Cloud Run 服務 sandbox-executor 意外叫用次數超過免費層級的每月 Cloud Run 叫用次數配額),您可以刪除 Cloud Run 服務,或刪除在步驟 2 中建立的專案。

如要刪除 Cloud Run 服務,請前往 Cloud 控制台的 Cloud Run 頁面 (https://console.cloud.google.com/run/),然後刪除您在本程式碼研究室中建立的服務。

如要刪除整個專案,請前往 https://console.cloud.google.com/cloud-resource-manager,選取您在步驟 2 中建立的專案,然後選擇「刪除」。刪除專案後,您必須在 Cloud SDK 中變更專案。如要查看所有可用專案的清單,請執行 gcloud projects list。