エクスポートのスケジュール

このページでは、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 ジョブを作成します。

Cloud Functions の関数 datastore_export を作成する

  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_exportmain.py 内の関数の名前)を入力します。
  11. [デプロイ] をクリックして Cloud Functions の関数をデプロイします。

アクセス権限を構成する

次は、Cloud Functions の関数に、エクスポート オペレーションを開始する権限と Cloud Storage バケットに書き込む権限を付与します。

この Cloud Functions の関数は、プロジェクトのデフォルト サービス アカウントを使用して、エクスポート オペレーションを認証および承認します。プロジェクトを作成すると、次の名前のデフォルト サービス アカウントが作成されます。

project_id@appspot.gserviceaccount.com

このサービス アカウントには、エクスポート オペレーションを開始する権限と、Cloud Storage バケットに書き込む権限が必要です。これらの権限を付与するには、次の IAM ロールをデフォルトのサービス アカウントに割り当てます。

  • Cloud Datastore Import Export Admin
  • バケットに対する Owner ロールまたは Storage Admin ロール

gcloud および gsutil コマンドライン ツールを使用して、これらのロールを割り当てることが可能です。これらのツールには、Google Cloud Console の Cloud Shell からアクセスできます。
Cloud Shell の起動

  1. Cloud Datastore インポート / エクスポート管理者のロールを割り当てます。project_id を実際のプロジェクト ID で置き換えて、次のコマンドを実行します。

    gcloud projects add-iam-policy-binding project_id \
        --member serviceAccount:project_id@appspot.gserviceaccount.com \
        --role roles/datastore.importExportAdmin
    
  2. バケットに対するストレージ管理者ロールを割り当てます。project_idbucket_name を実際のプロジェクト ID、バケット名で置き換えて、次のコマンドを実行します。

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

Cloud Scheduler ジョブを作成する

次に、Cloud Functions の関数 datastore_export を呼び出す Cloud Scheduler ジョブを作成します。

  1. Google Cloud コンソールの [Cloud Scheduler] ページに移動します。

    Cloud Scheduler に移動

  2. [ジョブを作成] をクリックします。

  3. [名前] にジョブの名前を入力します(例: scheduledDatastoreExport)。

  4. [頻度] に unix-cron 形式で入力します。

  5. [タイムゾーン] でタイムゾーンを選択します。

  6. [ターゲット] で [Pub/Sub] を選択します。[トピック] フィールドに、Cloud Functions の関数とともに定義した Pub/Sub トピックの名前を入力します。上記の例では、startDatastoreExport です。

  7. [ペイロード] フィールドに、エクスポート オペレーションを構成する JSON オブジェクトを入力します。Cloud Functions の関数 datastore_export には bucket 値が必要です。必要に応じて、kinds 値または namespaceIDs 値を指定してエンティティ フィルタを設定できます。次に例を示します。

    すべてのエンティティをエクスポートする

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

    エンティティ フィルタでエクスポートする

    • すべての名前空間から種類が User または Task のエンティティをエクスポートします。

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

    • 種類が User または Task のエンティティを、デフォルトの名前空間と Testers 名前空間からエクスポートします。デフォルトの名前空間を指定するには、空の文字列("")を使用します。

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

    • デフォルトの名前空間と Testers 名前空間から任意の種類のエンティティをエクスポートします。デフォルトの名前空間を指定するには、空の文字列("")を使用します。

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

    ここで bucket_name は Cloud Storage バケット名です。

  8. [作成] をクリックします。

スケジュールされたエクスポートをテストする

Cloud Functions の関数と Cloud Scheduler ジョブをテストするには、Google Cloud Console の [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 Functions の関数がエクスポート オペレーションを正常に開始したかどうかを確認するには、Google Cloud コンソールの [ログ エクスプローラ] ページをご覧ください。

[ログ エクスプローラ] に移動

Cloud Functions の関数のログでは、エラーとエクスポートの正常な開始が報告されます。

エクスポートの進行状況を確認する

gcloud datastore operations list コマンドを使用すると、エクスポート オペレーションの進行状況を確認できます。すべての長時間実行オペレーションの一覧表示をご覧ください。

エクスポート オペレーションの完了後は、Cloud Storage バケット内の出力ファイルを表示できます。マネージド エクスポート サービスでは、タイムスタンプを使用してエクスポート オペレーションを整理します。

[Cloud Storage] に移動