由事件驅動的 Cloud Storage 轉移作業

Storage 移轉服務可以監聽 Google Cloud中的事件通知,自動移轉 Cloud Storage bucket 中新增或更新的資料。進一步瞭解事件導向移轉作業的優點。

Cloud Storage 的事件導向移轉作業會使用 Pub/Sub 通知,瞭解來源 bucket 中的物件何時遭到修改或新增。系統不會偵測物件刪除作業;刪除來源物件時,不會刪除目的地 bucket 中的相關聯物件。

事件導向移轉作業一律會使用 Cloud Storage bucket 做為目的地。

設定權限

除了所有移轉工作所需的權限,事件導向移轉作業還需要 Pub/Sub Subscriber 角色。

  1. 找出專案的 Storage 移轉服務代理程式名稱:

    1. 前往 googleServiceAccounts.get 參考資料頁面。

      互動式面板隨即開啟,標題為「試用這個方法」。

    2. 在面板的「Request parameters」(要求參數) 下方,輸入專案 ID。您在此指定的專案必須是用來管理 Storage 移轉服務的專案,可能與來源 bucket 的專案不同。

    3. 點選「Execute」。

    服務代理的電子郵件會以 accountEmail 的值傳回。複製這個值。

    服務代理的電子郵件地址格式為 project-PROJECT_NUMBER@storage-transfer-service.。

  2. 將 Pub/Sub Subscriber 角色授予 Storage 移轉服務的服務代理。

    Cloud 控制台

    請按照「透過 Google Cloud 控制台控管存取權」中的操作說明,將 Pub/Sub Subscriber 角色授予 Storage 移轉服務。您可以在主題、訂閱項目或專案層級授予這個角色。

    gcloud CLI

    按照「設定政策」中的操作說明,新增下列繫結:

    {
      "role": "roles/pubsub.subscriber",
      "members": [
        "serviceAccount:project-PROJECT_NUMBER@storage-transfer-service."
    }

設定 Pub/Sub

  1. 確認您已符合搭配使用 Pub/Sub 與 Cloud Storage 的必要條件。

  2. 為來源 Cloud Storage bucket 建立 Pub/Sub 通知。

    您無法使用 Google Cloud 控制台管理 Pub/Sub 通知。請改用 gcloud CLI 或其中一個可用的用戶端程式庫。

    gcloud storage buckets notifications create gs://SOURCE_BUCKET_NAME --topic=TOPIC_NAME
  3. 為主題建立提取訂閱項目。您必須為每項轉移工作建立個別訂閱項目。

    下列範例顯示建立提取訂閱項目的 Google Cloud CLI 指令。如需控制台操作說明和用戶端程式庫程式碼,請參閱「建立提取訂閱項目」。

    gcloud pubsub subscriptions create SUBSCRIPTION_ID --topic=TOPIC_NAME --ack-deadline=300

建立移轉工作

您可以使用 Google Cloud 控制台、Google Cloud CLI 或 REST API 建立事件式移轉工作。

Google Cloud 控制台

  1. 前往 Google Cloud 控制台的「Create transfer job」(建立移轉工作) 頁面。

    前往「Create transfer job」(建立移轉工作)

  2. 選取「Cloud Storage」做為來源和目的地。

  3. 在「Scheduling mode」(排程模式) 中選取「Event-driven」(事件導向),然後點選「Next step」(下一步)。

  4. 選取這項移轉作業的來源 bucket。

  5. 在「Event stream」(事件串流) 部分,輸入訂閱項目名稱:

    projects/PROJECT_NAME/subscriptions/SUBSCRIPTION_ID

  6. 視需要定義篩選器,然後點選「下一步」。

  7. 選取這項移轉作業的目的地 bucket。

  8. (選用) 輸入轉移作業的開始和結束時間。如未指定時間,移轉作業會立即開始,並持續執行,直到手動停止為止。

  9. 指定任何轉移選項。詳情請參閱「建立移轉作業」頁面。

  10. 點選「建立」。

建立後,移轉工作就會開始執行,事件監聽器則會等待 Pub/Sub 訂閱項目的通知。工作詳細資料頁面會顯示每小時的一項作業,並包含每項工作的資料移轉詳細資料。

gcloud

如要使用 Google Cloud CLI 建立事件導向移轉工作,請使用 gcloud transfer jobs create 指令和 --event-stream-name 旗標:

gcloud transfer jobs create \
  gs://SOURCE_BUCKET \
  gs://DESTINATION_BUCKET \
  --event-stream-name=projects/PROJECT_NAME/subscriptions/SUBSCRIPTION_ID \
  --event-stream-starts=EVENT_STREAM_STARTS \
  --event-stream-expires=EVENT_STREAM_EXPIRES

將預留位置替換為實際值:

  • SOURCE_BUCKET:來源 Cloud Storage bucket 的名稱。
  • DESTINATION_BUCKET:目的地 Cloud Storage bucket。
  • PROJECT_NAME:Pub/Sub 訂閱項目所在的專案。
  • SUBSCRIPTION_ID:您建立的 Pub/Sub 訂閱項目 ID (例如 my-subscription)。
  • EVENT_STREAM_STARTS:開始監聽事件的時間,使用 %Y-%m-%dT%H:%M:%S%z 日期時間格式 (例如 2020-04-12T06:42:12+04:00)。如未設定,工作會在成功提交建立工作指令後,開始執行並監聽事件。
  • EVENT_STREAM_EXPIRES:停止監聽事件的時間。如未設定,工作會持續執行,直到手動停止為止。

如需支援欄位的完整清單,請參閱 gcloud transfer jobs create 參考資料。

REST

如要使用 REST API 建立事件導向移轉作業,請將下列 JSON 物件傳送至 transferJobs.create 端點:

transfer_job {
  "description": "YOUR DESCRIPTION",
  "status": "ENABLED",
  "projectId": "PROJECT_ID",
  "transferSpec" {
    "gcsDataSource" {
      "bucketName": "GCS_SOURCE_NAME"
    },
    "gcsDataSink": {
        "bucketName": "GCS_SINK_NAME"
    }
  }
  "eventStream" {
    "name": "projects/PROJECT_NAME/subscriptions/SUBSCRIPTION_ID",
    "eventStreamStartTime": "2022-12-02T01:00:00+00:00",
    "eventStreamExpirationTime": "2023-01-31T01:00:00+00:00"
  }
}

eventStreamStartTime 和 eventStreamExpirationTime 為選用項目。如果省略開始時間,移轉作業會立即開始;如果省略結束時間,移轉作業會持續進行,直到手動停止為止。

用戶端程式庫

Go

如要瞭解如何安裝及使用 Storage 移轉服務的用戶端程式庫,請參閱「Storage 移轉服務用戶端程式庫」。詳情請參閱 Storage 移轉服務 Go API 參考文件。

如要向 Storage 移轉服務進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


func createEventDrivenGCSTransfer(w io.Writer, projectID string, gcsSourceBucket string, gcsSinkBucket string, pubSubId string) (*storagetransferpb.TransferJob, error) {
	// Your Google Cloud Project ID.
	// projectID := "my-project-id"

	// The name of the source GCS bucket.
	// gcsSourceBucket := "my-source-bucket"

	// The name of the GCS bucket to transfer objects to.
	// gcsSinkBucket := "my-sink-bucket"

	// The Pub/Sub topic to subscribe the event driven transfer to.
	// pubSubID := "projects/PROJECT_NAME/subscriptions/SUBSCRIPTION_ID"

	ctx := context.Background()
	client, err := storagetransfer.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storagetransfer.NewClient: %w", err)
	}
	defer client.Close()

	req := &storagetransferpb.CreateTransferJobRequest{
		TransferJob: &storagetransferpb.TransferJob{
			ProjectId: projectID,
			TransferSpec: &storagetransferpb.TransferSpec{
				DataSource: &storagetransferpb.TransferSpec_GcsDataSource{
					GcsDataSource: &storagetransferpb.GcsData{BucketName: gcsSourceBucket}},
				DataSink: &storagetransferpb.TransferSpec_GcsDataSink{
					GcsDataSink: &storagetransferpb.GcsData{BucketName: gcsSinkBucket}},
			},
			EventStream: &storagetransferpb.EventStream{Name: pubSubId},
			Status:      storagetransferpb.TransferJob_ENABLED,
		},
	}
	resp, err := client.CreateTransferJob(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("failed to create transfer job: %w", err)
	}

	fmt.Fprintf(w, "Created an event driven transfer job from %v to %v subscribed to %v with name %v", gcsSourceBucket, gcsSinkBucket, pubSubId, resp.Name)
	return resp, nil
}

