使用 Cloud Scheduler 和 Cloud Run 排定工作站作業


本教學課程說明如何使用 Cloud Scheduler 和 Cloud Run 自動執行作業,例如:

  • 排定自動增加和減少「快速啟動集區大小」
  • 依排程自動啟動工作站。

本教學課程說明如何配合一般營業時間,增加及減少快速啟動集區大小

目標

  1. 撰寫及部署 Cloud Run 服務,更新工作站設定的「快速啟動集區大小」
  2. 設定 Cloud Scheduler 工作,將步驟 1 中建立的服務排程設定為在太平洋標準時間的週一到週五 09:00 到 17:00 執行,以配合營業時間。

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

  • Cloud Scheduler
  • Cloud Run

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 Google Cloud 的使用者可能符合免費試用資格。

完成本文所述工作後,您可以刪除已建立的資源,避免繼續計費。詳情請參閱清除所用資源一節。

事前準備

  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. Enable the Cloud Run, Cloud Scheduler, Cloud Workstations APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

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

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

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

    Go to project selector

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

  10. Enable the Cloud Run, Cloud Scheduler, Cloud Workstations APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

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

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

    gcloud init

準備環境

設定下列環境變數,這些變數會用於稍後建立的自動化指令碼。

  1. 設定要使用的 PROJECT_IDREGION 變數:

    PROJECT_ID=$PROJECT_ID
    REGION=$REGION
    

    $REGION 替換為您打算使用的區域名稱,例如 us-central1

    如要進一步瞭解可用區域,請參閱「Cloud Workstations 服務據點」。

應用程式架構

本解決方案包含下列 Google Cloud 元件:

  • Cloud Run,更新 WorkstationConfig 的「快速啟動集區大小」
  • Cloud Scheduler 工作:依照設定的排程進行呼叫,以更新 WorkstationConfig

系統架構圖:顯示如何使用 Cloud Scheduler 和 Cloud Run 排定工作站作業

建立 Cloud Run 服務

第一步是設定簡易網路伺服器,監聽通訊埠 8080 收到的 HTTP 要求。由於應用程式已容器化,因此您可以使用任何語言編寫伺服器。

