首页 > 解决方案 > 谷歌云功能“触发器桶”没有按预期工作

问题描述

我制作了一个简单的 Cloud Function,它应该在 Cloud Storage 存储桶中记录文件操作的详细信息。

我使用以下命令部署它:gcloud functions deploy bucket_logger --runtime=python37 --memory=256 --region=us-east1 --entry-point=bucket_logger_function --trigger-bucket=[BUCKET_NAME]

def bucket_logger_function(data, context):
    id = context.event_id
    type = context.event_type

    print('Event ID: ' + id)
    print('Event Type: ' + type)

    if type == 'google.storage.object.finalize':
            print('File created: ' + data['name'])
    elif type == 'google.storage.objects.delete':
            print('File deleted: ' + data['name'])
    elif type == 'google.storage.objects.metadataUpdate':
            print('Metadata updated: ' + data['name'])
    else:
            print('File archived: ' + data['name'])

我希望每当我上传、删除、存档和更新存储桶中任何对象的元数据时都会触发该功能,但它仅在上传文件时触发。

我会错过什么?该文档没有提到任何具体的内容,它声称上述操作会起作用。

标签: google-cloud-platformgoogle-cloud-functionsgoogle-cloud-storage

解决方案


仔细查看文档:

使用标志 --trigger-resource MY_RESOURCE 和 --trigger-event MY_EVENT 是为后台函数指定触发器的最明确方式。但是,gcloud 提供了 Pub/Sub 和 Cloud Storage 的简写:

简写。因此,这隐含地为您执行选择。要了解该命令的更多功能,我建议您使用--log-http查看执行 gcloud 的 http 调用的选项。对于这个命令,有很多,有一刻,我得到了这个

==== request start ====
uri: https://cloudfunctions.googleapis.com/v1/projects/<MyProject>/locations/us-central1/functions?alt=json
method: POST
== headers start ==
b'Authorization': --- Token Redacted ---
b'accept': b'application/json'
b'accept-encoding': b'gzip, deflate'
b'content-length': b'903'
b'content-type': b'application/json'
b'user-agent': b'google-cloud-sdk gcloud/293.0.0 command/gcloud.functions.deploy invocation-id/480b4938d2e1469bab2e1a236c5ac53a environment/devshell environment-version/None interactive/True from-script/False python/3.7.3 term/screen (Linux 4.1
9.112+)'
== headers end ==
== body start ==
{"eventTrigger": {"eventType": "google.storage.object.finalize", "resource": "projects/_/buckets/<myBucket>"}, ....

您可以看到"eventType": "google.storage.object.finalize",因此您看到的行为是正确的。仅当文件完成并且事件被触发到您的函数时。这个选择是为你而做的。

现在,如何解决您的用例。2种方式

  • 部署 4 个云函数,每个事件类型一个(完成、删除、元数据更新和存档)(不是我最喜欢的建议,见下文)
  • 创建一个 PubSub 主题。创建 4 个,每个事件类型一个,在 Cloud Storage 上发布订阅通知。然后将您的功能插入 pubsub 主题--trigger-topic=...而不是--trigger-bucket=...

推荐阅读