您可以使用以下 boto3 代码(我相信这也可以使用适用于 Java 的 AWS 开发工具包在 Java 中完成)来删除日志,为了定期删除,您可以选择
- 使用 Airflow 等工作流调度程序,请参见下面的示例
- 将其用作 lambda 函数并安排它定期运行(更容易)
- 在本地使用 cron jon(不太可行)
日志删除功能(输入即将过期的threshold、bucket name和prefix,可以是"logs/sparksteps/j-")
def clean_s3(buck, match_prefix,exp_threshold):
s3_client = boto3.client('s3')
key_names = []
file_timestamp = []
file_size = []
kwargs = {"Bucket": buck, "Prefix": match_prefix}
while True:
result = s3_client.list_objects_v2(**kwargs)
for obj in result["Contents"]:
if "." in obj["Key"]:
key_names.append(obj["Key"])
file_timestamp.append(obj["LastModified"].timestamp())
file_size.append(obj["Size"])
try:
kwargs["ContinuationToken"] = result["NextContinuationToken"]
except KeyError:
break
key_info = {
"key_path": key_names,
"timestamp": file_timestamp,
"size": file_size
}
#print(f'All Keys in {buck} with {prefix} Prefix found!')
s3_file = key_info
for i, fs in enumerate(s3_file["timestamp"]):
#file_expired = is_expired(fs)
#print(fs)
if fs < exp_threshold: #if True is recieved
print("Deleting %s" % {s3_file["key_path"][i]})
s3_client.delete_object(Bucket=buck, Key=s3_file["key_path"][i])
您可以计算需要通过的到期阈值(以纪元秒为单位),如下所示
date_now = time.time()
days = 7 # 7 days
total_time = 86400*days
exp_threshold = date_now-total_time
现在,对于选项 1,您可以制作如下所示的气流运算符
s3_cleanup = PythonOperator(
task_id='s3cleanup',
python_callable=clean_s3,
op_kwargs={
'buck': '<you bucket>',
'match_prefix': "logs/sparksteps/j-",
'exp_threshold':exp_threshold,
},dag=dag)
或者,使用 apporach 2,您可以使用 AWS lamda 进行调度,请参阅 guide for schedling with lambda here