安排导出

本页面介绍了如何安排导出 Datastore 模式 Firestore 数据。如需按时间表运行导出作业,我们建议使用 Cloud Functions 和 Cloud Scheduler。创建启动导出的 Cloud Functions 函数,并使用 Cloud Scheduler 运行您的函数。

准备工作

在安排数据导出作业之前,您必须先完成以下几项任务:

  1. 为 Google Cloud 项目启用结算功能。只有启用了结算功能的 Google Cloud 项目才能使用导出和导入功能。
  2. Datastore 模式数据库的位置附近创建一个 Cloud Storage 存储桶。导出操作需要一个目标 Cloud Storage 存储桶。您不能使用“请求者付款”存储桶执行导出操作。

创建 Cloud Functions 函数和 Cloud Scheduler 作业

请按照以下步骤创建一个 Cloud Functions 函数(用于启动数据导出作业)和一个 Cloud Scheduler 作业(用于调用该函数):

创建 datastore_export Cloud Functions 函数

  1. 转到 Google Cloud 控制台中的 Cloud Functions 页面:

    转到 Cloud Functions

  2. 点击创建函数
  3. 输入函数名称,例如 datastoreExport
  4. 触发器下,选择 Cloud Pub/Sub。Cloud Scheduler 使用您的 pub/sub 主题来调用函数。
  5. 主题字段中,选择创建主题。为 Pub/Sub 主题输入一个名称,例如 startDatastoreExport。请记下此主题名称,以便在创建 Cloud Scheduler 作业时使用。
  6. 源代码下,选择內嵌编辑器
  7. 运行时下拉列表中,选择 Python 3.7
  8. main.py 输入以下代码:
    # Copyright 2021 Google LLC All Rights Reserved.
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    import base64
    import json
    import os
    
    from google.cloud import datastore_admin_v1
    
    project_id = os.environ.get("GCP_PROJECT")
    client = datastore_admin_v1.DatastoreAdminClient()
    
    def datastore_export(event, context):
        """Triggers a Datastore export from a Cloud Scheduler job.
    
        Args:
            event (dict): event[data] must contain a json object encoded in
                base-64. Cloud Scheduler encodes payloads in base-64 by default.
                Object must include a 'bucket' value and can include 'kinds'
                and 'namespaceIds' values.
            context (google.cloud.functions.Context): The Cloud Functions event
                metadata.
        """
        if "data" in event:
            # Triggered via Cloud Scheduler, decode the inner data field of the json payload.
            json_data = json.loads(base64.b64decode(event["data"]).decode("utf-8"))
        else:
            # Otherwise, for instance if triggered via the Cloud Console on a Cloud Function, the event is the data.
            json_data = event
    
        bucket = json_data["bucket"]
        entity_filter = datastore_admin_v1.EntityFilter()
    
        if "kinds" in json_data:
            entity_filter.kinds = json_data["kinds"]
    
        if "namespaceIds" in json_data:
            entity_filter.namespace_ids = json_data["namespaceIds"]
    
        export_request = datastore_admin_v1.ExportEntitiesRequest(
            project_id=project_id, output_url_prefix=bucket, entity_filter=entity_filter
        )
        operation = client.export_entities(request=export_request)
        response = operation.result()
        print(response)
    
  9. requirements.txt 中,添加以下依赖项:
    google-cloud-datastore==2.19.0
    
  10. 入口点下,输入 datastore_export,即 main.py 中函数的名称。
  11. 点击部署以部署该 Cloud Functions 函数。

配置访问权限

接下来,请向 Cloud Functions 函数授予启动导出操作以及向 Cloud Storage 存储桶写入内容的权限。

此 Cloud Functions 函数使用您项目的默认服务账号来对其导出操作进行身份验证和授权。当您创建项目时,系统将使用以下名称为您创建一个默认服务账号:

project_id@appspot.gserviceaccount.com

