forked from mtusi2026/mtusi2026lab5
Добавить варианты изображений, очистку staging, replay и сценарии отказа
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
"""Очистка staging с блокировкой, общей с HTTP upload и replay."""
|
||||
|
||||
import logging
|
||||
import signal
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psycopg
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from src.config import setting
|
||||
from src.objects import BUCKET, client, object_lock
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def cleanup(s3, retention):
|
||||
count = 0
|
||||
now = datetime.now(timezone.utc)
|
||||
pages = s3.get_paginator('list_objects_v2')
|
||||
for page in pages.paginate(Bucket=BUCKET, Prefix='staging/'):
|
||||
for item in page.get('Contents', []):
|
||||
key = item['Key']
|
||||
with storage.pool.connection() as conn:
|
||||
if not object_lock(conn, key, wait=False):
|
||||
continue
|
||||
job = conn.execute(
|
||||
'SELECT j.state,a.updated_at FROM attachment_jobs j JOIN attachments a '
|
||||
'ON a.id=j.attachment_id WHERE j.staging_key=%s', (key,),
|
||||
).fetchone()
|
||||
retention_start = job['updated_at'] if job else item['LastModified']
|
||||
age = (now - retention_start).total_seconds()
|
||||
if job and job['state'] in ('queued', 'processing'):
|
||||
continue
|
||||
if (job and job['state'] == 'ready') or age >= retention:
|
||||
s3.delete_object(Bucket=BUCKET, Key=key)
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def main():
|
||||
stop = threading.Event()
|
||||
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||
signal.signal(sig, lambda *_: stop.set())
|
||||
retention = max(60, int(setting('STAGING_RETENTION_SECONDS', '86400')))
|
||||
storage.pool.open(wait=True)
|
||||
try:
|
||||
while not stop.is_set():
|
||||
try:
|
||||
cleanup(client(), retention)
|
||||
except (BotoCoreError, ClientError, OSError, psycopg.Error, PoolTimeout) as exc:
|
||||
logging.warning('staging cleanup temporarily unavailable: %s', type(exc).__name__)
|
||||
stop.wait(30)
|
||||
finally:
|
||||
storage.pool.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user