내보내기 예약

이 페이지에서는 Datastore 모드 데이터에서 Firestore 내보내기를 예약하는 방법을 설명합니다. 일정에 따라 내보내기를 실행하려면 Cloud Functions 및 Cloud Scheduler를 사용하는 것이 좋습니다. 내보내기를 시작하는 Cloud 함수를 만들고 Cloud Scheduler를 사용하여 함수를 실행합니다.

시작하기 전에

데이터 내보내기를 예약하려면 먼저 다음 작업을 완료해야 합니다.

  1. Google Cloud 프로젝트에 결제를 사용 설정합니다. 결제가 사용 설정된 Google Cloud 프로젝트만 내보내기 및 가져오기 기능을 사용할 수 있습니다.
  2. Datastore 모드 데이터베이스 위치와 가까운 곳에 Cloud Storage 버킷을 생성합니다. 내보내기 작업에는 대상 Cloud Storage 버킷이 필요합니다. 내보내기 작업에는 요청자 지불 버킷을 사용할 수 없습니다.

Cloud 함수 및 Cloud Scheduler 작업 만들기

데이터 내보내기를 시작하는 Cloud 함수와 이 함수를 호출하는 Cloud Scheduler 작업을 만들려면 다음 안내를 따르세요.

datastore_export Cloud 함수 만들기

  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. 진입점 아래에 main.py에 있는 함수의 이름인 datastore_export를 입력합니다.
  11. 배포를 클릭하여 Cloud 함수를 배포합니다.

액세스 권한 구성

다음으로 Cloud 함수에 내보내기 작업을 시작하고 Cloud Storage 버킷에 쓸 수 있는 권한을 부여합니다.

이 Cloud 함수는 프로젝트의 기본 서비스 계정을 사용하여 내보내기 작업을 인증하고 승인합니다. 프로젝트를 만들면 다음과 같은 이름의 기본 서비스 계정이 생성됩니다.

project_id@appspot.gserviceaccount.com

이 서비스 계정은 내보내기 작업을 시작하고 Cloud Storage 버킷에 쓸 수 있는 권한이 필요합니다. 이러한 권한을 부여하려면 다음 IAM 역할을 기본 서비스 계정에 할당합니다.

  • Cloud Datastore Import Export Admin
  • 버킷에 대한 Owner 또는 Storage Admin 역할

이러한 역할은 gcloudgsutil 명령줄 도구를 사용하여 할당할 수 있습니다. Google Cloud 콘솔의 Cloud Shell에서 이 도구에 액세스할 수 있습니다.
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. 버킷에 대한 스토리지 관리자 역할을 할당합니다. project_idbucket_name을 바꾸고 다음 명령어를 실행합니다.

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

Cloud Scheduler 작업 만들기

다음으로 datastore_export Cloud 함수를 호출하는 Cloud Scheduler 작업을 만듭니다.

  1. Google Cloud 콘솔에서 Cloud Scheduler 페이지로 이동합니다.

    Cloud Scheduler로 이동

  2. 작업 만들기를 클릭합니다.

  3. 작업의 이름을 입력합니다(예: scheduledDatastoreExport).

  4. Unix 크론 형식으로 빈도를 입력합니다.

  5. 시간대를 선택합니다.

  6. 대상에서 Pub/Sub를 선택합니다. 주제 필드에 Cloud 함수와 함께 정의한 Pub/Sub 주제의 이름을 입력합니다(예: startDatastoreExport).

  7. 페이로드 필드에 JSON 객체를 입력하여 내보내기 작업을 구성합니다. datastore_export Cloud 함수에는 bucket 값이 필요합니다. 선택적으로 kinds 또는 namespaceIDs 값을 포함하여 다음과 같이 항목 필터를 설정할 수 있습니다.

    모든 항목 내보내기

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

    항목 필터로 내보내기

    • 모든 네임스페이스에서 User 또는 Task 종류의 항목을 내보냅니다.

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

    • 기본 및 Testers 네임스페이스에서 User 또는 Task 종류의 항목을 내보냅니다. 빈 문자열("")을 사용하여 기본 네임스페이스를 지정합니다.

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

    • 기본 및 Testers 네임스페이스에서 모든 종류의 항목을 내보냅니다. 빈 문자열("")을 사용하여 기본 네임스페이스를 지정합니다.

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

    여기서 bucket_name은 Cloud Storage 버킷의 이름입니다.

  8. 만들기를 클릭합니다.

예약된 내보내기 테스트

Cloud 함수 및 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 함수의 로그를 확인하세요.

Cloud 함수 로그 보기

Cloud 함수가 내보내기 작업을 성공적으로 시작했는지 확인하려면 Cloud 콘솔의 로그 탐색기 페이지를 참조하세요.

로그 탐색기로 이동

Cloud 함수의 로그는 오류와 성공적인 내보내기 시작을 보고합니다.

내보내기 진행률 보기

gcloud datastore operations list 명령어를 사용하여 내보내기 작업의 진행률을 볼 수 있습니다. 모든 장기 실행 작업 나열을 참조하세요.

내보내기 작업이 완료된 후에는 Cloud Storage 버킷에서 결과 파일을 볼 수 있습니다. 관리형 내보내기 서비스는 타임스탬프를 사용하여 내보내기 작업을 구성합니다.

Cloud Storage로 이동