该服务账号需要具备启动导出操作以及向 Cloud Storage 存储桶写入内容的权限。如需授予这些权限,请将以下 IAM 角色分配给默认服务账号:

  • Cloud Datastore Import Export Admin
  • 针对存储桶的 OwnerStorage Admin 角色

您可以使用 gcloudgsutil 命令行工具分配这些角色。您可以通过 Google Cloud 控制台中的 Cloud Shell 访问这些工具:
启动 Cloud Shell

  1. 分配 Cloud Datastore Import Export Admin 角色。 替换 project_id,然后运行以下命令:

    gcloud projects add-iam-policy-binding project_id \
        --member serviceAccount:project_id@appspot.gserviceaccount.com \
        --role roles/datastore.importExportAdmin
    
  2. 分配针对存储桶的 Storage Admin 角色。替换 project_idbucket_name,然后运行以下命令:

    gsutil iam ch serviceAccount:project_id@appspot.gserviceaccount.com:admin \
        gs://bucket_name
    

创建 Cloud Scheduler 作业

接下来,创建一个 Cloud Scheduler 作业以调用 datastore_export Cloud Functions 函数:

  1. 转到 Google Cloud 控制台中的 Cloud Scheduler 页面:

    转到 Cloud Scheduler

  2. 点击创建作业

  3. 为作业输入名称,例如 scheduledDatastoreExport

  4. 输入 unix-cron 格式频率

  5. 选择时区

  6. 目标下选择 Pub/Sub。在主题字段中,输入与 Cloud Functions 函数一起定义的 Pub/Sub 主题的名称,即上例中的 startDatastoreExport

  7. 载荷字段中,输入一个 JSON 对象以配置导出操作。datastore_export Cloud Functions 函数需要 bucket 值。您可以选择性地添加 kindsnamespaceIDs 值以设置实体过滤条件,例如:

    导出所有实体

    {
    "bucket": "gs://bucket_name"
    }
    

    使用实体过滤条件导出

    • 从所有命名空间中导出 UserTask 种类的实体:

      {
      "bucket": "gs://bucket_name",
      "kinds": ["User", "Task"]
      }
      

    • 从默认命名空间和 Testers 命名空间中导出 UserTask 种类的实体。使用空字符串 ("") 可以指定默认命名空间:

      {
      "bucket": "gs://bucket_name",
      "kinds": ["User", "Task"],
      "namespaceIds": ["", "Testers"]
      }
      

    • 从默认命名空间和 Testers 命名空间中导出任何种类的实体。使用空字符串 ("") 可以指定默认命名空间:

      {
      "bucket": "gs://bucket_name",
      "namespaceIds": ["", "Testers"]
      }
      

    其中 bucket_name 是您的 Cloud Storage 存储桶的名称。

  8. 点击创建

测试预定导出

如需测试您的 Cloud Function 和 Cloud Scheduler 作业,请在 Google Cloud 控制台的 Cloud Scheduler 页面中运行 Cloud Scheduler 作业。如果成功,将启动实际导出操作。

  1. 在 Google Cloud 控制台中,转到 Cloud Scheduler 页面。
    转到 Cloud Scheduler

  2. 在新 Cloud Scheduler 作业所在的行中,点击立即运行

    几秒钟后,点击刷新。Cloud Scheduler 作业应将结果列更新为成功,将上次运行时间更新为当前时间。

Cloud Scheduler 页面仅会确认作业已将消息发送到 pub/sub 主题。如需查看您的导出请求是否成功,请查看您的 Cloud Functions 函数的日志。

查看 Cloud Functions 函数日志

如需查看 Cloud Function 是否成功启动导出操作,请参阅 Google Cloud 控制台中的日志浏览器页面。

转到 Logs Explorer

Cloud Functions 函数的日志会报告错误和成功启动的导出。

查看导出操作进度

您可以使用 gcloud datastore operations list 命令查看导出操作的进度,请参阅列出所有长时间运行的操作

导出操作完成后,您可以查看 Cloud Storage 存储桶中的输出文件。代管式导出服务使用时间戳来组织您的导出操作:

转到 Cloud Storage