יצירת מאגר עובדים ב-Cloud Run למינויים ב-Pub/Sub שמבוססים על משיכה

1. מבוא

סקירה כללית

מאגרי עובדים הם משאב ב-Cloud Run שנועד במיוחד לעומסי עבודה שלא קשורים לבקשות, כמו תורים של משימות pull. חשוב לזכור שבמאגרי עובדים לא זמינות התכונות הבאות:

  • אין נקודת קצה או כתובת URL
  • אין דרישה שהקונטיינר שנפרס יאזין לבקשות ביציאה
  • ללא שינוי גודל אוטומטי

ב-codelab הזה תיצרו מאגר עובדים שיאחזר באופן רציף הודעות ממינוי מסוג pull ב-Pub/Sub. מידע נוסף על מינויי pull ל-Pub/Sub זמין בתיעוד ובדוגמת הקוד הזו.

מה תלמדו

  • איך יוצרים ומבצעים פריסה למאגר עובדים ב-Cloud Run
  • איך מאחזרים הודעות ממינוי Pub/Sub מבוסס-משיכה

2. הגדרה ודרישות

קודם כל, מגדירים את משתני הסביבה של ה-Codelab הזה:

export PROJECT_ID=<your_project_id>
export REGION=<your_region>

export WORKER_POOL_NAME=codelab-workers-pubsub
export SERVICE_ACCOUNT=worker-pools-sa
export SERVICE_ACCOUNT_EMAIL=${SERVICE_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com
export TOPIC=pull-pubsub-topic

לאחר מכן, מגדירים את gcloud לשימוש במזהה הפרויקט

gcloud config set project $PROJECT_ID

לפני שמתחילים להשתמש ב-codelab הזה, מפעילים את ממשקי ה-API הבאים באמצעות הפקודה:

gcloud services enable run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com \
    pubsub.googleapis.com

יוצרים את חשבון השירות על ידי הרצת הפקודה:

gcloud iam service-accounts create ${SERVICE_ACCOUNT} \
  --display-name="Service account for worker pool codelab"

לבסוף, נותנים לחשבון השירות ב-Cloud Run גישה ל-PubSub:

gcloud projects add-iam-policy-binding $PROJECT_ID \
    --member serviceAccount:$SERVICE_ACCOUNT_EMAIL \
    --role='roles/pubsub.admin'

3. יצירת מאגר העובדים של Cloud Run

קודם יוצרים ספרייה לקוד של מאגר העובדים:

mkdir codelab-worker-pools
cd codelab-worker-pools

לאחר מכן, יוצרים קובץ בשם package.json

{
    "name": "codelab-worker-pools",
    "version": "1.0.0",
    "description": "A codelab example of a Cloud Run worker pool retrieving messages from a Pull-based PubSub subscription",
    "main": "index.js",
    "scripts": {
        "start": "node index.js"
    },
    "engines": {
        "node": ">=22.0.0"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "@google-cloud/pubsub": "^5.1.0"
    }
}

עכשיו יוצרים קובץ בשם index.js:

'use strict';

const subscriptionNameOrId = 'pull-pubsub-topic';

const { PubSub } = require('@google-cloud/pubsub');

// Creates a Pub/Sub client; cache this for further use.
const pubSubClient = new PubSub();

// References an existing subscription.
const subscription = pubSubClient.subscription(subscriptionNameOrId);

// This function is called when a shutdown signal is received.
const handleShutdown = async (signal) => {
  console.log(`\n${signal} signal caught. Shutting down gracefully...`);

  try {
    // 1. Stop listening for new messages. The `close()` method returns a Promise.
    console.log('Closing Pub/Sub subscription...');
    await subscription.close();
    console.log('Pub/Sub subscription closed.');

    // 2. Add any other cleanup logic here, like closing database connections.

  } catch (err) {
    console.error('Error during graceful shutdown:', err);
  } finally {
    console.log('Worker Pool exited.');
    process.exit(0);
  }
};

// Listen for termination signals.
// SIGINT handles Ctrl+C locally.
// SIGTERM handles signals from services like Cloud Run.
process.on('SIGINT', () => handleShutdown('SIGINT'));
process.on('SIGTERM', () => handleShutdown('SIGTERM'));

// ------------------ Pub/Sub Message Handling ------------------

// Create an event handler to process incoming messages.
const messageHandler = message => {
  console.log(`Received message ${message.id}:`);
  console.log(`\tData: ${message.data}`);
  console.log(`\tAttributes: ${JSON.stringify(message.attributes)}`);

  // Ack the message so it is not sent again.
  message.ack();
};

// Register the message handler and listen for messages.
subscription.on('message', messageHandler);

console.log(
  `Worker started. Listening for messages on "${subscriptionNameOrId}".`
);
console.log('If running locally, press Ctrl+C to quit.');

// The application will now listen for messages indefinitely until a shutdown
// signal is received.

4. פריסת מאגר העובדים

מריצים את הפקודה הבאה כדי ליצור את מאגר העובדים של Cloud Run:

gcloud beta run worker-pools deploy $WORKER_POOL_NAME --region=$REGION --source .

הפקודה הזו יוצרת את האימג' ממקור ופורסת את הג'וב. התהליך יימשך כמה דקות.

5. פרסום הודעה ב-PubSub

יצירת נושא PubSub

gcloud pubsub topics create $TOPIC

יצירת מינוי PubSub מסוג pull

gcloud pubsub subscriptions create codelab-subscription --topic=$TOPIC

מריצים את הפקודה הבאה כדי לפרסם הודעה בנושא ב-PubSub.

gcloud pubsub topics publish $TOPIC --message "Hello Worker Pools"

בדיקת היומנים של מאגר העובדים

gcloud logging read 'resource.type="cloud_run_worker_pool" AND resource.labels.worker_pool_name="'$WORKER_POOL_NAME'" AND resource.labels.location="'$REGION'"' --limit 10

הערך Hello Worker Pools אמור להופיע ביומנים.

6. מחיקת מאגר העובדים

מאגרי העובדים פועלים באופן רציף, ולכן כדאי למחוק את מאגר העובדים.

gcloud beta run worker-pools delete $WORKER_POOL_NAME --region $REGION

7. מעולה!

כל הכבוד על השלמת ה-Codelab!

מומלץ לעיין במסמכי התיעוד של Cloud Run.

מה נכלל

  • איך יוצרים ומבצעים פריסה למאגר עובדים ב-Cloud Run
  • איך מאחזרים הודעות ממינוי Pub/Sub מבוסס-משיכה

8. הסרת המשאבים

כדי למחוק את מאגר העובדים של Cloud Run, נכנסים למסוף Cloud Run בכתובת https://console.cloud.google.com/run ומוחקים את codelab-workers-pubsub מאגר העובדים.

כדי למחוק את הפרויקט כולו, עוברים אל Manage Resources (ניהול משאבים), בוחרים את הפרויקט שיצרתם בשלב 2 ולוחצים על Delete (מחיקה). אם תמחקו את הפרויקט, תצטרכו לשנות את הפרויקטים ב-Cloud SDK. כדי לראות את רשימת כל הפרויקטים הזמינים, מריצים את הפקודה gcloud projects list.