forked from mtusi2026/mtusi2026lab6
4 grade_and_report
This commit is contained in:
+86
-43
@@ -4,17 +4,27 @@ import json
|
||||
import logging
|
||||
import hashlib
|
||||
import random
|
||||
import time
|
||||
|
||||
import aio_pika
|
||||
from PIL import Image
|
||||
from psycopg.rows import dict_row
|
||||
from opentelemetry import trace
|
||||
from opentelemetry import trace, context as otel_context
|
||||
from opentelemetry.propagate import extract
|
||||
|
||||
# Импорты для метрик
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry import metrics as otel_metrics
|
||||
|
||||
from src.app.config import get_settings
|
||||
from src.app.db import init_pool, transaction
|
||||
from src.app.s3 import download_fileobj, upload_fileobj
|
||||
from src.app.otel import setup_otel
|
||||
from src.app.logging_config import setup_logging
|
||||
from worker.metrics import worker_duration, worker_processed, worker_in_flight
|
||||
|
||||
from worker.outbox_publisher import publish_loop
|
||||
|
||||
@@ -58,27 +68,31 @@ def generate_variants(img: Image.Image):
|
||||
return variants
|
||||
|
||||
|
||||
async def _re_publish(body: bytes):
|
||||
async def _re_publish(body: bytes, headers: dict):
|
||||
settings = get_settings()
|
||||
connection = await aio_pika.connect_robust(settings.broker_url)
|
||||
async with connection:
|
||||
channel = await connection.channel()
|
||||
await channel.declare_queue(settings.broker_queue, durable=True)
|
||||
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT)
|
||||
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT, headers=headers)
|
||||
await channel.default_exchange.publish(msg, routing_key=settings.broker_queue)
|
||||
|
||||
|
||||
async def _send_to_dlq(body: bytes):
|
||||
async def _send_to_dlq(body: bytes, headers: dict):
|
||||
settings = get_settings()
|
||||
connection = await aio_pika.connect_robust(settings.broker_url)
|
||||
async with connection:
|
||||
channel = await connection.channel()
|
||||
await channel.declare_queue("dead_letters", durable=True)
|
||||
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT)
|
||||
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT, headers=headers)
|
||||
await channel.default_exchange.publish(msg, routing_key="dead_letters")
|
||||
|
||||
|
||||
async def process_message(message: aio_pika.IncomingMessage):
|
||||
headers = message.headers or {}
|
||||
ctx = extract(headers)
|
||||
token = otel_context.attach(ctx)
|
||||
|
||||
async with message.process(requeue=False, reject_on_redelivered=False):
|
||||
data = json.loads(message.body)
|
||||
att_id = data["attachment_id"]
|
||||
@@ -86,41 +100,51 @@ async def process_message(message: aio_pika.IncomingMessage):
|
||||
|
||||
with tracer.start_as_current_span("worker.process_attachment") as span:
|
||||
span.set_attribute("attachment.id", att_id)
|
||||
worker_in_flight.add(1)
|
||||
start_time = time.time()
|
||||
result = "error"
|
||||
attempts = 0
|
||||
|
||||
logger.info("Processing attachment %s", att_id)
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"SELECT attempts FROM attachment_retries WHERE attachment_id = %s",
|
||||
(att_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
attempts = row["attempts"] if row else 0
|
||||
|
||||
if attempts >= 5:
|
||||
logger.error("Max retries (5) reached for %s. Sending to DLQ.", att_id)
|
||||
try:
|
||||
with transaction() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='failed', error_code='max_retries_exceeded', updated_at=now() WHERE id=%s",
|
||||
"SELECT attempts FROM attachment_retries WHERE attachment_id = %s",
|
||||
(att_id,),
|
||||
)
|
||||
await _send_to_dlq(message.body)
|
||||
span.set_attribute("worker.result", "max_retries")
|
||||
return
|
||||
row = cur.fetchone()
|
||||
attempts = row["attempts"] if row else 0
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO attachment_retries (attachment_id, attempts)
|
||||
VALUES (%s, 1)
|
||||
ON CONFLICT (attachment_id) DO UPDATE SET attempts = attachment_retries.attempts + 1
|
||||
""",
|
||||
(att_id,),
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s",
|
||||
(att_id,),
|
||||
)
|
||||
if attempts >= 5:
|
||||
logger.error("Max retries (5) reached for %s. Sending to DLQ.", att_id)
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='failed', error_code='max_retries_exceeded', updated_at=now() WHERE id=%s",
|
||||
(att_id,),
|
||||
)
|
||||
await _send_to_dlq(message.body, headers)
|
||||
span.set_attribute("worker.result", "max_retries")
|
||||
result = "error_max_retries"
|
||||
worker_duration.record(time.time() - start_time)
|
||||
worker_processed.add(1, {"result": result})
|
||||
worker_in_flight.add(-1)
|
||||
otel_context.detach(token)
|
||||
return
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO attachment_retries (attachment_id, attempts)
|
||||
VALUES (%s, 1)
|
||||
ON CONFLICT (attachment_id) DO UPDATE SET attempts = attachment_retries.attempts + 1
|
||||
""",
|
||||
(att_id,),
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s",
|
||||
(att_id,),
|
||||
)
|
||||
|
||||
try:
|
||||
body = download_fileobj(obj_key)
|
||||
img = Image.open(body)
|
||||
|
||||
@@ -162,6 +186,7 @@ async def process_message(message: aio_pika.IncomingMessage):
|
||||
|
||||
span.set_attribute("worker.result", "ready")
|
||||
logger.info("Successfully processed %s", att_id)
|
||||
result = "success"
|
||||
|
||||
except PermanentError as e:
|
||||
logger.error("Permanent error for %s: %s", att_id, e)
|
||||
@@ -172,24 +197,42 @@ async def process_message(message: aio_pika.IncomingMessage):
|
||||
("invalid_image", att_id),
|
||||
)
|
||||
span.set_attribute("worker.result", "permanent_error")
|
||||
result = "error_permanent"
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Temporary error for %s: %s", att_id, e)
|
||||
span.set_attribute("worker.result", "retry")
|
||||
delay = min(2 ** attempts, 60)
|
||||
jitter = random.uniform(0, 3)
|
||||
total_delay = delay + jitter
|
||||
logger.info(
|
||||
"Retrying %s in %.2f seconds (attempt %s/5)", att_id, total_delay, attempts + 1
|
||||
)
|
||||
await asyncio.sleep(total_delay)
|
||||
await _re_publish(message.body)
|
||||
logger.error("Error processing %s: %s", att_id, e)
|
||||
span.set_attribute("worker.result", "error")
|
||||
result = "error"
|
||||
if not isinstance(e, PermanentError):
|
||||
delay = min(2 ** attempts, 60)
|
||||
jitter = random.uniform(0, 3)
|
||||
total_delay = delay + jitter
|
||||
logger.info("Retrying %s in %.2f seconds (attempt %s/5)", att_id, total_delay, attempts + 1)
|
||||
await asyncio.sleep(total_delay)
|
||||
await _re_publish(message.body, headers)
|
||||
finally:
|
||||
duration = time.time() - start_time
|
||||
worker_duration.record(duration, {"result": result})
|
||||
worker_processed.add(1, {"result": result})
|
||||
worker_in_flight.add(-1)
|
||||
otel_context.detach(token)
|
||||
|
||||
|
||||
async def main():
|
||||
setup_logging(get_settings().log_level)
|
||||
setup_otel("messenger-worker")
|
||||
|
||||
# --- ЭКСПОРТ МЕТРИК ИЗ ВОРКЕРА ---
|
||||
s = get_settings()
|
||||
resource = Resource.create({"service.name": "messenger-worker"})
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=s.otel_exporter_otlp_endpoint, insecure=True),
|
||||
export_interval_millis=5000,
|
||||
)
|
||||
meter_provider = MeterProvider(resource=resource, metric_readers=[reader])
|
||||
otel_metrics.set_meter_provider(meter_provider)
|
||||
# ---------------------------------
|
||||
|
||||
init_pool()
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
from opentelemetry import metrics
|
||||
|
||||
# Объявляем глобальные переменные
|
||||
worker_duration = None
|
||||
worker_processed = None
|
||||
queue_depth = None
|
||||
worker_in_flight = None
|
||||
|
||||
def init_metrics():
|
||||
global worker_duration, worker_processed, queue_depth, worker_in_flight
|
||||
|
||||
# Получаем meter ПОСЛЕ того, как установлен MeterProvider
|
||||
meter = metrics.get_meter("messenger-worker")
|
||||
|
||||
worker_duration = meter.create_histogram(
|
||||
name="worker_duration_seconds",
|
||||
description="Time taken to process attachment",
|
||||
unit="s"
|
||||
)
|
||||
|
||||
worker_processed = meter.create_counter(
|
||||
name="worker_processed_total",
|
||||
description="Total processed jobs by result"
|
||||
)
|
||||
|
||||
queue_depth = meter.create_up_down_counter(
|
||||
name="rabbitmq_queue_depth",
|
||||
description="Number of messages in queue"
|
||||
)
|
||||
|
||||
worker_in_flight = meter.create_up_down_counter(
|
||||
name="worker_in_flight",
|
||||
description="Current number of in-flight jobs"
|
||||
)
|
||||
@@ -3,12 +3,11 @@ import json
|
||||
import logging
|
||||
import aio_pika
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.propagate import inject
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from src.app.config import get_settings
|
||||
from src.app.db import transaction
|
||||
from src.app.otel import setup_otel
|
||||
from src.app.logging_config import setup_logging
|
||||
|
||||
logger = logging.getLogger("outbox")
|
||||
tracer = trace.get_tracer("messenger-outbox")
|
||||
@@ -42,9 +41,15 @@ async def publish_loop():
|
||||
payload = msg["payload"]
|
||||
with tracer.start_as_current_span("outbox.publish") as span:
|
||||
span.set_attribute("outbox.message_id", str(msg["id"]))
|
||||
|
||||
# Внедряем W3C traceparent в заголовки
|
||||
headers = {}
|
||||
inject(headers)
|
||||
|
||||
message = aio_pika.Message(
|
||||
body=json.dumps(payload).encode(),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
headers=headers
|
||||
)
|
||||
await channel.default_exchange.publish(
|
||||
message, routing_key=settings.broker_queue
|
||||
|
||||
Reference in New Issue
Block a user