forked from mtusi2026/mtusi2026lab6
лаба на 4
This commit is contained in:
+123
-1
@@ -1,8 +1,14 @@
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
import socket
|
||||
from threading import Lock
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.pool import AsyncAdaptedQueuePool
|
||||
from sqlalchemy.util.queue import AsyncAdaptedQueue
|
||||
|
||||
from sqlalchemy import event, text
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
@@ -24,10 +30,66 @@ def read_database_url() -> str:
|
||||
return file.read().strip()
|
||||
|
||||
|
||||
class MeasuredQueue(AsyncAdaptedQueue):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.waiting = 0
|
||||
self.waiting_lock = Lock()
|
||||
|
||||
def get(self, block=True, timeout=None):
|
||||
waiting = block and self.empty()
|
||||
|
||||
if waiting:
|
||||
with self.waiting_lock:
|
||||
self.waiting += 1
|
||||
|
||||
try:
|
||||
return super().get(block, timeout)
|
||||
finally:
|
||||
if waiting:
|
||||
with self.waiting_lock:
|
||||
self.waiting -= 1
|
||||
|
||||
|
||||
class MeasuredPool(AsyncAdaptedQueuePool):
|
||||
_queue_class = MeasuredQueue
|
||||
|
||||
def connect(self):
|
||||
tracer = trace.get_tracer("messenger.database")
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
"postgresql.pool.acquire",
|
||||
kind=SpanKind.CLIENT,
|
||||
attributes={
|
||||
"db.system.name": "postgresql",
|
||||
"db.operation.name": "CONNECT",
|
||||
"server.address": "postgres",
|
||||
},
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
) as span:
|
||||
try:
|
||||
connection = super().connect()
|
||||
except BaseException as exc:
|
||||
span.set_attribute(
|
||||
"error.type", type(exc).__name__
|
||||
)
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
raise
|
||||
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
return connection
|
||||
|
||||
def waiting_count(self):
|
||||
with self._pool.waiting_lock:
|
||||
return self._pool.waiting
|
||||
|
||||
|
||||
database_url = read_database_url()
|
||||
|
||||
engine = create_async_engine(
|
||||
database_url,
|
||||
poolclass=MeasuredPool,
|
||||
pool_size=POOL_SIZE,
|
||||
max_overflow=MAX_OVERFLOW,
|
||||
pool_timeout=POOL_TIMEOUT_SECONDS,
|
||||
@@ -37,6 +99,66 @@ engine = create_async_engine(
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
|
||||
@event.listens_for(engine.sync_engine, "before_cursor_execute")
|
||||
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
||||
operation = statement.lstrip().split(None, 1)
|
||||
operation = operation[0].upper() if operation else "OTHER"
|
||||
|
||||
if operation not in {
|
||||
"SELECT", "INSERT", "UPDATE", "DELETE",
|
||||
"WITH", "CREATE", "ALTER", "DROP",
|
||||
}:
|
||||
operation = "OTHER"
|
||||
|
||||
tracer = trace.get_tracer("messenger.database")
|
||||
|
||||
manager = tracer.start_as_current_span(
|
||||
f"postgresql.{operation}",
|
||||
kind=SpanKind.CLIENT,
|
||||
attributes={
|
||||
"db.system.name": "postgresql",
|
||||
"db.operation.name": operation,
|
||||
"server.address": "postgres",
|
||||
},
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
)
|
||||
|
||||
span = manager.__enter__()
|
||||
context._messenger_db_span = (manager, span)
|
||||
|
||||
|
||||
def finish_database_span(context, failed=False):
|
||||
if context is None:
|
||||
return
|
||||
|
||||
state = getattr(context, "_messenger_db_span", None)
|
||||
|
||||
if state is None:
|
||||
return
|
||||
|
||||
context._messenger_db_span = None
|
||||
manager, span = state
|
||||
|
||||
span.set_status(
|
||||
Status(StatusCode.ERROR if failed else StatusCode.OK)
|
||||
)
|
||||
|
||||
manager.__exit__(None, None, None)
|
||||
|
||||
|
||||
@event.listens_for(engine.sync_engine, "after_cursor_execute")
|
||||
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
||||
finish_database_span(context)
|
||||
|
||||
|
||||
@event.listens_for(engine.sync_engine, "handle_error")
|
||||
def handle_database_error(exception_context):
|
||||
finish_database_span(
|
||||
exception_context.execution_context,
|
||||
failed=True,
|
||||
)
|
||||
|
||||
SessionFactory = async_sessionmaker(
|
||||
bind=engine,
|
||||
expire_on_commit=False,
|
||||
|
||||
+174
-148
@@ -1,149 +1,175 @@
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.database import SessionFactory, engine
|
||||
from src.queue import connect, publish, publish_failed
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
async def dispatch(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued',
|
||||
published_at = NULL,
|
||||
started_at = NULL,
|
||||
execution_id = NULL
|
||||
WHERE status = 'processing'
|
||||
AND started_at < now() - interval '90 seconds'
|
||||
""")
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
updated_at = now()
|
||||
WHERE status = 'processing'
|
||||
AND id IN (
|
||||
SELECT attachment_id
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued'
|
||||
)
|
||||
""")
|
||||
)
|
||||
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation, created_at
|
||||
FROM attachment_jobs
|
||||
WHERE published_at IS NULL
|
||||
AND status = 'queued'
|
||||
AND (
|
||||
next_attempt_at IS NULL
|
||||
OR next_attempt_at <= now()
|
||||
)
|
||||
ORDER BY created_at LIMIT 25
|
||||
FOR
|
||||
UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
publish(channel, row)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def dispatch_failed(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation,
|
||||
last_error_code, created_at, finished_at
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'failed'
|
||||
AND failed_published_at IS NULL
|
||||
ORDER BY created_at
|
||||
LIMIT 25
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"type": "attachment.failed.v1",
|
||||
"job_id": str(row.id),
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"error_code": row.last_error_code,
|
||||
"created_at": row.created_at.isoformat(),
|
||||
"finished_at": (
|
||||
row.finished_at.isoformat()
|
||||
if row.finished_at
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
publish_failed(channel, payload)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET failed_published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def main():
|
||||
while True:
|
||||
connection = None
|
||||
|
||||
try:
|
||||
connection, channel = connect()
|
||||
channel.confirm_delivery()
|
||||
|
||||
while True:
|
||||
count = await dispatch(channel)
|
||||
failed_count = await dispatch_failed(channel)
|
||||
await asyncio.sleep(0.2 if count or failed_count else 1)
|
||||
|
||||
except Exception:
|
||||
logging.exception("Dispatcher reconnect")
|
||||
await asyncio.sleep(3)
|
||||
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
finally:
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.database import SessionFactory, engine
|
||||
from src.queue import connect, publish, publish_failed
|
||||
from src.telemetry import setup
|
||||
from src.runtime_metrics import update_queue
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
async def collect_queue_metrics():
|
||||
async with SessionFactory() as session:
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT
|
||||
count(*) AS depth,
|
||||
COALESCE(
|
||||
EXTRACT(EPOCH FROM (
|
||||
now() - min(created_at)
|
||||
)),
|
||||
0
|
||||
) AS oldest
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued'
|
||||
""")
|
||||
)
|
||||
|
||||
row = result.one()
|
||||
update_queue(row.depth, row.oldest)
|
||||
|
||||
|
||||
async def dispatch(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued',
|
||||
published_at = NULL,
|
||||
started_at = NULL,
|
||||
execution_id = NULL
|
||||
WHERE status = 'processing'
|
||||
AND started_at < now() - interval '90 seconds'
|
||||
""")
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
updated_at = now()
|
||||
WHERE status = 'processing'
|
||||
AND id IN (
|
||||
SELECT attachment_id
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued'
|
||||
)
|
||||
""")
|
||||
)
|
||||
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation, created_at,
|
||||
traceparent, tracestate
|
||||
FROM attachment_jobs
|
||||
WHERE published_at IS NULL
|
||||
AND status = 'queued'
|
||||
AND (
|
||||
next_attempt_at IS NULL
|
||||
OR next_attempt_at <= now()
|
||||
)
|
||||
ORDER BY created_at LIMIT 25
|
||||
FOR
|
||||
UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
publish(channel, row)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def dispatch_failed(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation,
|
||||
last_error_code, created_at, finished_at
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'failed'
|
||||
AND failed_published_at IS NULL
|
||||
ORDER BY created_at
|
||||
LIMIT 25
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"type": "attachment.failed.v1",
|
||||
"job_id": str(row.id),
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"error_code": row.last_error_code,
|
||||
"created_at": row.created_at.isoformat(),
|
||||
"finished_at": (
|
||||
row.finished_at.isoformat()
|
||||
if row.finished_at
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
publish_failed(channel, payload)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET failed_published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def main():
|
||||
setup("messenger-dispatcher")
|
||||
while True:
|
||||
connection = None
|
||||
|
||||
try:
|
||||
connection, channel = connect()
|
||||
channel.confirm_delivery()
|
||||
|
||||
while True:
|
||||
count = await dispatch(channel)
|
||||
failed_count = await dispatch_failed(channel)
|
||||
await collect_queue_metrics()
|
||||
await asyncio.sleep(0.2 if count or failed_count else 1)
|
||||
|
||||
except Exception:
|
||||
logging.exception("Dispatcher reconnect")
|
||||
await asyncio.sleep(3)
|
||||
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
finally:
|
||||
asyncio.run(engine.dispose())
|
||||
+11
-3
@@ -56,7 +56,7 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
|
||||
from src.telemetry import setup, HTTPMetricsMiddleware
|
||||
from src.telemetry import setup, HTTPMetricsMiddleware, capture_trace_context
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
|
||||
setup("messenger-api")
|
||||
@@ -637,14 +637,22 @@ async def upload_attachment_endpoint(
|
||||
s3_key=s3_key,
|
||||
)
|
||||
|
||||
trace_context = capture_trace_context()
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO attachment_jobs (id, attachment_id)
|
||||
VALUES (:job_id, :attachment_id)
|
||||
INSERT INTO attachment_jobs (
|
||||
id, attachment_id, traceparent, tracestate
|
||||
)
|
||||
VALUES (
|
||||
:job_id, :attachment_id, :traceparent, :tracestate
|
||||
)
|
||||
"""),
|
||||
{
|
||||
"job_id": uuid4(),
|
||||
"attachment_id": attachment_id,
|
||||
"traceparent": trace_context.get("traceparent"),
|
||||
"tracestate": trace_context.get("tracestate"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
+109
-77
@@ -1,78 +1,110 @@
|
||||
import json
|
||||
import os
|
||||
from datetime import timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
|
||||
QUEUE = "attachment.process.v1"
|
||||
DLQ = "attachment.failed.v1"
|
||||
|
||||
|
||||
def connect():
|
||||
password = Path(
|
||||
os.environ["RABBITMQ_PASSWORD_FILE"]
|
||||
).read_text().strip()
|
||||
|
||||
credentials = pika.PlainCredentials(
|
||||
"messenger",
|
||||
password,
|
||||
)
|
||||
|
||||
connection = pika.BlockingConnection(
|
||||
pika.ConnectionParameters(
|
||||
host=os.getenv("RABBITMQ_HOST", "rabbitmq"),
|
||||
credentials=credentials,
|
||||
heartbeat=60,
|
||||
blocked_connection_timeout=30,
|
||||
connection_attempts=3,
|
||||
retry_delay=2,
|
||||
)
|
||||
)
|
||||
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.queue_declare(queue=DLQ, durable=True)
|
||||
|
||||
return connection, channel
|
||||
|
||||
|
||||
def publish(channel, row):
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(row.id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"pipeline_version": 1,
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"created_at": row.created_at.astimezone(
|
||||
timezone.utc
|
||||
).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=QUEUE,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=str(row.id),
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
|
||||
def publish_failed(channel, payload: dict):
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=DLQ,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=payload["job_id"],
|
||||
),
|
||||
mandatory=True,
|
||||
import json
|
||||
import os
|
||||
from datetime import timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from src.telemetry import capture_trace_context, restore_trace_context
|
||||
|
||||
QUEUE = "attachment.process.v1"
|
||||
DLQ = "attachment.failed.v1"
|
||||
|
||||
|
||||
def connect():
|
||||
password = Path(
|
||||
os.environ["RABBITMQ_PASSWORD_FILE"]
|
||||
).read_text().strip()
|
||||
|
||||
credentials = pika.PlainCredentials(
|
||||
"messenger",
|
||||
password,
|
||||
)
|
||||
|
||||
connection = pika.BlockingConnection(
|
||||
pika.ConnectionParameters(
|
||||
host=os.getenv("RABBITMQ_HOST", "rabbitmq"),
|
||||
credentials=credentials,
|
||||
heartbeat=60,
|
||||
blocked_connection_timeout=30,
|
||||
connection_attempts=3,
|
||||
retry_delay=2,
|
||||
)
|
||||
)
|
||||
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.queue_declare(queue=DLQ, durable=True)
|
||||
|
||||
return connection, channel
|
||||
|
||||
|
||||
def publish(channel, row):
|
||||
tracer = trace.get_tracer("messenger.dispatcher")
|
||||
context = restore_trace_context({
|
||||
"traceparent": row.traceparent,
|
||||
"tracestate": row.tracestate,
|
||||
})
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
"attachment.publish",
|
||||
context=context,
|
||||
kind=SpanKind.PRODUCER,
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
attributes={
|
||||
"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": QUEUE,
|
||||
"job.attempt": row.attempt,
|
||||
"job.generation": row.generation,
|
||||
},
|
||||
) as span:
|
||||
try:
|
||||
publish_message(channel, row)
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
except Exception:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
raise
|
||||
|
||||
|
||||
def publish_message(channel, row):
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(row.id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"pipeline_version": 1,
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"created_at": row.created_at.astimezone(
|
||||
timezone.utc
|
||||
).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=QUEUE,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=str(row.id),
|
||||
headers=capture_trace_context(),
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
|
||||
def publish_failed(channel, payload: dict):
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=DLQ,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=payload["job_id"],
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
@@ -0,0 +1,158 @@
|
||||
import os
|
||||
import resource
|
||||
import time
|
||||
from threading import Lock
|
||||
|
||||
from opentelemetry import metrics
|
||||
from opentelemetry.metrics import Observation
|
||||
|
||||
|
||||
_lock = Lock()
|
||||
_busy = 0
|
||||
_backlog = 0
|
||||
_oldest = 0.0
|
||||
_queue_updated = 0.0
|
||||
_initialized = False
|
||||
_last_cpu = time.process_time()
|
||||
_last_wall = time.monotonic()
|
||||
|
||||
|
||||
def cpu_usage(options):
|
||||
global _last_cpu, _last_wall
|
||||
|
||||
with _lock:
|
||||
cpu = time.process_time()
|
||||
wall = time.monotonic()
|
||||
|
||||
value = (cpu - _last_cpu) / max(wall - _last_wall, 0.001)
|
||||
|
||||
_last_cpu = cpu
|
||||
_last_wall = wall
|
||||
|
||||
return [Observation(max(0, value) * 100)]
|
||||
|
||||
|
||||
def memory_usage(options):
|
||||
with open("/proc/self/statm", encoding="utf-8") as file:
|
||||
resident = int(file.read().split()[1])
|
||||
|
||||
return [Observation(resident * os.sysconf("SC_PAGE_SIZE"))]
|
||||
|
||||
|
||||
def worker_started():
|
||||
global _busy
|
||||
|
||||
with _lock:
|
||||
_busy += 1
|
||||
|
||||
|
||||
def worker_finished():
|
||||
global _busy
|
||||
|
||||
with _lock:
|
||||
_busy -= 1
|
||||
|
||||
|
||||
def update_queue(depth, oldest):
|
||||
global _backlog, _oldest, _queue_updated
|
||||
|
||||
with _lock:
|
||||
_backlog = int(depth)
|
||||
_oldest = float(oldest)
|
||||
_queue_updated = time.monotonic()
|
||||
|
||||
|
||||
def queue_observation(field):
|
||||
def callback(options):
|
||||
with _lock:
|
||||
if not _queue_updated:
|
||||
return []
|
||||
|
||||
if time.monotonic() - _queue_updated > 15:
|
||||
return []
|
||||
|
||||
value = _backlog if field == "depth" else _oldest
|
||||
|
||||
return [
|
||||
Observation(
|
||||
value,
|
||||
{"queue_name": "attachment.process.v1"},
|
||||
)
|
||||
]
|
||||
|
||||
return callback
|
||||
|
||||
|
||||
def setup_runtime_metrics(service_name):
|
||||
global _initialized
|
||||
|
||||
if _initialized:
|
||||
return
|
||||
|
||||
from src.database import engine, POOL_SIZE, MAX_OVERFLOW
|
||||
|
||||
meter = metrics.get_meter("messenger.runtime")
|
||||
pool = engine.sync_engine.pool
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_process_cpu_percent",
|
||||
callbacks=[cpu_usage],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_process_memory_bytes",
|
||||
callbacks=[memory_usage],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_db_pool_used",
|
||||
callbacks=[
|
||||
lambda options: [Observation(pool.checkedout())]
|
||||
],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_db_pool_capacity",
|
||||
callbacks=[
|
||||
lambda options: [
|
||||
Observation(POOL_SIZE + MAX_OVERFLOW)
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_db_pool_waiting",
|
||||
callbacks=[
|
||||
lambda options: [
|
||||
Observation(pool.waiting_count())
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
if service_name == "messenger-worker":
|
||||
meter.create_observable_gauge(
|
||||
"messenger_worker_busy",
|
||||
callbacks=[
|
||||
lambda options: [Observation(_busy)]
|
||||
],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_worker_capacity",
|
||||
callbacks=[
|
||||
lambda options: [Observation(1)]
|
||||
],
|
||||
)
|
||||
|
||||
if service_name == "messenger-dispatcher":
|
||||
meter.create_observable_gauge(
|
||||
"messenger_queue_depth",
|
||||
callbacks=[queue_observation("depth")],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_queue_oldest_age_seconds",
|
||||
callbacks=[queue_observation("oldest")],
|
||||
)
|
||||
|
||||
_initialized = True
|
||||
+115
-86
@@ -1,87 +1,116 @@
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
|
||||
def read_secret(env_name: str) -> str:
|
||||
path = os.environ[env_name]
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
region_name=os.getenv("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=read_secret("S3_ACCESS_KEY_ID_FILE"),
|
||||
aws_secret_access_key=read_secret("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
connect_timeout=2,
|
||||
read_timeout=3,
|
||||
retries={"total_max_attempts": 1, "mode": "standard"},
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
S3_BUCKET = os.environ["S3_BUCKET"]
|
||||
|
||||
|
||||
async def put_object(key: str, body: bytes, content_type: str) -> None:
|
||||
await asyncio.to_thread(
|
||||
s3_client.put_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
Body=body,
|
||||
ContentType=content_type,
|
||||
)
|
||||
|
||||
|
||||
async def get_object(key: str) -> bytes:
|
||||
def download() -> bytes:
|
||||
response = s3_client.get_object(Bucket=S3_BUCKET, Key=key)
|
||||
stream = response["Body"]
|
||||
try:
|
||||
return stream.read()
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
return await asyncio.to_thread(download)
|
||||
|
||||
|
||||
async def delete_object(key: str) -> None:
|
||||
await asyncio.to_thread(
|
||||
s3_client.delete_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
|
||||
|
||||
async def ping_storage() -> bool:
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_bucket,
|
||||
Bucket=S3_BUCKET,
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
async def object_exists(key: str) -> bool:
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if exc.response["Error"]["Code"] in {"404", "NoSuchKey", "NotFound"}:
|
||||
return False
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from contextlib import contextmanager
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
|
||||
@contextmanager
|
||||
def storage_span(operation):
|
||||
tracer = trace.get_tracer("messenger.storage")
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
f"s3.{operation}",
|
||||
kind=SpanKind.CLIENT,
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
attributes={
|
||||
"rpc.system": "aws-api",
|
||||
"rpc.service": "S3",
|
||||
"rpc.method": operation,
|
||||
},
|
||||
) as span:
|
||||
try:
|
||||
yield
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
except Exception:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
raise
|
||||
|
||||
|
||||
def read_secret(env_name: str) -> str:
|
||||
path = os.environ[env_name]
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
region_name=os.getenv("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=read_secret("S3_ACCESS_KEY_ID_FILE"),
|
||||
aws_secret_access_key=read_secret("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
connect_timeout=2,
|
||||
read_timeout=3,
|
||||
retries={"total_max_attempts": 1, "mode": "standard"},
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
S3_BUCKET = os.environ["S3_BUCKET"]
|
||||
|
||||
|
||||
async def put_object(key: str, body: bytes, content_type: str) -> None:
|
||||
with storage_span("PutObject"):
|
||||
await asyncio.to_thread(
|
||||
s3_client.put_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
Body=body,
|
||||
ContentType=content_type,
|
||||
)
|
||||
|
||||
|
||||
async def get_object(key: str) -> bytes:
|
||||
with storage_span("GetObject"):
|
||||
def download() -> bytes:
|
||||
response = s3_client.get_object(Bucket=S3_BUCKET, Key=key)
|
||||
stream = response["Body"]
|
||||
try:
|
||||
return stream.read()
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
return await asyncio.to_thread(download)
|
||||
|
||||
|
||||
async def delete_object(key: str) -> None:
|
||||
with storage_span("DeleteObject"):
|
||||
await asyncio.to_thread(
|
||||
s3_client.delete_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
|
||||
|
||||
async def ping_storage() -> bool:
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_bucket,
|
||||
Bucket=S3_BUCKET,
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
async def object_exists(key: str) -> bool:
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if exc.response["Error"]["Code"] in {"404", "NoSuchKey", "NotFound"}:
|
||||
return False
|
||||
raise
|
||||
+58
-1
@@ -5,11 +5,13 @@ import socket
|
||||
import time
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
@@ -19,6 +21,25 @@ from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
|
||||
propagator = TraceContextTextMapPropagator()
|
||||
|
||||
|
||||
def capture_trace_context():
|
||||
carrier = {}
|
||||
propagator.inject(carrier)
|
||||
return carrier
|
||||
|
||||
|
||||
def restore_trace_context(carrier):
|
||||
headers = {
|
||||
key: value
|
||||
for key, value in (carrier or {}).items()
|
||||
if key in {"traceparent", "tracestate"}
|
||||
and isinstance(value, str)
|
||||
}
|
||||
return propagator.extract(headers)
|
||||
|
||||
|
||||
_initialized = False
|
||||
logger = logging.getLogger("messenger.telemetry")
|
||||
|
||||
@@ -89,6 +110,35 @@ def setup(service_name):
|
||||
MeterProvider(
|
||||
resource=resource,
|
||||
metric_readers=[reader],
|
||||
views=[
|
||||
View(
|
||||
instrument_name="messenger_http_request_duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(
|
||||
boundaries=[
|
||||
0.005, 0.01, 0.025, 0.05, 0.1,
|
||||
0.25, 0.5, 1, 2.5, 5, 10, 30
|
||||
]
|
||||
),
|
||||
),
|
||||
View(
|
||||
instrument_name="messenger_job_duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(
|
||||
boundaries=[
|
||||
0.01, 0.025, 0.05, 0.1, 0.25,
|
||||
0.5, 1, 2.5, 5, 10, 30, 60
|
||||
]
|
||||
),
|
||||
),
|
||||
View(
|
||||
instrument_name="messenger_attachment_ready_duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(
|
||||
boundaries=[
|
||||
0.1, 0.25, 0.5, 1, 2, 3, 5,
|
||||
10, 15, 30, 60, 120, 300
|
||||
]
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
@@ -117,6 +167,10 @@ def setup(service_name):
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
|
||||
from src.runtime_metrics import setup_runtime_metrics
|
||||
|
||||
setup_runtime_metrics(service_name)
|
||||
|
||||
_initialized = True
|
||||
|
||||
|
||||
@@ -198,7 +252,7 @@ class HTTPMetricsMiddleware:
|
||||
)
|
||||
|
||||
|
||||
async def observe_job(process, payload):
|
||||
async def observe_job(process, payload, headers=None):
|
||||
tracer = trace.get_tracer("messenger.worker")
|
||||
meter = metrics.get_meter("messenger.worker")
|
||||
|
||||
@@ -219,6 +273,7 @@ async def observe_job(process, payload):
|
||||
with tracer.start_as_current_span(
|
||||
"attachment.process",
|
||||
kind=SpanKind.CONSUMER,
|
||||
context=restore_trace_context(headers),
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
) as span:
|
||||
@@ -237,6 +292,8 @@ async def observe_job(process, payload):
|
||||
|
||||
span.set_attribute("job.outcome", outcome)
|
||||
span.set_attribute("job.type", "attachment.process.v1")
|
||||
span.set_attribute("job.attempt", payload.get("attempt", 1))
|
||||
span.set_attribute("job.generation", payload.get("generation", 1))
|
||||
|
||||
if outcome in {"failed", "retry", "error", "unknown"}:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
|
||||
+34
-2
@@ -13,6 +13,8 @@ from sqlalchemy import text
|
||||
|
||||
from src.database import SessionFactory
|
||||
from src.telemetry import setup, observe_job
|
||||
from src.runtime_metrics import worker_started, worker_finished
|
||||
from opentelemetry import metrics
|
||||
from src.queue import QUEUE, connect
|
||||
from src.storage import get_object, put_object
|
||||
from src.images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES
|
||||
@@ -128,7 +130,7 @@ async def process(payload: dict):
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT j.status, j.attempt, j.generation,
|
||||
a.s3_key, a.content_type, a.chat_id
|
||||
a.s3_key, a.content_type, a.chat_id, j.created_at
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.id = :job_id
|
||||
@@ -173,6 +175,15 @@ async def process(payload: dict):
|
||||
)
|
||||
|
||||
try:
|
||||
retry_marker = "/tmp/lab6_retry_once"
|
||||
try:
|
||||
os.unlink(retry_marker)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
else:
|
||||
await asyncio.sleep(8)
|
||||
raise RuntimeError("controlled_temporary_failure")
|
||||
|
||||
body = await get_object(row.s3_key)
|
||||
validate_worker_image(body)
|
||||
thumbnail, width, height = await asyncio.to_thread(
|
||||
@@ -310,6 +321,19 @@ async def process(payload: dict):
|
||||
)
|
||||
|
||||
|
||||
meter = metrics.get_meter("messenger.worker")
|
||||
|
||||
end_to_end = meter.create_histogram(
|
||||
"messenger_attachment_ready_duration",
|
||||
unit="s",
|
||||
description="Time from durable acceptance to ready",
|
||||
)
|
||||
|
||||
end_to_end.record(
|
||||
max(0, time.time() - row.created_at.timestamp()),
|
||||
{"job_type": "attachment.process.v1"},
|
||||
)
|
||||
|
||||
return "success"
|
||||
|
||||
except Exception as exc:
|
||||
@@ -421,10 +445,16 @@ def main():
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
def callback(ch, method, properties, body):
|
||||
|
||||
worker_started()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
asyncio.wait_for(
|
||||
observe_job(process, json.loads(body)),
|
||||
observe_job(
|
||||
process,
|
||||
json.loads(body),
|
||||
properties.headers,
|
||||
),
|
||||
timeout=MAX_PROCESSING_SECONDS,
|
||||
)
|
||||
)
|
||||
@@ -437,6 +467,8 @@ def main():
|
||||
requeue=True,
|
||||
)
|
||||
time.sleep(2)
|
||||
finally:
|
||||
worker_finished()
|
||||
|
||||
channel.basic_consume(
|
||||
queue=QUEUE,
|
||||
|
||||
Reference in New Issue
Block a user