Реализовать observability для лабораторной 6
This commit is contained in:
+114
-6
@@ -7,20 +7,28 @@ import multiprocessing
|
||||
import os
|
||||
import random
|
||||
import socket
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID
|
||||
|
||||
import aio_pika
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from ..config import Settings, load_settings
|
||||
from ..domain.errors import Unavailable
|
||||
from ..domain.models import AttachmentVariant
|
||||
from ..observability import get_metrics
|
||||
from ..observability.logging import safe_extra
|
||||
from ..observability.propagation import extract_trace_context
|
||||
from ..repositories import JobRepository
|
||||
from .broker import connect, topology
|
||||
from .pipeline import GeneratedVariant, PermanentImageError, process_image
|
||||
from .runtime import configure_logging, dependencies
|
||||
|
||||
logger = logging.getLogger('app.worker')
|
||||
tracer = trace.get_tracer('messenger.worker', '1.6.0')
|
||||
|
||||
|
||||
class ProcessingTimeout(Exception):
|
||||
@@ -84,6 +92,19 @@ class Worker:
|
||||
self.storage = storage
|
||||
self.worker_id = f'{socket.gethostname()}:{os.getpid()}'
|
||||
self.semaphore = asyncio.Semaphore(settings.worker_concurrency)
|
||||
self.metrics = get_metrics()
|
||||
self.metric_attributes = {'job.type': 'attachment.process.v1'}
|
||||
self.metrics.worker_busy.set(0, self.metric_attributes)
|
||||
self.metrics.worker_capacity.set(settings.worker_concurrency, self.metric_attributes)
|
||||
|
||||
@asynccontextmanager
|
||||
async def _busy_slot(self):
|
||||
async with self.semaphore:
|
||||
self.metrics.worker_busy.add(1, self.metric_attributes)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.metrics.worker_busy.add(-1, self.metric_attributes)
|
||||
|
||||
def _delay(self, attempt: int) -> float:
|
||||
base = min(
|
||||
@@ -116,12 +137,72 @@ class Worker:
|
||||
await incoming.nack(requeue=True)
|
||||
return
|
||||
if state == 'failed':
|
||||
logger.error(
|
||||
'job reached terminal failure',
|
||||
extra=safe_extra(
|
||||
'job.failed', job_id=str(job_id), attempt=attempt, error_code=code
|
||||
),
|
||||
)
|
||||
await incoming.reject(requeue=False)
|
||||
else:
|
||||
logger.warning(
|
||||
'job retry scheduled',
|
||||
extra=safe_extra(
|
||||
'job.retry_scheduled', job_id=str(job_id), attempt=attempt,
|
||||
error_code=code,
|
||||
),
|
||||
)
|
||||
await incoming.ack()
|
||||
|
||||
async def handle(self, incoming: aio_pika.IncomingMessage) -> None:
|
||||
async with self.semaphore:
|
||||
context = extract_trace_context(incoming.headers)
|
||||
job_id: UUID | None = None
|
||||
before = None
|
||||
try:
|
||||
preview = json.loads(incoming.body)
|
||||
job_id = UUID(preview['job_id'])
|
||||
before = await self.jobs.state(job_id)
|
||||
except (ValueError, TypeError, KeyError, json.JSONDecodeError):
|
||||
pass
|
||||
started_at = time.perf_counter()
|
||||
attributes = {
|
||||
'messaging.system': 'rabbitmq',
|
||||
'messaging.destination.name': 'attachments.process',
|
||||
'messaging.operation.name': 'process',
|
||||
'messaging.operation.type': 'process',
|
||||
}
|
||||
if job_id is not None:
|
||||
attributes['job.id'] = str(job_id)
|
||||
with tracer.start_as_current_span(
|
||||
'attachments process', context=context, kind=SpanKind.CONSUMER,
|
||||
attributes=attributes,
|
||||
) as span:
|
||||
await self._handle_message(incoming)
|
||||
if before is None or before.state != 'queued' or job_id is None:
|
||||
return
|
||||
after = await self.jobs.state(job_id)
|
||||
if after is None or after.state not in {'queued', 'ready', 'failed'}:
|
||||
return
|
||||
if after.state == 'queued' and after.attempt == before.attempt:
|
||||
return
|
||||
outcome = 'retry' if after.state == 'queued' else after.state
|
||||
duration = time.perf_counter() - started_at
|
||||
metric_attributes = {**self.metric_attributes, 'outcome': outcome}
|
||||
self.metrics.jobs_processed.add(1, metric_attributes)
|
||||
self.metrics.job_duration.record(duration, metric_attributes)
|
||||
span.set_attribute('job.outcome', outcome)
|
||||
span.set_attribute('job.attempt', before.attempt)
|
||||
if outcome == 'ready':
|
||||
ready_seconds = max(
|
||||
0.0, (datetime.now(timezone.utc) - after.created_at).total_seconds()
|
||||
)
|
||||
self.metrics.time_to_ready.record(
|
||||
ready_seconds,
|
||||
{'pipeline.version': str(after.pipeline_version), 'outcome': 'ready'},
|
||||
)
|
||||
|
||||
async def _handle_message(self, incoming: aio_pika.IncomingMessage) -> None:
|
||||
async with self._busy_slot():
|
||||
try:
|
||||
payload = json.loads(incoming.body)
|
||||
if payload.get('schema_version') != 1 or payload.get('type') != 'attachment.process.v1':
|
||||
@@ -228,7 +309,19 @@ class Worker:
|
||||
try:
|
||||
await self.storage.remove(attachment.staging_key)
|
||||
except Unavailable:
|
||||
logger.warning('staging cleanup deferred attachment_id=%s', attachment.id)
|
||||
logger.warning(
|
||||
'staging cleanup deferred',
|
||||
extra=safe_extra(
|
||||
'staging.cleanup_deferred', attachment_id=str(attachment.id)
|
||||
),
|
||||
)
|
||||
logger.info(
|
||||
'job completed',
|
||||
extra=safe_extra(
|
||||
'job.completed', job_id=str(job.id),
|
||||
attachment_id=str(attachment.id), attempt=job.attempt,
|
||||
),
|
||||
)
|
||||
await incoming.ack()
|
||||
except PermanentImageError as error:
|
||||
await self._handle_failure(
|
||||
@@ -239,12 +332,24 @@ class Worker:
|
||||
incoming, job.id, job.attempt, str(error), False
|
||||
)
|
||||
except (Unavailable, OSError, ValueError):
|
||||
logger.exception('temporary processing failure job_id=%s', job.id)
|
||||
logger.exception(
|
||||
'temporary processing failure',
|
||||
extra=safe_extra(
|
||||
'job.processing_failed', job_id=str(job.id),
|
||||
error_code='storage_unavailable',
|
||||
),
|
||||
)
|
||||
await self._handle_failure(
|
||||
incoming, job.id, job.attempt, 'storage_unavailable', False
|
||||
)
|
||||
except Exception:
|
||||
logger.exception('unexpected processing failure job_id=%s', job.id)
|
||||
logger.exception(
|
||||
'unexpected processing failure',
|
||||
extra=safe_extra(
|
||||
'job.processing_failed', job_id=str(job.id),
|
||||
error_code='processing_failed',
|
||||
),
|
||||
)
|
||||
await self._handle_failure(
|
||||
incoming, job.id, job.attempt, 'processing_failed', False
|
||||
)
|
||||
@@ -274,8 +379,11 @@ async def run() -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
configure_logging()
|
||||
asyncio.run(run())
|
||||
telemetry = configure_logging('messenger-worker')
|
||||
try:
|
||||
asyncio.run(run())
|
||||
finally:
|
||||
telemetry.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Reference in New Issue
Block a user