1. परिचय
खास जानकारी
Cloud Run सैंडबॉक्स, भरोसेमंद न होने वाले कोड को चलाने या टूल इस्तेमाल करने के लिए, एक तेज़, सुरक्षित, और अलग एनवायरमेंट उपलब्ध कराते हैं. जैसे, आपकी मौजूदा सेवा में एआई एजेंटों ने कोड लिखा हो.
इस कोडलैब में, Cloud Run सैंडबॉक्स में nodejs और python, दोनों को चलाने का तरीका बताया गया है. इसमें, --allow-egress फ़्लैग का इस्तेमाल करके, सैंडबॉक्स में डिपेंडेंसी इंस्टॉल करने का तरीका भी बताया गया है.
सैंडबॉक्स के बारे में ज़्यादा जानने के लिए, Cloud Run के दस्तावेज़ों में सैंडबॉक्स के बारे में जानकारी, सैंडबॉक्स में कोड चलाने का तरीका, और ब्लॉग पोस्ट पढ़ें.
आपको क्या सीखने को मिलेगा
- Cloud Run सैंडबॉक्स में कोड (nodejs और python) चलाने का तरीका
- Cloud Run सैंडबॉक्स में डिपेंडेंसी इंस्टॉल करने का तरीका
- Cloud Run के साथ FastAPI का इस्तेमाल करने का तरीका
2. सेटअप और ज़रूरी शर्तें
ज़रूरी शर्तें
- आपने Cloud Console में लॉग इन किया हो.
- आपने पहले Cloud Run सेवा डिप्लॉय की हो. उदाहरण के लिए, शुरू करने के लिए, Cloud Run सेवा डिप्लॉय करने के लिए, यह क्विकस्टार्ट फ़ॉलो करें.
एनवायरमेंट वैरिएबल सेट करना
सबसे पहले, पक्का करें कि आपने कोई प्रोजेक्ट आईडी कॉन्फ़िगर किया हो.
gcloud config set project <YOUR_PROJECT_ID>
मौजूदा प्रोजेक्ट आईडी की पुष्टि करने के लिए, यह कमांड चलाएं
gcloud config get project
इसके बाद, अपनी पसंद का इलाका कॉन्फ़िगर करें.
export REGION=<YOUR_REGION>
3. सेवा बनाना
इस कोडलैब में, सैंडबॉक्स में 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
डिप्लॉय करने के बाद, एनवायरमेंट वैरिएबल में सेवा का यूआरएल रिकॉर्ड करें.
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 में कुछ एनपीएम लॉग भी दिखेंगे:
{"stdout":"Is 13 odd? true\n","stderr":"...","exit_code":0}
5. बधाई हो!
कोडलैब पूरा करने के लिए बधाई!
हमारा सुझाव है कि आप Cloud Run के दस्तावेज़ों में सैंडबॉक्स के बारे में जानकारी और सैंडबॉक्स में कोड चलाने का तरीका देखें.
हमने क्या-क्या कवर किया
- Cloud Run सैंडबॉक्स में कोड चलाने का तरीका
- Cloud Run सैंडबॉक्स में डिपेंडेंसी इंस्टॉल करने का तरीका
- Cloud Run के साथ FastAPI का इस्तेमाल करने का तरीका
6. स्टोरेज में जगह बनाएं
अनजाने में लगने वाले शुल्क से बचने के लिए, Cloud Run सेवा sandbox-executor को अनजाने में, हर महीने Cloud Run के लिए मुफ़्त टियर में मिलने वाले कॉल की संख्या से ज़्यादा बार कॉल किया गया हो, तो Cloud Run सेवा मिटाएं या चरण 2 में बनाया गया प्रोजेक्ट मिटाएं.
Cloud Run सेवा मिटाने के लिए, Cloud Console में Cloud Run पर जाएं. इसके लिए, https://console.cloud.google.com/run/ पर जाएं और इस कोडलैब में बनाई गई सेवा को मिटाएं.
अगर आपको पूरा प्रोजेक्ट मिटाना है, तो https://console.cloud.google.com/cloud-resource-manager पर जाएं. इसके बाद, चरण 2 में बनाया गया प्रोजेक्ट चुनें और मिटाएं को चुनें. प्रोजेक्ट मिटाने पर, आपको Cloud SDK में प्रोजेक्ट बदलने होंगे. gcloud projects list चलाकर, उपलब्ध सभी प्रोजेक्ट की सूची देखी जा सकती है.