Files
mtusi2026lab6/src/bootstrap_storage.py
T

43 lines
1.8 KiB
Python

"""Idempotent private bucket bootstrap; only this one-shot service receives admin credentials."""
import time
from botocore.exceptions import BotoCoreError, ClientError
from .storage import Storage, HEALTH_KEY, HEALTH_BYTES
storage=Storage()
for attempt in range(60):
try:
storage.client.list_buckets()
break
except (BotoCoreError,ClientError):
if attempt==59: raise RuntimeError('Object storage did not become available') from None
time.sleep(1)
try:
storage.client.head_bucket(Bucket=storage.bucket)
except ClientError as exc:
if exc.response['Error']['Code'] not in ('404','NoSuchBucket'): raise
storage.client.create_bucket(Bucket=storage.bucket)
# No anonymous identity and no public bucket policy. Do not overwrite any policy
# silently on repeat; reject a public policy if an operator added one accidentally.
try:
policy=storage.client.get_bucket_policy(Bucket=storage.bucket)
except ClientError as exc:
if exc.response['Error']['Code'] not in ('NoSuchBucketPolicy','404'): raise
else:
raise RuntimeError('Unexpected bucket policy; inspect it before starting API')
deadline=time.monotonic()+90
while True:
try:
try:
storage.client.head_object(Bucket=storage.bucket, Key=HEALTH_KEY)
except ClientError as exc:
if exc.response['Error']['Code'] not in ('404','NoSuchKey'): raise
# Fixed, reserved key/content: retry after uncertain PUT is safe.
storage.client.put_object(Bucket=storage.bucket, Key=HEALTH_KEY, Body=HEALTH_BYTES)
storage.ready()
break
except (BotoCoreError,ClientError):
if time.monotonic()>=deadline:
raise RuntimeError('Storage volumes did not become ready within bootstrap deadline') from None
time.sleep(1)
print('Private bucket ready; bootstrap is repeatable')