排定備份週期


本教學課程將說明如何使用 Cloud Scheduler 和 Cloud Run 函式,為 Filestore 執行個體安排備份作業。

目標

  • 為 Cloud Scheduler 建立客戶端服務帳戶,該帳戶具備叫用 Cloud Run 函式所需的憑證。
  • 為 Cloud Run 函式建立用戶端服務帳戶,該帳戶具有呼叫 Filestore 端點的憑證。
  • 建立 Cloud Run 函式,用於建立 Filestore 執行個體的備份。
  • 建立 Cloud Run 函式,用於刪除 Filestore 執行個體的備份。
  • 建立 Cloud Scheduler 工作,以定期間隔執行任一函式。

費用

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

您可以使用 Pricing Calculator 根據預測用量產生預估費用。 新 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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  4. Enable the Artifact Registry, Cloud Build, Filestore, Cloud Run functions, Cloud Logging, Pub/Sub, Cloud Run, and Cloud Scheduler APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

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

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

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  10. Enable the Artifact Registry, Cloud Build, Filestore, Cloud Run functions, Cloud Logging, Pub/Sub, Cloud Run, and Cloud Scheduler APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

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

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

    gcloud init
  14. 如果專案中沒有 Filestore 執行個體,您必須先建立一個。

為 Cloud Scheduler 和 Cloud Run 函式建立用戶端服務帳戶

  1. 如果您尚未這樣做,請在 Google Cloud 控制台中按一下「啟用 Cloud Shell」

  2. 建立 Cloud Scheduler 以呼叫 Cloud Run 函式為目標執行的用戶端服務帳戶。在本例中,請使用 iam service-accounts create 指令為帳戶命名為 schedulerunner,並將顯示名稱設為「Service Account for FS Backups-Scheduler」:

    gcloud iam service-accounts create schedulerunner \
        --display-name="Service Account for FS Backups-Scheduler"
    
  3. 建立用於 Cloud Run 函式呼叫 Filestore 端點的用戶端服務帳戶。在本範例中,我們將帳戶命名為 backupagent,並將顯示名稱設為「FS Backups-GCF 的服務帳戶」:

    gcloud iam service-accounts create backupagent \
        --display-name="Service Account for FS Backups-GCF"
    

    您可以執行 iam service-accounts list 指令,檢查服務帳戶是否已建立:

    gcloud iam service-accounts list
    

    指令會傳回類似以下的內容:

    NAME                                         EMAIL                                                   DISABLED
    Service Account for FS Backups-GCF           backupagent@$PROJECT_ID.iam.gserviceaccount.com         False
    Service Account for FS Backups-Scheduler     schedulerunner@$PROJECT_ID.iam.gserviceaccount.com      False
    

設定環境變數

在本機環境中設定下列環境變數:

  • Google Cloud 專案 ID 和專案:

    export PROJECT_ID=`gcloud config get-value core/project`
    export PROJECT_NUMBER=`gcloud projects describe $PROJECT_ID --format="value(projectNumber)"`
    
  • Cloud Scheduler 服務代理人和 Cloud Scheduler 和 Cloud Run 函式的用戶端服務帳戶

    export SCHEDULER_SA=service-$PROJECT_NUMBER@gcp-sa-cloudscheduler.iam.gserviceaccount.com
    export SCHEDULER_CLIENT_SA=schedulerunner@$PROJECT_ID.iam.gserviceaccount.com
    export GCF_CLIENT_SA=backupagent@$PROJECT_ID.iam.gserviceaccount.com
    
  • Filestore 執行個體:

    export SOURCE_INSTANCE_LOCATION=fs-location
    export SOURCE_INSTANCE_NAME=instance-id
    export SHARE_NAME=file-share-name
    

    更改下列內容:

    • fs-location 與來源 Filestore 執行個體所在的區域或區域。
    • instance-id,其中包含來源 Filestore 執行個體的執行個體 ID。
    • file-share-name 與您為從執行個體提供的 NFS 檔案共用區指定的名稱。
  • 設定 Filestore 備份的環境變數:

    export BACKUP_REGION=backup-region
    

    backup-region 替換為您要儲存備份的區域。

