Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,6 @@ jobs:
steps:
- uses: actions/checkout@main

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
allow-prereleases: true

- uses: astral-sh/setup-uv@v7
with:
python-version: ${{ matrix.python-version }}
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Reusable Django utilities and management commands for Toggle projects.
## Features

- Shared management command: `wait_for_resources`
— Wait for database, Redis, Minio (S3) resources to be available before startup
— Wait for database, Redis, Minio, S3 resources to be available before startup
- Create Initial Users: `create_initial_users`
- Create Users with specified roles and permissions, useful to populate the database with default users during development or testing
- Health endpoints: `HealthProbeMiddleware`
Expand Down Expand Up @@ -61,13 +61,15 @@ python manage.py wait_for_resources --db --cache
- `--db`: Wait for database
- `--cache`: Wait for the Django cache backend (requires a redis client in your project, e.g. via `django-redis` or `redis`; it is not a banjo-utils runtime dependency)
- `--minio`: Wait for Minio (S3 storage)
- `--s3`: Wait for the bucket of every S3-backed storage in `STORAGES` (`storages.backends.s3.S3Storage`, `S3Boto3Storage` or a subclass). Each bucket is checked with `HeadBucket` using that storage's own client, so its endpoint, credentials, region and addressing style apply; the credentials need `s3:ListBucket` on the bucket. Non-S3 storages are skipped; with none configured it prints a warning and does not wait. On Django < 4.2 only the default storage is checked. Requires `django-storages[s3]`; it is not a banjo-utils runtime dependency
- `--celery-broker`: Wait for the Celery broker at `CELERY_BROKER_URL` (requires `kombu`, installed with celery; it is not a banjo-utils runtime dependency)
- `--timeout`: Set max wait time (seconds)

