วิธีเรียกใช้ Python และ Node.js ในแซนด์บ็อกซ์ของ Cloud Run

1. บทนำ

ภาพรวม

แซนด์บ็อกซ์ของ Cloud Run มีสภาพแวดล้อมที่รวดเร็ว ปลอดภัย และแยกจากกันเพื่อเรียกใช้โค้ดที่ไม่น่าเชื่อถือหรือเครื่องมือต่างๆ เช่น โค้ดที่เขียนโดย Agentic AI ภายในบริการที่มีอยู่

Codelab นี้จะแสดงวิธีเรียกใช้ทั้ง nodejs และ python ในแซนด์บ็อกซ์ของ Cloud Run นอกจากนี้ คุณจะได้ดูวิธีติดตั้งการพึ่งพาภายในแซนด์บ็อกซ์โดยใช้แฟล็ก --allow-egress

ดูข้อมูลเพิ่มเติมเกี่ยวกับแซนด์บ็อกซ์ได้ในเอกสารประกอบของ Cloud Run สำหรับ แซนด์บ็อกซ์ วิธี เรียกใช้โค้ดในแซนด์บ็อกซ์ และใน บล็อกโพสต์

สิ่งที่คุณจะได้เรียนรู้

  • วิธีเรียกใช้โค้ด (nodejs และ python) ในแซนด์บ็อกซ์ของ Cloud Run
  • วิธีติดตั้งการพึ่งพาในแซนด์บ็อกซ์ของ Cloud Run
  • วิธีใช้ FastAPI กับ Cloud Run

2. การตั้งค่าและข้อกำหนด

ข้อกำหนดเบื้องต้น

  • คุณเข้าสู่ระบบ Cloud Console แล้ว
  • คุณเคยทำให้บริการ Cloud Run ใช้งานได้แล้ว เช่น คุณสามารถทำตามคู่มือเริ่มต้นฉบับย่อนี้เพื่อทำให้บริการ Cloud Run ใช้งานได้เพื่อเริ่มต้นใช้งาน

ตั้งค่าตัวแปรสภาพแวดล้อม

ขั้นแรก ตรวจสอบว่าคุณได้กำหนดค่ารหัสโปรเจ็กต์แล้ว

gcloud config set project <YOUR_PROJECT_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)')

ขั้นแรก ลองเรียกปลายทาง python ซึ่งจะเพิ่มตัวเลข 2 ตัวภายในแซนด์บ็อกซ์

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

คุณควรเห็นผลลัพธ์ต่อไปนี้สำหรับโค้ด Python

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

ตอนนี้ลองใช้ปลายทาง nodejs ซึ่งจะติดตั้งทรัพยากร Dependency (is-odd) และใช้ทรัพยากร Dependency ในแซนด์บ็อกซ์

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

คุณควรเห็นผลลัพธ์ต่อไปนี้ในการตอบกลับ (พร้อมกับบันทึก npm บางรายการใน stderr)

{"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 Run ใน Cloud Console ที่ https://console.cloud.google.com/run/ แล้วลบบริการที่คุณสร้างใน Codelab นี้

หากต้องการลบทั้งโปรเจ็กต์ ให้ไปที่ https://console.cloud.google.com/cloud-resource-manager เลือกโปรเจ็กต์ที่สร้างในขั้นตอนที่ 2 แล้วเลือก "ลบ" หากลบโปรเจ็กต์ คุณจะต้องเปลี่ยนโปรเจ็กต์ใน Cloud SDK คุณสามารถดูรายการโปรเจ็กต์ทั้งหมดที่พร้อมใช้งานได้โดยเรียกใช้ gcloud projects list