Rsync 不是无法通过storage rest API 中的单个请求执行的操作,并且gsutil 在 Cloud Functions 上不可用,因此无法通过 python 脚本对两个存储桶进行 rsync。
您可以创建一个函数以使用startup script 启动preemptible VM,该函数在存储桶之间执行rsync,并在完成rsync 操作后关闭实例。
通过使用虚拟机而不是无服务器服务,您可以避免长时间 rsync 进程可能产生的任何超时。
抢占式虚拟机在停止前最多可以运行 24 小时,并且仅在实例开启时收费(磁盘存储将独立于状态收费)
如果虚拟机在一分钟前关闭,则不会按使用量收费。
对于这种方法,首先需要在存储桶中创建一个 bash 脚本,这将由可抢占式 VM 在启动时执行,例如:
#! /bin/bash
gstuil rsync -r gs://mybucket1 gs://mybucket2
sudo init 0 #this is similar to poweroff, halt or shutdown -h now
之后,您需要使用启动脚本创建一个抢占式 VM,我推荐一个 f1-micro 实例,因为存储桶之间的 rsync 命令不需要太多资源。
1.- 转到VM Instances page。
2.- 点击创建实例。
3.- 在创建新实例页面上,填写您的实例的属性。
4.- 点击管理、安全、磁盘、网络、单租。
5.在身份和 API 访问部分中,选择有权读取 Cloud Storage 中的启动脚本文件和要同步的存储桶的服务帐号
- 选择允许完全访问所有云 API。
7.- 在可用性策略下,将抢占性选项设置为开。 此设置禁用实例的自动重启,并将主机维护操作设置为终止。
8.- 在 Metadata 部分,提供 startup-script-url 作为元数据键。
9.- 在“值”框中,提供启动脚本文件的 URL,格式为 gs://BUCKET/FILE 或 https://storage.googleapis.com/BUCKET/FILE。
10.点击创建创建实例。
使用此配置,每次启动您的实例时,脚本也会执行。
这是启动VM的python函数(如果这是可抢占的,则独立)
def power(request):
import logging
# this libraries are mandatory to reach compute engine api
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
# the function will take the service account of your function
credentials = GoogleCredentials.get_application_default()
# this line is to specify the api that we gonna use, in this case compute engine
service = discovery.build('compute', 'v1', credentials=credentials, cache_discovery=False)
# set correct log level (to avoid noise in the logs)
logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)
# Project ID for this request.
project = "yourprojectID" # Update placeholder value.
zone = "us-central1-a" # update this to the zone of your vm
instance = "myvm" # update with the name of your vm
response = service.instances().start(project=project, zone=zone, instance=instance).execute()
print(response)
return ("OK")
requirements.txt 文件
google-api-python-client
oauth2client
flask
您可以通过 Cloud Scheduler 来安排您的功能:
-
Create a service account 和 functions.invoker permission 在你的函数中
- Create new Cloud scheduler job
- 以 cron 格式指定频率。
- 将 HTTP 指定为目标类型。
- 一如既往地添加您的云函数和方法的 URL。
- 从 Auth 标头下拉列表中选择令牌 OIDC
- 在服务帐户文本框中添加服务帐户电子邮件。
-
audience field中只需要写函数的URL,不需要任何附加参数
在云调度程序上,我使用这些 URL 来实现我的功能
https://us-central1-yourprojectID.cloudfunctions.net/power
我使用了这些观众
https://us-central1-yourprojectID.cloudfunctions.net/power
请替换代码中的yourprojectID,在网址和区域us-central1