diff --git a/.gitattributes b/.gitattributes index a1c22612..5294b68f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,5 @@ *.py text eol=lf *.sql text eol=lf *.yaml text eol=lf +*.conf text eol=lf +*.cmd text eol=crlf diff --git a/compose.yaml b/compose.yaml index c44c1cc4..8a20f196 100644 --- a/compose.yaml +++ b/compose.yaml @@ -121,6 +121,15 @@ services: cpus: 0.75 mem_limit: 768m stop_grace_period: 95s + staging-cleaner: + <<: *app + command: [python, -m, src.staging] + restart: unless-stopped + depends_on: *dependencies + healthcheck: + disable: true + cpus: 0.25 + mem_limit: 256m lb: image: haproxy:3.0.6-alpine ports: ['127.0.0.1:${LAB5_PORT:-8085}:8080'] diff --git a/scripts/actions.py b/scripts/actions.py new file mode 100644 index 00000000..48246fee --- /dev/null +++ b/scripts/actions.py @@ -0,0 +1,31 @@ +"""Windows hooks for the public resilience client.""" + +import os +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def docker(*args): + return subprocess.check_output(['docker', *args], cwd=ROOT, text=True).strip() + + +def main(): + if sys.argv[1] == 'restart': + docker('compose', 'restart', '-t', '4', 'db', 'redis', 's3', 'broker', 'api', + 'dispatcher', 'worker', 'staging-cleaner', 'lb') + return + target = os.environ['TARGET_INSTANCE_ID'] + for container in docker('compose', 'ps', '-q', 'api').splitlines(): + name = docker('inspect', '--format', '{{.Config.Hostname}}', container) + prefix, _, suffix = target.rpartition('-') + if prefix == name and len(suffix) == 8: + docker('stop', '-t', '2', container) + return + raise SystemExit('API instance not found') + + +if __name__ == '__main__': + main() diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..1e76668c --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,2 @@ +@echo off +python "%~dp0actions.py" restart diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..c4a7a9fd --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,5 @@ +#!/bin/sh +set -eu +root="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)" +cd "$root" +docker compose restart -t 4 db redis s3 broker api dispatcher worker staging-cleaner lb diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..0a94006e --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,2 @@ +@echo off +python "%~dp0actions.py" stop-one diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..c80f3f62 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +root="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)" +cd "$root" +: "${TARGET_INSTANCE_ID:?}" +for container in $(docker compose ps -q api); do + hostname="$(docker inspect --format '{{.Config.Hostname}}' "$container")" + case "$TARGET_INSTANCE_ID" in + "$hostname"-????????) + docker compose ps -q api | grep -Fx "$container" >/dev/null + docker stop -t 2 "$container" >/dev/null + exit 0 + ;; + esac +done +exit 1 diff --git a/src/image_pipeline.py b/src/image_pipeline.py index b2512e7a..86f651e0 100644 --- a/src/image_pipeline.py +++ b/src/image_pipeline.py @@ -33,7 +33,15 @@ def render(source, target): del image thumbnail = fit(rgb, 256) thumbnail.save(target / 'thumbnail', 'JPEG', quality=85) - return [['thumbnail', 'image/jpeg', *thumbnail.size]] + crop = ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS) + crop.save(target / 'crop', 'JPEG', quality=85) + optimized = fit(rgb, 1280) + optimized.save(target / 'optimized', 'WEBP', quality=82, method=4) + return [ + ['thumbnail', 'image/jpeg', *thumbnail.size], + ['crop', 'image/jpeg', *crop.size], + ['optimized', 'image/webp', *optimized.size], + ] def main(): diff --git a/src/jobs.py b/src/jobs.py index 9e4d7e10..e4156e71 100644 --- a/src/jobs.py +++ b/src/jobs.py @@ -4,6 +4,7 @@ import random from uuid import UUID, uuid4 from src.config import setting +from src.objects import BUCKET, client, object_lock from src.storage import storage, timestamp JOB_TIMEOUT = int(setting('JOB_TIMEOUT_SECONDS', '60')) @@ -159,3 +160,29 @@ def recover_expired(): if (job and job['state'] == 'processing' and not owns(conn, job, job)): settle_error(conn, job, 'lease_expired') + + +def replay(attachment_id): + with storage.pool.connection() as conn: + attachment = conn.execute('SELECT id FROM attachments WHERE id=%s FOR UPDATE', + (attachment_id,)).fetchone() + if not attachment: + return None + job = conn.execute('SELECT * FROM attachment_jobs WHERE attachment_id=%s FOR UPDATE', + (attachment_id,)).fetchone() + if not job or job['state'] != 'failed': + return None + object_lock(conn, job['staging_key']) + client().head_object(Bucket=BUCKET, Key=job['staging_key']) + new_attempt = job['attempt'] + 1 + budget = int(setting('JOB_MAX_ATTEMPTS', '5')) + conn.execute( + """UPDATE attachment_jobs SET state='queued', attempt=%s, attempt_limit=%s, + next_publish_at=clock_timestamp(), published_at=NULL, publish_failures=0 + WHERE id=%s""", (new_attempt, new_attempt + budget - 1, job['id']), + ) + conn.execute("INSERT INTO attachment_replays(job_id,attempt,reason) VALUES (%s,%s,'operator')", + (job['id'], new_attempt)) + conn.execute("UPDATE attachments SET state='queued',error_code=NULL,updated_at=clock_timestamp() " + "WHERE id=%s", (attachment_id,)) + return job['id'], new_attempt diff --git a/src/operator.py b/src/operator.py new file mode 100644 index 00000000..96508c49 --- /dev/null +++ b/src/operator.py @@ -0,0 +1,43 @@ +"""Локальные операции над реестром заданий.""" + +import argparse +import json +from uuid import UUID + +from botocore.exceptions import BotoCoreError, ClientError + +from src import jobs +from src.storage import storage, timestamp + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('action', choices=('failed', 'replay')) + parser.add_argument('attachment_id', type=UUID, nargs='?') + args = parser.parse_args() + if args.action == 'replay' and args.attachment_id is None: + parser.error('replay requires attachment_id') + storage.pool.open(wait=True) + try: + if args.action == 'replay': + try: + result = jobs.replay(args.attachment_id) + except (BotoCoreError, ClientError): + raise SystemExit('Источник для replay недоступен') from None + if result is None: + raise SystemExit('Нет подходящей failed-задачи') + print(json.dumps({'job_id': str(result[0]), 'attempt': result[1]})) + else: + with storage.pool.connection() as conn: + rows = conn.execute( + """SELECT j.id, j.attachment_id, j.attempt, j.last_error, a.updated_at + FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id + WHERE j.state='failed' ORDER BY a.updated_at DESC LIMIT 100""" + ).fetchall() + print(json.dumps(rows, default=lambda value: str(value) if isinstance(value, UUID) else timestamp(value))) + finally: + storage.pool.close() + + +if __name__ == '__main__': + main() diff --git a/src/staging.py b/src/staging.py new file mode 100644 index 00000000..466269e6 --- /dev/null +++ b/src/staging.py @@ -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() diff --git a/student-tests/test_images.py b/student-tests/test_images.py new file mode 100644 index 00000000..eadae04d --- /dev/null +++ b/student-tests/test_images.py @@ -0,0 +1,53 @@ +import hashlib +import tempfile +import unittest +from pathlib import Path + +from PIL import Image + +from src.image_pipeline import render + +ROOT = Path(__file__).resolve().parents[1] + + +class Images(unittest.TestCase): + def test_public_fixture_and_repeat(self): + fixture = ROOT / 'tests' / 'fixtures' / 'sample.png' + original = hashlib.sha256(fixture.read_bytes()).hexdigest() + with tempfile.TemporaryDirectory() as directory: + target = Path(directory) + expected = { + 'thumbnail': ('JPEG', (256, 160)), + 'crop': ('JPEG', (128, 128)), + 'optimized': ('WEBP', (320, 200)), + } + first = render(fixture, target) + self.assertEqual(len(first), len(expected)) + digests = {name: hashlib.sha256((target / name).read_bytes()).hexdigest() for name in expected} + self.assertEqual(first, render(fixture, target)) + for name, properties in expected.items(): + with Image.open(target / name) as image: + self.assertEqual((image.format, image.size), properties) + self.assertEqual(hashlib.sha256((target / name).read_bytes()).hexdigest(), digests[name]) + self.assertEqual(hashlib.sha256(fixture.read_bytes()).hexdigest(), original) + + def test_orientation_alpha_and_small_image(self): + with tempfile.TemporaryDirectory() as directory: + target = Path(directory) + source = target / 'source.png' + image = Image.new('RGBA', (35, 15), (255, 0, 0, 0)) + image.save(source, exif=self.orientation()) + render(source, target) + with Image.open(target / 'thumbnail') as thumbnail: + self.assertEqual(thumbnail.size, (15, 35)) + self.assertEqual(thumbnail.getpixel((4, 4)), (255, 255, 255)) + self.assertFalse(thumbnail.getexif()) + with Image.open(target / 'optimized') as optimized: + self.assertEqual(optimized.size, (15, 35)) + self.assertFalse(optimized.getexif()) + + @staticmethod + def orientation(): + exif = Image.Exif() + exif[274] = 6 + return exif