Cloud Run Sandbox で Python と Node.js を実行する方法

1. はじめに

概要

Cloud Run サンドボックスは、既存のサービス内で信頼できないコードを実行したり、AI エージェントによって記述されたコードなどのツールを実行したりするための、高速で安全な分離された環境を提供します。

この Codelab では、Cloud Run サンドボックスで nodejs と Python の両方を実行する方法について説明します。--allow-egress フラグを使用して、サンドボックス内に依存関係をインストールする方法についても説明します。

サンドボックスの詳細については、Cloud Run のサンドボックスに関するドキュメント、サンドボックスでコードを実行する方法、ブログ投稿をご覧ください。

学習内容

  • Cloud Run サンドボックスでコード(nodejs と Python)を実行する方法
  • Cloud Run サンドボックスに依存関係をインストールする方法
  • Cloud Run で FastAPI を使用する方法

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 ではサンドボックスで nodejs と Python のコードを実行しますが、任意の言語でコードを実行できます。後述するように、実行するコマンドまたはツールがコンテナ イメージにインストールされていることを確認してください。

まず、ソースコードのディレクトリを作成し、そのディレクトリに移動します。

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

デプロイしたら、サービス URL を環境変数に記録します。

SERVICE_URL=$(gcloud run services describe sandbox-executor --region $REGION --format 'value(status.url)')

まず、サンドボックス内で 2 つの数値を加算する python エンドポイントを呼び出してみます。

curl -X GET $SERVICE_URL/python \
    -H "Authorization: Bearer $(gcloud auth print-identity-token)"

Python コードに対して次の値が返されます。

{"stdout":"65\n","stderr":"","exit_code":0}

次に、依存関係(is-odd)をインストールしてサンドボックスで使用する nodejs エンドポイントを試します。

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 サンドボックスに依存関係をインストールする方法
  • Cloud Run で FastAPI を使用する方法

6. クリーンアップ

意図しない料金が発生しないようにするには(たとえば、Cloud Run サービス sandbox-executor が、無料枠の月間 Cloud Run 呼び出し割り当てよりも多く誤って呼び出された場合)、Cloud Run サービスを削除するか、ステップ 2 で作成したプロジェクトを削除します。

Cloud Run サービスを削除するには、Cloud コンソール(https://console.cloud.google.com/run/)で Cloud Run に移動し、この Codelab で作成したサービスを削除します。

プロジェクト全体を削除する場合は、https://console.cloud.google.com/cloud-resource-manager に移動し、ステップ 2 で作成したプロジェクトを選択して [削除] を選択します。プロジェクトを削除する場合は、Cloud SDK でプロジェクトを変更する必要があります。gcloud projects list を実行すると、使用可能なすべてのプロジェクトのリストが表示されます。