如要使用 Python 編寫網路伺服器接聽應用程式,請按照下列步驟操作:

  1. 建立名為 workstation-config-updater 的新目錄,然後將目錄變更為該目錄:

    mkdir workstation-config-updater
    cd workstation-config-updater
    
  2. 建立名為 app.py 的檔案,將下列程式碼貼入其中:

    import os, subprocess
    from flask import Flask, request, abort
    
    app = Flask(__name__)
    
    @app.route("/", methods=["POST"])
    def update():
        app.logger.info("Update request received.")
        data = request.json
        cluster = data["cluster"]
        region = data["region"]
        pool_size = data["pool-size"]
    
        path = os.path.join(app.root_path, "update_config.sh")
        o = subprocess.run(
            [path, cluster, region, pool_size],
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
        )
        app.logger.info("Sending response:", o.stdout)
        return o.stdout
    
    if __name__ == "__main__":
        app.run(host="0.0.0.0", port=8080, debug=True)
    

    這段程式碼會建立基本的網路伺服器,用於監聽 PORT 環境變數定義的通訊埠,並執行 update_config.sh 指令碼。

  3. 建立名為 update_config.sh 的檔案,將下列程式碼貼入其中:

    #!/bin/bash
    
    set -e
    
    if [ $# -ne 3 ]
    then
       echo "Usage: update_config.sh CLUSTER REGION POOL_SIZE"
       exit 1
    fi
    
    CLUSTER=$1
    REGION=$2
    POOL_SIZE=$3
    
    # list workstation configs
    echo "Attempting to list workstation configs in cluster $CLUSTER and region $REGION ..."
    for CONFIG in $(gcloud  workstations configs list --cluster $CLUSTER --region $REGION --format="value(NAME)"); do
        echo "Attempting to update Quick Pool Size to $POOL_SIZE for config $CONFIG ..."
        # update the workstation config pool-size
        RET=$(gcloud workstations configs update $CONFIG --cluster $CLUSTER  --region $REGION --pool-size=$POOL_SIZE)
        if [[ $RET -eq 0 ]]; then
            echo "Workstation config $CONFIG updated."
        else
            echo "Workstation config $CONFIG update failed."
        fi
    done
    
    

    這個指令碼會使用 gcloud 指令列出指定叢集中的所有 WorkstationConfig,並將「快速入門集區大小」更新為 POOL_SIZE

  4. 建立名為 Dockerfile 的檔案,將下列程式碼貼入其中:

    FROM google/cloud-sdk
    
    RUN apt-get update && apt-get install -y python3-pip python3
    
    # Copy local code to the container image.
    ENV APP_HOME /app
    WORKDIR $APP_HOME
    COPY . ./
    
    RUN /bin/bash -c 'ls -la; chmod +x ./update_config.sh'
    
    # Install production dependencies.
    RUN pip3 install Flask gunicorn
    
    # Run the web service on container startup
    CMD exec gunicorn --bind :8080 --workers 1 --threads 8 app:app
    

    這段程式碼會將應用程式容器化,以便部署至 Cloud Run。

部署至 Cloud Run

如要部署至 Cloud Run,請執行下列指令:

gcloud run deploy --source . --project $PROJECT_ID --region $REGION
  1. 系統提示您輸入服務名稱時,請按下「Enter」鍵,接受預設名稱 workstation-config-updater

  2. 如果系統提示您啟用 Artifact Registry API 或允許建立 Artifact Registry 存放區,請按下 y

  3. 系統提示允許未經驗證的叫用時,請按下 n

  4. 等待部署作業完成。

  5. 如果服務網址的格式如下,請複製該網址:

SERVICE_URL=$SERVICE_URL

設定用來叫用 Cloud Run 的服務帳戶

您部署的 workstation-config-updater 服務不允許未經驗證的叫用。

Cloud Scheduler 需要具備適當憑證的服務帳戶,才能呼叫 workstation-config-updater 服務。

設定服務帳戶

  1. 如果您還沒有要用於 Cloud Scheduler 工作的服務帳戶,請建立新的服務帳戶

    gcloud iam service-accounts create $SERVICE_ACCOUNT_NAME \
        --description="$DESCRIPTION" \
        --display-name="$DISPLAY_NAME"
  2. 新增必要的 IAM 角色繫結,允許服務帳戶叫用 Cloud Run。

    gcloud run services add-iam-policy-binding workstation-config-updater \
        --member=serviceAccount:$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com \
        --region $REGION \
        --role=roles/run.invoker

建立具備驗證機制的 Cloud Scheduler 設定

  1. 建立工作,並指定從「Deploy to Cloud Run」(部署至 Cloud Run) 複製的 URL

    gcloud scheduler jobs create http workstation-pool-increaser-cron \
        --http-method=POST \
        --location=us-central1 \
        --schedule="0 9 * * 1-5" \
        --time-zone="America/Los_Angeles" \
        --headers "Content-Type=application/json" \
        --message-body='{"cluster":"$CLUSTER", "region":"$REGION", "pool-size": "2"}' \
        --uri=$SERVICE_URL \
        --oidc-service-account-email=$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com

    這項指令會排定工作,在 WorkstationCluster $CLUSTER 中,將所有 WorkstationConfigs 的「快速入門集區大小」從週一到週五的太平洋標準時間上午 9 點,增加至 2。

    詳情請參閱設定工作時間表一文。

  2. 同樣地,如要在工作日結束時將工作站設定的集區大小縮減為 0,請執行下列指令:

    gcloud scheduler jobs create http workstation-pool-decreaser-cron \
        --http-method=POST \
        --location=$REGION \
        --schedule="0 17 * * 1-5" \
        --time-zone="America/Los_Angeles" \
        --headers "Content-Type=application/json" \
        --message-body='{"cluster":"$CLUSTER", "region":"$REGION", "pool-size": "0"}' \
        --uri=$SERVICE_URL \
        --oidc-service-account-email=$SERVICE-ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com

選用:驗證工作

如要確保工作正常運作,可以驗證工作。

  1. 前往 Google Cloud 控制台的「Cloud Scheduler」頁面。

    前往 Cloud Scheduler

    workstation-pool-increaser-cron 應該會顯示在工作清單中。

  2. workstation-pool-increaser-cron 工作的資料列中,依序按一下「 Actions」(動作) >「Force a job run」(強制執行工作)

    在專案中建立的第一項工作可能需要幾分鐘的時間才能執行。

  3. 如果在「Status of last execution」(上次執行狀態) 欄中看到 Success 狀態,表示工作執行成功。

如要確認工作站設定已更新,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「工作站設定」頁面。

    前往工作站設定頁面

  2. 確認「快速啟動集區大小」為 2。

  3. 查看 Cloud Run 服務的記錄

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

移除測試專案

雖然 Cloud Run 在服務未用時不會產生費用,但將容器映像檔儲存於 Artifact Registry 仍可能會產生費用。您可以刪除容器映像檔或刪除 Google Cloud 專案,以免產生費用。刪除 Google Cloud 專案後,系統就會停止對專案使用的所有資源收取費用。

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

刪除 Cloud Scheduler 工作

如要刪除個別 Cloud Scheduler 資源,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「Cloud Scheduler」頁面。

    前往 Cloud Scheduler

  2. 按一下工作旁邊的核取方塊。

  3. 按一下頁面頂端的 [Delete] (刪除) 按鈕,並確認您要刪除工作。

後續步驟

  • 探索 Google Cloud 的參考架構、圖表和最佳做法。 歡迎瀏覽我們的雲端架構中心