Google有云存储数据传输选项,可以从一个存储桶复制到另一个存储桶,但只有当两个存储桶都在同一个项目中时,这才会起作用。作为cron运行,使用gutil -m rsync -r -d是一个简单的选择,但是我们将所有的bash迁移到python3。因此,我需要一个Python3脚本来使用它作为google cloud函数,每周将整个存储桶从project1复制到project2中的另一个存储桶。
Language: python 3
app : Cloud Function
Process : Copy one bucket to another
Source Project: project1
Source bucket : bucket1
Dest Project: project2
Dest Bucket: bucket2
pseudo cmd: rsync -r gs://project1/bucket1 gs://project2/bucket2任何快速可读的python 3代码脚本都可以做到这一点。
发布于 2020-09-22 01:54:42
Rsync不是不能在storage rest API中通过单个请求执行的操作,并且gsutil在云函数上不可用,因此无法通过python脚本实现两个buckets的rsync。
您可以创建一个函数,使用执行存储桶之间同步的startup script启动preemptible VM,并在完成同步操作后关闭实例。
通过使用VM而不是无服务器服务,您可以避免长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访问部分,选择有权读取云存储中的启动脚本文件和要同步的存储桶的服务帐户
7.-在可用性策略下,将抢占选项设置为On。此设置禁用实例的自动重新启动,并将主机维护操作设置为终止。
8.-在元数据部分,提供startup-script-url作为元数据密钥。
9.-在值框中,以gs://存储桶/文件或https://storage.googleapis.com/BUCKET/FILE格式提供启动脚本文件的URL。
10.单击Create创建实例。
使用此配置,每次启动实例时,脚本也将被执行。
这是启动虚拟机的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计划您的功能:
在function
audience field中,您只需编写函数的URL,而不需要任何其他参数<functions.invoker permission>G235
在云调度器上,我使用以下URL访问我的函数
https://us-central1-yourprojectID.cloudfunctions.net/power
我利用了这些观众
https://us-central1-yourprojectID.cloudfunctions.net/power
请在代码、URL和区域us-central1中替换yourprojectID
发布于 2020-09-22 02:22:55
执行此操作的python脚本将变得非常慢()。我将使用Dataflow (apache bream)批处理进程来完成此操作。您可以很容易地在python3中对此进行编码。
基本上,您需要:
好的部分是Google将为您扩展工人,并且不会花费太多时间。您将为存储操作和移动所有数据所需的to + cpu付费。
https://stackoverflow.com/questions/63988682
复制相似问题