建立建立備份的函式

  1. 前往 Google Cloud 控制台的「Cloud Run functions」頁面。

    前往「Cloud Run functions」頁面

  2. 按一下「Write a function」(編寫函式),然後依下列方式設定函式:

    • 設定
      • 服務名稱:在本例中,我們將函式命名為 fsbackup
      • 區域:在本例中,請選取 us-central1
      • 執行階段:從選單中選取任何支援的 Python 3 執行階段,並由 Cloud Run 函式完全支援
    • 觸發條件
      • 這個範例不需要設定觸發條件。
    • 驗證:選取 Require authentication
    • 輸入:選取 All
    • 容器、磁碟區、網路與安全性
      • 前往「安全性」分頁,然後從選單中選取 Service Account for FS Backups-GCF (backupagent@$PROJECT_ID.iam.gserviceaccount.com)。
  3. 按一下「建立」,然後按照以下步驟繼續設定:

    • 函式進入點:輸入 create_backup
    • requirements.txt 檔案中新增下列依附元件:

      functions-framework==3.*
      google-auth==2.29.0
      requests==2.31.0
      

      視用途而定,您可能需要指定其他依附元件,以及相應的版本編號。詳情請參閱「預先安裝的套件」。

    • 使用內嵌編輯器,將下列 Python 程式碼範例複製到 main.py 檔案中:

      建立備份

      這個程式碼範例會建立名為 mybackup- 的備份,並附加建立時間。

      PROJECT_ID = 'project-id'
      SOURCE_INSTANCE_LOCATION = 'fs-location'
      SOURCE_INSTANCE_NAME = 'instance-id'
      SOURCE_FILE_SHARE_NAME = 'file-share-name'
      BACKUP_REGION = 'backup-region'
      
      import functions_framework
      import google.auth
      import google.auth.transport.requests
      from google.auth.transport.requests import AuthorizedSession
      import time
      import requests
      import json
      
      credentials, project = google.auth.default()
      request = google.auth.transport.requests.Request()
      credentials.refresh(request)
      authed_session = AuthorizedSession(credentials)
      
      def get_backup_id():
          return "mybackup-" + time.strftime("%Y%m%d-%H%M%S")
      
      @functions_framework.http
      def create_backup(request):
          trigger_run_url = "https://file.googleapis.com/v1/projects/{}/locations/{}/backups?backupId={}".format(PROJECT_ID, BACKUP_REGION, get_backup_id())
          headers = {
            'Content-Type': 'application/json'
          }
          post_data = {
            "description": "my new backup",
            "source_instance": "projects/{}/locations/{}/instances/{}".format(PROJECT_ID, SOURCE_INSTANCE_LOCATION, SOURCE_INSTANCE_NAME),
            "source_file_share": "{}".format(SOURCE_FILE_SHARE_NAME)
          }
          print("Making a request to " + trigger_run_url)
          r = authed_session.post(url=trigger_run_url, headers=headers, data=json.dumps(post_data))
          data = r.json()
          print(data)
          if r.status_code == requests.codes.ok:
            print(str(r.status_code) + ": The backup is uploading in the background.")
          else:
            raise RuntimeError(data['error'])
          return "Backup creation has begun!"
      

      更改下列內容:

      • project-id 與來源 Filestore 執行個體的 Google Cloud 專案 ID。
      • fs-location 與來源 Filestore 執行個體的區域或區域。
      • instance-id 替換為來源 Filestore 執行個體的名稱。
      • file-share-name 替換為檔案共用區的名稱。
      • backup-region 與備份儲存區域。
      1. 按一下「Test」

        Cloud Shell 會開啟新的分頁工作階段。在成功執行後,系統會傳回下列訊息:

        Backup creation has begun!
        
      2. 按一下「儲存並重新部署」,然後等待部署作業完成。

      3. 切換回先前的 Cloud Shell 分頁。

      刪除備份

      這個程式碼範例會刪除超過預定時間的備份。

      您一次只能刪除一個來源執行個體的備份。詳情請參閱「備份」。

      請按照建立備份時使用的函式,設定這個函式,並使用下列修改項目:

      • 函式名稱deletefsbackup
      • 進入點delete_backup
      PROJECT_ID = 'project-id'
      BACKUP_REGION = 'region'
      BACKUP_RETENTION_TIME_HRS = hours
      
      import functions_framework
      import google.auth
      import google.auth.transport.requests
      from google.auth.transport.requests import AuthorizedSession
      import time
      import requests
      import json
      
      credentials, project = google.auth.default()
      request = google.auth.transport.requests.Request()
      credentials.refresh(request)
      authed_session = AuthorizedSession(credentials)
      
      retention_seconds = BACKUP_RETENTION_TIME_HRS * 60 * 60
      
      @functions_framework.http
      def delete_backup(request):
          now = time.time()
          backup_list = []
          trigger_run_url = "https://file.googleapis.com/v1/projects/{}/locations/{}/backups".format(PROJECT_ID, BACKUP_REGION)
          r = authed_session.get(trigger_run_url)
          data = r.json()
          if not data:
              print("No backups to delete.")
              return "No backups to delete."
          else:
              backup_list.extend(data['backups'])
              while "nextPageToken" in data.keys():
                  nextPageToken = data['nextPageToken']
                  trigger_run_url_next = "https://file.googleapis.com/v1/projects/{}/locations/{}/backups?pageToken={}".format(PROJECT_ID, BACKUP_REGION, nextPageToken)
                  r = authed_session.get(trigger_run_url_next)
                  data = r.json()
                  backup_list.extend(data['backups'])
          for i in backup_list:
              backup_time = i['createTime']
              backup_time = backup_time[:-4]
              backup_time = float(time.mktime(time.strptime(backup_time, "%Y-%m-%dT%H:%M:%S.%f")))
              i['backup_timestamp'] = backup_time
          sorted_backup_list = sorted(backup_list, key=lambda d: d['backup_timestamp'])
          oldest_backup = sorted_backup_list[0]
          if now - oldest_backup['backup_timestamp'] > retention_seconds:
              print(oldest_backup['name'] + " is older than the indicated retention time.")
              r = authed_session.delete("https://file.googleapis.com/v1/{}".format(oldest_backup['name']))
              data = r.json()
              print(data)
              if r.status_code == requests.codes.ok:
                  print(str(r.status_code) + ": Deleting " + oldest_backup['name'] + " in the background.")
              else:
                  raise RuntimeError(data['error'])
              return "Backup deletion has begun!"
          return "All backups are within the indicated retention period."
      

      更改下列內容:

      • project-id 替換為備份的 Google Cloud 專案 ID。
      • region 改成備份所在的區域。備份、排程器工作和函式都應位於相同位置。
      • hours 與備份保留時數。舉例來說,如果您想保留備份資料 10 天,請輸入 240

