在 Cloud Run 中建構及建立 Go 工作

瞭解如何建立簡單的 Cloud Run 作業,然後從來源部署,這會自動將程式碼封裝到容器映像檔中、將容器映像檔上傳至 Artifact Registry,然後部署至 Cloud Run。您也可以使用其他語言。

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Install the Google Cloud CLI.

  5. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  8. Make sure that billing is enabled for your Google Cloud project.

  9. Install the Google Cloud CLI.

  10. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. 啟用 Cloud Run Admin API 和 Cloud Build API:

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

    啟用 Cloud Run Admin API 後,系統會自動建立 Compute Engine 預設服務帳戶。

  13. 將下列 IAM 角色授予 Cloud Build 服務帳戶。

    按一下即可查看 Cloud Build 服務帳戶的必要角色

    除非您覆寫這項行為,否則 Cloud Build 會自動使用 Compute Engine 預設服務帳戶做為預設的 Cloud Build 服務帳戶,建構您的原始碼和 Cloud Run 資源。如要讓 Cloud Build 建構來源,請要求管理員將 Cloud Run Builder (roles/run.builder) 授予專案中的 Compute Engine 預設服務帳戶:

      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
          --role=roles/run.builder
      

    請將 PROJECT_NUMBER 替換為專案編號,並將 PROJECT_ID 替換為專案 ID。 Google CloudGoogle Cloud如需如何找出專案 ID 和專案編號的詳細操作說明,請參閱「建立及管理專案」。

    將 Cloud Run 建構者角色授予 Compute Engine 預設服務帳戶後,需要幾分鐘才能傳播

撰寫範例工作

如要以 Go 撰寫工作:

  1. 建立名為 jobs 的新目錄,然後將目錄變更為該目錄:

    mkdir jobs
    cd jobs
    
  2. 在同一個目錄中,建立 main.go 檔案做為實際工作程式碼。將下列範例行複製到該檔案中:

    package main
    
    import (
    	"fmt"
    	"log"
    	"math/rand"
    	"os"
    	"strconv"
    	"time"
    )
    
    type Config struct {
    	// Job-defined
    	taskNum    string
    	attemptNum string
    
    	// User-defined
    	sleepMs  int64
    	failRate float64
    }
    
    func configFromEnv() (Config, error) {
    	// Job-defined
    	taskNum := os.Getenv("CLOUD_RUN_TASK_INDEX")
    	attemptNum := os.Getenv("CLOUD_RUN_TASK_ATTEMPT")
    	// User-defined
    	sleepMs, err := sleepMsToInt(os.Getenv("SLEEP_MS"))
    	failRate, err := failRateToFloat(os.Getenv("FAIL_RATE"))
    
    	if err != nil {
    		return Config{}, err
    	}
    
    	config := Config{
    		taskNum:    taskNum,
    		attemptNum: attemptNum,
    		sleepMs:    sleepMs,
    		failRate:   failRate,
    	}
    	return config, nil
    }
    
    func sleepMsToInt(s string) (int64, error) {
    	sleepMs, err := strconv.ParseInt(s, 10, 64)
    	return sleepMs, err
    }
    
    func failRateToFloat(s string) (float64, error) {
    	// Default empty variable to 0
    	if s == "" {
    		return 0, nil
    	}
    
    	// Convert string to float
    	failRate, err := strconv.ParseFloat(s, 64)
    
    	// Check that rate is valid
    	if failRate < 0 || failRate > 1 {
    		return failRate, fmt.Errorf("Invalid FAIL_RATE value: %f. Must be a float between 0 and 1 inclusive.", failRate)
    	}
    
    	return failRate, err
    }
    
    func main() {
    	config, err := configFromEnv()
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	log.Printf("Starting Task #%s, Attempt #%s ...", config.taskNum, config.attemptNum)
    
    	// Simulate work
    	if config.sleepMs > 0 {
    		time.Sleep(time.Duration(config.sleepMs) * time.Millisecond)
    	}
    
    	// Simulate errors
    	if config.failRate > 0 {
    		if failure := randomFailure(config); failure != nil {
    			log.Fatalf("%v", failure)
    		}
    	}
    
    	log.Printf("Completed Task #%s, Attempt #%s", config.taskNum, config.attemptNum)
    }
    
    // Throw an error based on fail rate
    func randomFailure(config Config) error {
    	rand.Seed(time.Now().UnixNano())
    	randomFailure := rand.Float64()
    
    	if randomFailure < config.failRate {
    		return fmt.Errorf("Task #%s, Attempt #%s failed.", config.taskNum, config.attemptNum)
    	}
    	return nil
    }
    

    使用者可以透過 Cloud Run 工作指定工作要執行的工作數量。這個程式碼範例說明如何使用內建的 CLOUD_RUN_TASK_INDEX 環境變數。每個工作都代表一個正在執行的容器副本。 請注意,工作通常會並行執行。如果每個工作都能獨立處理部分資料,使用多個工作就很有幫助。

    每項工作都會知道自己的索引,並儲存在 CLOUD_RUN_TASK_INDEX 環境變數中。內建的 CLOUD_RUN_TASK_COUNT 環境變數包含透過 --tasks 參數在工作執行時間提供的任務數量。

    程式碼也顯示如何使用內建的 CLOUD_RUN_TASK_ATTEMPT 環境變數重試工作。這個變數包含這項工作重試的次數,第一次嘗試時為 0,每次重試都會遞增 1,最多為 --max-retries

    您也可以透過這段程式碼產生失敗,測試重試機制並產生錯誤記錄,瞭解錯誤記錄的樣貌。

  3. 使用以下內容建立 go.mod 檔案:

    module github.com/GoogleCloudPlatform/golang-samples/run/jobs
    
    go 1.23.0
    

程式碼已完成,可以封裝在容器中。

建構工作容器、傳送至 Artifact Registry,並部署至 Cloud Run

重要事項:本快速入門導覽課程假設您在用於快速入門導覽課程的專案中,具備擁有者或編輯者角色。否則,請參閱 Cloud Run Source Developer 角色,瞭解從來源部署 Cloud Run 資源所需的權限。

本快速入門導覽課程會使用從來源部署功能,建構容器、將容器上傳至 Artifact Registry,並將工作部署至 Cloud Run:

gcloud run jobs deploy job-quickstart \
    --source . \
    --tasks 50 \
    --set-env-vars SLEEP_MS=10000 \
    --set-env-vars FAIL_RATE=0.1 \
    --max-retries 5 \
    --region REGION \
    --project=PROJECT_ID

其中 PROJECT_ID 是您的專案 ID,REGION 則是您的區域,例如 europe-west1。請注意,您可以將各種參數變更為您想用於測試的值。SLEEP_MS 會模擬工作,並導致 X% 的工作失敗,方便您實驗平行處理和重試失敗工作。FAIL_RATE

在 Cloud Run 中執行工作

如要執行剛建立的工作,請按照下列指示操作:

gcloud run jobs execute job-quickstart --region REGION

REGION 替換為您在建立及部署工作時使用的區域,例如 europe-west1

後續步驟

如要進一步瞭解如何從程式碼來源建構容器並推送至存放區,請參閱: