"""Доступ к S3-совместимому хранилищу (SeaweedFS) через клиент minio-py. API работает с bucket под ОТДЕЛЬНЫМИ credentials с правами только Read+Write на этот bucket (без List, без создания/удаления bucket, без политик и IAM) — см. scripts/init-secrets.sh и REPORT.md. Публичных URL/redirect нет: байты всегда идут через авторизованный API. Lab6: каждый запрос к S3 — CLIENT span «s3 <Операция>» (внутри запроса/задания) и гистограмма messenger.s3.operation.duration{messenger.s3.operation, outcome}. В span — bucket и ключ объекта (ключи назначает сервер: staging/, attachments//v1/; filename в ключ не входит), без credentials и подписанных URL. """ import contextlib import logging import os import threading import time from urllib.parse import urlsplit import urllib3 from minio import Minio from minio.error import S3Error import telemetry import tlsutil import vault from telemetry import SpanKind log = logging.getLogger("messenger.s3") # minio-py для объектов больше part_size делает multipart и держит в памяти # один part. 5 MiB — минимум S3: файл 10 MiB -> 2 части по 5 MiB. PART_SIZE = 5 * 1024 * 1024 STREAM_CHUNK = 64 * 1024 # Служебные объекты S3Health: health/<реплика> (вне prefix originals/, janitor их не трогает). HEALTH_PREFIX = "health/" class StorageUnavailable(Exception): """S3 недоступен/таймаут/ошибка сервера -> 503.""" class ObjectMissing(Exception): """Метаданные есть, объекта нет (рассогласование) -> 503 + лог.""" def _secret(name): # S3_CLIENT_REQUIRED=0 — только job migrate (импортирует server.py, к S3 не обращается). return vault.secret(name, required=os.environ.get("S3_CLIENT_REQUIRED", "1") == "1") def make_client(access_env="S3_ACCESS_KEY_ID", secret_env="S3_SECRET_ACCESS_KEY", connect_timeout=None, read_timeout=None): endpoint = urlsplit(os.environ.get("S3_ENDPOINT", "https://s3:8333")) connect_timeout = connect_timeout or float(os.environ.get("S3_CONNECT_TIMEOUT_SECONDS", "2")) read_timeout = read_timeout or float(os.environ.get("S3_READ_TIMEOUT_SECONDS", "5")) # Короткие таймауты и без собственных повторов: зависший S3 не держит поток # дольше таймаута LB, повтор решает клиент (для upload — новым запросом). # Lab7: HTTPS к S3 с проверкой CA и hostname; plaintext endpoint запрещён. if endpoint.scheme != "https": raise SystemExit("S3_ENDPOINT must be https:// in lab7") http = urllib3.PoolManager( cert_reqs="CERT_REQUIRED", ca_certs=tlsutil.CA_FILE, timeout=urllib3.Timeout(connect=connect_timeout, read=read_timeout), retries=urllib3.Retry(total=0, connect=0, read=0, redirect=0, status=0), maxsize=int(os.environ.get("S3_POOL_SIZE", "16")), block=False) return Minio(endpoint.netloc, access_key=_secret(access_env), secret_key=_secret(secret_env), secure=endpoint.scheme == "https", region=os.environ.get("S3_REGION", "us-east-1"), http_client=http) def _is_transport_error(exc): return isinstance(exc, (urllib3.exceptions.HTTPError, OSError)) @contextlib.contextmanager def _s3_op(operation, bucket, key): started = time.perf_counter() outcome = "ok" attrs = {"rpc.system": "aws-api", "rpc.service": "S3", "rpc.method": operation, "aws.s3.bucket": bucket, "server.address": "s3"} if key and not key.startswith(HEALTH_PREFIX): attrs["aws.s3.key"] = key try: with telemetry.child_span("s3 " + operation, SpanKind.CLIENT, attrs): yield except ObjectMissing: outcome = "not_found" raise except BaseException: outcome = "error" raise finally: telemetry.s3_duration.record(time.perf_counter() - started, {"messenger.s3.operation": operation, "outcome": outcome}) class ObjectStore: def __init__(self, client, bucket): self.client = client self.bucket = bucket def put(self, key, fileobj, length, content_type): with _s3_op("PutObject", self.bucket, key): self._put(key, fileobj, length, content_type) def _put(self, key, fileobj, length, content_type): try: self.client.put_object(self.bucket, key, fileobj, length, content_type=content_type, part_size=PART_SIZE) except S3Error as exc: log.warning("s3 put failed: %s", exc.code) raise StorageUnavailable() except Exception as exc: if _is_transport_error(exc): log.warning("s3 put failed: %s", type(exc).__name__) raise StorageUnavailable() raise def open(self, key): """Поток объекта (urllib3 response). Закрывать: resp.close(); resp.release_conn().""" with _s3_op("GetObject", self.bucket, key): return self._open(key) def _open(self, key): try: return self.client.get_object(self.bucket, key) except S3Error as exc: if exc.code in ("NoSuchKey", "NoSuchObject"): raise ObjectMissing() log.warning("s3 get failed: %s", exc.code) raise StorageUnavailable() except Exception as exc: if _is_transport_error(exc): log.warning("s3 get failed: %s", type(exc).__name__) raise StorageUnavailable() raise def delete(self, key): """Идемпотентно: отсутствие объекта — не ошибка (S3 DELETE так и работает).""" with _s3_op("DeleteObject", self.bucket, key): self._delete(key) def _delete(self, key): try: self.client.remove_object(self.bucket, key) except S3Error as exc: if exc.code in ("NoSuchKey", "NoSuchObject"): return raise StorageUnavailable() except Exception as exc: if _is_transport_error(exc): raise StorageUnavailable() raise def ping(self, probe_key): """PUT + GET маленького служебного объекта health/<реплика>: проверяет S3, credentials и РЕАЛЬНЫЕ пути записи и чтения. HEAD bucket/healthz для этого мало: у SeaweedFS после рестарта они успешны, а первая запись ещё ~5 с висит (выбор raft-лидера master, выдача volume под запись).""" import io with _s3_op("HealthProbe", self.bucket, None): return self._ping(probe_key, io) def _ping(self, probe_key, io): self.client.put_object(self.bucket, probe_key, io.BytesIO(b"ok"), 2, content_type="text/plain") resp = self.client.get_object(self.bucket, probe_key) try: if resp.read() != b"ok": raise RuntimeError("probe mismatch") finally: resp.close() resp.release_conn() return True class S3Health: """Фоновая проверка S3, как DbHealth для PostgreSQL. S3 НЕ входит в /health/ready: он общий для всех реплик, и его отказ не лечится исключением реплики из LB, а текстовые сообщения без него работают. Флаг нужен, чтобы upload при известном отказе S3 сразу получал 503, не принимая 10 MiB.""" def __init__(self, store, interval, stale_after, instance_id): self.store = store self.probe_key = HEALTH_PREFIX + instance_id self.interval = interval self.stale_after = stale_after self.last_ok = None self._stop = threading.Event() self._ok_event = threading.Event() # выставлен, пока последняя проверка успешна def start(self): threading.Thread(target=self._loop, name="s3-health", daemon=True).start() def stop(self): self._stop.set() def ok(self): last = self.last_ok return last is not None and time.monotonic() - last <= self.stale_after def wait_startup(self, timeout): """Только на старте реплики (успешной проверки ещё не было): подождать до timeout, пока S3 станет доступен для записи. При подтверждённом отказе — не ждать.""" if self.last_ok is None: self._ok_event.wait(timeout) return self.ok() def known_down(self): """S3 был доступен и перестал отвечать. На старте реплики (успешной проверки ещё не было) — False: чтение может работать раньше, чем прогреется запись.""" last = self.last_ok return last is not None and time.monotonic() - last > self.stale_after def _loop(self): healthy = None while not self._stop.is_set(): try: self.store.ping(self.probe_key) self.last_ok = time.monotonic() self._ok_event.set() if healthy is not True: log.info("s3 health: ok", extra={"event": "s3.health.ok"}) healthy = True except Exception as exc: self._ok_event.clear() if healthy is not False: log.warning("s3 health: failing (%s)", type(exc).__name__, extra={"event": "s3.health.failing", "error.type": type(exc).__name__}) healthy = False self._stop.wait(self.interval)