使用 Eventarc 建立 BigQuery 處理管道


本教學課程說明如何使用 Eventarc 建構處理管道,排定查詢公開 BigQuery 資料集的作業、根據資料產生圖表,以及透過電子郵件分享圖表連結。

目標

在本教學課程中,您將建構及部署三項允許未經驗證存取,並使用 Eventarc 接收事件的 Cloud Run 服務:

  1. 查詢執行器:當 Cloud 任務排程器作業將訊息發布至 Pub/Sub 主題時,這項服務會使用 BigQuery API 從公開的 COVID-19 資料集擷取資料,並將結果儲存至新的 BigQuery 資料表。
  2. 圖表建立工具:當 Query Runner 服務將訊息發布至 Pub/Sub 主題時,這項服務會使用 Python 繪圖程式庫 Matplotlib 產生圖表,並將圖表儲存至 Cloud Storage 值區。
  3. 通知程式:當 Chart Creator 服務將圖表儲存在 Cloud Storage 值區時,這個服務會由稽核記錄觸發,並使用電子郵件服務 SendGrid,將圖表連結傳送至電子郵件地址。

下圖顯示高階架構:

BigQuery 處理管道

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 Google Cloud 的使用者可能符合免費試用資格。

事前準備

貴機構定義的安全性限制,可能會導致您無法完成下列步驟。如需疑難排解資訊,請參閱「在受限的 Google Cloud 環境中開發應用程式」。

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Artifact Registry, Cloud Build, Cloud Logging, Cloud Run, Cloud Scheduler, Eventarc, and Pub/Sub APIs:

    gcloud services enable artifactregistry.googleapis.com cloudbuild.googleapis.com cloudscheduler.googleapis.com eventarc.googleapis.com logging.googleapis.com pubsub.googleapis.com run.googleapis.com
  8. Install the Google Cloud CLI.

  9. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  10. To initialize the gcloud CLI, run the following command:

    gcloud init
  11. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. Make sure that billing is enabled for your Google Cloud project.

  13. Enable the Artifact Registry, Cloud Build, Cloud Logging, Cloud Run, Cloud Scheduler, Eventarc, and Pub/Sub APIs:

    gcloud services enable artifactregistry.googleapis.com cloudbuild.googleapis.com cloudscheduler.googleapis.com eventarc.googleapis.com logging.googleapis.com pubsub.googleapis.com run.googleapis.com
  14. 如果是 Cloud Storage,請為 ADMIN_READDATA_WRITEDATA_READ 資料存取類型啟用稽核記錄。

    1. 讀取與 Google Cloud 專案、資料夾或機構相關聯的 Identity and Access Management (IAM) 政策,並儲存在暫時檔案中:
      gcloud projects get-iam-policy PROJECT_ID > /tmp/policy.yaml
    2. 在文字編輯器中開啟 /tmp/policy.yaml,然後在 auditConfigs 區段中新增或變更稽核記錄設定:

      
        auditConfigs:
        - auditLogConfigs:
          - logType: ADMIN_READ
          - logType: DATA_WRITE
          - logType: DATA_READ
          service: storage.googleapis.com
        bindings:
        - members:
        [...]
        etag: BwW_bHKTV5U=
        version: 1
    3. 撰寫新的 IAM 政策:

      gcloud projects set-iam-policy PROJECT_ID /tmp/policy.yaml

      如果上述指令回報與其他變更發生衝突,請重複這些步驟,從讀取 IAM 政策開始。詳情請參閱「使用 API 設定資料存取稽核記錄」一文。

  15. eventarc.eventReceiver 角色指派給 Compute Engine 服務帳戶:

    export PROJECT_NUMBER="$(gcloud projects describe $(gcloud config get-value project) --format='value(projectNumber)')"
    
    gcloud projects add-iam-policy-binding $(gcloud config get-value project) \
        --member=serviceAccount:${PROJECT_NUMBER}-compute@developer.gserviceaccount.com \
        --role='roles/eventarc.eventReceiver'

  16. 如果您是在 2021 年 4 月 8 日當天或之前啟用 Pub/Sub 服務帳戶,請將 iam.serviceAccountTokenCreator 角色授予 Pub/Sub 服務帳戶:

    gcloud projects add-iam-policy-binding $(gcloud config get-value project) \
        --member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com"\
        --role='roles/iam.serviceAccountTokenCreator'

  17. 設定本教學課程中使用的預設值:
    export REGION=REGION
    gcloud config set run/region ${REGION}
    gcloud config set run/platform managed
    gcloud config set eventarc/location ${REGION}

    REGION 替換為您選擇的支援 Eventarc 位置

