Add MariaDB database requests and deployment manifests
This commit is contained in:
1 parent
e1dc9a26cb
commit
9746bd8a74
12 files changed
+418
-8
No files matched your search
@@ -45,6 +45,24 @@ and node deployment files.
|
||||
The local database defaults to `db.sqlite3`. Set `COULOBRE_SQLITE_PATH` to use a
|
||||
different file. Keep `COULOBRE_DEBUG` for local development.
|
||||
|
||||
## Request a MariaDB database
|
||||
|
||||
Open a hosting account and select **Request database**. Choose a short suffix
|
||||
such as `wordpress`. The panel derives the full database name from the account
|
||||
ID and suffix, so two accounts can each request a database named `wordpress`.
|
||||
|
||||
The account page shows the requested databases. Operators can download a
|
||||
versioned deployment manifest containing the account ID and suffix. Resellers
|
||||
can view the requested database names on their own assigned accounts. The
|
||||
manifest describes the database to provision on a MariaDB node.
|
||||
|
||||
Use the installed node command to validate the manifest and display the derived
|
||||
database and login names.
|
||||
|
||||
```sh
|
||||
coulobre-database-node inspect coulobre-database-1.json
|
||||
```
|
||||
|
||||
## Request an Apache configuration preview
|
||||
|
||||
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
|
||||
|
||||
@@ -16,6 +16,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
coulobre-database-node = "coulobre.database_node:main"
|
||||
coulobre-web-node = "coulobre.web_node:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
MANIFEST_KIND = "mariadb_database"
|
||||
DATABASE_SUFFIX_PATTERN = r"\A[a-z][a-z0-9_]{0,23}\Z"
|
||||
INVALID_SUFFIX = (
|
||||
"Use 1 to 24 lowercase letters, digits, or underscores. Start with a letter."
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DatabaseSpec:
|
||||
account_id: int
|
||||
suffix: str
|
||||
|
||||
def __post_init__(self):
|
||||
if type(self.account_id) is not int or not 1 <= self.account_id <= 2**63 - 1:
|
||||
raise ValueError("The account ID must be a positive 64-bit integer.")
|
||||
if not isinstance(self.suffix, str) or not re.fullmatch(
|
||||
DATABASE_SUFFIX_PATTERN, self.suffix
|
||||
):
|
||||
raise ValueError(INVALID_SUFFIX)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return f"coulobre_{self.account_id}_{self.suffix}"
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
"version": MANIFEST_VERSION,
|
||||
"kind": MANIFEST_KIND,
|
||||
"account_id": self.account_id,
|
||||
"suffix": self.suffix,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
if not isinstance(data, dict) or data.keys() != {
|
||||
"version",
|
||||
"kind",
|
||||
"account_id",
|
||||
"suffix",
|
||||
}:
|
||||
raise ValueError("Expected a MariaDB database manifest.")
|
||||
if type(data["version"]) is not int or data["version"] != MANIFEST_VERSION:
|
||||
raise ValueError("Unsupported database manifest version.")
|
||||
if data["kind"] != MANIFEST_KIND:
|
||||
raise ValueError("Expected a MariaDB database manifest.")
|
||||
return cls(data["account_id"], data["suffix"])
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(prog="coulobre-database-node")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
inspect = commands.add_parser(
|
||||
"inspect", help="Inspect a database deployment manifest."
|
||||
)
|
||||
inspect.add_argument("manifest", type=Path)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
|
||||
database = DatabaseSpec.from_manifest(payload)
|
||||
except (OSError, ValueError) as error:
|
||||
parser.exit(1, f"coulobre-database-node: {error}\n")
|
||||
|
||||
print(json.dumps({"database": database.name, "user": database.name}, indent=2))
|
||||
return 0
|
||||
@@ -0,0 +1,59 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-19 21:37
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0005_reseller_account_limit_reseller_hosting_plans"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="HostingDatabase",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
(
|
||||
"suffix",
|
||||
models.CharField(
|
||||
help_text="Use 1 to 24 lowercase letters, digits, or underscores. Start with a letter.",
|
||||
max_length=24,
|
||||
validators=[
|
||||
django.core.validators.RegexValidator(
|
||||
"\\A[a-z][a-z0-9_]{0,23}\\Z",
|
||||
"Use 1 to 24 lowercase letters, digits, or underscores. Start with a letter.",
|
||||
)
|
||||
],
|
||||
verbose_name="database suffix",
|
||||
),
|
||||
),
|
||||
(
|
||||
"account",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.PROTECT,
|
||||
related_name="databases",
|
||||
to="hosting.hostingaccount",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"ordering": ("suffix",),
|
||||
"constraints": [
|
||||
models.UniqueConstraint(
|
||||
fields=("account", "suffix"),
|
||||
name="hosting_database_account_suffix_unique",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -1,7 +1,10 @@
|
||||
from django.conf import settings
|
||||
from django.core.validators import RegexValidator
|
||||
from django.db import models
|
||||
from django.urls import reverse
|
||||
|
||||
from coulobre.database_node import DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX, DatabaseSpec
|
||||
|
||||
from .fields import DomainNameField
|
||||
|
||||
|
||||
@@ -51,6 +54,34 @@ class HostingAccount(models.Model):
|
||||
return str(self.primary_domain)
|
||||
|
||||
|
||||
class HostingDatabase(models.Model):
|
||||
account = models.ForeignKey(
|
||||
HostingAccount, on_delete=models.PROTECT, related_name="databases"
|
||||
)
|
||||
suffix = models.CharField(
|
||||
"database suffix",
|
||||
max_length=24,
|
||||
validators=[RegexValidator(DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX)],
|
||||
help_text=INVALID_SUFFIX,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
ordering = ("suffix",)
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=("account", "suffix"),
|
||||
name="hosting_database_account_suffix_unique",
|
||||
)
|
||||
]
|
||||
|
||||
@property
|
||||
def spec(self):
|
||||
return DatabaseSpec(self.account_id, self.suffix)
|
||||
|
||||
def __str__(self):
|
||||
return self.spec.name
|
||||
|
||||
|
||||
class WebProvisioningPlan(models.Model):
|
||||
account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE)
|
||||
primary_domain = DomainNameField(max_length=253)
|
||||
|
||||
@@ -237,6 +237,10 @@ h2 {
|
||||
box-shadow: 0 2px 5px #1a2e2010;
|
||||
}
|
||||
|
||||
.main > section.surface + section.surface {
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.button {
|
||||
display: inline-flex;
|
||||
min-height: 2.55rem;
|
||||
|
||||
@@ -35,4 +35,33 @@
|
||||
{% include "hosting/plan_table.html" %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if is_reseller or perms.hosting.view_hostingdatabase %}
|
||||
<section class="surface" aria-labelledby="databases-heading">
|
||||
<header class="section-heading">
|
||||
<h2 id="databases-heading">MariaDB database requests</h2>
|
||||
{% if not is_reseller and perms.hosting.add_hostingdatabase %}
|
||||
<a class="button primary" href="{% url 'panel:database_create' account.pk %}">Request database</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if databases %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Database</th>{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %}</tr></thead>
|
||||
<tbody>
|
||||
{% for database in databases %}
|
||||
<tr>
|
||||
<td class="domain">{{ database }}</td>
|
||||
{% if not is_reseller %}
|
||||
<td><a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a></td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty">No databases requested yet.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -18,7 +18,7 @@
|
||||
<nav class="navigation" aria-label="Main navigation">
|
||||
{% with current=request.resolver_match.url_name %}
|
||||
{% if is_reseller or perms.hosting.view_hostingaccount %}
|
||||
<a href="{% url 'panel:accounts' %}"{% if current == 'accounts' or current == 'account' or current == 'account_create' or current == 'account_edit' %} aria-current="page"{% endif %}>
|
||||
<a href="{% url 'panel:accounts' %}"{% if current == 'accounts' or current == 'account' or current == 'account_create' or current == 'account_edit' or current == 'database_create' %} aria-current="page"{% endif %}>
|
||||
<span class="nav-icon nav-icon-accounts" aria-hidden="true"></span>
|
||||
Hosting accounts
|
||||
</a>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Request MariaDB database · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading"><h1>Request MariaDB database</h1></header>
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Request database</button>
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,123 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db.models.deletion import ProtectedError
|
||||
from django.test import SimpleTestCase, TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from coulobre.database_node import DatabaseSpec
|
||||
|
||||
from .models import HostingAccount, HostingDatabase, Reseller
|
||||
|
||||
|
||||
class DatabaseRequestTests(TestCase):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
users = get_user_model().objects
|
||||
cls.operator = users.create_superuser("operator")
|
||||
cls.user = users.create_user("reseller")
|
||||
reseller = Reseller.objects.create(user=cls.user)
|
||||
cls.account = HostingAccount.objects.create(
|
||||
name="Account A", primary_domain="account-a.example", reseller=reseller
|
||||
)
|
||||
cls.other_account = HostingAccount.objects.create(
|
||||
name="Account B", primary_domain="account-b.example"
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.client.force_login(self.operator)
|
||||
self.request_url = reverse("panel:database_create", args=[self.account.pk])
|
||||
|
||||
def test_operator_can_request_a_database_and_download_its_manifest(self):
|
||||
response = self.client.post(self.request_url, {"suffix": "wordpress"})
|
||||
self.assertRedirects(response, self.account.get_absolute_url())
|
||||
database = HostingDatabase.objects.get()
|
||||
self.assertEqual(database.account, self.account)
|
||||
name = f"coulobre_{self.account.pk}_wordpress"
|
||||
self.assertContains(self.client.get(self.account.get_absolute_url()), name)
|
||||
|
||||
manifest = self.client.get(
|
||||
reverse("panel:database_manifest", args=[database.pk])
|
||||
)
|
||||
self.assertEqual(manifest.status_code, 200)
|
||||
self.assertEqual(manifest["Cache-Control"], "private, no-store")
|
||||
self.assertIn("attachment", manifest["Content-Disposition"])
|
||||
self.assertEqual(
|
||||
manifest.json(),
|
||||
{
|
||||
"version": 1,
|
||||
"kind": "mariadb_database",
|
||||
"account_id": self.account.pk,
|
||||
"suffix": "wordpress",
|
||||
},
|
||||
)
|
||||
self.assertEqual(DatabaseSpec.from_manifest(manifest.json()).name, name)
|
||||
|
||||
def test_duplicate_suffix_is_scoped_to_the_owning_account(self):
|
||||
HostingDatabase.objects.create(account=self.account, suffix="wordpress")
|
||||
duplicate = self.client.post(self.request_url, {"suffix": "wordpress"})
|
||||
self.assertContains(
|
||||
duplicate, "This account already has a database with that suffix."
|
||||
)
|
||||
|
||||
other_url = reverse("panel:database_create", args=[self.other_account.pk])
|
||||
self.assertRedirects(
|
||||
self.client.post(other_url, {"suffix": "wordpress"}),
|
||||
self.other_account.get_absolute_url(),
|
||||
)
|
||||
self.assertEqual(
|
||||
len({str(database) for database in HostingDatabase.objects.all()}), 2
|
||||
)
|
||||
|
||||
def test_request_rejects_invalid_suffixes(self):
|
||||
for suffix in ("UPPER", "bad-name", "3db", "mysql`", "a" * 25):
|
||||
with self.subTest(suffix=suffix):
|
||||
response = self.client.post(self.request_url, {"suffix": suffix})
|
||||
self.assertIn("suffix", response.context["form"].errors)
|
||||
self.assertFalse(HostingDatabase.objects.exists())
|
||||
|
||||
def test_reseller_view_is_scoped_and_node_actions_require_an_operator(self):
|
||||
owned = HostingDatabase.objects.create(account=self.account, suffix="wordpress")
|
||||
HostingDatabase.objects.create(account=self.other_account, suffix="othersite")
|
||||
self.client.force_login(self.user)
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, str(owned))
|
||||
self.assertNotContains(account, "othersite")
|
||||
self.assertNotContains(account, "Download manifest")
|
||||
self.assertNotContains(account, "Request database")
|
||||
self.assertEqual(
|
||||
self.client.get(self.other_account.get_absolute_url()).status_code, 404
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.post(self.request_url, {"suffix": "another"}).status_code, 403
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.get(
|
||||
reverse("panel:database_manifest", args=[owned.pk])
|
||||
).status_code,
|
||||
403,
|
||||
)
|
||||
|
||||
def test_account_deletion_protects_database_requests(self):
|
||||
HostingDatabase.objects.create(account=self.account, suffix="wordpress")
|
||||
with self.assertRaises(ProtectedError):
|
||||
self.account.delete()
|
||||
|
||||
|
||||
class DatabaseManifestTests(SimpleTestCase):
|
||||
def test_manifest_validates_identity_and_suffix_at_the_node_boundary(self):
|
||||
manifest = DatabaseSpec(42, "example_db").manifest()
|
||||
self.assertEqual(
|
||||
DatabaseSpec.from_manifest(manifest).name, "coulobre_42_example_db"
|
||||
)
|
||||
for changes in (
|
||||
{"kind": "unknown"},
|
||||
{"version": True},
|
||||
{"version": 2},
|
||||
{"account_id": True},
|
||||
{"account_id": 2**63},
|
||||
{"account_id": -1},
|
||||
{"suffix": "schema`"},
|
||||
{"suffix": None},
|
||||
{"password": "unused"},
|
||||
):
|
||||
with self.subTest(changes=changes), self.assertRaises(ValueError):
|
||||
DatabaseSpec.from_manifest(manifest | changes)
|
||||
@@ -19,6 +19,16 @@ urlpatterns = [
|
||||
path("accounts/new/", views.AccountCreate.as_view(), name="account_create"),
|
||||
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
|
||||
path("accounts/<int:pk>/edit/", views.AccountEdit.as_view(), name="account_edit"),
|
||||
path(
|
||||
"accounts/<int:pk>/databases/new/",
|
||||
views.DatabaseCreate.as_view(),
|
||||
name="database_create",
|
||||
),
|
||||
path(
|
||||
"databases/<int:pk>/manifest/",
|
||||
views.DownloadDatabaseManifest.as_view(),
|
||||
name="database_manifest",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan"
|
||||
),
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import IntegrityError
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.db.models import Q
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import redirect
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.functional import cached_property
|
||||
from django.views import View
|
||||
from django.views.generic import CreateView, DetailView, ListView, UpdateView
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from .access import OperatorOnlyMixin, ResellerScopeMixin, reseller_for_user
|
||||
from .models import HostingAccount, HostingPlan, WebProvisioningPlan
|
||||
from .models import HostingAccount, HostingDatabase, HostingPlan, WebProvisioningPlan
|
||||
from .reseller_accounts import create_reseller_account
|
||||
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
|
||||
|
||||
@@ -19,6 +20,7 @@ CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
|
||||
VIEW_PLANS = "hosting.view_webprovisioningplan"
|
||||
VIEW_HOSTING_PLANS = "hosting.view_hostingplan"
|
||||
VIEW_RESELLERS = "hosting.view_reseller"
|
||||
VIEW_DATABASES = "hosting.view_hostingdatabase"
|
||||
|
||||
|
||||
class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
|
||||
@@ -140,15 +142,60 @@ class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
if reseller_for_user(
|
||||
self.request.user
|
||||
) is not None or self.request.user.has_perm(VIEW_PLANS):
|
||||
user = self.request.user
|
||||
reseller = reseller_for_user(user)
|
||||
if reseller is not None or user.has_perm(VIEW_PLANS):
|
||||
context["plans"] = self.object.webprovisioningplan_set.order_by(
|
||||
"-requested_at", "-pk"
|
||||
)[:10]
|
||||
if reseller is not None or user.has_perm(VIEW_DATABASES):
|
||||
context["databases"] = self.object.databases.all()
|
||||
return context
|
||||
|
||||
|
||||
class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView):
|
||||
model = HostingDatabase
|
||||
fields = ("suffix",)
|
||||
template_name = "hosting/database_form.html"
|
||||
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase")
|
||||
|
||||
@cached_property
|
||||
def account(self):
|
||||
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(account=self.account, **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
self.object = form.save(commit=False)
|
||||
self.object.account = self.account
|
||||
try:
|
||||
with transaction.atomic():
|
||||
self.object.save()
|
||||
except IntegrityError:
|
||||
if not self.account.databases.filter(suffix=self.object.suffix).exists():
|
||||
raise
|
||||
form.add_error(
|
||||
"suffix", "This account already has a database with that suffix."
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
return redirect(self.account)
|
||||
|
||||
|
||||
class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
||||
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES)
|
||||
|
||||
def get(self, request, pk):
|
||||
database = get_object_or_404(HostingDatabase, pk=pk)
|
||||
return JsonResponse(
|
||||
database.spec.manifest(),
|
||||
headers={
|
||||
"Cache-Control": "private, no-store",
|
||||
"Content-Disposition": f'attachment; filename="coulobre-database-{database.pk}.json"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
|
||||
model = HostingPlan
|
||||
permission_required = VIEW_HOSTING_PLANS
|
||||
|
||||
Reference in new issue
Block a user