Java

如要瞭解如何安裝及使用 Storage 移轉服務的用戶端程式庫,請參閱「Storage 移轉服務用戶端程式庫」。詳情請參閱 Storage 移轉服務 Java API 參考文件。

如要向 Storage 移轉服務進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import com.google.storagetransfer.v1.proto.StorageTransferServiceClient;
import com.google.storagetransfer.v1.proto.TransferProto;
import com.google.storagetransfer.v1.proto.TransferTypes;

public class CreateEventDrivenGcsTransfer {
  public static void main(String[] args) throws Exception {
    // Your Google Cloud Project ID
    String projectId = "your-project-id";

    // The name of the GCS AWS bucket to transfer data from
    String gcsSourceBucket = "your-gcs-source-bucket";

    // The name of the GCS bucket to transfer data to
    String gcsSinkBucket = "your-gcs-sink-bucket";

    // The ARN of the PubSub queue to subscribe to
    String sqsQueueArn = "projects/PROJECT_NAME/subscriptions/SUBSCRIPTION_ID";

    createEventDrivenGcsTransfer(projectId, gcsSourceBucket, gcsSinkBucket, sqsQueueArn);
  }

  public static void createEventDrivenGcsTransfer(
      String projectId, String gcsSourceBucket, String gcsSinkBucket, String pubSubId)
      throws Exception {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources,
    // or use "try-with-close" statement to do this automatically.
    try (StorageTransferServiceClient storageTransfer = StorageTransferServiceClient.create()) {

      TransferTypes.TransferJob transferJob =
          TransferTypes.TransferJob.newBuilder()
              .setProjectId(projectId)
              .setTransferSpec(
                  TransferTypes.TransferSpec.newBuilder()
                      .setGcsDataSource(
                          TransferTypes.GcsData.newBuilder().setBucketName(gcsSourceBucket))
                      .setGcsDataSink(
                          TransferTypes.GcsData.newBuilder().setBucketName(gcsSinkBucket)))
              .setStatus(TransferTypes.TransferJob.Status.ENABLED)
              .setEventStream(TransferTypes.EventStream.newBuilder().setName(pubSubId).build())
              .build();

      TransferTypes.TransferJob response =
          storageTransfer.createTransferJob(
              TransferProto.CreateTransferJobRequest.newBuilder()
                  .setTransferJob(transferJob)
                  .build());

      System.out.println(
          "Created a transfer job between from "
              + gcsSourceBucket
              + " to "
              + gcsSinkBucket
              + " subscribed to "
              + pubSubId
              + " with name "
              + response.getName());
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Storage 移轉服務的用戶端程式庫,請參閱「Storage 移轉服務用戶端程式庫」。詳情請參閱 Storage 移轉服務 Node.js API 參考文件。

如要向 Storage 移轉服務進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


// Imports the Google Cloud client library
const {
  StorageTransferServiceClient,
} = require('@google-cloud/storage-transfer');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of the Google Cloud Platform Project that owns the job
// projectId = 'my-project-id'

// Google Cloud Storage source bucket name
// gcsSourceBucket = 'my-gcs-source-bucket'

// Google Cloud Storage destination bucket name
// gcsSinkBucket = 'my-gcs-destination-bucket'

// The subscription ID to a Pubsub queue to track
// pubsubId = 'projects/PROJECT_NAME/subscriptions/SUBSCRIPTION_ID'

// Creates a client
const client = new StorageTransferServiceClient();

/**
 * Creates an event driven transfer that tracks a Pubsub subscription.
 */
async function createEventDrivenGcsTransfer() {
  const [transferJob] = await client.createTransferJob({
    transferJob: {
      projectId,
      status: 'ENABLED',
      transferSpec: {
        gcsDataSource: {
          bucketName: gcsSourceBucket,
        },
        gcsDataSink: {
          bucketName: gcsSinkBucket,
        },
      },
      eventStream: {
        name: pubsubId,
      },
    },
  });

  console.log(
    `Created an event driven transfer from '${gcsSourceBucket}' to '${gcsSinkBucket}' with name ${transferJob.name}`
  );
}

createEventDrivenGcsTransfer();

Python

如要瞭解如何安裝及使用 Storage 移轉服務的用戶端程式庫,請參閱「Storage 移轉服務用戶端程式庫」。詳情請參閱 Storage 移轉服務 Python API 參考文件。

如要向 Storage 移轉服務進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


from google.cloud import storage_transfer


def create_event_driven_gcs_transfer(
    project_id: str,
    description: str,
    source_bucket: str,
    sink_bucket: str,
    pubsub_id: str,
):
    """Create an event driven transfer between two GCS buckets that tracks a PubSub subscription"""

    client = storage_transfer.StorageTransferServiceClient()

    # The ID of the Google Cloud Platform Project that owns the job
    # project_id = 'my-project-id'

    # A description of this job
    # description = 'Creates an event-driven transfer that tracks a pubsub subscription'

    # Google Cloud Storage source bucket name
    # source_bucket = 'my-gcs-source-bucket'

    # Google Cloud Storage destination bucket name
    # sink_bucket = 'my-gcs-destination-bucket'

    # The Pubsub Subscription ID to track
    # pubsub_id = 'projects/PROJECT_NAME/subscriptions/SUBSCRIPTION_ID'

    transfer_job_request = storage_transfer.CreateTransferJobRequest(
        {
            "transfer_job": {
                "project_id": project_id,
                "description": description,
                "status": storage_transfer.TransferJob.Status.ENABLED,
                "transfer_spec": {
                    "gcs_data_source": {
                        "bucket_name": source_bucket,
                    },
                    "gcs_data_sink": {
                        "bucket_name": sink_bucket,
                    },
                },
                "event_stream": {
                    "name": pubsub_id,
                },
            },
        }
    )

    result = client.create_transfer_job(transfer_job_request)
    print(f"Created transferJob: {result.name}")

監控事件導向移轉作業

建立事件導向移轉作業時,Storage 移轉服務會建立移轉工作。到達開始時間後,移轉作業就會開始執行,事件監聽器則會等待 Pub/Sub 佇列的通知。

轉移作業會執行約 24 小時,狀態為 in progress。24 小時後,作業會結束,並開始新的作業。每 24 小時會建立一項新作業,直到轉移工作的結束時間,或手動停止工作為止。

如果作業排定結束時,檔案傳輸作業仍在進行中,則目前作業會繼續進行,直到檔案完全傳輸完畢為止。新作業會啟動,且兩項作業會同時執行,直到舊作業完成為止。在這段期間偵測到的任何事件,都會由新作業處理。

如要查看目前作業和任何已完成的作業,請按照下列步驟操作:

Google Cloud 控制台

  1. 前往 Google Cloud 控制台的「Storage 移轉服務」頁面。

    前往 Storage 移轉服務

  2. 在工作清單中,選取「全部」分頁標籤或「雲端對雲端」。

  3. 按一下移轉作業的工作 ID。「Scheduling mode」(排程模式) 欄會列出所有事件導向移轉作業和批次移轉作業。

  4. 選取「作業」分頁標籤。系統會顯示目前作業的詳細資料,並在「Run history」(執行記錄) 表格中列出已完成的作業。點選任何已完成的作業,即可查看其他詳細資料。

gcloud

如要即時監控工作進度,請使用 gcloud transfer jobs monitor。回應會顯示目前作業、工作開始時間、移轉的資料量、略過的位元組數和錯誤計數。

gcloud transfer jobs monitor JOB_NAME

如要擷取目前作業名稱,請執行下列操作:

gcloud transfer jobs describe JOB_NAME --format="value(latestOperationName)"

如要列出目前和已完成的作業,請按照下列步驟操作:

gcloud transfer operations list --job-names=JOB_NAME

如要查看作業詳細資料,請按照下列步驟操作:

gcloud transfer operations describe OPERATION_NAME