建立 SendGrid API 金鑰

SendGrid 是一項雲端電子郵件服務,可讓您傳送電子郵件,不必維護電子郵件伺服器。

  1. 登入 SendGrid,然後前往「Settings」>「API Keys」
  2. 按一下「建立 API 金鑰」
  3. 選取金鑰的權限。至少必須具備「郵件傳送」權限,才能傳送電子郵件。
  4. 為金鑰命名,然後按一下「儲存」即可建立金鑰。
  5. SendGrid 會產生一個新金鑰。此為唯一一份金鑰,因此請務必複製並儲存金鑰,以供日後使用。

建立 Artifact Registry 標準存放區

建立 Artifact Registry 標準存放區,用於儲存 Docker 容器映像檔:

gcloud artifacts repositories create REPOSITORY \
    --repository-format=docker \
    --location=$REGION

REPOSITORY 替換成存放區的專屬名稱。

建立 Cloud Storage 值區

建立不重複的 Cloud Storage bucket,用來儲存圖表。請確認值區和圖表皆為公開資源,且與 Cloud Run 服務位於相同區域:

export BUCKET="$(gcloud config get-value core/project)-charts"
gcloud storage buckets create gs://${BUCKET} --location=$(gcloud config get-value run/region)
gcloud storage buckets update gs://${BUCKET} --uniform-bucket-level-access
gcloud storage buckets add-iam-policy-binding gs://${BUCKET} --member=allUsers --role=roles/storage.objectViewer

部署 Notifier 服務

部署 Cloud Run 服務,接收圖表建立工具事件,並使用 SendGrid 透過電子郵件傳送所產生圖表的連結。

  1. 複製 GitHub 存放區並變更為 notifier/python 目錄:

    git clone https://github.com/GoogleCloudPlatform/eventarc-samples
    cd eventarc-samples/processing-pipelines/bigquery/notifier/python/
  2. 建構及推送容器映像檔:

    export SERVICE_NAME=notifier
    docker build -t $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/${SERVICE_NAME}:v1 .
    docker push $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/${SERVICE_NAME}:v1
  3. 將容器映像檔部署到 Cloud Run,並傳遞要傳送電子郵件的地址和 SendGrid API 金鑰:

    export TO_EMAILS=EMAIL_ADDRESS
    export SENDGRID_API_KEY=YOUR_SENDGRID_API_KEY
    gcloud run deploy ${SERVICE_NAME} \
        --image $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/${SERVICE_NAME}:v1 \
        --update-env-vars TO_EMAILS=${TO_EMAILS},SENDGRID_API_KEY=${SENDGRID_API_KEY},BUCKET=${BUCKET} \
        --allow-unauthenticated

    更改下列內容:

    • EMAIL_ADDRESS,並提供電子郵件地址,以便傳送產生的圖表連結
    • YOUR_SENDGRID_API_KEY,並替換為您先前記下的 SendGrid API 金鑰

看到服務網址時,表示部署作業已完成。

為 Notifier 服務建立觸發條件

部署在 Cloud Run 上的 Notifier 服務的 Eventarc 觸發條件,會篩選 methodNamestorage.objects.create 的 Cloud Storage 稽核記錄。

  1. 建立觸發條件:

    gcloud eventarc triggers create trigger-${SERVICE_NAME} \
        --destination-run-service=${SERVICE_NAME} \
        --destination-run-region=${REGION} \
        --event-filters="type=google.cloud.audit.log.v1.written" \
        --event-filters="serviceName=storage.googleapis.com" \
        --event-filters="methodName=storage.objects.create" \
        --service-account=${PROJECT_NUMBER}-compute@developer.gserviceaccount.com

    這項操作會建立名為 trigger-notifier 的觸發條件。