將 IAM 角色指派給客戶服務帳戶

  1. 將 Cloud Scheduler 服務代理人新增至 Cloud Scheduler 用戶端服務帳戶的 IAM 政策,並授予 roles/cloudscheduler.serviceAgent 角色。這可讓服務代理程式模擬客戶服務帳戶,以便叫用建立備份的函式。執行 iam service-accounts add-iam-policy-binding 指令:

    gcloud iam service-accounts add-iam-policy-binding $SCHEDULER_CLIENT_SA \
        --member=serviceAccount:$SCHEDULER_SA \
        --role=roles/cloudscheduler.serviceAgent
    
  2. roles/file.editor 角色授予 Cloud Run 函式的用戶端服務帳戶,以便該帳戶可以呼叫 Filestore 端點。執行 projects add-iam-policy-binding 指令:

    gcloud projects add-iam-policy-binding $PROJECT_ID \
        --member=serviceAccount:$GCF_CLIENT_SA \
        --role=roles/file.editor
    
  3. 針對要使用的函式,將 roles/run.invoker 角色授予 Cloud Scheduler 的用戶端服務帳戶。執行下列 run services add-iam-policy-binding 指令:

    建立備份

    gcloud run services add-iam-policy-binding fsbackup \
        --member serviceAccount:$SCHEDULER_CLIENT_SA \
        --role roles/run.invoker \
        --region=us-central1
    

    目前只有 Cloud Scheduler 的用戶端服務帳戶可以叫用 fsbackup

    刪除備份

    gcloud run services add-iam-policy-binding deletefsbackup \
        --member serviceAccount:$SCHEDULER_CLIENT_SA \
        --role roles/run.invoker
    

    目前只有 Cloud Scheduler 的用戶端服務帳戶可以叫用 deletefsbackup

建立 Cloud Scheduler 工作,以指定時程觸發函式

