ЛР6: наблюдаемость, SLO и диагностика отказов
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
FROM python:3.12.12-slim@sha256:f3fa41d74a768c2fce8016b98c191ae8c1bacd8f1152870a3f9f87d350920b7c
|
||||
WORKDIR /app
|
||||
COPY worker/requirements.txt ./
|
||||
RUN pip install --no-cache-dir -r requirements.txt && useradd --system --uid 10001 worker
|
||||
COPY worker/pipeline ./pipeline
|
||||
USER worker
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
CMD ["python", "-m", "pipeline.main"]
|
||||
@@ -0,0 +1,42 @@
|
||||
import json
|
||||
|
||||
PUBLISH = """
|
||||
local previous = redis.call('HGET', KEYS[2], ARGV[1])
|
||||
if previous then
|
||||
local attempt, id = string.match(previous, '^(%d+)|(%d+%-%d+)$')
|
||||
if attempt == ARGV[2] and #redis.call('XRANGE', KEYS[1], id, id, 'COUNT', 1) > 0 then
|
||||
return {id, 0}
|
||||
end
|
||||
end
|
||||
local id = redis.call('XADD', KEYS[1], '*', 'job', ARGV[3])
|
||||
redis.call('HSET', KEYS[2], ARGV[1], ARGV[2] .. '|' .. id)
|
||||
return {id, 1}
|
||||
"""
|
||||
|
||||
ACK = """
|
||||
redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
|
||||
redis.call('XDEL', KEYS[1], ARGV[2])
|
||||
local previous = redis.call('HGET', KEYS[2], ARGV[3])
|
||||
if previous then
|
||||
local attempt, id = string.match(previous, '^(%d+)|(%d+%-%d+)$')
|
||||
if id == ARGV[2] then redis.call('HDEL', KEYS[2], ARGV[3]) end
|
||||
end
|
||||
return 1
|
||||
"""
|
||||
|
||||
|
||||
def publish(broker, settings, payload):
|
||||
result = broker.eval(
|
||||
PUBLISH,
|
||||
2,
|
||||
settings.stream,
|
||||
"job-publications",
|
||||
payload["job_id"],
|
||||
payload["attempt"],
|
||||
json.dumps(payload),
|
||||
)
|
||||
return bool(result[1])
|
||||
|
||||
|
||||
def acknowledge(broker, settings, message_id, job_id=""):
|
||||
broker.eval(ACK, 2, settings.stream, "job-publications", settings.group, message_id, job_id)
|
||||
@@ -0,0 +1,64 @@
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
|
||||
class Cleanup:
|
||||
def __init__(self, repository, storage):
|
||||
self.repository = repository
|
||||
self.storage = storage
|
||||
|
||||
def run(self):
|
||||
with self.repository.connection() as db:
|
||||
row = db.execute("SELECT pg_try_advisory_xact_lock(741204) AS acquired").fetchone()
|
||||
if not row["acquired"]:
|
||||
return
|
||||
self._clear_failed(db)
|
||||
self._clear_ready(db)
|
||||
self._scan(db)
|
||||
|
||||
def _clear_ready(self, db):
|
||||
rows = db.execute(
|
||||
"""SELECT id,staging_key FROM attachments WHERE status='READY'
|
||||
AND staging_key IS NOT NULL LIMIT 100 FOR UPDATE SKIP LOCKED"""
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
self.storage.client.delete_object(
|
||||
Bucket=self.storage.settings.bucket, Key=row["staging_key"]
|
||||
)
|
||||
db.execute("UPDATE attachments SET staging_key=NULL WHERE id=%s", (row["id"],))
|
||||
|
||||
def _clear_failed(self, db):
|
||||
rows = db.execute(
|
||||
"""SELECT id,staging_key,pipeline_version FROM attachments WHERE status='FAILED'
|
||||
AND staging_key IS NOT NULL AND updated_at < now() - %s * interval '1 second'
|
||||
LIMIT 100 FOR UPDATE SKIP LOCKED""",
|
||||
(self.storage.settings.retention,),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
self.storage.client.delete_object(
|
||||
Bucket=self.storage.settings.bucket, Key=row["staging_key"]
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE attachments SET staging_key=NULL,error_code='staging_expired' WHERE id=%s",
|
||||
(row["id"],),
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE processing_jobs SET error_code='staging_expired' WHERE attachment_id=%s AND pipeline_version=%s",
|
||||
(row["id"], row["pipeline_version"]),
|
||||
)
|
||||
|
||||
def _scan(self, db):
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=self.storage.settings.retention)
|
||||
pages = self.storage.client.get_paginator("list_objects_v2")
|
||||
for page in pages.paginate(Bucket=self.storage.settings.bucket):
|
||||
for item in page.get("Contents", []):
|
||||
if item["LastModified"] < cutoff and not self._referenced(db, item["Key"]):
|
||||
self.storage.client.delete_object(
|
||||
Bucket=self.storage.settings.bucket, Key=item["Key"]
|
||||
)
|
||||
|
||||
def _referenced(self, db, key):
|
||||
return db.execute(
|
||||
"""SELECT 1 FROM attachments WHERE object_key=%s OR staging_key=%s
|
||||
UNION ALL SELECT 1 FROM attachment_variants WHERE object_key=%s LIMIT 1""",
|
||||
(key, key, key),
|
||||
).fetchone()
|
||||
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def secret(name):
|
||||
return Path("/run/secrets/" + name).read_text().strip()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
db_host: str = os.getenv("DB_HOST", "db")
|
||||
broker_host: str = os.getenv("BROKER_HOST", "broker")
|
||||
bucket: str = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||
endpoint: str = os.getenv("S3_ENDPOINT", "http://minio:9000")
|
||||
max_attempts: int = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
|
||||
timeout: int = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
|
||||
retention: int = int(os.getenv("STAGING_RETENTION_SECONDS", "86400"))
|
||||
lease: int = int(os.getenv("JOB_LEASE_SECONDS", "75"))
|
||||
faults: bool = os.getenv("FAULT_INJECTION_ENABLED", "false").lower() == "true"
|
||||
max_bytes: int = 10485760
|
||||
max_pixels: int = 40000000
|
||||
stream: str = "attachment-jobs"
|
||||
group: str = "image-workers"
|
||||
@@ -0,0 +1,16 @@
|
||||
import os
|
||||
import time
|
||||
|
||||
|
||||
def inject(repository, job, point):
|
||||
action = repository.fault(job, point)
|
||||
if action == "crash":
|
||||
os._exit(71)
|
||||
if action == "pause":
|
||||
time.sleep(12)
|
||||
if action == "timeout":
|
||||
time.sleep(repository.settings.timeout + 5)
|
||||
if action == "transient":
|
||||
raise TimeoutError("injected_transient")
|
||||
if action == "permanent":
|
||||
raise ValueError("injected_permanent")
|
||||
@@ -0,0 +1,63 @@
|
||||
import io
|
||||
import warnings
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
|
||||
class ImagePipeline:
|
||||
def __init__(self, settings, version=1):
|
||||
self.settings = settings
|
||||
self.jpeg_quality = 85 if version == 1 else 90
|
||||
self.webp_quality = 80 if version == 1 else 85
|
||||
Image.MAX_IMAGE_PIXELS = settings.max_pixels
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
|
||||
def render(self, data):
|
||||
with Image.open(io.BytesIO(data)) as source:
|
||||
self.validate(source)
|
||||
source.load()
|
||||
ImageOps.exif_transpose(source, in_place=True)
|
||||
image = self.flatten(source)
|
||||
try:
|
||||
yield self.scaled(image, "thumbnail", 256, "JPEG", self.jpeg_quality)
|
||||
yield self.crop(image)
|
||||
yield self.scaled(image, "optimized", 1280, "WEBP", self.webp_quality)
|
||||
finally:
|
||||
image.close()
|
||||
|
||||
def validate(self, image):
|
||||
if image.format not in ("PNG", "JPEG"):
|
||||
raise ValueError("invalid_image")
|
||||
if image.width * image.height > self.settings.max_pixels:
|
||||
raise ValueError("image_too_large")
|
||||
|
||||
def flatten(self, image):
|
||||
if "A" in image.getbands() or "transparency" in image.info:
|
||||
with image.convert("RGBA") as alpha:
|
||||
result = Image.new("RGB", alpha.size, "white")
|
||||
result.paste(alpha, mask=alpha.getchannel("A"))
|
||||
return result
|
||||
return image.convert("RGB")
|
||||
|
||||
def scaled(self, image, name, limit, format_name, quality):
|
||||
divisor = max(limit, image.width, image.height)
|
||||
size = (max(1, image.width * limit // divisor), max(1, image.height * limit // divisor))
|
||||
with image.resize(size, Image.Resampling.LANCZOS) as resized:
|
||||
return self.encode(resized, name, format_name, quality)
|
||||
|
||||
def crop(self, image):
|
||||
with ImageOps.fit(
|
||||
image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)
|
||||
) as cropped:
|
||||
return self.encode(cropped, "crop", "JPEG", self.jpeg_quality)
|
||||
|
||||
def encode(self, image, name, format_name, quality):
|
||||
output = io.BytesIO()
|
||||
image.info.clear()
|
||||
image.save(output, format=format_name, quality=quality)
|
||||
return {
|
||||
"name": name,
|
||||
"data": output.getvalue(),
|
||||
"width": image.width,
|
||||
"height": image.height,
|
||||
"content_type": "image/jpeg" if format_name == "JPEG" else "image/webp",
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
import redis
|
||||
from .config import Settings
|
||||
from .repository import Repository
|
||||
from .cleanup import Cleanup
|
||||
from .storage import Storage
|
||||
from .outbox import OutboxDispatcher
|
||||
from .faults import inject
|
||||
from .broker import acknowledge
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from .telemetry import PROPAGATOR, PipelineMetrics, child_environment, event, setup, span
|
||||
|
||||
|
||||
def validate_message(payload):
|
||||
required = {
|
||||
"schema_version",
|
||||
"job_id",
|
||||
"type",
|
||||
"attachment_id",
|
||||
"pipeline_version",
|
||||
"attempt",
|
||||
"created_at",
|
||||
}
|
||||
allowed = required | {"traceparent", "tracestate"}
|
||||
if not isinstance(payload, dict) or not required.issubset(payload) or set(payload) - allowed:
|
||||
raise ValueError("invalid_job_fields")
|
||||
if (
|
||||
type(payload["schema_version"]) is not int
|
||||
or payload["schema_version"] != 1
|
||||
or payload["type"] != "attachment.process.v1"
|
||||
):
|
||||
raise ValueError("invalid_job_type")
|
||||
if any(not isinstance(payload[key], str) for key in ("job_id", "attachment_id", "created_at")):
|
||||
raise ValueError("invalid_job_strings")
|
||||
uuid.UUID(payload["job_id"])
|
||||
uuid.UUID(payload["attachment_id"])
|
||||
for key in ("pipeline_version", "attempt"):
|
||||
if type(payload[key]) is not int or payload[key] < 1:
|
||||
raise ValueError("invalid_job_counter")
|
||||
if datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00")).tzinfo is None:
|
||||
raise ValueError("invalid_job_time")
|
||||
|
||||
|
||||
def process_delivery(settings, payload):
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "pipeline.process", json.dumps(payload)],
|
||||
timeout=settings.timeout,
|
||||
env=child_environment(),
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
outcomes = [json.loads(line) for line in result.stdout.splitlines()]
|
||||
outcome = outcomes[0] if outcomes else {"outcome": "crash"}
|
||||
return result.returncode, outcome
|
||||
|
||||
|
||||
def handle(broker, settings, repository, item, metrics):
|
||||
message_id, fields = item
|
||||
try:
|
||||
payload = json.loads(fields["job"])
|
||||
validate_message(payload)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
acknowledge(broker, settings, message_id)
|
||||
event("worker.rejected_job", error=True)
|
||||
return
|
||||
with span(
|
||||
"attachments consume",
|
||||
SpanKind.CONSUMER,
|
||||
PROPAGATOR.extract(payload),
|
||||
{
|
||||
"messaging.destination.name": "attachments",
|
||||
"job.attempt": payload["attempt"],
|
||||
"pipeline.version": payload["pipeline_version"],
|
||||
},
|
||||
) as active:
|
||||
started = time.monotonic()
|
||||
metrics.busy = 1
|
||||
try:
|
||||
code, result = process_delivery(settings, payload)
|
||||
except subprocess.TimeoutExpired:
|
||||
with repository.connection() as db:
|
||||
repository.event(db, payload, "worker_timeout")
|
||||
code, result = 124, {"outcome": "timeout"}
|
||||
finally:
|
||||
metrics.busy = 0
|
||||
metrics.complete(started, result)
|
||||
outcome = result["outcome"]
|
||||
failed = outcome in ("retry", "failed", "timeout", "crash")
|
||||
active.set_attribute("job.outcome", outcome)
|
||||
if failed:
|
||||
active.set_status(Status(StatusCode.ERROR))
|
||||
event("worker.delivery", error=failed, outcome=outcome, attempt=payload["attempt"])
|
||||
if code == 0:
|
||||
inject(repository, payload, "before_ack")
|
||||
acknowledge(broker, settings, message_id, payload["job_id"])
|
||||
elif code == 75:
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def messages(broker, settings, consumer):
|
||||
pending = broker.xreadgroup(settings.group, consumer, {settings.stream: "0"}, count=1)
|
||||
if pending and pending[0][1]:
|
||||
return pending[0][1]
|
||||
claimed = broker.xautoclaim(
|
||||
settings.stream, settings.group, consumer, settings.lease * 1000, "0-0", count=1
|
||||
)
|
||||
if claimed[1]:
|
||||
return claimed[1]
|
||||
rows = broker.xreadgroup(settings.group, consumer, {settings.stream: ">"}, count=1, block=1000)
|
||||
return rows[0][1] if rows else []
|
||||
|
||||
|
||||
def consume(broker, settings, repository, consumer, metrics):
|
||||
try:
|
||||
broker.xgroup_create(settings.stream, settings.group, id="0", mkstream=True)
|
||||
except redis.ResponseError as error:
|
||||
if "BUSYGROUP" not in str(error):
|
||||
raise
|
||||
for item in messages(broker, settings, consumer):
|
||||
handle(broker, settings, repository, item, metrics)
|
||||
|
||||
|
||||
def main():
|
||||
role = os.getenv("ROLE", "worker")
|
||||
setup(role, metrics=True)
|
||||
metrics = PipelineMetrics(role)
|
||||
settings = Settings()
|
||||
repository = Repository(settings)
|
||||
broker = redis.Redis(
|
||||
host=settings.broker_host, decode_responses=True, socket_connect_timeout=3, socket_timeout=3
|
||||
)
|
||||
cleanup = Cleanup(repository, Storage(settings))
|
||||
consumer = str(uuid.uuid4())
|
||||
dispatcher = OutboxDispatcher(repository, broker)
|
||||
cleaned = 0
|
||||
while True:
|
||||
try:
|
||||
if role == "dispatcher":
|
||||
dispatcher.run()
|
||||
metrics.observe_queue(repository)
|
||||
if time.monotonic() - cleaned > 60:
|
||||
cleanup.run()
|
||||
cleaned = time.monotonic()
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
consume(broker, settings, repository, consumer, metrics)
|
||||
except Exception as error:
|
||||
print(
|
||||
json.dumps({"event": "loop_error", "error_type": type(error).__name__}), flush=True
|
||||
)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,104 @@
|
||||
import argparse
|
||||
import json
|
||||
import uuid
|
||||
from .config import Settings
|
||||
from .repository import Repository
|
||||
|
||||
|
||||
def enqueue(db, attachment, version, settings):
|
||||
job_id = uuid.uuid4()
|
||||
row = db.execute(
|
||||
"""INSERT INTO processing_jobs(job_id,attachment_id,pipeline_version,attempt_limit)
|
||||
VALUES (%s,%s,%s,%s) RETURNING created_at""",
|
||||
(job_id, attachment, version, settings.max_attempts),
|
||||
).fetchone()
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment),
|
||||
"pipeline_version": version,
|
||||
"attempt": 1,
|
||||
"created_at": row["created_at"].isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
db.execute(
|
||||
"INSERT INTO processing_outbox(job_id,payload) VALUES (%s,%s::jsonb)",
|
||||
(job_id, json.dumps(payload)),
|
||||
)
|
||||
return {"job_id": job_id, "attempt": 0}
|
||||
|
||||
|
||||
def upgrade(repository, attachment, version):
|
||||
with repository.connection() as db:
|
||||
db.execute("SELECT pg_advisory_xact_lock_shared(741204)")
|
||||
current = db.execute(
|
||||
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment,)
|
||||
).fetchone()
|
||||
if not current or version <= current["pipeline_version"]:
|
||||
raise ValueError("version_must_increase")
|
||||
db.execute(
|
||||
"UPDATE processing_jobs SET status='SUPERSEDED',lease_until=NULL WHERE attachment_id=%s AND status IN ('QUEUED','PROCESSING','FAILED')",
|
||||
(attachment,),
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE attachments SET pipeline_version=%s,status='QUEUED',error_code=NULL,updated_at=now() WHERE id=%s",
|
||||
(version, attachment),
|
||||
)
|
||||
job = enqueue(db, attachment, version, repository.settings)
|
||||
repository.event(db, job, "operator_upgrade")
|
||||
return {"event": "upgraded", "version": version}
|
||||
|
||||
|
||||
def replay(repository, attachment):
|
||||
with repository.connection() as db:
|
||||
db.execute("SELECT pg_advisory_xact_lock_shared(741204)")
|
||||
current = db.execute(
|
||||
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment,)
|
||||
).fetchone()
|
||||
if not current:
|
||||
raise ValueError("attachment_not_found")
|
||||
job = db.execute(
|
||||
"SELECT * FROM processing_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE",
|
||||
(attachment, current["pipeline_version"]),
|
||||
).fetchone()
|
||||
if job["status"] == "READY":
|
||||
repository.event(db, job, "operator_replay_noop")
|
||||
return {"event": "already_ready", "replayed": False}
|
||||
if job["error_code"] == "staging_expired":
|
||||
raise ValueError("staging_expired")
|
||||
if job["status"] != "FAILED":
|
||||
raise ValueError("only_failed_can_be_replayed")
|
||||
reset(db, job, repository.settings.max_attempts)
|
||||
repository.event(db, job, "operator_replay")
|
||||
return {"event": "replayed", "replayed": True}
|
||||
|
||||
|
||||
def reset(db, job, budget):
|
||||
db.execute(
|
||||
"""UPDATE processing_jobs SET status='QUEUED',error_code=NULL,lease_token=NULL,
|
||||
lease_until=NULL,completed_at=NULL,attempt_limit=attempt+%s,next_at=now(),next_publish_at=now() WHERE job_id=%s""",
|
||||
(budget, job["job_id"]),
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE attachments SET status='QUEUED',error_code=NULL,updated_at=now() WHERE id=%s",
|
||||
(job["attachment_id"],),
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=["upgrade", "replay"])
|
||||
parser.add_argument("attachment", type=uuid.UUID)
|
||||
parser.add_argument("--version", type=int, default=2)
|
||||
args = parser.parse_args()
|
||||
repository = Repository(Settings())
|
||||
result = (
|
||||
upgrade(repository, args.attachment, args.version)
|
||||
if args.action == "upgrade"
|
||||
else replay(repository, args.attachment)
|
||||
)
|
||||
print(json.dumps(result), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
from .faults import inject
|
||||
from .broker import publish
|
||||
from opentelemetry.trace import SpanKind
|
||||
from .telemetry import PROPAGATOR, current_carrier, event, span
|
||||
|
||||
|
||||
class OutboxDispatcher:
|
||||
def __init__(self, repository, broker):
|
||||
self.repository = repository
|
||||
self.broker = broker
|
||||
|
||||
def run(self):
|
||||
self.recover_expired()
|
||||
with self.repository.connection() as db:
|
||||
rows = db.execute(
|
||||
"""SELECT j.*,o.payload,o.published_at AS previous_publish FROM processing_jobs j
|
||||
JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version
|
||||
JOIN processing_outbox o ON o.job_id=j.job_id
|
||||
WHERE j.status='QUEUED' AND j.next_at<=now() AND j.next_publish_at<=now()
|
||||
ORDER BY j.created_at LIMIT 20 FOR UPDATE OF o SKIP LOCKED"""
|
||||
).fetchall()
|
||||
for job in rows:
|
||||
self.publish(db, job)
|
||||
|
||||
def publish(self, db, job):
|
||||
inject(self.repository, job, "before_publish")
|
||||
payload = dict(job["payload"], attempt=job["attempt"] + 1)
|
||||
with span(
|
||||
"attachments publish",
|
||||
SpanKind.PRODUCER,
|
||||
PROPAGATOR.extract(payload),
|
||||
{"messaging.destination.name": "attachments", "job.attempt": payload["attempt"]},
|
||||
):
|
||||
current_carrier(payload)
|
||||
created = publish(self.broker, self.repository.settings, payload)
|
||||
event("outbox.published", attempt=payload["attempt"], publication_created=created)
|
||||
inject(self.repository, job, "after_publish")
|
||||
db.execute(
|
||||
"UPDATE processing_jobs SET next_publish_at=now()+interval '10 seconds' WHERE job_id=%s",
|
||||
(job["job_id"],),
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE processing_outbox SET published_at=now(),publish_count=publish_count+1 WHERE job_id=%s",
|
||||
(job["job_id"],),
|
||||
)
|
||||
if created or job["previous_publish"] is None:
|
||||
self.repository.event(db, dict(job, attempt=payload["attempt"]), "published")
|
||||
|
||||
def recover_expired(self):
|
||||
with self.repository.connection() as db:
|
||||
rows = db.execute(
|
||||
"""SELECT j.* FROM processing_jobs j
|
||||
JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version
|
||||
WHERE j.status='PROCESSING' AND j.lease_until<now()
|
||||
LIMIT 20 FOR UPDATE OF a,j SKIP LOCKED"""
|
||||
).fetchall()
|
||||
for job in rows:
|
||||
terminal = job["attempt"] >= job["attempt_limit"]
|
||||
code = "retry_exhausted" if terminal else "lease_expired"
|
||||
self.repository.set_failure(db, job, "FAILED" if terminal else "QUEUED", code, 1)
|
||||
self.repository.event(db, job, "lease_expired")
|
||||
@@ -0,0 +1,91 @@
|
||||
import hashlib
|
||||
import json
|
||||
import resource
|
||||
import sys
|
||||
from PIL import UnidentifiedImageError, Image
|
||||
from .config import Settings
|
||||
from .repository import Repository
|
||||
from .storage import Storage
|
||||
from .images import ImagePipeline
|
||||
from .faults import inject
|
||||
from .telemetry import child_context, event, setup, span
|
||||
|
||||
|
||||
def write_effects(storage, job, data, settings):
|
||||
prefix = f"results/{job['attachment_id']}/v{job['pipeline_version']}"
|
||||
original = prefix + "/original-" + job["checksum"]
|
||||
storage.write_result(original, data, job["content_type"])
|
||||
variants = []
|
||||
for variant in ImagePipeline(settings, job["pipeline_version"]).render(data):
|
||||
body = variant.pop("data")
|
||||
key = prefix + "/" + variant["name"] + "-" + hashlib.sha256(body).hexdigest()
|
||||
item = storage.write_result(key, body, variant["content_type"])
|
||||
variants.append(
|
||||
dict(item, name=variant["name"], width=variant["width"], height=variant["height"])
|
||||
)
|
||||
return original, variants
|
||||
|
||||
|
||||
def process(repository, settings, job):
|
||||
storage = Storage(settings)
|
||||
with repository.connection() as fence:
|
||||
fence.execute("SELECT pg_advisory_xact_lock_shared(741204)")
|
||||
inject(repository, job, "before_effects")
|
||||
with span("s3.staging.read"):
|
||||
data = storage.read_original(job)
|
||||
with span("image.render_and_write"):
|
||||
original, variants = write_effects(storage, job, data, settings)
|
||||
inject(repository, job, "after_effects")
|
||||
with span("postgres.publish_result"):
|
||||
ready_seconds = repository.publish_result(job, original, variants)
|
||||
if ready_seconds is not False:
|
||||
report("ready", ready_seconds=ready_seconds)
|
||||
else:
|
||||
report("deferred")
|
||||
inject(repository, job, "after_commit")
|
||||
if ready_seconds is not False:
|
||||
storage.remove_staging(job, repository)
|
||||
|
||||
|
||||
def report(outcome, **fields):
|
||||
print(json.dumps({"outcome": outcome, **fields}), flush=True)
|
||||
event("worker." + outcome, error=outcome in ("retry", "failed"))
|
||||
|
||||
|
||||
def execute(message, settings):
|
||||
repository = Repository(settings)
|
||||
with span("postgres.claim"):
|
||||
job = repository.claim(message)
|
||||
if not job:
|
||||
done = repository.delivery_done(message)
|
||||
report("duplicate" if done else "deferred")
|
||||
return 0 if done else 75
|
||||
try:
|
||||
process(repository, settings, job)
|
||||
except (
|
||||
ValueError,
|
||||
UnidentifiedImageError,
|
||||
Image.DecompressionBombError,
|
||||
Image.DecompressionBombWarning,
|
||||
MemoryError,
|
||||
):
|
||||
report(repository.fail(job, permanent=True, code="invalid_image") or "deferred")
|
||||
except Exception:
|
||||
report(repository.fail(job) or "deferred")
|
||||
return 0 if repository.delivery_done(message) else 75
|
||||
|
||||
|
||||
def main():
|
||||
resource.setrlimit(resource.RLIMIT_AS, (768 * 1024 * 1024, 768 * 1024 * 1024))
|
||||
providers = setup("worker")
|
||||
message = json.loads(sys.argv[1])
|
||||
try:
|
||||
with span("attachment.process", parent=child_context()):
|
||||
return execute(message, Settings())
|
||||
finally:
|
||||
for provider in providers:
|
||||
provider.force_flush(1200)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,171 @@
|
||||
import json
|
||||
import random
|
||||
import uuid
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from .config import secret
|
||||
|
||||
|
||||
class Repository:
|
||||
def __init__(self, settings):
|
||||
self.settings = settings
|
||||
|
||||
def connection(self):
|
||||
return psycopg.connect(
|
||||
host=self.settings.db_host,
|
||||
dbname=secret("postgres_db"),
|
||||
user=secret("postgres_user"),
|
||||
password=secret("postgres_password"),
|
||||
connect_timeout=3,
|
||||
options="-c statement_timeout=10000",
|
||||
row_factory=dict_row,
|
||||
)
|
||||
|
||||
def event(self, db, job, name):
|
||||
db.execute(
|
||||
"INSERT INTO pipeline_events(job_id,event,attempt) VALUES (%s,%s,%s)",
|
||||
(job["job_id"], name, job.get("attempt", 0)),
|
||||
)
|
||||
|
||||
def claim(self, message):
|
||||
with self.connection() as db:
|
||||
job = self._lock_job(db, message)
|
||||
if (
|
||||
not job
|
||||
or job["status"] != "QUEUED"
|
||||
or not job["due"]
|
||||
or message["attempt"] != job["attempt"] + 1
|
||||
):
|
||||
return None
|
||||
token = uuid.uuid4()
|
||||
db.execute(
|
||||
"""UPDATE processing_jobs SET status='PROCESSING', attempt=attempt+1,
|
||||
lease_token=%s, lease_until=now() + %s * interval '1 second' WHERE job_id=%s""",
|
||||
(token, self.settings.lease, job["job_id"]),
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE attachments SET status='PROCESSING',updated_at=now() WHERE id=%s",
|
||||
(job["attachment_id"],),
|
||||
)
|
||||
job.update(lease_token=token, attempt=job["attempt"] + 1)
|
||||
self.event(db, job, "claimed")
|
||||
return job
|
||||
|
||||
def _lock_job(self, db, message):
|
||||
return db.execute(
|
||||
"""SELECT j.*, a.object_key, a.staging_key, a.content_type,
|
||||
a.checksum, a.size_bytes, j.next_at <= now() AS due, j.lease_until > now() AS live
|
||||
FROM attachments a JOIN processing_jobs j ON a.id=j.attachment_id
|
||||
WHERE j.job_id=%s AND j.attachment_id=%s AND j.pipeline_version=%s
|
||||
AND a.pipeline_version=j.pipeline_version
|
||||
FOR UPDATE OF a,j SKIP LOCKED""",
|
||||
(message["job_id"], message["attachment_id"], message["pipeline_version"]),
|
||||
).fetchone()
|
||||
|
||||
def delivery_done(self, message):
|
||||
with self.connection() as db:
|
||||
row = db.execute(
|
||||
"""SELECT j.status,j.attempt,a.pipeline_version FROM processing_jobs j
|
||||
JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s AND j.attachment_id=%s""",
|
||||
(message["job_id"], message["attachment_id"]),
|
||||
).fetchone()
|
||||
if not row or row["pipeline_version"] != message["pipeline_version"]:
|
||||
return True
|
||||
if row["status"] not in ("QUEUED", "PROCESSING"):
|
||||
return True
|
||||
expected = row["attempt"] + (1 if row["status"] == "QUEUED" else 0)
|
||||
return message["attempt"] != expected
|
||||
|
||||
def publish_result(self, job, original_key, variants):
|
||||
with self.connection() as db:
|
||||
current = self._lock_job(db, job)
|
||||
if not self._owns(current, job):
|
||||
self.event(db, job, "fenced_stale_result")
|
||||
return False
|
||||
self._save_variants(db, job, variants)
|
||||
db.execute(
|
||||
"""UPDATE attachments SET object_key=%s,status='READY',error_code=NULL,
|
||||
updated_at=now() WHERE id=%s AND pipeline_version=%s""",
|
||||
(original_key, job["attachment_id"], job["pipeline_version"]),
|
||||
)
|
||||
result = db.execute(
|
||||
"""UPDATE processing_jobs SET status='READY',completed_at=now(),
|
||||
lease_until=NULL,error_code=NULL WHERE job_id=%s
|
||||
RETURNING EXTRACT(EPOCH FROM completed_at-created_at) AS ready_seconds""",
|
||||
(job["job_id"],),
|
||||
)
|
||||
self.event(db, job, "ready")
|
||||
return float(result.fetchone()["ready_seconds"])
|
||||
|
||||
def _owns(self, current, job):
|
||||
return (
|
||||
current
|
||||
and current["status"] == "PROCESSING"
|
||||
and current["lease_token"] == job["lease_token"]
|
||||
and current["live"]
|
||||
)
|
||||
|
||||
def _save_variants(self, db, job, variants):
|
||||
for item in variants:
|
||||
db.execute(
|
||||
"""INSERT INTO attachment_variants
|
||||
(attachment_id,pipeline_version,name,object_key,content_type,size_bytes,width,height,sha256)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT DO NOTHING""",
|
||||
(
|
||||
job["attachment_id"],
|
||||
job["pipeline_version"],
|
||||
item["name"],
|
||||
item["object_key"],
|
||||
item["content_type"],
|
||||
item["size_bytes"],
|
||||
item["width"],
|
||||
item["height"],
|
||||
item["sha256"],
|
||||
),
|
||||
)
|
||||
|
||||
def fail(self, job, permanent=False, code="processing_failed"):
|
||||
with self.connection() as db:
|
||||
current = self._lock_job(db, job)
|
||||
if not self._owns(current, job):
|
||||
return
|
||||
terminal = permanent or job["attempt"] >= job["attempt_limit"]
|
||||
status = "FAILED" if terminal else "QUEUED"
|
||||
delay = min(30, 2 ** job["attempt"]) + random.uniform(0, 1)
|
||||
code = code if permanent else ("retry_exhausted" if terminal else code)
|
||||
self.set_failure(db, job, status, code, delay)
|
||||
self.event(db, job, "failed" if terminal else "retry_scheduled")
|
||||
return "failed" if terminal else "retry"
|
||||
|
||||
def set_failure(self, db, job, status, code, delay):
|
||||
db.execute(
|
||||
"""UPDATE processing_jobs SET status=%s,error_code=%s,lease_until=NULL,
|
||||
next_at=now() + %s * interval '1 second',next_publish_at=now(),
|
||||
completed_at=CASE WHEN %s='FAILED' THEN now() ELSE NULL END WHERE job_id=%s""",
|
||||
(status, code, delay, status, job["job_id"]),
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE attachments SET status=%s,error_code=%s,updated_at=now() WHERE id=%s",
|
||||
(status, code if status == "FAILED" else None, job["attachment_id"]),
|
||||
)
|
||||
|
||||
def clear_staging(self, job):
|
||||
with self.connection() as db:
|
||||
result = db.execute(
|
||||
"""UPDATE attachments SET staging_key=NULL WHERE id=%s AND pipeline_version=%s
|
||||
AND status='READY' AND staging_key=%s""",
|
||||
(job["attachment_id"], job["pipeline_version"], job["staging_key"]),
|
||||
)
|
||||
return result.rowcount == 1
|
||||
|
||||
def fault(self, job, point):
|
||||
if not self.settings.faults:
|
||||
return None
|
||||
with self.connection() as db:
|
||||
row = db.execute(
|
||||
"""UPDATE pipeline_faults SET remaining=remaining-1,hits=hits+1
|
||||
WHERE attachment_id=%s AND pipeline_version=%s AND point=%s AND remaining>0
|
||||
RETURNING action""",
|
||||
(job["attachment_id"], job["pipeline_version"], point),
|
||||
).fetchone()
|
||||
return row["action"] if row else None
|
||||
@@ -0,0 +1,62 @@
|
||||
import hashlib
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
from .config import secret
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self, settings):
|
||||
self.settings = settings
|
||||
self.client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.endpoint,
|
||||
region_name="us-east-1",
|
||||
aws_access_key_id=secret("s3_access_key_id"),
|
||||
aws_secret_access_key=secret("s3_secret_access_key"),
|
||||
config=Config(
|
||||
connect_timeout=3,
|
||||
read_timeout=10,
|
||||
retries={"max_attempts": 1},
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
def read_original(self, job):
|
||||
key = job["staging_key"] or job["object_key"]
|
||||
try:
|
||||
data = self._read(key)
|
||||
except ClientError as error:
|
||||
if error.response["Error"]["Code"] != "NoSuchKey" or key == job["object_key"]:
|
||||
raise
|
||||
data = self._read(job["object_key"])
|
||||
if (
|
||||
len(data) > self.settings.max_bytes
|
||||
or len(data) != job["size_bytes"]
|
||||
or hashlib.sha256(data).hexdigest() != job["checksum"]
|
||||
):
|
||||
raise ValueError("invalid_staging")
|
||||
return data
|
||||
|
||||
def _read(self, key):
|
||||
response = self.client.get_object(Bucket=self.settings.bucket, Key=key)
|
||||
with response["Body"] as stream:
|
||||
return stream.read(self.settings.max_bytes + 1)
|
||||
|
||||
def write_result(self, key, data, content_type):
|
||||
self.client.put_object(
|
||||
Bucket=self.settings.bucket, Key=key, Body=data, ContentType=content_type
|
||||
)
|
||||
return {
|
||||
"object_key": key,
|
||||
"content_type": content_type,
|
||||
"size_bytes": len(data),
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
}
|
||||
|
||||
def remove_staging(self, job, repository):
|
||||
if not job["staging_key"]:
|
||||
return
|
||||
if not repository.clear_staging(job):
|
||||
return
|
||||
self.client.delete_object(Bucket=self.settings.bucket, Key=job["staging_key"])
|
||||
@@ -0,0 +1,187 @@
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from opentelemetry import trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.metrics import Observation, get_meter
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
|
||||
PROPAGATOR = TraceContextTextMapPropagator()
|
||||
LOGGER = logging.getLogger("pipeline.telemetry")
|
||||
BUCKETS = [0.05, 0.1, 0.25, 0.5, 1, 2, 3, 5, 10, 20, 30, 60, 120, 300]
|
||||
|
||||
|
||||
def setup(role, metrics=False):
|
||||
endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
|
||||
if not endpoint:
|
||||
return ()
|
||||
resource = Resource.create(
|
||||
{
|
||||
"service.name": "messenger-" + role,
|
||||
"service.version": "6.0.0",
|
||||
"service.instance.id": socket.gethostname(),
|
||||
"deployment.environment.name": "lab",
|
||||
}
|
||||
)
|
||||
tracer = TracerProvider(resource=resource)
|
||||
tracer.add_span_processor(
|
||||
BatchSpanProcessor(
|
||||
OTLPSpanExporter(timeout=1), max_queue_size=128, max_export_batch_size=32
|
||||
)
|
||||
)
|
||||
trace.set_tracer_provider(tracer)
|
||||
logger = LoggerProvider(resource=resource)
|
||||
logger.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
OTLPLogExporter(timeout=1), max_queue_size=128, max_export_batch_size=32
|
||||
)
|
||||
)
|
||||
set_logger_provider(logger)
|
||||
LOGGER.addHandler(LoggingHandler(logger_provider=logger))
|
||||
LOGGER.setLevel(logging.INFO)
|
||||
LOGGER.propagate = False
|
||||
if not metrics:
|
||||
return tracer, logger
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(timeout=1), export_interval_millis=5000, export_timeout_millis=1500
|
||||
)
|
||||
meter = MeterProvider(
|
||||
resource=resource,
|
||||
metric_readers=[reader],
|
||||
views=[
|
||||
View(
|
||||
instrument_name="lab_*_duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(BUCKETS),
|
||||
)
|
||||
],
|
||||
)
|
||||
from opentelemetry.metrics import set_meter_provider
|
||||
|
||||
set_meter_provider(meter)
|
||||
return tracer, logger, meter
|
||||
|
||||
|
||||
def event(name, error=False, **fields):
|
||||
LOGGER.log(logging.ERROR if error else logging.INFO, name, extra={"event": name, **fields})
|
||||
|
||||
|
||||
@contextmanager
|
||||
def span(name, kind=SpanKind.INTERNAL, parent=None, attributes=None):
|
||||
with trace.get_tracer("messenger.pipeline").start_as_current_span(
|
||||
name,
|
||||
context=parent,
|
||||
kind=kind,
|
||||
attributes=attributes,
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
) as active:
|
||||
try:
|
||||
yield active
|
||||
except Exception as error:
|
||||
active.set_status(Status(StatusCode.ERROR))
|
||||
active.set_attribute("error.type", type(error).__name__)
|
||||
raise
|
||||
|
||||
|
||||
def child_environment():
|
||||
carrier = {}
|
||||
PROPAGATOR.inject(carrier)
|
||||
return {
|
||||
**os.environ,
|
||||
"PIPELINE_TRACEPARENT": carrier.get("traceparent", ""),
|
||||
"PIPELINE_TRACESTATE": carrier.get("tracestate", ""),
|
||||
}
|
||||
|
||||
|
||||
def child_context():
|
||||
return PROPAGATOR.extract(
|
||||
{
|
||||
"traceparent": os.getenv("PIPELINE_TRACEPARENT", ""),
|
||||
"tracestate": os.getenv("PIPELINE_TRACESTATE", ""),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def current_carrier(payload):
|
||||
payload.pop("tracestate", None)
|
||||
PROPAGATOR.inject(payload)
|
||||
|
||||
|
||||
class PipelineMetrics:
|
||||
def __init__(self, role):
|
||||
meter = get_meter("messenger.pipeline")
|
||||
self.jobs = meter.create_counter("lab_jobs")
|
||||
self.duration = meter.create_histogram("lab_job_duration", unit="s")
|
||||
self.ready = meter.create_histogram("lab_ready_duration", unit="s")
|
||||
self.terminal = meter.create_counter("lab_ready_sli")
|
||||
self.busy = 0
|
||||
self.depth = 0
|
||||
self.age = 0.0
|
||||
for outcome in ("ready", "duplicate", "retry", "failed", "timeout", "crash", "deferred"):
|
||||
self.jobs.add(0, {"job_type": "attachment", "outcome": outcome})
|
||||
for outcome in ("good", "bad"):
|
||||
self.terminal.add(0, {"outcome": outcome})
|
||||
if role == "worker":
|
||||
meter.create_observable_gauge("lab_worker_busy", [self.observe_busy])
|
||||
meter.create_observable_gauge("lab_worker_capacity", [lambda _: [Observation(1)]])
|
||||
else:
|
||||
meter.create_observable_gauge("lab_queue_depth", [self.observe_depth])
|
||||
meter.create_observable_gauge("lab_queue_oldest", [self.observe_age], unit="s")
|
||||
meter.create_observable_counter("lab_process_cpu", [observe_cpu], unit="s")
|
||||
meter.create_observable_gauge("lab_process_rss", [observe_rss], unit="By")
|
||||
|
||||
def observe_busy(self, _):
|
||||
return [Observation(self.busy)]
|
||||
|
||||
def observe_depth(self, _):
|
||||
return [Observation(self.depth, {"queue": "attachments"})]
|
||||
|
||||
def observe_age(self, _):
|
||||
return [Observation(self.age, {"queue": "attachments"})]
|
||||
|
||||
def observe_queue(self, repository):
|
||||
with repository.connection() as db:
|
||||
row = db.execute(
|
||||
"""SELECT count(*) AS depth, COALESCE(EXTRACT(EPOCH FROM
|
||||
clock_timestamp() - min(created_at)),0) AS age
|
||||
FROM processing_jobs WHERE status IN ('QUEUED','PROCESSING')"""
|
||||
).fetchone()
|
||||
self.depth, self.age = row["depth"], max(0.0, float(row["age"]))
|
||||
|
||||
def complete(self, started, result):
|
||||
outcome = result["outcome"]
|
||||
attributes = {"job_type": "attachment", "outcome": outcome}
|
||||
self.jobs.add(1, attributes)
|
||||
self.duration.record(time.monotonic() - started, attributes)
|
||||
if outcome == "ready":
|
||||
seconds = result["ready_seconds"]
|
||||
self.ready.record(seconds, {"job_type": "attachment"})
|
||||
self.terminal.add(1, {"outcome": "good" if seconds <= 5 else "bad"})
|
||||
elif outcome == "failed":
|
||||
self.terminal.add(1, {"outcome": "bad"})
|
||||
|
||||
|
||||
def observe_cpu(_):
|
||||
return [Observation(time.process_time())]
|
||||
|
||||
|
||||
def observe_rss(_):
|
||||
rss_pages = int(Path("/proc/self/statm").read_text().split()[1])
|
||||
return [Observation(rss_pages * os.sysconf("SC_PAGE_SIZE"))]
|
||||
@@ -0,0 +1,6 @@
|
||||
Pillow==12.0.0
|
||||
redis==6.4.0
|
||||
psycopg[binary]==3.2.10
|
||||
boto3==1.40.59
|
||||
opentelemetry-sdk==1.34.1
|
||||
opentelemetry-exporter-otlp-proto-http==1.34.1
|
||||
Reference in New Issue
Block a user