Files
mtusi2026lab7/scripts/worker_probe.py
T
gytall 43949458a6
Skeleton contracts / contracts (pull_request) Canceled after 0s
completed grade 5 track 1
2026-11-27 08:57:51 +03:00

201 lines
7.4 KiB
Python

"""Матрица операций worker на синтетических объектах отдельного стенда."""
import asyncio
from collections.abc import Callable
from contextlib import closing
from io import BytesIO
import json
import ssl
import sys
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from asyncpg.exceptions import InvalidPasswordError
from aiormq.exceptions import AMQPConnectionError, ChannelAccessRefused
from minio.error import S3Error
from sqlalchemy import text
from sqlalchemy.exc import DBAPIError
from app.core.bao import database_secret
from app.core.config import Settings
from app.core.database import create_db_engine
from app.core.jobs import JobSettings
from app.storage.broker import connect_broker
from app.storage.s3 import create_s3_storage
OTHER_QUEUE = "experiment-private"
PAYLOAD = b"synthetic worker experiment"
FORBIDDEN_S3 = {"AccessDenied", "InvalidAccessKeyId", "SignatureDoesNotMatch"}
def s3_access(operation: Callable[[], None]) -> bool:
try:
operation()
except S3Error as error:
if error.code not in FORBIDDEN_S3:
raise
return False
return True
async def probe_s3(settings: Settings, phase: str) -> dict[str, bool]:
storage = create_s3_storage(settings.s3)
client = storage._client
bucket = settings.s3.bucket
try:
def read(key):
with closing(client.get_object(bucket, key)) as response:
assert response.read() == PAYLOAD
def write(key):
client.put_object(bucket, key, BytesIO(PAYLOAD), len(PAYLOAD))
if phase == "revoked":
return {"read_staging": s3_access(lambda: read("staging/experiment/fixture"))}
def list_private_names():
objects = client.list_objects(bucket, prefix="private/experiment/", recursive=True)
assert any(item.object_name == "private/experiment/fixture" for item in objects)
return {
"list_private_names": s3_access(list_private_names),
"read_staging": s3_access(lambda: read("staging/experiment/fixture")),
"write_staging": s3_access(lambda: write(f"staging/experiment/{phase}")),
"write_originals": s3_access(lambda: write(f"originals/experiment/{phase}")),
"write_variants": s3_access(lambda: write(f"variants/experiment/{phase}")),
"read_private": s3_access(lambda: read("private/experiment/fixture")),
"write_private": s3_access(lambda: write(f"private/experiment/{phase}")),
"delete_staging": s3_access(
lambda: client.remove_object(bucket, f"staging/experiment/delete-{phase}")
),
}
finally:
await storage.aclose()
async def probe_db(settings: Settings, statements: dict[str, str]) -> dict[str, bool]:
engine = create_db_engine(settings)
results = {}
try:
for operation, statement in statements.items():
try:
async with engine.connect() as connection:
await connection.execute(text(statement))
await connection.rollback()
except InvalidPasswordError:
results[operation] = False
except DBAPIError as error:
if error.orig.sqlstate not in {"42501", "28P01"}:
raise
results[operation] = False
else:
results[operation] = True
finally:
await engine.dispose()
return results
async def probe_broker(phase: str) -> dict[str, bool]:
settings = JobSettings()
try:
connection = await connect_broker(settings)
except (AMQPConnectionError, OSError):
if phase != "revoked":
raise
return {"connect": False}
async with connection:
if phase == "revoked":
return {"connect": True}
results = {}
for name, label in ((settings.broker_queue, "jobs"), (OTHER_QUEUE, "private")):
channel = await connection.channel()
try:
await channel.declare_queue(name, durable=True)
except ChannelAccessRefused:
results[f"configure_{label}"] = False
else:
results[f"configure_{label}"] = True
await channel.close()
channel = await connection.channel()
try:
queue = await channel.get_queue(name, ensure=False)
message = await queue.get(fail=False)
assert message is None, "Очередь проверки должна быть пустой"
except ChannelAccessRefused:
results[f"read_{label}"] = False
else:
results[f"read_{label}"] = True
await channel.close()
channel = await connection.channel()
try:
from aio_pika import Message
await channel.default_exchange.publish(
Message(PAYLOAD), routing_key=OTHER_QUEUE, mandatory=True
)
except ChannelAccessRefused:
results["publish_private"] = False
else:
results["publish_private"] = True
marker = await (await channel.get_queue(OTHER_QUEUE, ensure=False)).get()
assert marker.body == PAYLOAD
await marker.ack()
await channel.close()
return results
def probe_collector() -> bool:
context = ssl.create_default_context(cafile="/run/tls/ca.crt")
context.load_cert_chain("/run/tls/otel-agent.crt", "/run/tls/otel-agent.key")
request = Request("https://otel-collector:4318/v1/traces", data=b"",
headers={"Content-Type": "application/x-protobuf"})
try:
with urlopen(request, context=context, timeout=5) as response:
return response.status == 200
except HTTPError as error:
if error.code != 403:
raise
return False
async def main(phase: str):
if phase == "old-db":
password = json.load(sys.stdin)["old_db_password"]
result = await probe_db(Settings(db_password=password), {"old_db": "SELECT 1"})
return result
if phase in {"revoked", "recovered"}:
result = {
"rabbitmq": await probe_broker(phase) if phase == "revoked" else {"connect": True},
"collector": probe_collector(),
}
if phase == "revoked":
result["s3"] = await probe_s3(Settings(db_password="unused-probe"), phase)
else:
connection = await connect_broker(JobSettings())
await connection.close()
old_password = json.load(sys.stdin)["old_db_password"]
result["old_db"] = (await probe_db(
Settings(db_password=old_password), {"connect": "SELECT 1"}
))["connect"]
return result
settings = Settings(**database_secret())
return {
"postgresql": await probe_db(settings, {
"read_jobs": "SELECT id FROM attachment_jobs LIMIT 1",
"update_jobs": "UPDATE attachment_jobs SET attempt = attempt WHERE false",
"read_users": "SELECT id FROM users LIMIT 1",
"update_users": "UPDATE users SET display_name = display_name WHERE false",
"read_messages": "SELECT id FROM messages LIMIT 1",
}),
"rabbitmq": await probe_broker(phase),
"s3": await probe_s3(settings, phase),
}
if __name__ == "__main__":
print(json.dumps(asyncio.run(main(sys.argv[1]))))