排定匯出時程

本頁說明如何排定 Firestore (Datastore 模式) 資料的匯出作業。如要排定匯出作業的執行時間,建議使用 Cloud Run 函式和 Cloud Scheduler。建立可啟動匯出的 Cloud 函式,並使用 Cloud Scheduler 執行函式。

事前準備

排定資料匯出作業前,請先完成下列工作:

  1. 為 Google Cloud 專案啟用計費功能。只有啟用計費服務的專案才能使用匯出及匯入功能。 Google Cloud
  2. 在靠近Datastore 模式資料庫位置的位置,建立 Cloud Storage 值區。匯出作業需要目的地 Cloud Storage bucket。匯出作業不適用於要求者付費值區。

建立 Cloud Function 和 Cloud Scheduler 工作

請按照下列步驟建立 Cloud Function,以啟動資料匯出作業,並建立 Cloud Scheduler 工作來呼叫該函式:

建立 datastore_export Cloud 函式

  1. 前往 Google Cloud 控制台的「Cloud Functions」頁面:

    前往「Cloud Functions」頁面

  2. 按一下「建立函式」
  3. 輸入函式名稱,例如 datastoreExport
  4. 在「Trigger」(觸發條件)下方,選取「Cloud Pub/Sub」。Cloud Scheduler 會使用您的 pub/sub 主題呼叫函式。
  5. 在「主題」欄位中,選取「建立主題」。輸入 Pub/Sub 主題的名稱,例如 startDatastoreExport。記下主題名稱,因為您需要這個名稱才能建立 Cloud Scheduler 工作。
  6. 在「Source code」(原始碼) 下,選取「Inline editor」(內嵌編輯器)
  7. 在「Runtime」(執行階段) 下拉式選單中,選取「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.20.0
    
  10. 在「進入點」下方輸入 datastore_export,這是 main.py 中的函式名稱。
  11. 按一下「Deploy」(部署) 即可部署 Cloud Function。

設定存取權限

接著,授予 Cloud Function 啟動匯出作業及寫入 Cloud Storage bucket 的權限。

這項 Cloud Function 會使用專案的預設服務帳戶進行驗證,並授權匯出作業。建立專案時,系統會為您建立預設服務帳戶,名稱如下:

project_id@appspot.gserviceaccount.com

此服務帳戶需要權限才能啟動匯出作業,以及寫入 Cloud Storage 值區。如要授予這些權限,請將下列身分與存取權管理角色指派給預設服務帳戶:

  • Cloud Datastore Import Export Admin
  • 值區的 Storage Object User 角色

您可以使用 Google Cloud CLI 指派這些角色。您可以在控制台的 Cloud Shell 中存取這項工具: Google Cloud
啟動 Cloud Shell

  1. 指派 Cloud Datastore 匯入匯出管理員角色。取代 project_id,然後執行下列指令:

    gcloud projects add-iam-policy-binding project_id \
        --member serviceAccount:project_id@appspot.gserviceaccount.com \
        --role roles/datastore.importExportAdmin
  2. 在值區中指派 Storage 物件使用者角色。取代 bucket_nameproject_id,然後執行下列 指令:

    gcloud storage buckets add-iam-policy-binding gs://bucket_name \
        --member=serviceAccount:project_id@appspot.gserviceaccount.com \
        --role=roles/storage.objectUser

建立 Cloud Scheduler 工作

接著,建立呼叫 datastore_export Cloud 函式的 Cloud Scheduler 工作:

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

    前往 Cloud Scheduler

  2. 按一下 [Create Job] (建立工作)

  3. 輸入工作「名稱」,例如 scheduledDatastoreExport

  4. unix-cron 格式輸入頻率

  5. 選取「時區」

  6. 在「目標」下方,選取「Pub/Sub」。在「主題」欄位中,輸入您與 Cloud Function 一併定義的 Pub/Sub 主題名稱,如上例中的 startDatastoreExport

  7. 在「酬載」欄位中,輸入 JSON 物件來設定匯出作業。datastore_export Cloud 函式需要 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 Function 的記錄。

查看 Cloud Functions 記錄檔

如要確認 Cloud Function 是否已順利啟動匯出作業,請查看 Google Cloud 控制台的「記錄檔探索工具」頁面。

前往記錄檔探索工具

Cloud 函式的記錄檔會回報錯誤和成功啟動的匯出作業。

查看匯出進度

您可以使用 gcloud datastore operations list 指令查看匯出作業的進度,請參閱列出所有長時間執行的作業

匯出作業完成後,您可以在 Cloud Storage 值區中查看輸出檔案。代管匯出服務會使用時間戳記來整理匯出作業:

前往 Cloud Storage