forked from mtusi2026/mtusi2026lab7
Complete lab 7 security infrastructure
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
#!/usr/bin/env python3
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import logging
|
||||
import time
|
||||
from io import BytesIO
|
||||
|
||||
import psycopg
|
||||
import redis.asyncio as redis
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor
|
||||
from opentelemetry.instrumentation.redis import RedisInstrumentor
|
||||
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
|
||||
|
||||
from src.s3_client import upload_file, download_file, configure_client
|
||||
from src.bao import read_secret
|
||||
from src.telemetry import get_logger, get_meter, log_event, setup_tracing, shutdown_telemetry
|
||||
|
||||
tracer = setup_tracing("messenger-worker")
|
||||
meter = get_meter("messenger.worker")
|
||||
worker_logger = get_logger("worker")
|
||||
JOBS_PROCESSED = meter.create_counter(
|
||||
"messenger_jobs_processed", unit="{job}", description="Image jobs completed by outcome"
|
||||
)
|
||||
JOB_DURATION = meter.create_histogram(
|
||||
"messenger_job_duration_seconds", unit="s", description="Image job processing duration"
|
||||
)
|
||||
|
||||
PsycopgInstrumentor().instrument()
|
||||
RedisInstrumentor().instrument()
|
||||
BotocoreInstrumentor().instrument()
|
||||
|
||||
DATABASE_URL = ""
|
||||
BROKER_URL = ""
|
||||
S3_BUCKET = "messenger-attachments"
|
||||
STREAM_KEY = "attachment_jobs"
|
||||
GROUP_NAME = "workers"
|
||||
CONSUMER_NAME = os.environ.get("HOSTNAME", "worker")
|
||||
MAX_RETRIES = 5
|
||||
|
||||
async def process_image(data: bytes, attachment_id: str):
|
||||
"""Создает 3 варианта изображения и загружает их в S3."""
|
||||
img = Image.open(BytesIO(data))
|
||||
img = ImageOps.exif_transpose(img)
|
||||
|
||||
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
||||
bg = Image.new("RGB", img.size, (255, 255, 255))
|
||||
bg.paste(img, mask=img.split()[-1])
|
||||
img = bg
|
||||
elif img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
|
||||
variants = []
|
||||
|
||||
# 1. Thumbnail 256x256
|
||||
thumb = img.copy()
|
||||
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
thumb_data = BytesIO()
|
||||
thumb.save(thumb_data, format="JPEG", quality=85)
|
||||
thumb_key = f"variants/{attachment_id}/thumbnail.jpg"
|
||||
upload_file(thumb_key, thumb_data.getvalue(), "image/jpeg")
|
||||
|
||||
variants.append({
|
||||
"name": "thumbnail",
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(thumb_data.getvalue()),
|
||||
"sha256": hashlib.sha256(thumb_data.getvalue()).hexdigest(),
|
||||
"width": thumb.width,
|
||||
"height": thumb.height,
|
||||
})
|
||||
|
||||
# 2. Crop 128x128
|
||||
crop = img.copy()
|
||||
min_dim = min(crop.size)
|
||||
left = (crop.width - min_dim) // 2
|
||||
top = (crop.height - min_dim) // 2
|
||||
crop = crop.crop((left, top, left + min_dim, top + min_dim))
|
||||
crop = crop.resize((128, 128), Image.Resampling.LANCZOS)
|
||||
crop_data = BytesIO()
|
||||
crop.save(crop_data, format="JPEG", quality=85)
|
||||
crop_key = f"variants/{attachment_id}/crop.jpg"
|
||||
upload_file(crop_key, crop_data.getvalue(), "image/jpeg")
|
||||
|
||||
variants.append({
|
||||
"name": "crop",
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(crop_data.getvalue()),
|
||||
"sha256": hashlib.sha256(crop_data.getvalue()).hexdigest(),
|
||||
"width": 128,
|
||||
"height": 128,
|
||||
})
|
||||
|
||||
# 3. Optimized WebP 1280x1280
|
||||
opt = img.copy()
|
||||
opt.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
|
||||
opt_data = BytesIO()
|
||||
opt.save(opt_data, format="WEBP", quality=80, method=6)
|
||||
opt_key = f"variants/{attachment_id}/optimized.webp"
|
||||
upload_file(opt_key, opt_data.getvalue(), "image/webp")
|
||||
|
||||
variants.append({
|
||||
"name": "optimized",
|
||||
"content_type": "image/webp",
|
||||
"size_bytes": len(opt_data.getvalue()),
|
||||
"sha256": hashlib.sha256(opt_data.getvalue()).hexdigest(),
|
||||
"width": opt.width,
|
||||
"height": opt.height,
|
||||
})
|
||||
|
||||
return variants
|
||||
|
||||
async def process_job(job: dict, redis_client):
|
||||
attachment_id = job["attachment_id"]
|
||||
s3_key = job["s3_key"]
|
||||
started = time.perf_counter()
|
||||
outcome = "error"
|
||||
|
||||
with tracer.start_as_current_span("process_attachment_job") as span:
|
||||
span.set_attribute("job.type", "image")
|
||||
log_event(worker_logger, logging.INFO, "attachment.processing.started", job_type="image")
|
||||
try:
|
||||
async with await psycopg.AsyncConnection.connect(DATABASE_URL) as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"UPDATE attachments SET status = 'processing', updated_at = now() "
|
||||
"WHERE id = %s AND status = 'queued'",
|
||||
(attachment_id,),
|
||||
)
|
||||
await conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
outcome = "skipped"
|
||||
span.set_attribute("job.outcome", outcome)
|
||||
log_event(worker_logger, logging.INFO, "attachment.processing.skipped", job_type="image")
|
||||
return
|
||||
|
||||
data = download_file(s3_key)
|
||||
variants = await process_image(data, attachment_id)
|
||||
|
||||
async with await psycopg.AsyncConnection.connect(DATABASE_URL) as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"UPDATE attachments SET status = 'ready', variants = %s, updated_at = now() WHERE id = %s",
|
||||
(json.dumps(variants), attachment_id),
|
||||
)
|
||||
await conn.commit()
|
||||
|
||||
outcome = "success"
|
||||
span.set_attribute("job.outcome", outcome)
|
||||
span.set_status(trace.Status(trace.StatusCode.OK))
|
||||
log_event(worker_logger, logging.INFO, "attachment.processing.completed", job_type="image", variant_count=len(variants))
|
||||
|
||||
# Test hook used only for the lab's controlled crash scenario.
|
||||
if os.environ.get("SIMULATE_CRASH") == "worker":
|
||||
log_event(worker_logger, logging.ERROR, "attachment.processing.crash_simulated", job_type="image")
|
||||
os._exit(1)
|
||||
|
||||
except Exception as exc:
|
||||
outcome = "error"
|
||||
span.record_exception(exc)
|
||||
span.set_status(trace.Status(trace.StatusCode.ERROR))
|
||||
log_event(
|
||||
worker_logger,
|
||||
logging.ERROR,
|
||||
"attachment.processing.failed",
|
||||
job_type="image",
|
||||
error_type=type(exc).__name__,
|
||||
)
|
||||
|
||||
async with await psycopg.AsyncConnection.connect(DATABASE_URL) as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("SELECT retry_count FROM attachments WHERE id = %s", (attachment_id,))
|
||||
row = await cur.fetchone()
|
||||
retry_count = row[0] if row else MAX_RETRIES
|
||||
if retry_count >= MAX_RETRIES:
|
||||
await cur.execute(
|
||||
"UPDATE attachments SET status = 'failed', error_code = %s, updated_at = now() WHERE id = %s",
|
||||
("processing_failed", attachment_id),
|
||||
)
|
||||
log_event(worker_logger, logging.ERROR, "attachment.processing.exhausted", job_type="image")
|
||||
else:
|
||||
await cur.execute(
|
||||
"UPDATE attachments SET status = 'queued', retry_count = retry_count + 1, updated_at = now() WHERE id = %s",
|
||||
(attachment_id,),
|
||||
)
|
||||
await redis_client.xadd(STREAM_KEY, {"job": json.dumps(job)})
|
||||
await conn.commit()
|
||||
finally:
|
||||
elapsed = max(0.0, time.perf_counter() - started)
|
||||
JOBS_PROCESSED.add(1, {"job_type": "image", "outcome": outcome})
|
||||
JOB_DURATION.record(elapsed, {"job_type": "image", "outcome": outcome})
|
||||
|
||||
async def main():
|
||||
global DATABASE_URL, BROKER_URL, S3_BUCKET
|
||||
service_secrets = read_secret(os.environ.get("BAO_SECRET_PATH", "messenger/worker"))
|
||||
DATABASE_URL = service_secrets["database_url"]
|
||||
BROKER_URL = service_secrets["broker_url"]
|
||||
S3_BUCKET = service_secrets.get("s3_bucket", S3_BUCKET)
|
||||
configure_client(
|
||||
service_secrets["s3_endpoint"],
|
||||
service_secrets["s3_access_key"],
|
||||
service_secrets["s3_secret_key"],
|
||||
os.environ.get("S3_CA_FILE", "/run/tls/service-ca.crt"),
|
||||
S3_BUCKET,
|
||||
)
|
||||
redis_client = redis.from_url(BROKER_URL, decode_responses=True, socket_connect_timeout=5)
|
||||
try:
|
||||
try:
|
||||
await redis_client.xgroup_create(STREAM_KEY, GROUP_NAME, id="0", mkstream=True)
|
||||
except Exception as exc:
|
||||
if "BUSYGROUP" not in str(exc):
|
||||
raise
|
||||
|
||||
log_event(worker_logger, logging.INFO, "worker.started", stream=STREAM_KEY, consumer=CONSUMER_NAME)
|
||||
while True:
|
||||
try:
|
||||
# Recover pending jobs whose previous consumer disappeared.
|
||||
claimed = await redis_client.xautoclaim(
|
||||
STREAM_KEY, GROUP_NAME, CONSUMER_NAME, min_idle_time=10000, start_id="0-0"
|
||||
)
|
||||
if claimed and claimed[1]:
|
||||
for msg_id, fields in claimed[1]:
|
||||
if fields:
|
||||
job = json.loads(fields["job"])
|
||||
await process_job(job, redis_client)
|
||||
await redis_client.xack(STREAM_KEY, GROUP_NAME, msg_id)
|
||||
|
||||
messages = await redis_client.xreadgroup(
|
||||
GROUP_NAME, CONSUMER_NAME, {STREAM_KEY: ">"}, count=1, block=3000
|
||||
)
|
||||
for _stream, msgs in messages or []:
|
||||
for msg_id, fields in msgs:
|
||||
job = json.loads(fields["job"])
|
||||
await process_job(job, redis_client)
|
||||
await redis_client.xack(STREAM_KEY, GROUP_NAME, msg_id)
|
||||
except Exception as exc:
|
||||
log_event(
|
||||
worker_logger,
|
||||
logging.ERROR,
|
||||
"worker.consume.failed",
|
||||
error_type=type(exc).__name__,
|
||||
)
|
||||
await asyncio.sleep(1)
|
||||
finally:
|
||||
await redis_client.aclose()
|
||||
shutdown_telemetry()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user