איך מריצים Python ו-Node.js בארגז חול של Cloud Run

1. מבוא

סקירה כללית

ארגזי חול של Cloud Run מספקים סביבה מהירה, מאובטחת ומבודדת להרצת קוד לא מהימן או להפעלת כלים, כמו קוד שנכתב על ידי סוכני 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 בארגז החול, אפשר להריץ קוד בכל שפה. חשוב לוודא שכל פקודה או כלי שמריצים מותקנים בקובץ אימג' של קונטיינר, כמו שמוסבר בהמשך.

קודם יוצרים ספרייה לקוד המקור ועוברים לספרייה הזו באמצעות הפקודה 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

אחרי הפריסה, מתעדים את כתובת ה-URL של השירות במשתנה סביבה.

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)"

בתגובה אמורים להופיע הנתונים הבאים (יחד עם כמה יומני 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 בכתובת https://console.cloud.google.com/run/ ומוחקים את השירות שיצרתם ב-codelab הזה.

אם אתם רוצים למחוק את הפרויקט כולו, אתם יכולים להיכנס לכתובת https://console.cloud.google.com/cloud-resource-manager, לבחור את הפרויקט שיצרתם בשלב 2 וללחוץ על 'מחיקה'. אם תמחקו את הפרויקט, תצטרכו לשנות את הפרויקטים ב-Cloud SDK. כדי לראות את רשימת כל הפרויקטים הזמינים, מריצים את הפקודה gcloud projects list.