我需要创建一个监视工具,该工具检查存储桶(每个存储桶中有1000多个文件)中是否有最近两个小时创建的新对象,如果未创建对象,则会发送一条消息。 我的第一个想法是创建一个lambda函数,该函数每20分钟运行一次。所以我创建了python3 + boto3代码:
import boto3
from datetime import datetime,timedelta
import pytz
import sys
s3 = boto3.resource('s3')
sns = boto3.client('sns')
buckets = ['bucket1', 'bucket2', 'bucket3']
check_fail = []
def check_bucket(event, context):
time_now_UTC = datetime.utcnow().replace(tzinfo=pytz.UTC)
delta_hours = time_now_UTC - timedelta(hours=2)
for bucket_name in buckets:
bucket = s3.Bucket(bucket_name)
for key in bucket.objects.all():
if key.last_modified >= delta_hours:
print("There are new files in the bucket %s" %bucket)
break
else:
check_fail.append(bucket)
if len(check_fail) >= 1:
sns.publish(
TopicArn='arn:aws:sns:us-east-1:xxxxxxxxxxxxxx:xxxxxx',
Message="The following buckets didn't receive new files for longer than 2 hours: %s" %check_fail,
Subject='AWS Notification Message' )
else:
print("All buckets have new files")
由于每个存储桶中有大量对象,因此此方法行不通。通过“ key.last_modified”检查花费的时间太长。
有人对我如何实现这一目标有想法吗?
谢谢!
答案 0 :(得分:1)
如您所见,S3已优化为获取您已经知道其路径的对象,而不是列出查询文件。实际上,listObjects API在迭代过程中并不是非常稳定,如果在开始查询之前添加文件,则很可能会丢失大量文件。
根据您拥有的存储桶数,一种解决方法是在S3事件上使用lambda触发器:
另一种解决方案是在存储桶上启用CloudWatch监控:https://docs.aws.amazon.com/AmazonS3/latest/dev/cloudwatch-monitoring.html
然后,您可以对过去两个小时内的PutRequests
和PostRequests
指标求和(您可以使用boto3以编程方式获取cloudwatch指标)以获取更新指示(尽管您的计数仅可能如果文件只被写入一次而从未被编辑过,则非常准确。)
答案 1 :(得分:0)
Amazon S3可以将事件发布到Lambda并通过传递S3事件数据作为参数来调用您的函数。因此,您可以通过以下方式配置它:已上传的每个新s3对象都将触发您的功能。完全不需要安排它。