建立備份

  1. 在本教學課程的範例中,如果您想安排每天晚上 10 點的備份作業,請使用 scheduler jobs create http 指令:

    gcloud scheduler jobs create http fsbackupschedule \
        --schedule "0 22 * * 1-5" \
        --http-method=GET \
        --uri=https://fsbackup-$PROJECT_NUMBER.us-central1.run.app \
        --oidc-service-account-email=$SCHEDULER_CLIENT_SA \
        --location=us-central1
    

    您可以使用 --schedule 標記,以 unix-cron 格式指定工作執行的頻率。詳情請參閱「設定 Cron 工作時間表」。

    每小時最多可為每個執行個體建立六個備份。

  2. 啟動在前一個步驟中建立的 Cloud Scheduler 工作。在本例中,請使用 scheduler jobs runs 指令立即執行:

    gcloud scheduler jobs run fsbackupschedule
    

    您執行指令後,fsbackupschedule 工作會立即叫用 fsbackup 函式,然後每週在晚上 10 點再次叫用,直到工作暫停為止。

  3. 檢查 fsbackup 函式的記錄檔,瞭解該函式是否正常執行並傳回 status 200

    如要在 Google Cloud 控制台中查看記錄,請使用記錄檔探索工具:

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

      前往「Logs Explorer」(記錄檔探索工具)

      如果您是使用搜尋列尋找這個頁面,請選取子標題為「Logging」的結果

      「Query results」(查詢結果) 窗格會顯示最近的記錄檔。

  4. 使用 backups list 指令檢查現有備份的狀態:

    gcloud filestore backups list
    

    指令會傳回類似以下的內容:

    NAME                      LOCATION     SRC_INSTANCE                        SRC_FILE_SHARE  STATE
    mybackup-20201123-184500  us-central1  us-central1-c/instances/nfs-server  vol1            READY
    

刪除備份

  1. 在本教學課程的範例中,如果您想安排作業,以便在每天晚上 10 點刪除備份,請使用 scheduler jobs create http 指令:

    gcloud scheduler jobs create http deletefsbackupschedule \
        --schedule "0 22 * * 1-5" \
        --http-method=GET \
        --uri=https://us-central1-$PROJECT_ID.cloudfunctions.net/deletefsbackup \
        --oidc-service-account-email=$SCHEDULER_CLIENT_SA    \
        --oidc-token-audience=https://us-central1-$PROJECT_ID.cloudfunctions.net/deletefsbackup
    

    您可以使用 --schedule 標記,以 unix-cron 格式指定工作執行的頻率。詳情請參閱「設定 Cron 工作時間表」。

    與相同來源執行個體相關聯的備份 delete 作業必須一次執行一個。詳情請參閱「備份」。

  2. 啟動在前一個步驟中建立的 Cloud Scheduler 工作。在本例中,我們使用 scheduler jobs runs 指令立即執行它:

    gcloud scheduler jobs run deletefsbackupschedule
    

    您執行指令後,deletefsbackupschedule 工作會立即叫用 deletefsbackup 函式,然後每週在晚上 10 點再次叫用,直到工作暫停為止。

  3. 檢查 deletefsbackup 函式的記錄檔,瞭解該函式是否正常執行並傳回 status 200

    如要在 Google Cloud 控制台中查看記錄,請使用記錄檔探索工具:

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

      前往「Logs Explorer」(記錄檔探索工具)

      如果您是使用搜尋列尋找這個頁面,請選取子標題為「Logging」的結果

      「Query results」(查詢結果) 窗格會顯示最近的記錄檔。

  4. 使用 backups list 指令檢查現有備份的狀態:

    gcloud filestore backups list
    

    指令會傳回類似以下的內容:

    NAME                      LOCATION     SRC_INSTANCE                        SRC_FILE_SHARE  STATE
    mybackup-20201123-184500  us-central1  us-central1-c/instances/nfs-server  vol1            READY
    

備份配額不足警示

如果您設定的備份排程可能導致備份配額用盡,建議您設定備份配額不足的快訊。這樣一來,系統就會在備份配額偏低時通知您。

清除所用資源

完成教學課程後,您可以清除所建立的資源,這樣資源就不會占用配額並產生費用。下列各節將說明如何刪除或關閉這些資源。

刪除專案

如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

如要刪除專案:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

後續步驟