Compare commits

...
2 Commits
Author SHA1 Message Date
parkel 84d94f7efa Add queued Apache configuration previews
Persist preview requests before dispatch and render them with Celery and RabbitMQ.
Show completed previews in Django admin and document the grouped PR workflow.
2026-11-19 21:18:37 +01:00
parkel 695c8ed212 Add the hosting account administration foundation 2026-11-19 21:08:13 +01:00
20 changed files with 638 additions and 0 deletions

No files matched your search

+1
View File
@@ -19,3 +19,4 @@ dist/
*.sqlite3-journal
*.sqlite3-shm
*.sqlite3-wal
celerybeat-schedule*
+2
View File
@@ -2,6 +2,8 @@
- Use Gitea issues for work items and milestones for release planning.
- Start changes on a dedicated branch from the default branch, named main.
- Keep related commits on the same branch and open one pull request when they
form a coherent change that can be reviewed and verified together.
- Reference the relevant issue in the pull request and describe what changed and
how it was verified.
- Submit changes for review before merging into main.
+4
View File
@@ -3,6 +3,10 @@
Coulobre Panel is an open-source web hosting control panel for hosting providers
and resellers. The project is in early development.
The development panel lets an administrator register hosting accounts and request
Apache configuration previews through a background worker.
See [Local development](docs/development.md) to run it.
## Planned scope
- Self-hosted installation on a single Ubuntu server, with Debian support planned.
+69
View File
@@ -0,0 +1,69 @@
# Local development
Use Python 3.12 or later. From the repository root, install the panel and its
development tools in a virtual environment.
```sh
python3 -m venv .venv
. .venv/bin/activate
python -m pip install -e '.[dev]'
export COULOBRE_SECRET_KEY="$(python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())')"
export COULOBRE_DEBUG=1
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
```
Open <http://127.0.0.1:8000/admin/> and sign in with the administrator account.
Under **Hosting accounts**, select **Add hosting account** and enter a name
and a primary domain such as `example.org`. The account is stored in the panel
database.
The local database defaults to `db.sqlite3`. Set `COULOBRE_SQLITE_PATH` to use a
different file. Keep `COULOBRE_DEBUG` for local development.
## Request an Apache configuration preview
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
default is `amqp://guest:guest@127.0.0.1:5672//`. Use the same database and
broker settings for the panel, worker, and scheduler.
In separate terminals with the virtual environment active, start a worker
and a scheduler. Use one worker process with SQLite.
```sh
celery -A coulobre worker --pool=solo
celery -A coulobre beat
```
Select an account in **Hosting accounts** and run **Request Apache plans**.
Open **Web provisioning plans** to see the request and its configuration once
the worker finishes. Each request captures the primary domain at queue time.
The preview references the future document root and PHP-FPM socket for the
account. Preview generation makes no changes to the hosting services.
The panel stores requests in its database before the scheduler publishes work
to RabbitMQ. After a broker outage, queued requests resume when the worker and
scheduler reconnect. Plans that remain incomplete five minutes after dispatch
are eligible for delivery again.
## MariaDB
Create a dedicated MariaDB database and application user. Install the MariaDB or
MySQL client headers, Python headers, a C compiler, and `pkg-config`, then add
the database driver with `python -m pip install -e '.[dev,mariadb]'`.
Set `COULOBRE_DB_NAME`, `COULOBRE_DB_USER`, and `COULOBRE_DB_PASSWORD` for your
database and rerun `python manage.py migrate`. Set `COULOBRE_DB_HOST` and
`COULOBRE_DB_PORT` if the database uses a different address from `127.0.0.1:3306`.
## Checks
```sh
ruff check .
ruff format --check .
python manage.py check
python manage.py makemigrations --check --dry-run
python manage.py test coulobre
git diff --check
```
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import os
import sys
from django.core.management import execute_from_command_line
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coulobre.settings")
execute_from_command_line(sys.argv)
+29
View File
@@ -0,0 +1,29 @@
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "coulobre-panel"
version = "0.1.0.dev0"
description = "A web hosting control panel for hosting providers and resellers."
readme = "README.md"
requires-python = ">=3.12"
license = "Apache-2.0"
dependencies = [
"Django>=5.2.8,<5.3",
"celery>=5.6,<6",
"idna>=3,<4",
]
[project.optional-dependencies]
dev = ["ruff>=0.11,<1"]
mariadb = ["mysqlclient>=2.2.1,<3"]
[tool.setuptools.package-data]
"coulobre.hosting" = ["templates/hosting/*.conf"]
[tool.ruff]
target-version = "py312"
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I"]
+3
View File
@@ -0,0 +1,3 @@
from .celery import app as celery_app
__all__ = ("celery_app",)
+9
View File
@@ -0,0 +1,9 @@
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coulobre.settings")
app = Celery("coulobre")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
View File
Whitespace-only changes.
+51
View File
@@ -0,0 +1,51 @@
from django.contrib import admin
from django.utils.html import format_html
from .models import HostingAccount, WebProvisioningPlan
@admin.register(HostingAccount)
class HostingAccountAdmin(admin.ModelAdmin):
list_display = ("name", "primary_domain", "created_at")
search_fields = ("name", "primary_domain")
ordering = ("primary_domain",)
actions = ("request_web_plans",)
@admin.action(permissions=["change"], description="Request Apache plans")
def request_web_plans(self, request, queryset):
plans = WebProvisioningPlan.objects.bulk_create(
WebProvisioningPlan(account=account, primary_domain=account.primary_domain)
for account in queryset.only("primary_domain")
)
self.message_user(request, f"Queued {len(plans)} Apache plan(s).")
@admin.register(WebProvisioningPlan)
class WebProvisioningPlanAdmin(admin.ModelAdmin):
list_display = ("primary_domain", "account", "requested_at", "completed_at")
list_select_related = ("account",)
ordering = ("-requested_at",)
fields = (
"account",
"primary_domain",
"requested_at",
"last_dispatched_at",
"completed_at",
"apache_preview",
)
readonly_fields = fields
@admin.display(description="Apache configuration", empty_value="Pending")
def apache_preview(self, obj):
if obj.apache_config:
return format_html("<pre>{}</pre>", obj.apache_config)
return None
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
+24
View File
@@ -0,0 +1,24 @@
import idna
from django.core.exceptions import ValidationError
from django.core.validators import DomainNameValidator
from django.db import models
validate_domain = DomainNameValidator(accept_idna=False)
class DomainNameField(models.CharField):
"""Store public hostnames in their canonical DNS representation."""
def to_python(self, value):
value = super().to_python(value)
if value in self.empty_values:
return value
try:
domain = idna.encode(value.strip(), uts46=True).decode("ascii")
except idna.IDNAError as error:
raise ValidationError(validate_domain.message, code="invalid") from error
domain = domain.removesuffix(".")
validate_domain(domain)
return domain
@@ -0,0 +1,36 @@
# Generated by Django 5.2.19 on 2026-11-19 20:03
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="HostingAccount",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=120)),
(
"primary_domain",
coulobre.hosting.fields.DomainNameField(
max_length=253, unique=True
),
),
("created_at", models.DateTimeField(auto_now_add=True)),
],
),
]
@@ -0,0 +1,44 @@
# Generated by Django 5.2.19 on 2026-11-19 20:12
import django.db.models.deletion
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
dependencies = [
("hosting", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="WebProvisioningPlan",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"primary_domain",
coulobre.hosting.fields.DomainNameField(max_length=253),
),
("requested_at", models.DateTimeField(auto_now_add=True)),
("last_dispatched_at", models.DateTimeField(blank=True, null=True)),
("completed_at", models.DateTimeField(blank=True, null=True)),
("apache_config", models.TextField(blank=True)),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="hosting.hostingaccount",
),
),
],
),
]
Whitespace-only changes.
+24
View File
@@ -0,0 +1,24 @@
from django.db import models
from .fields import DomainNameField
class HostingAccount(models.Model):
name = models.CharField(max_length=120)
primary_domain = DomainNameField(max_length=253, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.primary_domain)
class WebProvisioningPlan(models.Model):
account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE)
primary_domain = DomainNameField(max_length=253)
requested_at = models.DateTimeField(auto_now_add=True)
last_dispatched_at = models.DateTimeField(null=True, blank=True)
completed_at = models.DateTimeField(null=True, blank=True)
apache_config = models.TextField(blank=True)
def __str__(self):
return str(self.primary_domain)
+43
View File
@@ -0,0 +1,43 @@
from datetime import timedelta
from celery import shared_task
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils import timezone
from .models import WebProvisioningPlan
REDISPATCH_AFTER = timedelta(minutes=5)
@shared_task
def dispatch_web_plans():
stale_before = timezone.now() - REDISPATCH_AFTER
pending_ids = (
WebProvisioningPlan.objects.filter(completed_at__isnull=True)
.filter(
Q(last_dispatched_at__isnull=True) | Q(last_dispatched_at__lte=stale_before)
)
.order_by("requested_at", "pk")
.values_list("pk", flat=True)[:100]
)
for plan_id in list(pending_ids):
render_web_plan.apply_async(args=[plan_id], retry=False)
WebProvisioningPlan.objects.filter(
pk=plan_id, completed_at__isnull=True
).update(last_dispatched_at=timezone.now())
@shared_task(acks_late=True, reject_on_worker_lost=True)
def render_web_plan(plan_id):
pending = WebProvisioningPlan.objects.filter(pk=plan_id, completed_at__isnull=True)
plan = pending.first()
if plan is None:
return
apache_config = render_to_string(
"hosting/apache-vhost.conf",
{"account_id": str(plan.account_id), "domain": plan.primary_domain},
)
pending.update(apache_config=apache_config, completed_at=timezone.now())
@@ -0,0 +1,14 @@
<VirtualHost *:80>
ServerName {{ domain }}
DocumentRoot "/srv/coulobre/web/{{ account_id }}/public"
<Directory "/srv/coulobre/web/{{ account_id }}/public">
AllowOverride None
Options None
Require all granted
</Directory>
<FilesMatch "\.php$">
SetHandler "proxy:unix:/run/php/coulobre-{{ account_id }}.sock|fcgi://localhost/"
</FilesMatch>
</VirtualHost>
+163
View File
@@ -0,0 +1,163 @@
from datetime import timedelta
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from kombu.exceptions import OperationalError
from .models import HostingAccount, WebProvisioningPlan
from .tasks import REDISPATCH_AFTER, dispatch_web_plans, render_web_plan
class HostingAccountAdminTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.staff = users.create_user("staff", is_staff=True)
def setUp(self):
self.add_url = reverse("admin:hosting_hostingaccount_add")
self.client.force_login(self.operator)
def test_register_and_find_an_account(self):
response = self.client.post(
self.add_url,
{"name": "Example hosting", "primary_domain": "BÜCHER.example."},
follow=True,
)
self.assertContains(response, "Example hosting")
self.assertContains(response, "xn--bcher-kva.example")
self.assertEqual(
HostingAccount.objects.get().primary_domain, "xn--bcher-kva.example"
)
list_url = reverse("admin:hosting_hostingaccount_changelist")
results = self.client.get(list_url, {"q": "xn--bcher"})
self.assertContains(results, "Example hosting")
def test_equivalent_domain_is_rejected(self):
HostingAccount.objects.create(
name="Existing account", primary_domain="bücher.example"
)
response = self.client.post(
self.add_url,
{"name": "Duplicate account", "primary_domain": "XN--BCHER-KVA.Example."},
)
form = response.context["adminform"].form
self.assertEqual(form.errors.as_data()["primary_domain"][0].code, "unique")
self.assertEqual(HostingAccount.objects.count(), 1)
def test_invalid_domain_is_rejected(self):
response = self.client.post(
self.add_url,
{"name": "Invalid account", "primary_domain": "https://example.org"},
)
form = response.context["adminform"].form
self.assertEqual(form.errors.as_data()["primary_domain"][0].code, "invalid")
self.assertFalse(HostingAccount.objects.exists())
def test_staff_without_add_permission_cannot_register_an_account(self):
self.client.force_login(self.staff)
response = self.client.post(
self.add_url,
{"name": "Example hosting", "primary_domain": "example.org"},
)
self.assertEqual(response.status_code, 403)
self.assertFalse(HostingAccount.objects.exists())
class WebProvisioningPlanTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.account = HostingAccount.objects.create(
name="Example hosting", primary_domain="example.org"
)
def create_plan(self):
return WebProvisioningPlan.objects.create(
account=self.account, primary_domain=self.account.primary_domain
)
def test_admin_request_preserves_domain_until_worker_finishes(self):
self.client.force_login(get_user_model().objects.create_superuser("operator"))
list_url = reverse("admin:hosting_hostingaccount_changelist")
response = self.client.post(
list_url,
{"action": "request_web_plans", "_selected_action": [self.account.pk]},
)
self.assertRedirects(response, list_url)
plan = WebProvisioningPlan.objects.get()
self.assertIsNone(plan.completed_at)
HostingAccount.objects.filter(pk=self.account.pk).update(
primary_domain="new.example.org"
)
render_web_plan.run(plan.pk)
plan.refresh_from_db()
self.assertIsNotNone(plan.completed_at)
self.assertIn("ServerName example.org", plan.apache_config)
self.assertIn(f"/srv/coulobre/web/{self.account.pk}/public", plan.apache_config)
self.assertIn(f"/run/php/coulobre-{self.account.pk}.sock", plan.apache_config)
plan_url = reverse("admin:hosting_webprovisioningplan_change", args=[plan.pk])
response = self.client.get(plan_url)
self.assertContains(response, "<pre>&lt;VirtualHost")
self.assertContains(response, "ServerName example.org")
self.assertEqual(self.client.post(plan_url).status_code, 403)
@patch("coulobre.hosting.tasks.render_web_plan.apply_async")
def test_broker_failure_leaves_request_available_for_dispatch(self, publish):
plan = self.create_plan()
publish.side_effect = OperationalError("Broker unavailable")
with self.assertRaises(OperationalError):
dispatch_web_plans.run()
plan.refresh_from_db()
self.assertIsNone(plan.last_dispatched_at)
publish.side_effect = None
publish.reset_mock()
dispatch_web_plans.run()
publish.assert_called_once_with(args=[plan.pk], retry=False)
plan.refresh_from_db()
self.assertIsNotNone(plan.last_dispatched_at)
@patch("coulobre.hosting.tasks.render_web_plan.apply_async")
def test_only_incomplete_stale_deliveries_are_republished(self, publish):
now = timezone.now()
stale_at = now - REDISPATCH_AFTER - timedelta(seconds=1)
stale_plan = self.create_plan()
recent_plan = self.create_plan()
completed_plan = self.create_plan()
WebProvisioningPlan.objects.filter(pk=stale_plan.pk).update(
last_dispatched_at=stale_at
)
WebProvisioningPlan.objects.filter(pk=recent_plan.pk).update(
last_dispatched_at=now
)
WebProvisioningPlan.objects.filter(pk=completed_plan.pk).update(
last_dispatched_at=stale_at, completed_at=now
)
dispatch_web_plans.run()
publish.assert_called_once_with(args=[stale_plan.pk], retry=False)
def test_duplicate_delivery_preserves_the_completed_preview(self):
plan = self.create_plan()
render_web_plan.run(plan.pk)
plan.refresh_from_db()
original = (plan.completed_at, plan.apache_config)
render_web_plan.run(plan.pk)
plan.refresh_from_db()
self.assertEqual((plan.completed_at, plan.apache_config), original)
+101
View File
@@ -0,0 +1,101 @@
import os
from pathlib import Path
from django.core.exceptions import ImproperlyConfigured
def required_env(name):
value = os.environ.get(name)
if not value:
raise ImproperlyConfigured(f"Set the {name} environment variable.")
return value
SECRET_KEY = required_env("COULOBRE_SECRET_KEY")
DEBUG = os.environ.get("COULOBRE_DEBUG") == "1"
ALLOWED_HOSTS = os.environ.get(
"COULOBRE_ALLOWED_HOSTS", "localhost,127.0.0.1,[::1]"
).split(",")
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"coulobre.hosting",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "coulobre.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
database_name = os.environ.get("COULOBRE_DB_NAME")
if database_name:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": database_name,
"USER": required_env("COULOBRE_DB_USER"),
"PASSWORD": os.environ.get("COULOBRE_DB_PASSWORD", ""),
"HOST": os.environ.get("COULOBRE_DB_HOST", "127.0.0.1"),
"PORT": os.environ.get("COULOBRE_DB_PORT", "3306"),
"OPTIONS": {"charset": "utf8mb4"},
},
}
else:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": Path(os.environ.get("COULOBRE_SQLITE_PATH", "db.sqlite3")),
},
}
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
TIME_ZONE = "UTC"
STATIC_URL = "/static/"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
CELERY_BROKER_URL = os.environ.get(
"COULOBRE_BROKER_URL", "amqp://guest:guest@127.0.0.1:5672//"
)
CELERY_BROKER_TRANSPORT_OPTIONS = {"confirm_publish": True}
CELERY_TASK_DEFAULT_QUEUE = "coulobre"
CELERY_TASK_IGNORE_RESULT = True
CELERY_BEAT_SCHEDULE = {
"dispatch-web-provisioning-plans": {
"task": "coulobre.hosting.tasks.dispatch_web_plans",
"schedule": 5.0,
"options": {"expires": 5.0},
},
}
+12
View File
@@ -0,0 +1,12 @@
from django.contrib import admin
from django.urls import path
from django.views.generic import RedirectView
admin.site.site_header = "Coulobre Panel"
admin.site.site_title = "Coulobre Panel"
admin.site.index_title = "Administration"
urlpatterns = [
path("", RedirectView.as_view(pattern_name="admin:index")),
path("admin/", admin.site.urls),
]