ЛР6: наблюдаемость, SLO и диагностика отказов
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
|
||||
class Cleanup:
|
||||
def __init__(self, repository, storage):
|
||||
self.repository = repository
|
||||
self.storage = storage
|
||||
|
||||
def run(self):
|
||||
with self.repository.connection() as db:
|
||||
row = db.execute("SELECT pg_try_advisory_xact_lock(741204) AS acquired").fetchone()
|
||||
if not row["acquired"]:
|
||||
return
|
||||
self._clear_failed(db)
|
||||
self._clear_ready(db)
|
||||
self._scan(db)
|
||||
|
||||
def _clear_ready(self, db):
|
||||
rows = db.execute(
|
||||
"""SELECT id,staging_key FROM attachments WHERE status='READY'
|
||||
AND staging_key IS NOT NULL LIMIT 100 FOR UPDATE SKIP LOCKED"""
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
self.storage.client.delete_object(
|
||||
Bucket=self.storage.settings.bucket, Key=row["staging_key"]
|
||||
)
|
||||
db.execute("UPDATE attachments SET staging_key=NULL WHERE id=%s", (row["id"],))
|
||||
|
||||
def _clear_failed(self, db):
|
||||
rows = db.execute(
|
||||
"""SELECT id,staging_key,pipeline_version FROM attachments WHERE status='FAILED'
|
||||
AND staging_key IS NOT NULL AND updated_at < now() - %s * interval '1 second'
|
||||
LIMIT 100 FOR UPDATE SKIP LOCKED""",
|
||||
(self.storage.settings.retention,),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
self.storage.client.delete_object(
|
||||
Bucket=self.storage.settings.bucket, Key=row["staging_key"]
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE attachments SET staging_key=NULL,error_code='staging_expired' WHERE id=%s",
|
||||
(row["id"],),
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE processing_jobs SET error_code='staging_expired' WHERE attachment_id=%s AND pipeline_version=%s",
|
||||
(row["id"], row["pipeline_version"]),
|
||||
)
|
||||
|
||||
def _scan(self, db):
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=self.storage.settings.retention)
|
||||
pages = self.storage.client.get_paginator("list_objects_v2")
|
||||
for page in pages.paginate(Bucket=self.storage.settings.bucket):
|
||||
for item in page.get("Contents", []):
|
||||
if item["LastModified"] < cutoff and not self._referenced(db, item["Key"]):
|
||||
self.storage.client.delete_object(
|
||||
Bucket=self.storage.settings.bucket, Key=item["Key"]
|
||||
)
|
||||
|
||||
def _referenced(self, db, key):
|
||||
return db.execute(
|
||||
"""SELECT 1 FROM attachments WHERE object_key=%s OR staging_key=%s
|
||||
UNION ALL SELECT 1 FROM attachment_variants WHERE object_key=%s LIMIT 1""",
|
||||
(key, key, key),
|
||||
).fetchone()
|
||||
Reference in New Issue
Block a user