部署圖表建立服務

部署 Cloud Run 服務,接收 Query Runner 事件、從特定國家/地區的 BigQuery 資料表擷取資料,然後使用 Matplotlib 從資料產生圖表。圖表會上傳至 Cloud Storage bucket。

  1. 切換至 chart-creator/python 目錄:

    cd ../../chart-creator/python
  2. 建構及推送容器映像檔:

    export SERVICE_NAME=chart-creator
    docker build -t $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/${SERVICE_NAME}:v1 .
    docker push $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/${SERVICE_NAME}:v1
  3. 將容器映像檔部署至 Cloud Run,並傳遞 BUCKET

    gcloud run deploy ${SERVICE_NAME} \
        --image $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/${SERVICE_NAME}:v1 \
        --update-env-vars BUCKET=${BUCKET} \
        --allow-unauthenticated

看到服務網址時,表示部署作業已完成。

為圖表建立工具服務建立觸發條件

部署在 Cloud Run 上的 Chart Creator 服務的 Eventarc 觸發程序,會篩選發布至 Pub/Sub 主題的訊息。

  1. 建立觸發條件:

    gcloud eventarc triggers create trigger-${SERVICE_NAME} \
        --destination-run-service=${SERVICE_NAME} \
        --destination-run-region=${REGION} \
        --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished"

    這項操作會建立名為 trigger-chart-creator 的觸發條件。

  2. 設定 Pub/Sub 主題環境變數。

    export TOPIC_QUERY_COMPLETED=$(basename $(gcloud eventarc triggers describe trigger-${SERVICE_NAME} --format='value(transport.pubsub.topic)'))

部署 Query Runner 服務

部署 Cloud Run 服務,接收 Cloud Scheduler 事件、從 COVID-19 公開資料集擷取資料,並將結果儲存到新的 BigQuery 資料表。

  1. 切換至 processing-pipelines 目錄:

    cd ../../..
  2. 建構及推送容器映像檔:

    export SERVICE_NAME=query-runner
    docker build -t $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/${SERVICE_NAME}:v1 -f Dockerfile .
    docker push $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/${SERVICE_NAME}:v1
  3. 將容器映像檔部署至 Cloud Run,並傳遞 PROJECT_IDTOPIC_QUERY_COMPLETED

    gcloud run deploy ${SERVICE_NAME} \
        --image $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/${SERVICE_NAME}:v1 \
        --update-env-vars PROJECT_ID=$(gcloud config get-value project),TOPIC_ID=${TOPIC_QUERY_COMPLETED} \
        --allow-unauthenticated

看到服務網址時,表示部署作業已完成。

為 Query Runner 服務建立觸發條件

部署在 Cloud Run 上的 Query Runner 服務的 Eventarc 觸發程序,會篩選發布至 Pub/Sub 主題的訊息。

  1. 建立觸發條件:

    gcloud eventarc triggers create trigger-${SERVICE_NAME} \
        --destination-run-service=${SERVICE_NAME} \
        --destination-run-region=${REGION} \
        --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished"

    這項操作會建立名為 trigger-query-runner 的觸發條件。

  2. 設定 Pub/Sub 主題的環境變數。

    export TOPIC_QUERY_SCHEDULED=$(gcloud eventarc triggers describe trigger-${SERVICE_NAME} --format='value(transport.pubsub.topic)')

排定工作

