- 安排自动增加和减少快速启动池大小。
- 按预定时间表自动启动工作站。
本教程可帮助您根据典型营业时间增加和减少快速启动池大小。
目标
- 编写并部署 Cloud Run 服务,以更新工作站配置的快速启动池大小。
- 配置一个 Cloud Scheduler 作业,该作业会调度在第 1 步中创建的服务在周一至周五的 09:00-17:00 运行,以匹配太平洋标准时间 (PST) 的工作时间。
费用
在本文档中,您将使用 Google Cloud的以下收费组件:
- Cloud Scheduler
- Cloud Run
您可使用价格计算器根据您的预计使用情况来估算费用。
完成本文档中描述的任务后,您可以通过删除所创建的资源来避免继续计费。如需了解详情,请参阅清理。
准备工作
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Run, Cloud Scheduler, Cloud Workstations APIs.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the
gcloud
CLI with your federated identity. -
To initialize the
gcloud
CLI, run the following command:gcloud init
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Run, Cloud Scheduler, Cloud Workstations APIs.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the
gcloud
CLI with your federated identity. -
To initialize the
gcloud
CLI, run the following command:gcloud init
准备环境
设置以下环境变量,这些变量将由您稍后创建的自动化脚本使用。
设置您计划使用的
PROJECT_ID
和REGION
变量:PROJECT_ID=$PROJECT_ID REGION=$REGION
将 $REGION 替换为您打算使用的区域名称,例如
us-central1
。如需详细了解可用区域,请参阅 Cloud Workstations 位置。
应用架构
此解决方案包含以下 Google Cloud 组件:
- Cloud Run,以更新
WorkstationConfig
的快速启动池大小。 - Cloud Scheduler 作业:根据具体时间表进行调用以更新
WorkstationConfig
。
创建 Cloud Run 服务
第一步是设置一个简单的 Web 服务器,以侦听您在端口 8080 上收到的 HTTP 请求。由于应用已容器化,因此您可以使用任何语言编写服务器。
如需使用 Python 编写 Web 服务器监听器应用,请执行以下操作:
创建名为
workstation-config-updater
的新目录,并转到此目录中:mkdir workstation-config-updater cd workstation-config-updater
创建名为
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)
此代码会创建一个基本 Web 服务器,以侦听由
PORT
环境变量定义的端口并执行脚本update_config.sh
。创建名为
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
。创建名为
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
当系统提示您输入服务名称时,请按 Enter 键接受默认名称
workstation-config-updater
。如果系统提示您启用 Artifact Registry API 或允许创建 Artifact Registry 代码库,请按 y。
当系统提示您允许未经身份验证的调用时,请按 n。
等待部署完成。
当服务网址以以下格式显示时,请复制该网址:
SERVICE_URL=$SERVICE_URL
配置服务账号以调用 Cloud Run
您部署的 workstation-config-updater 服务不允许未经身份验证的调用。
Cloud Scheduler 需要一个具有适当凭据的服务账号才能调用 workstation-config-updater 服务。
设置服务账号
如果您还没有要用于 Cloud Scheduler 作业的服务账号,请创建一个新服务账号。
gcloud iam service-accounts create $SERVICE_ACCOUNT_NAME \ --description="$DESCRIPTION" \ --display-name="$DISPLAY_NAME"
添加必需的 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 配置
创建作业并指定从部署到 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。有关更多信息,请参阅配置作业时间表。
同样,如需在工作日结束时将工作站配置的池大小减小为 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
可选:验证作业
为确保作业按预期运行,您可以验证作业。
前往 Google Cloud 控制台中的 Cloud Scheduler 页面。
workstation-pool-increaser-cron
应显示在作业列表中。在
workstation-pool-increaser-cron
作业所在的行中,依次点击 操作 > 强制运行作业。在项目中创建的第一个作业可能需要几分钟才能运行。
在上次执行的状态列中,
Success
状态表示您已成功运行作业。
如需验证工作站配置是否已更新,请执行以下操作:
清理
为避免因本教程中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的项目,或者保留项目但删除各个资源。
移除测试项目
虽然 Cloud Run 不会对未在使用中的服务计费,但您可能仍然需要支付将容器映像存储在 Artifact Registry 中而产生的相关费用。为避免产生费用,您可以删除容器映像或删除 Google Cloud 项目。删除 Google Cloud 项目后,系统即会停止对该项目中使用的所有资源计费。
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
删除 Cloud Scheduler 作业
如需删除各个 Cloud Scheduler 资源,
前往 Google Cloud 控制台中的 Cloud Scheduler 页面。
点击作业旁边的复选框。
点击页面顶部的删除按钮并确认删除操作。
后续步骤
- 探索有关 Google Cloud 的参考架构、图表和最佳做法。查看我们的 Cloud 架构中心。