forked from mtusi2026/mtusi2026lab6
Перенести и адаптировать базу лабораторной 5 для отдельного стенда 6
This commit is contained in:
+123
@@ -0,0 +1,123 @@
|
||||
"""Worker обрабатывает одну доставку за раз и подтверждает после COMMIT."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from src import broker, jobs, faults
|
||||
from src.objects import BUCKET, ObjectConflict, client, put_immutable
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
class PermanentError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fetch(s3, key, attachment, destination):
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
obj = s3.get_object(Bucket=BUCKET, Key=key)
|
||||
with closing(obj['Body']) as stream, destination.open('wb') as output:
|
||||
for chunk in stream.iter_chunks(chunk_size=64 * 1024):
|
||||
size += len(chunk)
|
||||
if size > attachment['size_bytes']:
|
||||
raise PermanentError('staging_integrity')
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
if (size, digest.hexdigest()) != (attachment['size_bytes'], attachment['sha256']):
|
||||
raise PermanentError('staging_integrity')
|
||||
|
||||
|
||||
def process(job):
|
||||
faults.hit('before_effect', job)
|
||||
attachment = job['attachment']
|
||||
s3 = client()
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp)
|
||||
original = directory / 'original'
|
||||
source = attachment['object_key'] if attachment['published_pipeline_version'] else job['staging_key']
|
||||
fetch(s3, source, attachment, original)
|
||||
result = subprocess.run([sys.executable, '-m', 'src.image_pipeline', temp, str(job['pipeline_version'])],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
timeout=jobs.JOB_TIMEOUT, check=False)
|
||||
if result.returncode == 2:
|
||||
raise PermanentError('invalid_image')
|
||||
result.check_returncode()
|
||||
with original.open('rb') as stream:
|
||||
put_immutable(s3, attachment['object_key'], stream, attachment['size_bytes'],
|
||||
attachment['content_type'], attachment['sha256'])
|
||||
variants = []
|
||||
faults.hit('after_original', job)
|
||||
for name, mime, width, height in json.loads((directory / 'manifest.json').read_text()):
|
||||
key = f"variants/{attachment['id']}/v{job['pipeline_version']}/{name}"
|
||||
output = directory / name
|
||||
size = output.stat().st_size
|
||||
with output.open('rb') as stream:
|
||||
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
stream.seek(0)
|
||||
put_immutable(s3, key, stream, size, mime, digest)
|
||||
variants.append((name, key, mime, size, digest, width, height))
|
||||
faults.hit('after_variants', job)
|
||||
jobs.complete(job, variants)
|
||||
faults.hit('after_commit', job)
|
||||
|
||||
|
||||
def handle(channel, delivery, body):
|
||||
try:
|
||||
message = jobs.validate(json.loads(body))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
logging.warning('invalid broker job')
|
||||
channel.basic_reject(delivery.delivery_tag, requeue=False)
|
||||
return
|
||||
|
||||
job = jobs.claim(message)
|
||||
if job:
|
||||
try:
|
||||
process(job)
|
||||
except PermanentError as exc:
|
||||
jobs.fail(job, str(exc), permanent=True)
|
||||
except ObjectConflict:
|
||||
jobs.fail(job, 'object_conflict', permanent=True)
|
||||
except (BotoCoreError, ClientError, OSError, subprocess.SubprocessError) as exc:
|
||||
logging.warning('processing retry job=%s cause=%s', job['id'], type(exc).__name__)
|
||||
jobs.fail(job, 'processing_timeout' if isinstance(exc, subprocess.TimeoutExpired) else 'processing_failed')
|
||||
channel.basic_ack(delivery.delivery_tag)
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.WARNING)
|
||||
stopping = threading.Event()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
signal.signal(sig, lambda *_: stopping.set())
|
||||
storage.pool.open(wait=True)
|
||||
try:
|
||||
while not stopping.is_set():
|
||||
try:
|
||||
with broker.channel(heartbeat=jobs.LEASE_SECONDS + 15) as (_, channel):
|
||||
channel.basic_qos(prefetch_count=1)
|
||||
for delivery, _, body in channel.consume(broker.QUEUE, inactivity_timeout=0.5):
|
||||
if stopping.is_set():
|
||||
break
|
||||
if delivery:
|
||||
handle(channel, delivery, body)
|
||||
except (pika.exceptions.AMQPError, OSError, psycopg.Error, PoolTimeout) as exc:
|
||||
logging.warning('worker temporarily unavailable: %s', type(exc).__name__)
|
||||
stopping.wait(1)
|
||||
finally:
|
||||
storage.pool.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user