處理管道是由兩項 Cloud Scheduler 工作觸發。

  1. 建立 Cloud Scheduler 必須使用的 App Engine 應用程式,並指定適當的位置

    export APP_ENGINE_LOCATION=LOCATION
    gcloud app create --region=${APP_ENGINE_LOCATION}
  2. 建立兩項 Cloud Scheduler 工作,每天發布至 Pub/Sub 主題一次:

    gcloud scheduler jobs create pubsub cre-scheduler-uk \
        --schedule="0 16 * * *" \
        --topic=${TOPIC_QUERY_SCHEDULED} \
        --message-body="United Kingdom"
    gcloud scheduler jobs create pubsub cre-scheduler-cy \
        --schedule="0 17 * * *" \
        --topic=${TOPIC_QUERY_SCHEDULED} \
        --message-body="Cyprus"

    排程以 Unix-Cron 格式指定。 舉例來說,0 16 * * * 表示工作每天會在世界標準時間下午 4:00 執行。

執行管道

  1. 首先,請確認所有觸發條件都已建立成功:

    gcloud eventarc triggers list

    畫面會顯示如下的輸出內容:

    NAME: trigger-chart-creator
    TYPE: google.cloud.pubsub.topic.v1.messagePublished
    DESTINATION: Cloud Run service: chart-creator
    ACTIVE: Yes
    LOCATION: us-central1
    
    NAME: trigger-notifier
    TYPE: google.cloud.audit.log.v1.written
    DESTINATION: Cloud Run service: notifier
    ACTIVE: Yes
    LOCATION: us-central1
    
    NAME: trigger-query-runner
    TYPE: google.cloud.pubsub.topic.v1.messagePublished
    DESTINATION: Cloud Run service: query-runner
    ACTIVE: Yes
    LOCATION: us-central1
    
  2. 擷取 Cloud Scheduler 工作 ID:

    gcloud scheduler jobs list

    畫面會顯示如下的輸出內容:

    ID                LOCATION      SCHEDULE (TZ)         TARGET_TYPE  STATE
    cre-scheduler-cy  us-central1   0 17 * * * (Etc/UTC)  Pub/Sub      ENABLED
    cre-scheduler-uk  us-central1   0 16 * * * (Etc/UTC)  Pub/Sub      ENABLED
    
  3. 雖然系統已排定工作在每天下午 4 點和 5 點執行,您也可以手動執行 Cloud Scheduler 工作:

    gcloud scheduler jobs run cre-scheduler-cy
    gcloud scheduler jobs run cre-scheduler-uk
  4. 幾分鐘後,確認 Cloud Storage bucket 中有兩個圖表:

    gcloud storage ls gs://${BUCKET}

    畫面會顯示如下的輸出內容:

    gs://BUCKET/chart-cyprus.png
    gs://BUCKET/chart-unitedkingdom.png
    

恭喜!您也會收到兩封電子郵件,內含圖表連結。

清除所用資源

如果您是為了這個教學課程建立新專案,請刪除該專案。如果您使用現有專案,並想保留專案,但不要本教學課程新增的變更,請刪除為本教學課程建立的資源

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

刪除教學課程資源

  1. 刪除您在本教學課程中部署的任何 Cloud Run 服務:

    gcloud run services delete SERVICE_NAME

    其中 SERVICE_NAME 是您選擇的服務名稱。

    您也可以從Google Cloud 控制台刪除 Cloud Run 服務。

  2. 移除您在教學課程設定期間新增的任何 Google Cloud CLI 預設設定。

    gcloud config unset project
    gcloud config unset run/region
    gcloud config unset run/platform
    gcloud config unset eventarc/location
  3. 刪除您在本教學課程中建立的任何 Eventarc 觸發條件:

     gcloud eventarc triggers delete TRIGGER_NAME
     
    TRIGGER_NAME 替換為觸發條件的名稱。

  4. 從 Artifact Registry 刪除映像檔。

    gcloud artifacts docker images delete $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/notifier:v1
    gcloud artifacts docker images delete $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/chart-creator:v1
    gcloud artifacts docker images delete $REGION-docker.pkg.dev/$(gcloud config get-value project)/REPOSITORY/query-runner:v1
  5. 刪除值區和值區內的所有物件:

    gcloud storage rm --recursive gs://${BUCKET}/
  6. 刪除 Cloud Scheduler 工作:

    gcloud scheduler jobs delete cre-scheduler-cy
    gcloud scheduler jobs delete cre-scheduler-uk

後續步驟