本教程介绍如何使用 Cloud Scheduler 和 Cloud Run 函数为 Filestore 实例安排备份。
如需了解如何使用代管式服务调度程序创建备份,请参阅 Filestore 增强型备份。
目标
- 为 Cloud Scheduler 创建一个客户端服务账号,该账号具有调用 Cloud Run functions 函数所需的凭据。
- 为 Cloud Run functions 创建一个客户端服务账号,该账号具有调用 Filestore 端点的凭据。
- 创建一个 Cloud Run functions 函数,用于创建 Filestore 实例的备份。
- 创建一个 Cloud Run functions 函数,用于删除 Filestore 实例的备份。
- 创建以固定时间间隔运行任一函数的 Cloud Scheduler 作业。
费用
在本文档中,您将使用 Google Cloud的以下收费组件:
- Artifact Registry API
- Cloud Build API
- Filestore API
- Cloud Functions API
- Cloud Logging API
- Pub/Sub API
- Cloud Run Admin API
- Cloud Scheduler API
如需根据您的预计使用量来估算费用,请使用价格计算器。
准备工作
- 登录您的 Google Cloud 账号。如果您是 Google Cloud新手,请 创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Artifact Registry, Cloud Build, Filestore, Cloud Run functions, Cloud Logging, Pub/Sub, Cloud Run, and Cloud Scheduler APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
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.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Artifact Registry, Cloud Build, Filestore, Cloud Run functions, Cloud Logging, Pub/Sub, Cloud Run, and Cloud Scheduler APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
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 - 如果您的项目中没有 Filestore 实例,您必须先创建一个。
为 Cloud Scheduler 和 Cloud Run functions 创建客户端服务账号
如果您尚未这样做,请在 Google Cloud 控制台中点击激活 Cloud Shell。
创建 Cloud Scheduler 作为其运行的客户端服务账号,以调用 Cloud Run functions 函数。在此示例中,使用
iam service-accounts create命令将账号命名为schedulerunner,并将显示名称设置为“Service Account for FS Backups-Scheduler”:gcloud iam service-accounts create schedulerunner \ --display-name="Service Account for FS Backups-Scheduler"创建一个客户端服务账号,Cloud Run 函数将以该账号的身份运行,以调用 Filestore 端点。在此示例中,我们将账号命名为
backupagent,并将显示名设置为“FS Backups-GCF 的服务账号”:gcloud iam service-accounts create backupagent \ --display-name="Service Account for FS Backups-GCF"您可以运行
iam service-accounts list命令来检查是否已创建服务账号:gcloud iam service-accounts list该命令会返回如下内容:
NAME EMAIL DISABLED Service Account for FS Backups-GCF backupagent@$PROJECT_ID.iam.gserviceaccount.com False Service Account for FS Backups-Scheduler schedulerunner@$PROJECT_ID.iam.gserviceaccount.com False
设置环境变量
在本地环境中设置以下环境变量:
Google Cloud 项目 ID 和项目:
export PROJECT_ID=`gcloud config get-value core/project` export PROJECT_NUMBER=`gcloud projects describe $PROJECT_ID --format="value(projectNumber)"`Cloud Scheduler 服务代理和 Cloud Scheduler 与 Cloud Run functions 的客户端服务账号:
export SCHEDULER_SA=service-$PROJECT_NUMBER@gcp-sa-cloudscheduler.iam.gserviceaccount.com export SCHEDULER_CLIENT_SA=schedulerunner@$PROJECT_ID.iam.gserviceaccount.com export GCF_CLIENT_SA=backupagent@$PROJECT_ID.iam.gserviceaccount.com您的 Filestore 实例:
export SOURCE_INSTANCE_LOCATION=fs-location export SOURCE_INSTANCE_NAME=instance-id export SHARE_NAME=file-share-name替换以下内容:
- 将 fs-location 替换为源 Filestore 实例所在的可用区或区域。
- 将 instance-id 替换为源 Filestore 实例的实例 ID。
- 将 file-share-name 替换为您为从实例提供的 NFS 文件共享所指定的名称。
为 Filestore 备份设置环境变量:
export BACKUP_REGION=backup-region将 backup-region 替换为要存储备份的区域。
创建用于创建备份的函数
在 Google Cloud 控制台中,前往 Cloud Run functions 页面。
点击编写函数,然后按如下方式配置函数:
- 配置:
- 服务名称:在此示例中,我们将函数命名为
fsbackup。 - 区域:在此示例中,选择
us-central1。 - 运行时:从菜单中选择 Cloud Run functions 完全支持的任何受支持的 Python 3 运行时。
- 服务名称:在此示例中,我们将函数命名为
- 触发器:
- 此示例无需设置触发器。
- 鉴别:选择
Require authentication。 - 入站:选择
All。 - 容器、卷、网络、安全性
- 前往安全标签页,然后从菜单中选择
Service Account for FS Backups-GCF(backupagent@$PROJECT_ID.iam.gserviceaccount.com)。
- 前往安全标签页,然后从菜单中选择
- 配置:
点击创建,然后继续进行如下配置:
- 函数入口点:输入
create_backup。 将以下依赖项添加到
requirements.txt文件中:functions-framework==3.* google-auth==2.29.0 requests==2.31.0根据您的使用情形,您可能需要指定其他依赖项及其相应的版本号。如需了解详情,请参阅预安装的软件包。
使用内嵌编辑器将以下 Python 代码示例复制到
main.py文件中:创建备份
此代码示例会创建一个名为
mybackup-的备份,并在其后附加创建时间。PROJECT_ID = 'project-id' SOURCE_INSTANCE_LOCATION = 'fs-location' SOURCE_INSTANCE_NAME = 'instance-id' SOURCE_FILE_SHARE_NAME = 'file-share-name' BACKUP_REGION = 'backup-region' import functions_framework import google.auth import google.auth.transport.requests from google.auth.transport.requests import AuthorizedSession import time import requests import json credentials, project = google.auth.default() auth_request = google.auth.transport.requests.Request() credentials.refresh(auth_request) authed_session = AuthorizedSession(credentials) def get_backup_id(): return "mybackup-" + time.strftime("%Y%m%d-%H%M%S") @functions_framework.http def create_backup(request): trigger_run_url = "https://file.googleapis.com/v1/projects/{}/locations/{}/backups?backupId={}".format(PROJECT_ID, BACKUP_REGION, get_backup_id()) headers = { 'Content-Type': 'application/json' } post_data = { "description": "my new backup", "source_instance": "projects/{}/locations/{}/instances/{}".format(PROJECT_ID, SOURCE_INSTANCE_LOCATION, SOURCE_INSTANCE_NAME), "source_file_share": "{}".format(SOURCE_FILE_SHARE_NAME) } print("Making a request to " + trigger_run_url) r = authed_session.post(url=trigger_run_url, headers=headers, data=json.dumps(post_data)) data = r.json() print(data) if r.status_code == requests.codes.ok: print(str(r.status_code) + ": The backup is uploading in the background.") else: raise RuntimeError(data['error']) return "Backup creation has begun!"替换以下内容:
- 将 project-id 替换为源 Filestore 实例的 Google Cloud 项目 ID。
- 将 fs-location 替换为源 Filestore 实例的可用区或区域。
- 将 instance-id 替换为源 Filestore 实例的名称。
- 将 file-share-name 替换为文件共享的名称。
- 将 backup-region 替换为存储备份的地区。
点击测试。
Cloud Shell 中会打开一个新的标签页会话。如果成功,该消息中会返回以下内容:
Backup creation has begun!点击保存并重新部署,然后等待部署完成。
切换回之前的 Cloud Shell 标签页。
删除备份
此代码示例会删除早于预定义时段的备份。
您一次只能删除每个源实例的一个备份。如需了解详情,请参阅备份。
使用与创建备份时所用的函数相同的方式配置此函数,但需进行以下修改:
- 函数名称:
deletefsbackup。 - 入口点:
delete_backup。
PROJECT_ID = 'project-id' BACKUP_REGION = 'region' BACKUP_RETENTION_TIME_HRS = hours import functions_framework import google.auth import google.auth.transport.requests from google.auth.transport.requests import AuthorizedSession import time import requests import json credentials, project = google.auth.default() auth_request = google.auth.transport.requests.Request() credentials.refresh(auth_request) authed_session = AuthorizedSession(credentials) retention_seconds = BACKUP_RETENTION_TIME_HRS * 60 * 60 @functions_framework.http def delete_backup(request): now = time.time() backup_list = [] trigger_run_url = "https://file.googleapis.com/v1/projects/{}/locations/{}/backups".format(PROJECT_ID, BACKUP_REGION) r = authed_session.get(trigger_run_url) data = r.json() if not data: print("No backups to delete.") return "No backups to delete." else: backup_list.extend(data['backups']) while "nextPageToken" in data.keys(): nextPageToken = data['nextPageToken'] trigger_run_url_next = "https://file.googleapis.com/v1/projects/{}/locations/{}/backups?pageToken={}".format(PROJECT_ID, BACKUP_REGION, nextPageToken) r = authed_session.get(trigger_run_url_next) data = r.json() backup_list.extend(data['backups']) for i in backup_list: backup_time = i['createTime'] backup_time = backup_time[:-4] backup_time = float(time.mktime(time.strptime(backup_time, "%Y-%m-%dT%H:%M:%S.%f"))) i['backup_timestamp'] = backup_time sorted_backup_list = sorted(backup_list, key=lambda d: d['backup_timestamp']) oldest_backup = sorted_backup_list[0] if now - oldest_backup['backup_timestamp'] > retention_seconds: print(oldest_backup['name'] + " is older than the indicated retention time.") r = authed_session.delete("https://file.googleapis.com/v1/{}".format(oldest_backup['name'])) data = r.json() print(data) if r.status_code == requests.codes.ok: print(str(r.status_code) + ": Deleting " + oldest_backup['name'] + " in the background.") else: raise RuntimeError(data['error']) return "Backup deletion has begun!" return "All backups are within the indicated retention period."替换以下内容:
- 将 project-id 替换为备份的 Google Cloud 项目 ID。
- region 替换为备份所在的区域。备份、调度器作业和函数应位于同一位置。
- 将 hours 替换为保留备份的小时数。例如,如果您想将备份保留 10 天,请输入
240。
- 函数入口点:输入
将 IAM 角色分配给客户端服务账号
将 Cloud Scheduler 服务代理添加到 Cloud Scheduler 客户端服务账号的 IAM 政策中,并为其分配
roles/cloudscheduler.serviceAgent角色。这样,服务代理就可以模拟客户服务账号,以便调用用于创建备份的函数。运行iam service-accounts add-iam-policy-binding命令:gcloud iam service-accounts add-iam-policy-binding $SCHEDULER_CLIENT_SA \ --member=serviceAccount:$SCHEDULER_SA \ --role=roles/cloudscheduler.serviceAgent为 Cloud Run 函数的客户端服务账号授予
roles/file.editor角色,以便该服务账号可以调用 Filestore 端点。运行projects add-iam-policy-binding命令:gcloud projects add-iam-policy-binding $PROJECT_ID \ --member=serviceAccount:$GCF_CLIENT_SA \ --role=roles/file.editor为要使用的函数授予 Cloud Scheduler 的服务账号
roles/run.invoker角色。运行以下run services add-iam-policy-binding命令:创建备份
gcloud run services add-iam-policy-binding fsbackup \ --member serviceAccount:$SCHEDULER_CLIENT_SA \ --role roles/run.invoker \ --region=us-central1现在,只有 Cloud Scheduler 的客户端服务账号可以调用
fsbackup。删除备份
gcloud run services add-iam-policy-binding deletefsbackup \ --member serviceAccount:$SCHEDULER_CLIENT_SA \ --role roles/run.invoker现在,只有 Cloud Scheduler 的客户端服务账号可以调用
deletefsbackup。
创建 Cloud Scheduler 作业,以按指定的时间表触发函数
创建备份
在本教程的示例中,如果您想安排在每个工作日的晚上 10 点进行备份,可以使用
scheduler jobs create http命令:gcloud scheduler jobs create http fsbackupschedule \ --schedule "0 22 * * 1-5" \ --http-method=GET \ --uri=https://fsbackup-$PROJECT_NUMBER.us-central1.run.app \ --oidc-service-account-email=$SCHEDULER_CLIENT_SA \ --location=us-central1您可以使用 unix-cron 格式通过
--schedule标志指定作业的运行频率。如需了解详情,请参阅配置 Cron 作业时间表。每个实例每小时最多可以创建 6 个备份。
启动上一步中创建的 Cloud Scheduler 作业。在我们的示例中,使用
scheduler jobs runs命令立即运行该作业:gcloud scheduler jobs run fsbackupschedulefsbackupschedule作业会在您执行命令后立即调用fsbackup函数,然后每天(工作日)晚上 10 点再次调用该函数,直到作业暂停。检查
fsbackup函数的日志,看看它是否正常执行并返回status 200。如需在 Google Cloud 控制台中查看日志,请使用 Logs Explorer:
-
在 Google Cloud 控制台中,前往 Logs Explorer 页面:
如果您使用搜索栏查找此页面,请选择子标题为 Logging 的结果。
最近的日志会显示在查询结果窗格中。
-
使用
backups list命令检查现有备份的状态:gcloud filestore backups list该命令会返回类似如下的内容:
NAME LOCATION SRC_INSTANCE SRC_FILE_SHARE STATE mybackup-20201123-184500 us-central1 us-central1-c/instances/nfs-server vol1 READY
删除备份
在本教程的示例中,如果您想安排一项操作,以在每个工作日的晚上 10 点删除备份,则可以使用
scheduler jobs create http命令:gcloud scheduler jobs create http deletefsbackupschedule \ --schedule "0 22 * * 1-5" \ --http-method=GET \ --uri=https://us-central1-$PROJECT_ID.cloudfunctions.net/deletefsbackup \ --oidc-service-account-email=$SCHEDULER_CLIENT_SA \ --oidc-token-audience=https://us-central1-$PROJECT_ID.cloudfunctions.net/deletefsbackup您可以使用 unix-cron 格式通过
--schedule标志指定作业的运行频率。如需了解详情,请参阅配置 Cron 作业时间表。与同一来源实例关联的备份
delete操作必须一次执行一个。如需了解详情,请参阅备份。启动上一步中创建的 Cloud Scheduler 作业。在我们的示例中,我们使用
scheduler jobs runs命令立即运行它:gcloud scheduler jobs run deletefsbackupschedule在您执行该命令后,
deletefsbackupschedule作业会立即调用deletefsbackup函数,然后会在每个工作日的晚上 10 点再次调用该函数,直到作业暂停。检查
deletefsbackup函数的日志,看看它是否正常执行并返回status 200。如需在 Google Cloud 控制台中查看日志,请使用 Logs Explorer:
-
在 Google Cloud 控制台中,前往 Logs Explorer 页面:
如果您使用搜索栏查找此页面,请选择子标题为 Logging 的结果。
最近的日志会显示在查询结果窗格中。
-
使用
backups list命令检查现有备份的状态:gcloud filestore backups list该命令会返回类似如下的内容:
NAME LOCATION SRC_INSTANCE SRC_FILE_SHARE STATE mybackup-20201123-184500 us-central1 us-central1-c/instances/nfs-server vol1 READY
备份配额不足提醒
如果您在实现备份调度时面临备份配额即将用尽的风险,建议您设置备份配额不足提醒。这样,您会在备份配额即将用尽时收到通知。
清理
完成本教程后,您可以清理您创建的资源,让它们停止使用配额,以免产生费用。以下部分介绍如何删除或关闭这些资源。
删除项目
为了避免产生费用,最简单的方法是删除您为本教程创建的项目。
要删除项目,请执行以下操作:
- 在 Google Cloud 控制台中,前往管理资源页面。
- 在项目列表中,选择要删除的项目,然后点击删除。
- 在对话框中输入项目 ID,然后点击关闭以删除项目。
后续步骤
- 了解 Filestore 快照。
- 详细了解 Filestore 备份。
- 了解如何安排 Filestore Enterprise 快照的创建时间。