|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2017 Google Inc. All rights reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""This application demonstrates how to poll for GCS notifications from a |
| 18 | +Cloud Pub/Sub subscription, parse the incoming message, and acknowledge the |
| 19 | +successful processing of the message. |
| 20 | +
|
| 21 | +This application will work with any subscription configured for pull rather |
| 22 | +than push notifications. If you do not already have notifications configured, |
| 23 | +you may consult the docs at |
| 24 | +https://cloud.google.com/storage/docs/reporting-changes or follow the steps |
| 25 | +below: |
| 26 | +
|
| 27 | +1. Activate the Google Cloud Pub/Sub API, if you have not already done so. |
| 28 | + https://console.cloud.google.com/flows/enableapi?apiid=pubsub |
| 29 | +
|
| 30 | +2. Create a Google Cloud Storage bucket: |
| 31 | + $ gsutil mb gs://testbucket |
| 32 | +
|
| 33 | +3. Create a Cloud Pub/Sub topic and publish bucket notifications there: |
| 34 | + $ gsutil notification create -f json -t testtopic gs://testbucket |
| 35 | +
|
| 36 | +4. Create a subscription for your new topic: |
| 37 | + $ gcloud beta pubsub subscriptions create testsubscription --topic=testtopic |
| 38 | +
|
| 39 | +5. Run this program: |
| 40 | + $ python notification_polling testsubscription |
| 41 | +
|
| 42 | +6. While the program is running, upload and delete some files in the testbucket |
| 43 | + bucket (you could use the console or gsutil) and watch as changes scroll by |
| 44 | + in the app. |
| 45 | +""" |
| 46 | + |
| 47 | +import argparse |
| 48 | +import json |
| 49 | +import sys |
| 50 | + |
| 51 | +from google.cloud import pubsub |
| 52 | + |
| 53 | + |
| 54 | +def summarize(message): |
| 55 | + # [START parse_message] |
| 56 | + data = message.data |
| 57 | + attributes = message.attributes |
| 58 | + |
| 59 | + event_type = attributes['eventType'] |
| 60 | + bucket_id = attributes['bucketId'] |
| 61 | + object_id = attributes['objectId'] |
| 62 | + generation = attributes['objectGeneration'] |
| 63 | + description = ( |
| 64 | + '\tEvent type: {event_type}\n' |
| 65 | + '\tBucket ID: {bucket_id}\n' |
| 66 | + '\tObject ID: {object_id}\n' |
| 67 | + '\tGeneration: {generation}\n').format( |
| 68 | + event_type=event_type, |
| 69 | + bucket_id=bucket_id, |
| 70 | + object_id=object_id, |
| 71 | + generation=generation) |
| 72 | + |
| 73 | + payload_format = attributes['payloadFormat'] |
| 74 | + if payload_format == 'JSON_API_V1': |
| 75 | + object_metadata = json.loads(data) |
| 76 | + size = object_metadata['size'] |
| 77 | + content_type = object_metadata['contentType'] |
| 78 | + metageneration = object_metadata['metageneration'] |
| 79 | + description += ( |
| 80 | + '\tContent type: {content_type}\n' |
| 81 | + '\tSize: {object_size}\n' |
| 82 | + '\tMetageneration: {metageneration}\n').format( |
| 83 | + content_type=content_type, |
| 84 | + object_size=size, |
| 85 | + metageneration=metageneration) |
| 86 | + return description |
| 87 | + # [END parse_message] |
| 88 | + |
| 89 | + |
| 90 | +def poll_notifications(subscription_id): |
| 91 | + """Polls a Cloud Pub/Sub subscription for new GCS events for display.""" |
| 92 | + # [BEGIN poll_notifications] |
| 93 | + client = pubsub.Client() |
| 94 | + subscription = pubsub.subscription.Subscription( |
| 95 | + subscription_id, client=client) |
| 96 | + |
| 97 | + if not subscription.exists(): |
| 98 | + sys.stderr.write('Cannot find subscription {0}\n'.format(sys.argv[1])) |
| 99 | + return |
| 100 | + |
| 101 | + print('Polling for messages. Press ctrl+c to exit.') |
| 102 | + while True: |
| 103 | + pulled = subscription.pull(max_messages=100) |
| 104 | + for ack_id, message in pulled: |
| 105 | + print('Received message {0}:\n{1}'.format( |
| 106 | + message.message_id, summarize(message))) |
| 107 | + subscription.acknowledge([ack_id]) |
| 108 | + # [END poll_notifications] |
| 109 | + |
| 110 | + |
| 111 | +if __name__ == '__main__': |
| 112 | + parser = argparse.ArgumentParser( |
| 113 | + description=__doc__) |
| 114 | + parser.add_argument('subscription', |
| 115 | + help='The ID of the Pub/Sub subscription') |
| 116 | + args = parser.parse_args() |
| 117 | + poll_notifications(args.subscription) |
0 commit comments