Complete public hosting operations for Coulobre 0.9
This commit is contained in:
1 parent
a033d85d1f
commit
9e66510f7c
41 files changed
+2042
-44
No files matched your search
@@ -0,0 +1,53 @@
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from .node_files import read_root_file, replace_configuration
|
||||
|
||||
CATALOG = "catalog.coulobre.invalid"
|
||||
PATH = Path("/etc/bind/coulobre-catalog/zone")
|
||||
KEY = "coulobre-transfer"
|
||||
HEADER = re.compile(r"; Coulobre catalog (\d+)")
|
||||
MEMBER = re.compile(r"[a-f0-9]{32}\.zones 0 IN PTR ([a-z0-9.-]+)\.")
|
||||
|
||||
|
||||
def render_catalog(serial, members):
|
||||
records = [
|
||||
f"; Coulobre catalog {serial}",
|
||||
"$TTL 0",
|
||||
f"@ IN SOA localhost. hostmaster.invalid. {serial} 60 60 86400 0",
|
||||
"@ IN NS invalid.",
|
||||
'version IN TXT "2"',
|
||||
]
|
||||
for domain in sorted(members):
|
||||
label = hashlib.sha256(domain.encode("ascii")).hexdigest()[:32]
|
||||
records.append(f"{label}.zones 0 IN PTR {domain}.")
|
||||
return "\n".join(records) + "\n"
|
||||
|
||||
|
||||
def sync_member(domain, *, present):
|
||||
if not os.path.lexists(PATH):
|
||||
return
|
||||
from .dns_node_apply import RNDC, active_serial, run, wait_for_serial
|
||||
|
||||
content = read_root_file(PATH, mode=0o644)
|
||||
header = HEADER.fullmatch(content.split("\n", 1)[0])
|
||||
if header is None:
|
||||
raise ValueError("The managed DNS catalog has an unexpected format.")
|
||||
serial = int(header[1])
|
||||
members = set(MEMBER.findall(content))
|
||||
if render_catalog(serial, members) != content:
|
||||
raise ValueError(
|
||||
"The managed DNS catalog differs from its saved format."
|
||||
)
|
||||
if (domain in members) != present:
|
||||
if present:
|
||||
members.add(domain)
|
||||
else:
|
||||
members.remove(domain)
|
||||
serial = (serial + 1) % 2**32
|
||||
replace_configuration(PATH, render_catalog(serial, members))
|
||||
if active_serial(CATALOG) != serial:
|
||||
run(*RNDC, "reload", CATALOG)
|
||||
wait_for_serial(CATALOG, serial)
|
||||
@@ -7,6 +7,7 @@ import time
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from .dns_catalog import sync_member
|
||||
from .dns_node import MAX_SOA_SERIAL
|
||||
from .node_files import (
|
||||
locked_root_directory,
|
||||
@@ -74,6 +75,7 @@ def install_zone(zone, path, directory):
|
||||
if wanted != previous:
|
||||
install_zone_file(domain, path, wanted)
|
||||
if registered and loaded == zone.serial:
|
||||
sync_member(domain, present=True)
|
||||
return
|
||||
|
||||
os.fsync(directory)
|
||||
@@ -82,6 +84,7 @@ def install_zone(zone, path, directory):
|
||||
else:
|
||||
run(*RNDC, "addzone", domain, config)
|
||||
wait_for_serial(domain, zone.serial)
|
||||
sync_member(domain, present=True)
|
||||
|
||||
|
||||
def zone_configuration(path):
|
||||
@@ -93,6 +96,7 @@ def retire_zone(request):
|
||||
with locked_root_directory(ZONE_DIRECTORY):
|
||||
record = RetirementRecord(ZONE_DIRECTORY, request)
|
||||
if record.is_complete:
|
||||
sync_member(zone.domain, present=False)
|
||||
return
|
||||
path = ZONE_DIRECTORY / zone.domain
|
||||
managed = check_registration(zone.domain, zone_configuration(path))
|
||||
@@ -109,6 +113,7 @@ def retire_zone(request):
|
||||
raise ValueError("BIND9 still has the zone registered.")
|
||||
archive_path(path, record.directory / "zone")
|
||||
record.finish()
|
||||
sync_member(zone.domain, present=False)
|
||||
|
||||
|
||||
def check_registration(domain, config):
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import dns.exception
|
||||
import dns.flags
|
||||
import dns.message
|
||||
import dns.query
|
||||
import dns.rcode
|
||||
import dns.rdatatype
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||
from django.http import Http404
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.generic import DetailView
|
||||
|
||||
from .access import TenantScopeMixin
|
||||
from .models import HostingDnsZone
|
||||
|
||||
|
||||
def authoritative_serial(address, domain):
|
||||
query = dns.message.make_query(f"{domain}.", dns.rdatatype.SOA, flags=0)
|
||||
try:
|
||||
result, _ = dns.query.udp_with_fallback(query, address, timeout=1.5)
|
||||
except (dns.exception.DNSException, OSError, EOFError):
|
||||
return None
|
||||
if result.rcode() != dns.rcode.NOERROR or not result.flags & dns.flags.AA:
|
||||
return None
|
||||
for records in result.answer:
|
||||
if (
|
||||
records.name == query.question[0].name
|
||||
and records.rdtype == dns.rdatatype.SOA
|
||||
):
|
||||
return records[0].serial
|
||||
return None
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class DnsReplicaView(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
queryset = HostingDnsZone.objects.filter(account__retired_at__isnull=True)
|
||||
context_object_name = "zone"
|
||||
customer_relation = "account__customer"
|
||||
reseller_relation = "account__reseller"
|
||||
permission_required = (
|
||||
"hosting.view_hostingaccount",
|
||||
"hosting.view_hostingdnszone",
|
||||
)
|
||||
template_name = "hosting/dns_replica.html"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if not settings.DNS_REPLICATION_ADDRESSES:
|
||||
raise Http404
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
readings = [
|
||||
(
|
||||
label,
|
||||
address,
|
||||
authoritative_serial(str(address), self.object.domain),
|
||||
)
|
||||
for label, address in zip(
|
||||
("Primary", "Secondary"),
|
||||
settings.DNS_REPLICATION_ADDRESSES,
|
||||
strict=True,
|
||||
)
|
||||
]
|
||||
primary, secondary = (row[2] for row in readings)
|
||||
return super().get_context_data(
|
||||
nodes=readings,
|
||||
synchronized=primary is not None and primary == secondary,
|
||||
unreachable=primary is None or secondary is None,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,56 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||
from django.db import transaction
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.utils import timezone
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
from .access import OperatorOnlyMixin
|
||||
from .models import HostingMailDomain
|
||||
from .tasks import refresh_mail_queue
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class MailQueueView(OperatorOnlyMixin, PermissionRequiredMixin, TemplateView):
|
||||
permission_required = (
|
||||
"hosting.view_hostingaccount",
|
||||
"hosting.view_hostingmaildomain",
|
||||
)
|
||||
template_name = "hosting/mail_queue.html"
|
||||
|
||||
def get_domain(self, *, locked=False):
|
||||
if not settings.LOCAL_MAILBOX_PROVISIONING:
|
||||
raise Http404
|
||||
domains = HostingMailDomain.objects.filter(
|
||||
account__retired_at__isnull=True
|
||||
)
|
||||
if locked:
|
||||
domains = domains.select_for_update()
|
||||
return get_object_or_404(domains, pk=self.kwargs["pk"])
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(
|
||||
mail_domain=self.get_domain(), **kwargs
|
||||
)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
with transaction.atomic():
|
||||
domain = self.get_domain(locked=True)
|
||||
now = timezone.now()
|
||||
if (
|
||||
domain.queue_requested_at is None
|
||||
or domain.queue_requested_at <= now - timedelta(seconds=30)
|
||||
):
|
||||
domain.queue_requested_at = now
|
||||
domain.save(update_fields=["queue_requested_at"])
|
||||
transaction.on_commit(
|
||||
lambda: refresh_mail_queue.delay(
|
||||
domain.pk, now.isoformat()
|
||||
)
|
||||
)
|
||||
return redirect("panel:mail_queue", pk=domain.pk)
|
||||
@@ -0,0 +1,68 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-22 16:32
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
import coulobre.hosting.fields
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0050_offsite_backup_transfers"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="hostingmaildomain",
|
||||
name="queue_observed_at",
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="hostingmaildomain",
|
||||
name="queue_report",
|
||||
field=models.JSONField(blank=True, default=dict),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="hostingmaildomain",
|
||||
name="queue_requested_at",
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="WebsiteUsage",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("node_key", models.CharField(max_length=20)),
|
||||
(
|
||||
"domain",
|
||||
coulobre.hosting.fields.DomainNameField(max_length=253),
|
||||
),
|
||||
("report", models.JSONField(blank=True, default=dict)),
|
||||
("requested_at", models.DateTimeField(blank=True, null=True)),
|
||||
("observed_at", models.DateTimeField(blank=True, null=True)),
|
||||
(
|
||||
"account",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="website_usage",
|
||||
to="hosting.hostingaccount",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"constraints": [
|
||||
models.UniqueConstraint(
|
||||
fields=("account", "node_key"),
|
||||
name="website_usage_unique_site",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-22 16:33
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0051_hosting_operations"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="hostingmailbox",
|
||||
name="usage_bytes",
|
||||
field=models.PositiveBigIntegerField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="hostingmailbox",
|
||||
name="usage_observed_at",
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="hostingmailbox",
|
||||
name="usage_requested_at",
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -614,6 +614,25 @@ class HostingDnsZone(models.Model):
|
||||
)
|
||||
|
||||
|
||||
class WebsiteUsage(models.Model):
|
||||
account = models.ForeignKey(
|
||||
HostingAccount, on_delete=models.CASCADE, related_name="website_usage"
|
||||
)
|
||||
node_key = models.CharField(max_length=20)
|
||||
domain = DomainNameField(max_length=253)
|
||||
report = models.JSONField(default=dict, blank=True)
|
||||
requested_at = models.DateTimeField(null=True, blank=True)
|
||||
observed_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=("account", "node_key"),
|
||||
name="website_usage_unique_site",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
class HostingMailDomain(models.Model):
|
||||
account = models.ForeignKey(
|
||||
HostingAccount, on_delete=models.PROTECT, related_name="mail_domains"
|
||||
@@ -622,6 +641,9 @@ class HostingMailDomain(models.Model):
|
||||
dkim_record = models.CharField(max_length=1024, blank=True)
|
||||
dns_setup_problem = models.TextField(blank=True)
|
||||
dns_sync_requested = models.BooleanField(default=False)
|
||||
queue_report = models.JSONField(default=dict, blank=True)
|
||||
queue_requested_at = models.DateTimeField(null=True, blank=True)
|
||||
queue_observed_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return str(self.domain)
|
||||
@@ -632,6 +654,9 @@ class HostingMailbox(models.Model):
|
||||
HostingMailDomain, on_delete=models.PROTECT, related_name="mailboxes"
|
||||
)
|
||||
local_part = models.CharField(max_length=LOCAL_PART_MAX_LENGTH)
|
||||
usage_bytes = models.PositiveBigIntegerField(null=True, blank=True)
|
||||
usage_requested_at = models.DateTimeField(null=True, blank=True)
|
||||
usage_observed_at = models.DateTimeField(null=True, blank=True)
|
||||
quota_mib = models.PositiveIntegerField(
|
||||
"storage limit (MiB)",
|
||||
blank=True,
|
||||
|
||||
@@ -740,9 +740,15 @@ def provision_mailbox(provisioning_id):
|
||||
def apply_mailbox_provisioning(provisioning):
|
||||
if provisioning.quota_update:
|
||||
update_local_mailbox_quota(provisioning.mailbox.spec)
|
||||
elif settings.MANAGE_MAIL_DNS:
|
||||
elif settings.MANAGE_MAIL_DNS or settings.MAIL_NODE_DKIM:
|
||||
public_key = provision_signing_mailbox(provisioning.mailbox.spec)
|
||||
sync_mail_dns(provisioning.mailbox.mail_domain, public_key=public_key)
|
||||
domain = provisioning.mailbox.mail_domain
|
||||
if settings.MANAGE_MAIL_DNS:
|
||||
sync_mail_dns(domain, public_key=public_key)
|
||||
else:
|
||||
HostingMailDomain.objects.filter(pk=domain.pk).update(
|
||||
dkim_record=public_key
|
||||
)
|
||||
else:
|
||||
provision_local_mailbox(provisioning.mailbox.spec)
|
||||
|
||||
@@ -1043,3 +1049,161 @@ def execute_website_job(account_id, job_id, scheduled_for):
|
||||
except ValueError:
|
||||
result, code = WebsiteJobResult.FAILED, None
|
||||
save_website_job_result(job_id, request.run_id, result, code)
|
||||
|
||||
|
||||
@shared_task(queue="coulobre-mailbox-provisioning")
|
||||
def refresh_mail_queue(domain_id, requested_at):
|
||||
from coulobre.mail_queue import QUEUE_NAMES, MailQueueRequest
|
||||
|
||||
from .node_client import apply_on_local_node
|
||||
|
||||
domain = HostingMailDomain.objects.filter(
|
||||
pk=domain_id,
|
||||
account__retired_at__isnull=True,
|
||||
queue_requested_at=requested_at,
|
||||
).first()
|
||||
if domain is None or not settings.LOCAL_MAILBOX_PROVISIONING:
|
||||
return
|
||||
try:
|
||||
report = apply_on_local_node(
|
||||
MailQueueRequest(domain.domain),
|
||||
"/run/coulobre-mail-apply.sock",
|
||||
"mail node",
|
||||
"queue summary",
|
||||
timeout=20,
|
||||
)
|
||||
counts = report["counts"]
|
||||
if (
|
||||
set(counts) != set(QUEUE_NAMES)
|
||||
or any(
|
||||
type(value) is not int or not 0 <= value <= 20000
|
||||
for value in counts.values()
|
||||
)
|
||||
or type(report["partial"]) is not bool
|
||||
):
|
||||
raise ValueError
|
||||
snapshot = {"counts": counts, "partial": report["partial"]}
|
||||
except (KeyError, TypeError, ValueError, OSError):
|
||||
snapshot = {"error": "Could not read the queue from the mail node."}
|
||||
HostingMailDomain.objects.filter(
|
||||
pk=domain_id, queue_requested_at=requested_at
|
||||
).update(
|
||||
queue_report=snapshot,
|
||||
queue_observed_at=timezone.now(),
|
||||
)
|
||||
|
||||
|
||||
@shared_task(queue="coulobre-web-activation")
|
||||
def collect_website_usage(snapshot_id, requested_at):
|
||||
from .models import WebsiteUsage
|
||||
from .node_client import apply_on_local_node
|
||||
|
||||
if not settings.WEBSITE_USAGE:
|
||||
return
|
||||
snapshot = (
|
||||
WebsiteUsage.objects.select_related("account")
|
||||
.filter(
|
||||
pk=snapshot_id,
|
||||
requested_at=requested_at,
|
||||
account__retired_at__isnull=True,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if snapshot is None:
|
||||
return
|
||||
try:
|
||||
if snapshot.node_key == str(snapshot.account_id):
|
||||
if snapshot.account.primary_domain != snapshot.domain:
|
||||
return
|
||||
site = WebSite(snapshot.account_id, snapshot.domain)
|
||||
else:
|
||||
website = (
|
||||
active_websites(snapshot.account)
|
||||
.filter(
|
||||
pk=int(snapshot.node_key.removeprefix("s")),
|
||||
domain=snapshot.domain,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if website is None:
|
||||
return
|
||||
site = website.spec
|
||||
response = apply_on_local_node(
|
||||
site,
|
||||
"/run/coulobre-website-usage.sock",
|
||||
"web node",
|
||||
"website usage",
|
||||
timeout=20,
|
||||
)
|
||||
report = {
|
||||
name: response[name]
|
||||
for name in (
|
||||
"month",
|
||||
"storage_bytes",
|
||||
"traffic_bytes",
|
||||
"access_lines",
|
||||
"error_lines",
|
||||
"partial",
|
||||
)
|
||||
}
|
||||
datetime.strptime(report["month"], "%Y-%m")
|
||||
for field in ("storage_bytes", "traffic_bytes"):
|
||||
size = report[field]
|
||||
if (field != "traffic_bytes" or size is not None) and (
|
||||
type(size) is not int or not 0 <= size < 2**63
|
||||
):
|
||||
raise ValueError
|
||||
for field in ("access_lines", "error_lines"):
|
||||
lines = report[field]
|
||||
if (
|
||||
not isinstance(lines, list)
|
||||
or len(lines) > 8
|
||||
or any(
|
||||
not isinstance(line, str) or len(line) > 256
|
||||
for line in lines
|
||||
)
|
||||
):
|
||||
raise ValueError
|
||||
if type(report["partial"]) is not bool:
|
||||
raise ValueError
|
||||
except (KeyError, TypeError, ValueError, OSError):
|
||||
report = {"error": "Could not measure usage on the web node."}
|
||||
WebsiteUsage.objects.filter(
|
||||
pk=snapshot.pk, requested_at=requested_at
|
||||
).update(
|
||||
report=report,
|
||||
observed_at=timezone.now(),
|
||||
)
|
||||
|
||||
|
||||
@shared_task(queue="coulobre-mailbox-provisioning")
|
||||
def collect_mailbox_usage(mailbox_id, requested_at):
|
||||
from coulobre.mail_node import MailboxUsageRequest
|
||||
|
||||
from .models import HostingMailbox
|
||||
from .node_client import apply_on_local_node
|
||||
|
||||
if not settings.LOCAL_MAILBOX_PROVISIONING or not settings.WEBSITE_USAGE:
|
||||
return
|
||||
mailboxes = HostingMailbox.objects.filter(
|
||||
pk=mailbox_id,
|
||||
usage_requested_at=requested_at,
|
||||
mail_domain__account__retired_at__isnull=True,
|
||||
)
|
||||
mailbox = mailboxes.select_related("mail_domain").first()
|
||||
if mailbox is None:
|
||||
return
|
||||
try:
|
||||
reply = apply_on_local_node(
|
||||
MailboxUsageRequest(mailbox.spec),
|
||||
"/run/coulobre-mail-apply.sock",
|
||||
"mail node",
|
||||
"mailbox quota usage",
|
||||
timeout=15,
|
||||
)
|
||||
used = reply["usage_bytes"]
|
||||
if type(used) is not int or not 0 <= used < 2**63:
|
||||
raise ValueError
|
||||
except (KeyError, OSError, ValueError):
|
||||
used = None
|
||||
mailboxes.update(usage_bytes=used, usage_observed_at=timezone.now())
|
||||
@@ -10,8 +10,11 @@
|
||||
{% include "hosting/account_status.html" %}
|
||||
</div>
|
||||
</div>
|
||||
{% if primary_file_access or manage_website_jobs or manage_sftp or export_backup_manifest or is_operator and perms.hosting.change_hostingaccount or can_retire_account %}
|
||||
{% if primary_file_access or manage_website_jobs or manage_sftp or export_backup_manifest or is_operator and perms.hosting.change_hostingaccount or can_retire_account or show_website_usage %}
|
||||
<div class="form-actions">
|
||||
{% if show_website_usage %}
|
||||
<a class="button secondary" href="{% url 'panel:website_usage' account.pk %}">Usage and logs</a>
|
||||
{% endif %}
|
||||
{% if can_retire_account %}
|
||||
<a class="button secondary" href="{% url 'panel:account_retirement' account.pk %}">Retire account</a>
|
||||
{% endif %}
|
||||
@@ -199,6 +202,9 @@
|
||||
<td>
|
||||
<div class="form-actions">
|
||||
<a class="record-link" href="{% url 'panel:dns_zone_manifest' zone.pk %}" aria-label="Download DNS manifest for {{ zone.domain }}">Download manifest</a>
|
||||
{% if show_dns_replication %}
|
||||
<a class="record-link" href="{% url 'panel:dns_replication' zone.pk %}">Check replication</a>
|
||||
{% endif %}
|
||||
{% if manage_dns_publishing %}
|
||||
{% include "hosting/dns_publication.html" with publication=zone.publication %}
|
||||
{% endif %}
|
||||
@@ -232,7 +238,7 @@
|
||||
</header>
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Domain</th><th scope="col">DNS</th>{% if manage_mail_routing %}<th scope="col">Routing</th>{% endif %}</tr></thead>
|
||||
<thead><tr><th scope="col">Domain</th><th scope="col">DNS</th>{% if manage_mail_routing %}<th scope="col">Routing</th>{% endif %}{% if show_mail_queue %}<th scope="col">Delivery</th>{% endif %}</tr></thead>
|
||||
<tbody>
|
||||
{% for domain in mail_domains %}
|
||||
<tr>
|
||||
@@ -241,6 +247,9 @@
|
||||
{% if manage_mail_routing %}
|
||||
<td><a class="record-link" href="{% url 'panel:mail_routing' domain.pk %}" aria-label="Manage mail routing for {{ domain }}">Manage routing</a></td>
|
||||
{% endif %}
|
||||
{% if show_mail_queue %}
|
||||
<td><a class="record-link" href="{% url 'panel:mail_queue' domain.pk %}">Mail queue</a></td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
ServerName $domain
|
||||
DocumentRoot "$document_root"
|
||||
$tls_settings
|
||||
$usage_logs
|
||||
<Directory "$document_root">
|
||||
AllowOverride None
|
||||
Options None
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}DNS replication · {{ zone.domain }}{% endblock %}
|
||||
{% block content %}
|
||||
<section class="surface">
|
||||
<h1>DNS replication for {{ zone.domain }}</h1>
|
||||
<p><a href="{{ zone.account.get_absolute_url }}">Back to hosting account</a></p>
|
||||
{% if synchronized %}
|
||||
<p>Both nameservers publish the same SOA serial.</p>
|
||||
{% elif unreachable %}
|
||||
<p>One or both nameservers did not return an authoritative SOA record.</p>
|
||||
{% else %}
|
||||
<p>The nameservers currently publish different SOA serials.</p>
|
||||
{% endif %}
|
||||
<table>
|
||||
<thead><tr><th scope="col">Nameserver</th><th scope="col">Address</th><th scope="col">SOA serial</th></tr></thead>
|
||||
<tbody>
|
||||
{% for role, address, serial in nodes %}
|
||||
<tr><td>{{ role }}</td><td>{{ address }}</td><td>{{ serial|default_if_none:"Unavailable" }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,25 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Mail queue · {{ mail_domain }}{% endblock %}
|
||||
{% block content %}
|
||||
<section class="surface">
|
||||
<h1>Mail queue for {{ mail_domain }}</h1>
|
||||
<p><a href="{{ mail_domain.account.get_absolute_url }}">{{ mail_domain.account.name }}</a></p>
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<button class="button primary" type="submit">Collect queue summary</button>
|
||||
</form>
|
||||
{% if mail_domain.queue_requested_at and not mail_domain.queue_observed_at or mail_domain.queue_requested_at > mail_domain.queue_observed_at %}
|
||||
<p>Queue summary requested. Reload this page to check for results.</p>
|
||||
{% endif %}
|
||||
{% if mail_domain.queue_report.error %}<p role="alert">{{ mail_domain.queue_report.error }}</p>{% endif %}
|
||||
{% if mail_domain.queue_report.counts %}
|
||||
<p>Last checked {{ mail_domain.queue_observed_at }}</p>
|
||||
{% if mail_domain.queue_report.partial %}<p>Counts reflect a partial queue scan.</p>{% endif %}
|
||||
<dl>
|
||||
{% for queue, count in mail_domain.queue_report.counts.items %}
|
||||
<dt>{{ queue|capfirst }}</dt><dd>{{ count }}</dd>
|
||||
{% endfor %}
|
||||
</dl>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,49 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Usage · {{ account.name }}{% endblock %}
|
||||
{% block content %}
|
||||
<section class="surface">
|
||||
<h1>Usage for {{ account.name }}</h1>
|
||||
<p><a href="{{ account.get_absolute_url }}">Back to hosting account</a></p>
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<button class="button primary" type="submit">Collect current usage</button>
|
||||
</form>
|
||||
<p>{{ month }} (UTC) HTTP response data
|
||||
{% if total_traffic is not None %}{{ total_traffic|filesizeformat }}{% else %}No measurements{% endif %}
|
||||
{% if not complete and total_traffic is not None %} · Partial{% endif %}
|
||||
</p>
|
||||
</section>
|
||||
{% for site, snapshot, quota in sites %}
|
||||
<section class="surface">
|
||||
<h2>{{ site.domain }}</h2>
|
||||
{% if snapshot %}
|
||||
<p>Last checked {{ snapshot.observed_at }}</p>
|
||||
{% if snapshot.report.error %}
|
||||
<p role="alert">{{ snapshot.report.error }}</p>
|
||||
{% else %}
|
||||
<dl>
|
||||
<dt>Website storage used</dt><dd>{{ snapshot.report.storage_bytes|filesizeformat }}{% if quota is not None %} of {{ quota }} MiB{% endif %}</dd>
|
||||
<dt>HTTP response data for {{ snapshot.report.month }} (UTC)</dt>
|
||||
<dd>{% if snapshot.report.traffic_bytes is not None %}{{ snapshot.report.traffic_bytes|filesizeformat }}{% else %}Unavailable{% endif %}{% if snapshot.report.partial %} · Partial{% endif %}</dd>
|
||||
</dl>
|
||||
<h3>Recent access log</h3>
|
||||
{% for line in snapshot.report.access_lines %}<pre>{{ line }}</pre>{% empty %}<p>No entries.</p>{% endfor %}
|
||||
<h3>Recent error log</h3>
|
||||
{% for line in snapshot.report.error_lines %}<pre>{{ line }}</pre>{% empty %}<p>No entries.</p>{% endfor %}
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<p>No measurement yet. Reload this page after collecting usage.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endfor %}
|
||||
{% if mailboxes is not None %}
|
||||
<section class="surface">
|
||||
<h2>Mailbox storage</h2>
|
||||
<dl>
|
||||
{% for mailbox in mailboxes %}
|
||||
<dt>{{ mailbox }}</dt><dd>{% if mailbox.usage_bytes is not None %}{{ mailbox.usage_bytes|filesizeformat }} used · {% endif %}{{ mailbox.quota_mib|default_if_none:"Unlimited" }}{% if mailbox.quota_mib %} MiB{% endif %}</dd>
|
||||
{% empty %}<p>No mailboxes.</p>{% endfor %}
|
||||
</dl>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -4,6 +4,7 @@ from django.urls import path
|
||||
from . import views
|
||||
from .backup_restores import RestoreKind
|
||||
from .credential_views import DatabaseCredentialView, MailboxCredentialView
|
||||
from .dns_replica_views import DnsReplicaView
|
||||
from .health_views import ServiceHealthView
|
||||
from .independent_website_views import (
|
||||
IndependentWebsiteCreate,
|
||||
@@ -12,6 +13,7 @@ from .independent_website_views import (
|
||||
)
|
||||
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
|
||||
from .mail_policy_views import MailRoutingEditor, MailVacationEditor
|
||||
from .mail_queue_views import MailQueueView
|
||||
from .password_reset import (
|
||||
CustomerPasswordResetView,
|
||||
CustomerResetCompleteView,
|
||||
@@ -39,10 +41,21 @@ from .sign_in import (
|
||||
)
|
||||
from .website_file_views import WebsiteFilesView
|
||||
from .website_job_views import WebsiteJobEditor, WebsiteJobList
|
||||
from .website_usage_views import WebsiteUsageView
|
||||
|
||||
app_name = "panel"
|
||||
|
||||
urlpatterns = [
|
||||
path(
|
||||
"dns-zones/<int:pk>/replication/",
|
||||
DnsReplicaView.as_view(),
|
||||
name="dns_replication",
|
||||
),
|
||||
path(
|
||||
"mail-domains/<int:pk>/queue/",
|
||||
MailQueueView.as_view(),
|
||||
name="mail_queue",
|
||||
),
|
||||
path("", views.AccountList.as_view(), name="accounts"),
|
||||
path(
|
||||
"service-health/", ServiceHealthView.as_view(), name="service_health"
|
||||
@@ -84,6 +97,11 @@ urlpatterns = [
|
||||
name="account_retirement",
|
||||
),
|
||||
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
|
||||
path(
|
||||
"accounts/<int:pk>/usage/",
|
||||
WebsiteUsageView.as_view(),
|
||||
name="website_usage",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/files/",
|
||||
WebsiteFilesView.as_view(),
|
||||
|
||||
@@ -384,6 +384,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
reseller = reseller_for_user(user)
|
||||
customer = customer_for_user(user)
|
||||
tenant = reseller is not None or customer is not None
|
||||
context["show_website_usage"] = settings.WEBSITE_USAGE and (
|
||||
tenant or user.has_perm("hosting.view_websiteusage")
|
||||
)
|
||||
context["show_dns_replication"] = bool(
|
||||
settings.DNS_REPLICATION_ADDRESSES
|
||||
)
|
||||
context["show_mail_queue"] = (
|
||||
not tenant
|
||||
and settings.LOCAL_MAILBOX_PROVISIONING
|
||||
and user.has_perm("hosting.view_hostingmaildomain")
|
||||
)
|
||||
manage_resources = reseller is not None and reseller.manage_resources
|
||||
context["reseller_resource_management"] = manage_resources
|
||||
context["reseller_customer_link"] = reseller is not None and (
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.http import Http404
|
||||
from django.shortcuts import redirect
|
||||
from django.utils import timezone
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.generic import DetailView
|
||||
|
||||
from .access import TenantScopeMixin, is_tenant
|
||||
from .independent_websites import active_websites
|
||||
from .models import HostingAccount, HostingMailbox, WebsiteUsage
|
||||
from .sftp import site_is_active
|
||||
from .tasks import collect_mailbox_usage, collect_website_usage
|
||||
|
||||
|
||||
def managed_sites(account):
|
||||
from coulobre.web_node import WebSite
|
||||
|
||||
sites = [website.spec for website in active_websites(account)]
|
||||
if site_is_active(account):
|
||||
sites.insert(0, WebSite(account.pk, account.primary_domain))
|
||||
return sites
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class WebsiteUsageView(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
queryset = HostingAccount.objects.filter(retired_at__isnull=True)
|
||||
context_object_name = "account"
|
||||
customer_relation = "customer"
|
||||
permission_required = (
|
||||
"hosting.view_hostingaccount",
|
||||
"hosting.view_websiteusage",
|
||||
)
|
||||
template_name = "hosting/website_usage.html"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if not settings.WEBSITE_USAGE:
|
||||
raise Http404
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def can_view_mailboxes(self):
|
||||
user = self.request.user
|
||||
return is_tenant(user) or user.has_perm("hosting.view_hostingmailbox")
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
snapshots = {
|
||||
row.node_key: row
|
||||
for row in self.object.website_usage.all()
|
||||
if row.report and row.observed_at
|
||||
}
|
||||
rows = []
|
||||
for site in managed_sites(self.object):
|
||||
snapshot = snapshots.get(site.node_key)
|
||||
rows.append(
|
||||
(
|
||||
site,
|
||||
snapshot
|
||||
if snapshot and snapshot.domain == site.domain
|
||||
else None,
|
||||
)
|
||||
)
|
||||
month = timezone.now().strftime("%Y-%m")
|
||||
report_rows = [
|
||||
reading.report
|
||||
for _, reading in rows
|
||||
if reading and reading.report.get("month") == month
|
||||
]
|
||||
totals = [
|
||||
report["traffic_bytes"]
|
||||
for report in report_rows
|
||||
if report.get("traffic_bytes") is not None
|
||||
]
|
||||
complete = len(totals) == len(rows) and all(
|
||||
not report.get("partial") for report in report_rows
|
||||
)
|
||||
limits = {
|
||||
website.spec.node_key: website.storage_limit_mib
|
||||
for website in active_websites(self.object)
|
||||
}
|
||||
current_limit = getattr(self.object, "storage_limit", None)
|
||||
if (
|
||||
current_limit
|
||||
and current_limit.domain == self.object.primary_domain
|
||||
):
|
||||
limits[str(self.object.pk)] = current_limit.applied_mib
|
||||
return super().get_context_data(
|
||||
sites=[
|
||||
(site, reading, limits.get(site.node_key))
|
||||
for site, reading in rows
|
||||
],
|
||||
month=month,
|
||||
total_traffic=sum(totals) if totals else None,
|
||||
complete=complete,
|
||||
mailboxes=HostingMailbox.objects.filter(
|
||||
mail_domain__account=self.object
|
||||
).select_related("mail_domain")
|
||||
if self.can_view_mailboxes()
|
||||
else None,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
account = self.get_object()
|
||||
with transaction.atomic():
|
||||
account = HostingAccount.objects.select_for_update().get(
|
||||
pk=account.pk
|
||||
)
|
||||
now = timezone.now()
|
||||
for site in managed_sites(account):
|
||||
snapshot, _ = WebsiteUsage.objects.get_or_create(
|
||||
account=account,
|
||||
node_key=site.node_key,
|
||||
defaults={"domain": site.domain},
|
||||
)
|
||||
if (
|
||||
snapshot.domain == site.domain
|
||||
and snapshot.requested_at
|
||||
and snapshot.requested_at > now - timedelta(minutes=1)
|
||||
):
|
||||
continue
|
||||
if snapshot.domain != site.domain:
|
||||
snapshot.report = {}
|
||||
snapshot.observed_at = None
|
||||
snapshot.domain = site.domain
|
||||
snapshot.requested_at = now
|
||||
snapshot.save()
|
||||
transaction.on_commit(
|
||||
lambda pk=snapshot.pk: collect_website_usage.delay(
|
||||
pk, now.isoformat()
|
||||
),
|
||||
robust=True,
|
||||
)
|
||||
if (
|
||||
settings.LOCAL_MAILBOX_PROVISIONING
|
||||
and self.can_view_mailboxes()
|
||||
):
|
||||
mailboxes = HostingMailbox.objects.filter(
|
||||
mail_domain__account=account,
|
||||
provisioning__finished_at__isnull=False,
|
||||
provisioning__problem="",
|
||||
).filter(
|
||||
Q(usage_requested_at__isnull=True)
|
||||
| Q(usage_requested_at__lte=now - timedelta(minutes=1))
|
||||
)
|
||||
for pk in list(mailboxes.values_list("pk", flat=True)):
|
||||
mailboxes.filter(pk=pk).update(usage_requested_at=now)
|
||||
transaction.on_commit(
|
||||
lambda pk=pk: collect_mailbox_usage.delay(
|
||||
pk, now.isoformat()
|
||||
),
|
||||
robust=True,
|
||||
)
|
||||
return redirect("panel:website_usage", pk=account.pk)
|
||||
@@ -1,6 +1,7 @@
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
@@ -102,6 +103,48 @@ class MailboxQuotaUpdate:
|
||||
return {"operation": "set_quota", "mailbox": self.mailbox.manifest()}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MailboxUsageRequest:
|
||||
mailbox: MailboxSpec
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
"operation": "inspect_usage",
|
||||
"mailbox": self.mailbox.manifest(),
|
||||
}
|
||||
|
||||
|
||||
def inspect_mailbox_usage(mailbox):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"/usr/bin/doveadm",
|
||||
"-f",
|
||||
"tab",
|
||||
"quota",
|
||||
"get",
|
||||
"-u",
|
||||
mailbox.address,
|
||||
],
|
||||
stdin=subprocess.DEVNULL,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
check=True,
|
||||
env={"PATH": "/usr/bin:/usr/sbin", "LC_ALL": "C"},
|
||||
)
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
raise ValueError("Dovecot could not measure mailbox usage.") from None
|
||||
values = [
|
||||
fields[2]
|
||||
for line in result.stdout.splitlines()
|
||||
if len(fields := line.split("\t")) == 5 and fields[1] == "STORAGE"
|
||||
]
|
||||
if len(values) != 1 or not values[0].isdigit() or int(values[0]) >= 2**53:
|
||||
raise ValueError("Dovecot returned invalid mailbox usage.")
|
||||
return {"usage_bytes": int(values[0]) * 1024}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MailboxSigningRequest:
|
||||
mailbox: MailboxSpec
|
||||
@@ -124,7 +167,10 @@ class MailboxSigningRequest:
|
||||
|
||||
def parse_mailbox_request(data):
|
||||
from .mail_policy import OPERATIONS, parse_mail_policy
|
||||
from .mail_queue import MailQueueRequest
|
||||
|
||||
if isinstance(data, dict) and data.get("operation") == "inspect_queue":
|
||||
return MailQueueRequest.from_manifest(data)
|
||||
if isinstance(data, dict) and data.get("operation") in OPERATIONS:
|
||||
return parse_mail_policy(data)
|
||||
return parse_retirement(
|
||||
@@ -134,6 +180,10 @@ def parse_mailbox_request(data):
|
||||
|
||||
def parse_mailbox_apply(data):
|
||||
if isinstance(data, dict) and data.keys() == {"operation", "mailbox"}:
|
||||
if data["operation"] == "inspect_usage":
|
||||
return MailboxUsageRequest(
|
||||
MailboxSpec.from_manifest(data["mailbox"])
|
||||
)
|
||||
if data["operation"] == "set_quota":
|
||||
return MailboxQuotaUpdate(
|
||||
MailboxSpec.from_manifest(data["mailbox"])
|
||||
@@ -153,7 +203,12 @@ def mailbox_request_identity(spec):
|
||||
|
||||
def apply_mailbox_request(request):
|
||||
from .mail_policy import MailRouting, MailVacation
|
||||
from .mail_queue import MailQueueRequest, inspect_queue
|
||||
|
||||
if isinstance(request, MailQueueRequest):
|
||||
return inspect_queue(request)
|
||||
if isinstance(request, MailboxUsageRequest):
|
||||
return inspect_mailbox_usage(request.mailbox)
|
||||
if isinstance(request, MailRouting):
|
||||
from .mail_node_routing import apply_routing
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import json
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .domain_names import canonical_domain
|
||||
|
||||
MAX_QUEUE_ROWS = 20000
|
||||
QUEUE_NAMES = ("active", "deferred", "hold", "incoming", "maildrop")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MailQueueRequest:
|
||||
domain: str
|
||||
|
||||
def __post_init__(self):
|
||||
object.__setattr__(self, "domain", canonical_domain(self.domain))
|
||||
|
||||
def manifest(self):
|
||||
return {"operation": "inspect_queue", "domain": self.domain}
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
if data.keys() != {"operation", "domain"}:
|
||||
raise ValueError("Expected a mail queue request.")
|
||||
return cls(data["domain"])
|
||||
|
||||
|
||||
def summarize_queue(lines, domain):
|
||||
counts = dict.fromkeys(QUEUE_NAMES, 0)
|
||||
for index, line in enumerate(lines):
|
||||
if index == MAX_QUEUE_ROWS:
|
||||
return {"counts": counts, "partial": True}
|
||||
if len(line) > 1024 * 1024:
|
||||
raise ValueError("Postfix returned an oversized queue entry.")
|
||||
message = json.loads(line)
|
||||
queue = message["queue_name"]
|
||||
addresses = [
|
||||
message["sender"],
|
||||
*(item["address"] for item in message["recipients"]),
|
||||
]
|
||||
if queue in counts and any(
|
||||
address.rpartition("@")[2].lower() == domain
|
||||
for address in addresses
|
||||
):
|
||||
counts[queue] += 1
|
||||
return {"counts": counts, "partial": False}
|
||||
|
||||
|
||||
def inspect_queue(request):
|
||||
with subprocess.Popen(
|
||||
["/usr/sbin/postqueue", "-j"],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
env={"PATH": "/usr/sbin:/usr/bin", "LC_ALL": "C"},
|
||||
) as process:
|
||||
try:
|
||||
lines = iter(lambda: process.stdout.readline(1024 * 1024 + 1), b"")
|
||||
result = summarize_queue(lines, request.domain)
|
||||
if not result["partial"] and process.wait(timeout=5):
|
||||
raise ValueError("Postfix could not read the mail queue.")
|
||||
return result
|
||||
except (KeyError, TypeError, subprocess.TimeoutExpired) as error:
|
||||
raise ValueError(
|
||||
"Postfix returned an unusable queue report."
|
||||
) from error
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
@@ -208,6 +208,7 @@ except ValueError as error:
|
||||
raise ImproperlyConfigured(f"COULOBRE_SERVICE_HEALTH: {error}") from None
|
||||
|
||||
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
|
||||
WEBSITE_USAGE = os.environ.get("COULOBRE_WEBSITE_USAGE") == "1"
|
||||
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
|
||||
WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1"
|
||||
WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1"
|
||||
@@ -216,11 +217,19 @@ LOCAL_DATABASE_PROVISIONING = (
|
||||
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1"
|
||||
)
|
||||
LOCAL_DNS_PUBLISHING = os.environ.get("COULOBRE_LOCAL_DNS_PUBLISHING") == "1"
|
||||
DNS_REPLICATION_ADDRESSES = ip_addresses_env(
|
||||
"COULOBRE_DNS_REPLICATION_ADDRESSES", 2
|
||||
)
|
||||
if DNS_REPLICATION_ADDRESSES and len(set(DNS_REPLICATION_ADDRESSES)) != 2:
|
||||
raise ImproperlyConfigured(
|
||||
"Set distinct primary and secondary DNS addresses."
|
||||
)
|
||||
LOCAL_MAILBOX_PROVISIONING = (
|
||||
os.environ.get("COULOBRE_LOCAL_MAILBOX_PROVISIONING") == "1"
|
||||
)
|
||||
MAIL_ROUTING = os.environ.get("COULOBRE_MAIL_ROUTING") == "1"
|
||||
MAIL_VACATION = os.environ.get("COULOBRE_MAIL_VACATION") == "1"
|
||||
MAIL_NODE_DKIM = os.environ.get("COULOBRE_MAIL_NODE_DKIM") == "1"
|
||||
REMOTE_MAILBOX_CREDENTIALS = (
|
||||
os.environ.get("COULOBRE_REMOTE_MAILBOX_CREDENTIALS") == "1"
|
||||
)
|
||||
|
||||
@@ -122,8 +122,13 @@ class WebSite:
|
||||
template.substitute(values, max_children=options.worker_limit)
|
||||
+ options.render_overrides()
|
||||
)
|
||||
from .web_node_usage import apache_log_directives
|
||||
|
||||
return template.substitute(
|
||||
values, port=port, tls_settings=tls_settings
|
||||
values,
|
||||
port=port,
|
||||
tls_settings=tls_settings,
|
||||
usage_logs=apache_log_directives(self).rstrip(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -456,7 +456,9 @@ def configuration_installation():
|
||||
|
||||
|
||||
def check_configuration(path, content):
|
||||
if read_root_file(path) != content:
|
||||
from .web_node_usage import without_usage_logs
|
||||
|
||||
if read_root_file(path) not in (content, without_usage_logs(content)):
|
||||
raise ValueError(f"Existing configuration differs at {path}.")
|
||||
|
||||
|
||||
|
||||
@@ -93,7 +93,14 @@ def route_legacy_site(site, paths):
|
||||
for socket in (legacy.socket, paths.route)
|
||||
)
|
||||
actual = read_root_file(config)
|
||||
if actual not in (before, after):
|
||||
from .web_node_usage import without_usage_logs
|
||||
|
||||
if actual not in (
|
||||
before,
|
||||
after,
|
||||
without_usage_logs(before),
|
||||
without_usage_logs(after),
|
||||
):
|
||||
raise ValueError(f"Existing configuration differs at {config}.")
|
||||
if actual != after:
|
||||
changes.append((config, actual, after))
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import argparse
|
||||
import fcntl
|
||||
import gzip
|
||||
import os
|
||||
import stat
|
||||
from collections import deque
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from .node_requests import serve_apply_request
|
||||
from .web_node import WebSite
|
||||
|
||||
LOG_DIRECTORY = Path("/var/log/apache2")
|
||||
MAX_LOG_BYTES = 32 * 1024 * 1024
|
||||
LOG_LINES = 8
|
||||
MAX_LINE = 256
|
||||
|
||||
|
||||
def apache_log_directives(site):
|
||||
prefix = LOG_DIRECTORY / site.service_user
|
||||
return (
|
||||
" <IfDefine COULOBRE_WEBSITE_USAGE>\n"
|
||||
f' ErrorLog "{prefix}.error"\n'
|
||||
f' CustomLog "{prefix}.access" "%{{sec}}t %B %>s %m %U"\n'
|
||||
" </IfDefine>\n"
|
||||
)
|
||||
|
||||
|
||||
def without_usage_logs(configuration):
|
||||
before, marker, after = configuration.partition(
|
||||
" <IfDefine COULOBRE_WEBSITE_USAGE>\n"
|
||||
)
|
||||
return (
|
||||
before + after.partition(" </IfDefine>\n")[2] if marker else before
|
||||
)
|
||||
|
||||
|
||||
def open_log(path):
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
||||
stream = os.fdopen(fd, "rb")
|
||||
info = os.fstat(fd)
|
||||
if (
|
||||
not stat.S_ISREG(info.st_mode)
|
||||
or info.st_uid != 0
|
||||
or info.st_mode & 0o022
|
||||
or info.st_nlink != 1
|
||||
):
|
||||
stream.close()
|
||||
raise ValueError("An Apache usage log has unexpected permissions.")
|
||||
return stream, (info.st_dev, info.st_ino)
|
||||
|
||||
|
||||
def read_site_log(prefix, *, kind, cutoff):
|
||||
base = LOG_DIRECTORY / f"{prefix}.{kind}"
|
||||
logs = [base]
|
||||
logs += [
|
||||
base.with_name(f"{base.name}.{index}{suffix}")
|
||||
for index in range(1, 46)
|
||||
for suffix in ("", ".gz")
|
||||
]
|
||||
seen = set()
|
||||
recent = []
|
||||
traffic = consumed = 0
|
||||
partial = False
|
||||
for path in logs:
|
||||
try:
|
||||
raw, identity = open_log(path)
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
with raw:
|
||||
if identity in seen:
|
||||
continue
|
||||
seen.add(identity)
|
||||
stream = (
|
||||
gzip.GzipFile(fileobj=raw) if path.suffix == ".gz" else raw
|
||||
)
|
||||
tail = deque(maxlen=LOG_LINES)
|
||||
for line in iter(
|
||||
lambda stream=stream: stream.readline(65537), b""
|
||||
):
|
||||
consumed += len(line)
|
||||
if consumed > MAX_LOG_BYTES or len(line) > 65536:
|
||||
partial = True
|
||||
break
|
||||
if not line.endswith(b"\n"):
|
||||
continue
|
||||
if kind == "access":
|
||||
fields = line.split(b" ", 2)
|
||||
if (
|
||||
len(fields) == 3
|
||||
and fields[0].isdigit()
|
||||
and fields[1].isdigit()
|
||||
and int(fields[0]) >= cutoff
|
||||
):
|
||||
traffic += int(fields[1])
|
||||
if len(recent) < LOG_LINES:
|
||||
tail.append(
|
||||
line[:MAX_LINE]
|
||||
.decode("utf-8", errors="replace")
|
||||
.strip()
|
||||
)
|
||||
recent.extend(reversed(tail))
|
||||
if partial or (kind == "error" and len(recent) >= LOG_LINES):
|
||||
break
|
||||
return traffic, recent[:LOG_LINES], partial
|
||||
|
||||
|
||||
def inspect_site(site):
|
||||
from . import web_node_apply as web
|
||||
from .web_node_storage import measure_website_storage
|
||||
|
||||
with web.locked_web_node(fcntl.LOCK_SH):
|
||||
web.check_reservation(site)
|
||||
config = web.read_root_file(web.SitePaths.for_site(site).apache)
|
||||
enabled = apache_log_directives(site) in config
|
||||
month_start = datetime.now(UTC).replace(
|
||||
day=1, hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
cutoff = int(month_start.timestamp())
|
||||
traffic, access, partial = read_site_log(
|
||||
site.service_user, kind="access", cutoff=cutoff
|
||||
)
|
||||
_, errors, _ = read_site_log(
|
||||
site.service_user, kind="error", cutoff=cutoff
|
||||
)
|
||||
return {
|
||||
"month": month_start.strftime("%Y-%m"),
|
||||
"traffic_bytes": traffic if enabled or access else None,
|
||||
"storage_bytes": measure_website_storage(site),
|
||||
"access_lines": access,
|
||||
"error_lines": errors,
|
||||
"partial": partial,
|
||||
}
|
||||
|
||||
|
||||
def pending_log_changes(site):
|
||||
from . import web_node_apply as web
|
||||
from .web_node_aliases import alias_directory, alias_paths, read_alias
|
||||
from .web_node_tls import https_paths, render_https_configuration
|
||||
|
||||
paths = web.SitePaths.for_site(site)
|
||||
targets = [
|
||||
(paths.apache, site, False),
|
||||
(https_paths(paths)[0], site, True),
|
||||
]
|
||||
directory = alias_directory()
|
||||
if directory.is_dir():
|
||||
web.require_root_directory(directory)
|
||||
for marker in directory.glob("*.json"):
|
||||
alias = read_alias(marker)
|
||||
if alias.site == site:
|
||||
targets.extend(
|
||||
(alias_paths(alias, https=tls)[0], alias, tls)
|
||||
for tls in (False, True)
|
||||
)
|
||||
for path, resource, tls in targets:
|
||||
if not os.path.lexists(path):
|
||||
continue
|
||||
current = web.read_root_file(path)
|
||||
socket = paths.apache_socket
|
||||
desired = (
|
||||
render_https_configuration(resource, socket_path=socket)
|
||||
if tls
|
||||
else resource.render("apache", socket_path=socket)
|
||||
)
|
||||
if current != desired:
|
||||
web.check_configuration(path, desired)
|
||||
yield path, current, desired
|
||||
|
||||
|
||||
def install_usage_logs():
|
||||
import json
|
||||
|
||||
from . import web_node_apply as web
|
||||
from .node_files import replace_configuration
|
||||
from .web_node_runtime import reload_apache
|
||||
|
||||
if not web.STATE_DIRECTORY.exists():
|
||||
return
|
||||
with web.locked_web_node(fcntl.LOCK_EX):
|
||||
changes = []
|
||||
for path in web.STATE_DIRECTORY.glob("*.json"):
|
||||
site = WebSite.from_manifest(json.loads(web.read_root_file(path)))
|
||||
web.check_reservation(site)
|
||||
changes.extend(pending_log_changes(site))
|
||||
updated = []
|
||||
try:
|
||||
for path, current, desired in changes:
|
||||
replace_configuration(path, desired)
|
||||
updated.append((path, current))
|
||||
if updated:
|
||||
reload_apache()
|
||||
except (OSError, ValueError, KeyboardInterrupt):
|
||||
for path, current in reversed(updated):
|
||||
replace_configuration(path, current)
|
||||
reload_apache()
|
||||
raise
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description="Read hosted website usage.")
|
||||
parser.add_argument(
|
||||
"command", choices=("inspect-request", "enable-existing")
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
if args.command == "inspect-request":
|
||||
return serve_apply_request(
|
||||
1, WebSite.from_manifest, inspect_site, include_result=True
|
||||
)
|
||||
try:
|
||||
install_usage_logs()
|
||||
except (OSError, ValueError) as error:
|
||||
parser.exit(1, f"Coulobre website usage: {error}\n")
|
||||
return 0
|
||||
Reference in new issue
Block a user