Реализовать S3-вложения и reconciler
This commit is contained in:
Executable
+10
@@ -0,0 +1,10 @@
|
||||
import os
|
||||
import psycopg
|
||||
from pathlib import Path
|
||||
|
||||
url = os.getenv("DATABASE_URL", "postgresql://messenger:messenger@postgres:5432/messenger")
|
||||
with psycopg.connect(url) as conn:
|
||||
for path in sorted(Path("migrations").glob("*.sql")):
|
||||
conn.execute(path.read_text())
|
||||
conn.commit()
|
||||
print("migrations applied")
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Find and safely repair objects that disagree with attachment metadata."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import boto3
|
||||
import psycopg
|
||||
from botocore.config import Config
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--apply', action='store_true', help='delete old orphans and mark missing rows failed')
|
||||
parser.add_argument('--grace-seconds', type=int, default=300)
|
||||
args = parser.parse_args()
|
||||
|
||||
database_url = os.getenv('DATABASE_URL', 'postgresql://messenger:messenger@postgres:5432/messenger')
|
||||
bucket = os.getenv('S3_BUCKET', 'messenger-attachments')
|
||||
s3 = boto3.client(
|
||||
's3', endpoint_url=os.getenv('S3_ENDPOINT', 'http://minio:9000'),
|
||||
region_name=os.getenv('S3_REGION', 'us-east-1'),
|
||||
aws_access_key_id=os.getenv('S3_ACCESS_KEY_ID', 'messenger-api'),
|
||||
aws_secret_access_key=os.getenv('S3_SECRET_ACCESS_KEY', 'messenger-api-secret-123'),
|
||||
config=Config(connect_timeout=2, read_timeout=5, retries={'max_attempts': 1}),
|
||||
)
|
||||
objects = {}
|
||||
token = None
|
||||
while True:
|
||||
kwargs = {'Bucket': bucket}
|
||||
if token:
|
||||
kwargs['ContinuationToken'] = token
|
||||
page = s3.list_objects_v2(**kwargs)
|
||||
for item in page.get('Contents', []):
|
||||
objects[item['Key']] = item
|
||||
if not page.get('IsTruncated'):
|
||||
break
|
||||
token = page['NextContinuationToken']
|
||||
|
||||
with psycopg.connect(database_url) as connection:
|
||||
rows = connection.execute('SELECT id, object_key, status FROM attachments').fetchall()
|
||||
known = {row[1]: row for row in rows}
|
||||
missing = [row for row in rows if row[1] not in objects and row[2] == 'ready']
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
|
||||
orphan = [item for key, item in objects.items() if key not in known and item['LastModified'] < cutoff]
|
||||
deleted = []
|
||||
marked_failed = []
|
||||
if args.apply:
|
||||
for item in orphan:
|
||||
s3.delete_object(Bucket=bucket, Key=item['Key'])
|
||||
deleted.append(item['Key'])
|
||||
for row in missing:
|
||||
connection.execute(
|
||||
"UPDATE attachments SET status='failed', error_code='object_missing', updated_at=now() WHERE id=%s",
|
||||
(row[0],),
|
||||
)
|
||||
marked_failed.append(str(row[0]))
|
||||
connection.commit()
|
||||
|
||||
print(json.dumps({
|
||||
'objects': len(objects), 'metadata_rows': len(rows),
|
||||
'orphan_candidates': [item['Key'] for item in orphan],
|
||||
'missing_candidates': [str(row[0]) for row in missing],
|
||||
'deleted_orphans': deleted, 'marked_failed': marked_failed,
|
||||
'dry_run': not args.apply, 'grace_seconds': args.grace_seconds,
|
||||
}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Перезапускаем стенд, не удаляя volumes.
|
||||
# Балансировщик запускаем после API, чтобы DNS имён реплик уже был доступен.
|
||||
docker compose up -d minio postgres redis minio-init migrate api-1 api-2 api-3 api-4
|
||||
docker compose restart minio postgres redis api-1 api-2 api-3 api-4
|
||||
docker compose up -d --force-recreate lb
|
||||
docker compose ps
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
TARGET_INSTANCE_ID=${TARGET_INSTANCE_ID:-api-1}
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
api-1) service=api-1 ;;
|
||||
api-2) service=api-2 ;;
|
||||
api-3) service=api-3 ;;
|
||||
api-4) service=api-4 ;;
|
||||
*) echo "unknown TARGET_INSTANCE_ID: $TARGET_INSTANCE_ID" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
docker compose stop "$service"
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Small local experiment for the two-storage reconciler."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import boto3
|
||||
import psycopg
|
||||
from botocore.config import Config
|
||||
|
||||
|
||||
def main():
|
||||
bucket = os.getenv('S3_BUCKET', 'messenger-attachments')
|
||||
s3 = boto3.client(
|
||||
's3', endpoint_url=os.getenv('S3_ENDPOINT', 'http://minio:9000'),
|
||||
region_name=os.getenv('S3_REGION', 'us-east-1'),
|
||||
aws_access_key_id=os.getenv('S3_ACCESS_KEY_ID', 'messenger-api'),
|
||||
aws_secret_access_key=os.getenv('S3_SECRET_ACCESS_KEY', 'messenger-api-secret-123'),
|
||||
config=Config(connect_timeout=2, read_timeout=5, retries={'max_attempts': 1}),
|
||||
)
|
||||
old_key = 'reconcile-demo/old-' + uuid.uuid4().hex
|
||||
fresh_key = 'reconcile-demo/fresh-' + uuid.uuid4().hex
|
||||
s3.put_object(Bucket=bucket, Key=old_key, Body=b'old orphan')
|
||||
time.sleep(6)
|
||||
s3.put_object(Bucket=bucket, Key=fresh_key, Body=b'fresh orphan')
|
||||
|
||||
missing_id = uuid.uuid4()
|
||||
with psycopg.connect(os.getenv('DATABASE_URL', 'postgresql://messenger:messenger@postgres:5432/messenger')) as connection:
|
||||
owner, chat = connection.execute('SELECT user_id, chat_id FROM chat_members LIMIT 1').fetchone()
|
||||
connection.execute(
|
||||
'INSERT INTO attachments '
|
||||
'(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,status,error_code,created_at,updated_at) '
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),now())",
|
||||
(missing_id, chat, owner, 'missing.png', 'image/png', 10, '0' * 64,
|
||||
'attachments/missing-' + str(missing_id), 'ready', None),
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
root = Path(__file__).resolve().parent
|
||||
dry = subprocess.check_output(
|
||||
['python', str(root / 'reconcile_s3.py'), '--grace-seconds', '5'], text=True,
|
||||
)
|
||||
applied = subprocess.check_output(
|
||||
['python', str(root / 'reconcile_s3.py'), '--apply', '--grace-seconds', '5'], text=True,
|
||||
)
|
||||
applied_data = json.loads(applied)
|
||||
fresh_exists = True
|
||||
try:
|
||||
s3.head_object(Bucket=bucket, Key=fresh_key)
|
||||
except Exception:
|
||||
fresh_exists = False
|
||||
s3.delete_object(Bucket=bucket, Key=fresh_key)
|
||||
with psycopg.connect(os.getenv('DATABASE_URL', 'postgresql://messenger:messenger@postgres:5432/messenger')) as connection:
|
||||
missing_status = connection.execute('SELECT status,error_code FROM attachments WHERE id=%s', (missing_id,)).fetchone()
|
||||
connection.execute('DELETE FROM attachments WHERE id=%s', (missing_id,))
|
||||
connection.commit()
|
||||
print(json.dumps({
|
||||
'old_orphan_removed': old_key in applied_data['deleted_orphans'],
|
||||
'fresh_orphan_preserved': fresh_exists,
|
||||
'missing_marked_failed': list(missing_status) == ['failed', 'object_missing'],
|
||||
'dry_run': dry.strip(), 'apply': applied.strip(),
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user