forked from mtusi2026/mtusi2026lab4
60 lines
2.1 KiB
Python
60 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Idempotently create the private MinIO bucket before starting the API."""
|
|
import os
|
|
import time
|
|
|
|
import boto3
|
|
from botocore.config import Config
|
|
from botocore.exceptions import BotoCoreError, ClientError
|
|
|
|
|
|
def main():
|
|
endpoint = os.environ.get("S3_ENDPOINT", "").strip()
|
|
region = os.environ.get("S3_REGION", "us-east-1").strip()
|
|
bucket = os.environ.get("S3_BUCKET", "").strip()
|
|
access_key = os.environ.get("MINIO_ROOT_USER", "").strip()
|
|
secret_key = os.environ.get("MINIO_ROOT_PASSWORD", "")
|
|
if not all((endpoint, region, bucket, access_key, secret_key)):
|
|
raise SystemExit("S3 bootstrap configuration is incomplete")
|
|
|
|
client = boto3.client(
|
|
"s3",
|
|
endpoint_url=endpoint,
|
|
region_name=region,
|
|
aws_access_key_id=access_key,
|
|
aws_secret_access_key=secret_key,
|
|
config=Config(
|
|
signature_version="s3v4",
|
|
s3={"addressing_style": "path"},
|
|
connect_timeout=3,
|
|
read_timeout=5,
|
|
retries={"max_attempts": 1, "mode": "standard"},
|
|
),
|
|
)
|
|
for attempt in range(30):
|
|
try:
|
|
client.head_bucket(Bucket=bucket)
|
|
print("S3 bucket is ready")
|
|
return
|
|
except ClientError as error:
|
|
code = error.response.get("Error", {}).get("Code", "")
|
|
if code not in ("404", "NoSuchBucket", "NotFound"):
|
|
raise SystemExit("S3 bucket bootstrap failed") from None
|
|
try:
|
|
client.create_bucket(Bucket=bucket)
|
|
print("S3 bucket created and ready")
|
|
return
|
|
except ClientError as create_error:
|
|
create_code = create_error.response.get("Error", {}).get("Code", "")
|
|
if create_code not in ("BucketAlreadyExists", "BucketAlreadyOwnedByYou"):
|
|
raise SystemExit("S3 bucket bootstrap failed") from None
|
|
except BotoCoreError:
|
|
if attempt == 29:
|
|
raise SystemExit("S3 endpoint did not become available") from None
|
|
time.sleep(2)
|
|
raise SystemExit("S3 bucket bootstrap timed out")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|