**Examples:**
```bash
python manage.py wait_for_resources --db --cache
python manage.py wait_for_resources --timeout 300 --minio --celery-broker
python manage.py wait_for_resources --db --s3
python manage.py create_initial_users --users-json="
[
{
Expand Down
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ dev = [
# celery) because nothing imports ``django_redis`` and the redis path is
# fully mocked -- there is no version-sensitive surface to exercise.
"django-redis",
# django-storages[s3] (boto3) is NOT a runtime dependency either: a project
# using S3 storage installs it. It lives here so ``wait_for_resources --s3``
# tests can build real S3Storage instances (the boto3 client is mocked).
"django-storages[s3]>=1.14.6",
]
test = [
"pytest-django",
Expand Down
81 changes: 80 additions & 1 deletion src/banjo_utils/management/commands/wait_for_resources.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from __future__ import annotations

import signal
from typing import Any
from urllib.parse import urljoin

import httpx
from django.conf import settings
from django.core.cache import cache
from django.core.management.base import BaseCommand, CommandParser
from django.core.management.base import BaseCommand, CommandError, CommandParser
from django.db import connections
from django.db.utils import OperationalError
from typing_extensions import override
Expand Down Expand Up @@ -123,6 +125,76 @@ def wait_for_minio(self) -> None:
retry_helper.wait()
self.stdout.write(self.style.SUCCESS(f"Minio is available after {retry_helper.total_time()} seconds"))

def get_s3_storages(self, s3_storage_class: type) -> dict[str, Any]:
"""Return the configured storages (by alias) that are S3-backed."""
try:
from django.core.files.storage import storages # noqa: PLC0415
except ImportError:
# Django < 4.2 has no ``STORAGES``; only the default storage is checked.
from django.core.files.storage import default_storage # noqa: PLC0415

candidates: dict[str, Any] = {"default": default_storage}
else:
candidates = {alias: storages[alias] for alias in settings.STORAGES}
return {alias: storage for alias, storage in candidates.items() if isinstance(storage, s3_storage_class)}

def wait_for_s3(self) -> None:
# ``django-storages`` and ``boto3`` are not banjo-utils runtime
# dependencies; an S3-backed project supplies them. Import them lazily so
# the other checks never require them, and re-raise with a friendly
# message if the ``--s3`` path is used without them.
try:
from botocore.exceptions import BotoCoreError, ClientError # noqa: PLC0415

try:
from storages.backends.s3 import S3Storage # noqa: PLC0415

s3_storage_class: type = S3Storage
except ImportError:
# django-storages < 1.14 only ships the s3boto3 module.
from storages.backends.s3boto3 import S3Boto3Storage # noqa: PLC0415

s3_storage_class = S3Boto3Storage
except ImportError as e:
raise ImportError(
"wait_for_resources --s3 requires 'django-storages[s3]' (django-storages "
"with boto3), which is not a banjo-utils runtime dependency. Install it "
"in your project.",
) from e

s3_storages = self.get_s3_storages(s3_storage_class)
if not s3_storages:
self.stdout.write(self.style.WARNING("No S3-backed storage is configured. Skipping wait"))
return

for alias, storage in s3_storages.items():
if not storage.bucket_name:
raise CommandError(f"S3 storage '{alias}' has no bucket_name configured.")

self.stdout.write("Waiting for S3...")
pending = dict(s3_storages)
for alias, storage in pending.items():
self.stdout.write(f"Waiting for S3 bucket '{storage.bucket_name}' (storage '{alias}')...")
retry_helper = RetryHelper()
while True:
for alias, storage in list(pending.items()):
try:
# The storage's own client carries its endpoint, credentials,
# region and addressing style.
storage.connection.meta.client.head_bucket(Bucket=storage.bucket_name)
del pending[alias]
except (BotoCoreError, ClientError) as e:
self.stdout.write(
self.style.WARNING(
f"S3 bucket '{storage.bucket_name}' (storage '{alias}') not available: {type(e).__name__}: {e}",
),
)
if not pending:
break
self.stdout.write(self.style.WARNING(retry_helper.try_again_message("S3 not available")))
retry_helper.wait()
self.stdout.write(self.style.SUCCESS(f"S3 is available after {retry_helper.total_time()} seconds"))

@override
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument(
Expand All @@ -134,6 +206,11 @@ def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument("--db", action="store_true", help="Wait for DB to be available")
parser.add_argument("--cache", action="store_true", help="Wait for the Django cache backend to be available")
parser.add_argument("--minio", action="store_true", help="Wait for MinIO (S3) storage to be available")
parser.add_argument(
"--s3",
action="store_true",
help="Wait for the bucket of every S3-backed storage in STORAGES to be reachable (HeadBucket)",
)
parser.add_argument(
"--celery-broker",
action="store_true",
Expand All @@ -150,6 +227,8 @@ def handle(self, *_: Any, **kwargs: Any) -> None:
self.wait_for_db()
if kwargs.get("minio"):
self.wait_for_minio()
if kwargs.get("s3"):
self.wait_for_s3()
if kwargs.get("cache"):
self.wait_for_cache()
if kwargs.get("celery_broker"):
Expand Down
158 changes: 157 additions & 1 deletion tests/test_wait_for_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@
if typing.TYPE_CHECKING:
from django.conf import LazySettings

import sys
from io import StringIO
from typing import Any
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock, PropertyMock, patch

import django
import pytest
from botocore.exceptions import ClientError, EndpointConnectionError
from django.core.management import call_command
from django.core.management.base import CommandError
from django.db.utils import OperationalError
from kombu.exceptions import OperationalError as KombuOperationalError
from storages.backends.s3 import S3Storage

from banjo_utils.management.commands.wait_for_resources import (
TimeoutException,
Expand Down Expand Up @@ -127,3 +133,153 @@ def test_multiple_flags(mock_sleep: MagicMock, mock_cache: MagicMock, mock_conne

assert "DB is available" in out
assert "Cache is available" in out


S3_BACKEND = "storages.backends.s3.S3Storage"
FS_BACKEND = "django.core.files.storage.FileSystemStorage"

requires_django_storages_setting = pytest.mark.skipif(
django.VERSION < (4, 2),
reason="settings.STORAGES requires Django 4.2+",
)


def s3_storage(bucket_name: str) -> dict[str, Any]:
return {"BACKEND": S3_BACKEND, "OPTIONS": {"bucket_name": bucket_name}}


def storages_setting(**s3_buckets: str) -> dict[str, Any]:
# S3 storages use non-default aliases: on Django 4.2, overriding STORAGES in
# tests also overrides DEFAULT_FILE_STORAGE/STATICFILES_STORAGE, which drops
# the OPTIONS of the "default" and "staticfiles" aliases.
return {
"default": {"BACKEND": FS_BACKEND},
"staticfiles": {"BACKEND": FS_BACKEND},
**{alias: s3_storage(bucket) for alias, bucket in s3_buckets.items()},
}


def not_found() -> ClientError:
return ClientError({"Error": {"Code": "404", "Message": "Not Found"}}, "HeadBucket")


@pytest.fixture
def s3_client():
"""Mock boto3 client returned by every S3Storage's ``connection.meta.client``."""
with patch.object(S3Storage, "connection", new_callable=PropertyMock) as mock_connection:
yield mock_connection.return_value.meta.client


def head_bucket_calls(client: MagicMock) -> list[str]:
return [call.kwargs["Bucket"] for call in client.head_bucket.call_args_list]


@requires_django_storages_setting
@patch("time.sleep", return_value=None)
def test_wait_for_s3_multiple_buckets_success(mock_sleep: MagicMock, s3_client: MagicMock, settings: LazySettings):
settings.STORAGES = storages_setting(media="media", static="static")

out, _ = run_command("--s3")

assert "Waiting for S3 bucket 'media' (storage 'media')" in out
assert "Waiting for S3 bucket 'static' (storage 'static')" in out
assert "S3 is available" in out
assert sorted(head_bucket_calls(s3_client)) == ["media", "static"]
mock_sleep.assert_not_called()


@requires_django_storages_setting
@patch("time.sleep", return_value=None)
def test_wait_for_s3_retries_then_succeeds(mock_sleep: MagicMock, s3_client: MagicMock, settings: LazySettings):
settings.STORAGES = storages_setting(media="media", static="static")

attempts: dict[str, int] = {}

def head_bucket(Bucket: str):
attempts[Bucket] = attempts.get(Bucket, 0) + 1
if Bucket == "static" and attempts[Bucket] == 1:
raise not_found()

s3_client.head_bucket.side_effect = head_bucket

out, _ = run_command("--s3")

assert "S3 bucket 'static' (storage 'static') not available: ClientError" in out
assert "S3 is available" in out
assert attempts == {"media": 1, "static": 2}
assert mock_sleep.call_count == 1


@requires_django_storages_setting
@patch("time.sleep")
def test_wait_for_s3_timeout(mock_sleep: MagicMock, s3_client: MagicMock, settings: LazySettings):
settings.STORAGES = storages_setting(media="media")
s3_client.head_bucket.side_effect = EndpointConnectionError(endpoint_url="http://minio:9000/media")

def raise_timeout(_):
raise TimeoutException

mock_sleep.side_effect = raise_timeout

out, err = run_command("--s3")

assert "not available: EndpointConnectionError" in out
assert "S3 is available" not in out
assert "Timed out" in err


@requires_django_storages_setting
@patch("time.sleep", return_value=None)
def test_wait_for_s3_no_s3_storages(mock_sleep: MagicMock, s3_client: MagicMock, settings: LazySettings):
settings.STORAGES = storages_setting()

out, _ = run_command("--s3")

assert "No S3-backed storage is configured. Skipping wait" in out
s3_client.head_bucket.assert_not_called()
mock_sleep.assert_not_called()


@requires_django_storages_setting
@patch("time.sleep", return_value=None)
def test_wait_for_s3_skips_non_s3_storages(mock_sleep: MagicMock, s3_client: MagicMock, settings: LazySettings):
settings.STORAGES = {
**storages_setting(media="media"),
"uploads": {"BACKEND": FS_BACKEND},
"legacy": {"BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": {"bucket_name": "legacy"}},
}

out, _ = run_command("--s3")

assert "'default'" not in out
assert "'staticfiles'" not in out
assert "'uploads'" not in out
assert "S3 is available" in out
assert sorted(head_bucket_calls(s3_client)) == ["legacy", "media"]


@requires_django_storages_setting
def test_wait_for_s3_requires_bucket_name(s3_client: MagicMock, settings: LazySettings):
settings.STORAGES = {**storages_setting(), "media": {"BACKEND": S3_BACKEND}}

with pytest.raises(CommandError, match="no bucket_name"):
run_command("--s3")
s3_client.head_bucket.assert_not_called()


@pytest.mark.skipif(django.VERSION >= (4, 2), reason="Django < 4.2 falls back to DEFAULT_FILE_STORAGE")
@patch("time.sleep", return_value=None)
def test_wait_for_s3_default_file_storage_fallback(mock_sleep: MagicMock, s3_client: MagicMock, settings: LazySettings):
settings.DEFAULT_FILE_STORAGE = S3_BACKEND
settings.AWS_STORAGE_BUCKET_NAME = "media"

out, _ = run_command("--s3")

assert "Waiting for S3 bucket 'media' (storage 'default')" in out
assert head_bucket_calls(s3_client) == ["media"]


def test_wait_for_s3_requires_django_storages():
missing = {"storages.backends.s3": None, "storages.backends.s3boto3": None}
with patch.dict(sys.modules, missing), pytest.raises(ImportError, match=r"django-storages\[s3\]"):
run_command("--s3")
Loading
Loading