Complete public hosting operations for Coulobre v0.9 #116

Merged
parkel merged 4 commits from feature/public-hosting-0.9 into main 2026-11-22 19:33:09 +01:00
41 changed files with 2042 additions and 44 deletions
Showing only changes of commit 9e66510f7c - Show all commits

No files matched your search

@@ -0,0 +1 @@
Define COULOBRE_WEBSITE_USAGE
+13
View File
@@ -0,0 +1,13 @@
/var/log/apache2/coulobre-*.access /var/log/apache2/coulobre-*.error {
daily
rotate 45
missingok
notifempty
compress
delaycompress
create 0640 root adm
sharedscripts
postrotate
/usr/bin/systemctl reload apache2.service
endscript
}
+10
View File
@@ -21,3 +21,13 @@ mode = "off"
# A local mail role requires host, certificate, and key.
# A remote DNS or mail role requires mode = "remote", host, and host_key.
# Use port = 22 or the separate node's configured SSH port.
# For Let's Encrypt on the panel, use access = "acme" in [panel] and omit
# certificate and key. For new local mail, add tls = "acme" to request
# its own certificate, or use tls = "provided" with both file paths.
# To install a role on a prepared external host, set mode = "remote-install".
# In addition to host, host_key, and optional port, provide ssh_user and
# ssh_identity. ssh_identity is a root-owned 0600 file on the panel host.
# For remote mail installation, set mail_hostname to the public service
# hostname. Provide tls = "acme" or certificate and key paths on that host.
+84
View File
@@ -0,0 +1,84 @@
from hashlib import sha256
from pathlib import Path
from . import engine
from .config import certificate
WEBROOT = Path("/var/lib/coulobre-acme")
HOOK_DIRECTORY = Path("/etc/letsencrypt/renewal-hooks/deploy")
def configure_webroot(hosts, panel_host):
engine.root_directory(WEBROOT)
vhosts = []
for host in sorted(hosts):
redirect = ""
if host == panel_host:
redirect = (
' RedirectMatch permanent "^/(?!\\.well-known/'
'acme-challenge/)(.*)$" '
f'"https://{host}/$1"\n'
)
vhosts.append(
f"<VirtualHost *:80>\n ServerName {host}\n"
f' DocumentRoot "{WEBROOT}"\n'
f' <Directory "{WEBROOT}">\n'
" Options None\n AllowOverride None\n"
" Require all denied\n </Directory>\n"
f' <Directory "{WEBROOT}/.well-known/acme-challenge">\n'
" Require all granted\n </Directory>\n"
f"{redirect}</VirtualHost>\n"
)
engine.put_file(
Path("/etc/apache2/sites-available/001-coulobre-acme.conf"),
"\n".join(vhosts),
)
engine.run("a2enmod", "alias", label="Enable Apache redirects")
engine.run(
"a2ensite", "001-coulobre-acme.conf", label="Enable ACME challenges"
)
engine.run(
"apache2ctl", "configtest", label="Validate the ACME virtual hosts"
)
engine.systemctl("enable", "--now", "apache2.service")
engine.systemctl("reload", "apache2.service")
def issue(host, email, services, *, webroot=False):
method = ("--webroot", "-w", WEBROOT) if webroot else ("--standalone",)
engine.run(
"certbot",
"certonly",
"--non-interactive",
"--agree-tos",
"--email",
email,
"--cert-name",
host,
"--keep-until-expiring",
"--domains",
host,
*method,
label=f"Issue the certificate for {host}. Check /var/log/letsencrypt",
timeout=600,
)
directory = Path("/etc/letsencrypt/live") / host
certificate(
{
"certificate": str(directory / "fullchain.pem"),
"key": str(directory / "privkey.pem"),
},
host,
)
for parent in (HOOK_DIRECTORY.parent, HOOK_DIRECTORY):
engine.root_directory(parent)
fingerprint = sha256(host.encode("ascii")).hexdigest()[:24]
engine.put_file(
HOOK_DIRECTORY / f"coulobre-{fingerprint}",
"#!/bin/sh\n"
f'[ "${{RENEWED_LINEAGE:-}}" = "{directory}" ] || exit 0\n'
"exec /usr/bin/systemctl try-reload-or-restart "
f"{' '.join(services)}\n",
mode=0o755,
)
engine.systemctl("enable", "--now", "certbot.timer")
+23 -7
View File
@@ -4,6 +4,7 @@ import sys
from getpass import getpass
from .config import (
REMOTE_MODES,
InstallError,
check_password,
parse_plan,
@@ -28,7 +29,9 @@ def number(value, label):
def interactive_plan():
panel = {"hostname": prompt("Panel hostname")}
access = panel["access"] = prompt("Panel access (tls or proxy)", "tls")
access = panel["access"] = prompt(
"Panel access (tls, acme, or proxy)", "tls"
)
if access == "tls":
panel["certificate"] = prompt("Panel certificate path")
panel["key"] = prompt("Panel private key path")
@@ -46,9 +49,12 @@ def interactive_plan():
},
}
for name in ("dns", "mail"):
mode = prompt(f"{name.upper()} role (off, local, or remote)", "off")
mode = prompt(
f"{name.upper()} role (off, local, remote, or remote-install)",
"off",
)
target = data[name] = {"mode": mode}
if mode == "remote":
if mode in REMOTE_MODES:
target["host"] = prompt(
f"{name.upper()} node SSH hostname or address"
)
@@ -56,10 +62,20 @@ def interactive_plan():
prompt("SSH port", "22"), f"the {name} node"
)
target["host_key"] = prompt("Verified SSH host public key file")
elif name == "mail" and mode == "local":
target["host"] = prompt("Local mail hostname")
target["certificate"] = prompt("Mail certificate path")
target["key"] = prompt("Mail private key path")
if mode == "remote-install":
target["ssh_user"] = prompt("SSH administrator username")
target["ssh_identity"] = prompt(
"SSH administrator private key file"
)
if name == "mail" and mode in {"local", "remote-install"}:
field = "host" if mode == "local" else "mail_hostname"
target[field] = prompt("Public mail hostname")
target["tls"] = prompt("Mail TLS (provided or acme)", "provided")
if target["tls"] == "provided":
target["certificate"] = prompt(
"Certificate path on the mail host"
)
target["key"] = prompt("Private key path on the mail host")
return parse_plan(data)
+77 -8
View File
@@ -16,7 +16,9 @@ PLATFORMS = {
DNS_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")
FILE_PATH = re.compile(r"/[a-zA-Z0-9_./+-]+")
USERNAME = re.compile(r"[a-zA-Z0-9@.+_-]{1,150}")
SSH_USERNAME = re.compile(r"[a-z_][a-z0-9_-]{0,31}")
EMAIL = re.compile(r"[^\s@]+@[^\s@]+\.[^\s@]+")
REMOTE_MODES = {"remote", "remote-install"}
class InstallError(Exception):
@@ -103,6 +105,22 @@ def certificate(table, label):
return chain, key
def tls_files(table, host, label, *, remote=False):
if table.get("tls", "provided") == "acme":
if "certificate" in table or "key" in table:
raise InstallError(f"Choose one certificate source for {label}.")
directory = Path("/etc/letsencrypt/live") / host
return str(directory / "fullchain.pem"), str(directory / "privkey.pem")
if table.get("tls", "provided") != "provided":
raise InstallError(f"Choose provided or acme TLS for {label}.")
if remote:
return (
file_path(table.get("certificate"), f"the {label} certificate"),
file_path(table.get("key"), f"the {label} certificate key"),
)
return certificate(table, label)
@dataclass(frozen=True)
class Role:
mode: str
@@ -111,6 +129,10 @@ class Role:
host_key: str = ""
certificate: str = ""
key: str = ""
mail_hostname: str = ""
tls: str = "provided"
ssh_user: str = ""
ssh_identity: str = ""
def role(table, name):
@@ -121,12 +143,24 @@ def role(table, name):
keys(table, {"mode"}, name)
return Role(mode)
if mode == "local":
keys(table, {"mode", "host", "certificate", "key"}, name)
keys(table, {"mode", "host", "certificate", "key", "tls"}, name)
host = hostname(table.get("host"), "mail")
chain, key = certificate(table, "mail")
return Role(mode, host=host, certificate=chain, key=key)
if mode == "remote":
keys(table, {"mode", "host", "host_key", "port"}, name)
chain, key = tls_files(table, host, "mail")
return Role(
mode,
host=host,
certificate=chain,
key=key,
mail_hostname=host,
tls=table.get("tls", "provided"),
)
if mode in REMOTE_MODES:
allowed = {"mode", "host", "host_key", "port"}
if mode == "remote-install":
allowed |= {"ssh_user", "ssh_identity"}
if name == "mail":
allowed |= {"mail_hostname", "tls", "certificate", "key"}
keys(table, allowed, name)
host = table.get("host")
try:
normalized = address(host, f"the {name} node")
@@ -144,13 +178,40 @@ def role(table, name):
raise InstallError(
f"Read the pinned {name} SSH public key."
) from None
options = {}
if mode == "remote-install":
user = table.get("ssh_user")
if not isinstance(user, str) or not SSH_USERNAME.fullmatch(user):
raise InstallError(
f"Enter a valid SSH administrator for {name}."
)
options = {
"ssh_user": user,
"ssh_identity": file_path(
table.get("ssh_identity"), f"the {name} SSH private key"
),
}
if name == "mail":
mail_host = hostname(table.get("mail_hostname"), "mail")
chain, private_key = tls_files(
table, mail_host, "mail", remote=True
)
options.update(
mail_hostname=mail_host,
tls=table.get("tls", "provided"),
certificate=chain,
key=private_key,
)
return Role(
mode,
host=normalized,
port=port(table.get("port"), f"the {name} node", 22),
host_key=host_key,
**options,
)
raise InstallError(f"Choose off, local, or remote for {name}.")
raise InstallError(
f"Choose off, local, remote, or remote-install for {name}."
)
@dataclass(frozen=True)
@@ -168,9 +229,14 @@ class Plan:
mail: Role
def description(self):
def target(role):
if role.mode in REMOTE_MODES:
return f"{role.mode} ({role.host}, SSH port {role.port})"
return role.mode
return (
f"https://{self.hostname}/ · {self.access} · "
f"DNS {self.dns.mode} · mail {self.mail.mode} · "
f"DNS {target(self.dns)} · mail {target(self.mail)} · "
f"Administrator {self.admin_username}"
)
@@ -202,6 +268,9 @@ def parse_plan(data):
if access == "tls":
keys(panel, {"hostname", "access", "certificate", "key"}, "panel")
chain, key = certificate(panel, "the panel")
elif access == "acme":
keys(panel, {"hostname", "access"}, "panel")
chain, key = tls_files({"tls": "acme"}, host, "the panel")
elif access == "proxy":
keys(
panel,
@@ -218,7 +287,7 @@ def parse_plan(data):
"Use a separate origin port for the reverse proxy."
)
else:
raise InstallError("Choose tls or proxy for panel access.")
raise InstallError("Choose tls, acme, or proxy for panel access.")
return Plan(
host,
access,
+78 -5
View File
@@ -14,8 +14,8 @@ from contextlib import contextmanager
from pathlib import Path
from tempfile import TemporaryDirectory
from . import roles
from .config import InstallError, platform_settings
from . import certificates, roles
from .config import REMOTE_MODES, InstallError, platform_settings
SOURCE = Path(__file__).resolve().parents[2]
ASSETS = SOURCE / "deploy"
@@ -357,12 +357,47 @@ class Installer:
packages.extend(("bind9", "bind9-utils"))
if self.plan.mail.mode == "local":
packages.extend(
("postfix", "dovecot-core", "dovecot-imapd", "dovecot-lmtpd")
(
"postfix",
"dovecot-core",
"dovecot-imapd",
"dovecot-lmtpd",
"rspamd",
"redis-server",
)
)
if "remote" in (self.plan.dns.mode, self.plan.mail.mode):
if REMOTE_MODES.intersection(
(self.plan.dns.mode, self.plan.mail.mode)
):
packages.extend(("openssh-client", "socat"))
if self.plan.access == "acme" or (
self.plan.mail.mode == "local" and self.plan.mail.tls == "acme"
):
packages.append("certbot")
return packages
def install_certificates(self):
services = {}
if self.plan.access == "acme":
services[self.plan.hostname] = ["apache2.service"]
mail = self.plan.mail
if mail.mode == "local" and mail.tls == "acme":
services.setdefault(mail.host, []).extend(
("postfix.service", "dovecot.service")
)
if services:
self.progress(
"Requesting the selected Let's Encrypt certificates."
)
panel_host = (
self.plan.hostname if self.plan.access != "proxy" else ""
)
certificates.configure_webroot(services, panel_host)
for host, units in services.items():
certificates.issue(
host, self.plan.admin_email, units, webroot=True
)
def configure_stores(self):
put_file(
Path("/etc/mysql/mariadb.conf.d/90-coulobre-loopback.cnf"),
@@ -493,10 +528,13 @@ class Installer:
}
if self.php:
options["COULOBRE_LOCAL_WEB_ACTIVATION"] = "1"
options["COULOBRE_WEBSITE_USAGE"] = "1"
if self.plan.dns.mode != "off":
options["COULOBRE_LOCAL_DNS_PUBLISHING"] = "1"
if self.plan.mail.mode != "off":
options["COULOBRE_LOCAL_MAILBOX_PROVISIONING"] = "1"
if self.plan.mail.mode in {"local", "remote-install"}:
options["COULOBRE_MAIL_NODE_DKIM"] = "1"
return "".join(f"{key}={value}\n" for key, value in options.items())
def prepare_panel(self):
@@ -560,7 +598,7 @@ class Installer:
modules.append("proxy_fcgi")
systemctl("enable", "--now", f"php{self.php}-fpm.service")
plan = self.plan
if plan.access == "tls":
if plan.access in {"acme", "tls"}:
modules.append("ssl")
config = (ASSETS / "apache/panel-tls.conf.example").read_text()
config = (
@@ -570,6 +608,8 @@ class Installer:
)
.replace("/etc/ssl/coulobre-panel/privkey.pem", plan.key)
)
if plan.access == "acme":
config = config[config.index("<VirtualHost *:443>") :]
else:
modules.append("remoteip")
local = (
@@ -641,6 +681,7 @@ class Installer:
mail_host=mail.host if mail.mode == "local" else "",
)
install_release(self.release)
self.install_certificates()
self.progress("Preparing MariaDB and RabbitMQ on loopback.")
self.configure_stores()
self.progress(
@@ -663,6 +704,38 @@ class Installer:
"coulobre-provisioner.service",
)
)
group("coulobre-usage-requests")
install_unit("coulobre-website-usage.socket")
install_unit("coulobre-website-usage@.service")
drop_in = SYSTEMD / "coulobre-provisioner.service.d"
root_directory(drop_in)
put_file(
drop_in / "website-usage.conf",
(
ASSETS
/ "systemd"
/ drop_in.name
/ "website-usage.conf"
).read_text(),
)
put_file(
Path("/etc/logrotate.d/coulobre-websites"),
(ASSETS / "logrotate/coulobre-websites").read_text(),
)
put_file(
Path(
"/etc/apache2/conf-available/coulobre-website-usage.conf"
),
(
ASSETS / "apache/coulobre-website-usage.conf"
).read_text(),
)
run(
"a2enconf",
"coulobre-website-usage",
label="Enable website usage logging",
)
workers.append("coulobre-website-usage.socket")
for name in ("dns", "mail"):
target = getattr(self.plan, name)
if target.mode != "off":
+202
View File
@@ -0,0 +1,202 @@
import io
import json
import os
import shlex
import tarfile
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from . import certificates, engine, roles
from .config import InstallError, certificate, platform_settings
BOOTSTRAP = """set -eu
umask 077
work=$(mktemp -d /var/tmp/coulobre-node.XXXXXXXX)
trap 'rm -rf -- "$work"' EXIT
cd "$work"
tar --extract --gzip --no-same-owner --no-same-permissions
/usr/bin/flock -n /run/lock/coulobre-bootstrap.lock \\
/usr/bin/python3 -m deploy.panel_installer.remote
"""
SOURCE_ITEMS = (
"pyproject.toml",
"MANIFEST.in",
"README.md",
"LICENSE",
"src",
"deploy",
)
NODE_STATE = Path("/var/lib/coulobre-node-bootstrap")
def source_member(member):
path = Path(member.name)
if any(
part.startswith(".") or part == "__pycache__" for part in path.parts
):
return None
if not (member.isdir() or member.isfile()):
raise InstallError("Use an unpacked, verified source distribution.")
return member
def bootstrap_archive(settings):
output = io.BytesIO()
payload = json.dumps(settings).encode()
config = tarfile.TarInfo("node-settings.json")
config.size, config.mode = len(payload), 0o600
with tarfile.open(fileobj=output, mode="w:gz") as archive:
for name in SOURCE_ITEMS:
archive.add(
engine.SOURCE / name, arcname=name, filter=source_member
)
archive.addfile(config, io.BytesIO(payload))
return output.getvalue()
def install(name, target, email):
identity = Path(target.ssh_identity)
engine.root_file(identity, 0o600)
host_read = Path(target.host_key).read_text(encoding="ascii").split()
if len(host_read) < 2:
raise InstallError("Supply a verified SSH host key.")
host_key = " ".join(host_read[:2])
public = Path(f"/etc/coulobre-remote/{name}/id_ed25519.pub").read_text()
settings = {
"role": name,
"panel_key": public,
"email": email,
"hostname": target.mail_hostname,
"tls": target.tls,
"certificate": target.certificate,
"key": target.key,
}
host = (
target.host if target.port == 22 else f"[{target.host}]:{target.port}"
)
with TemporaryDirectory(prefix="coulobre-ssh-") as directory:
known_hosts = Path(directory) / "known_hosts"
known_hosts.write_text(f"{host} {host_key}\n")
engine.run(
"ssh",
"-F",
"/dev/null",
"-T",
"-p",
str(target.port),
"-l",
target.ssh_user,
"-i",
identity,
"-o",
"BatchMode=yes",
"-o",
"IdentitiesOnly=yes",
"-o",
"IdentityAgent=none",
"-o",
"ConnectTimeout=15",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"GlobalKnownHostsFile=/dev/null",
"-o",
f"UserKnownHostsFile={known_hosts}",
"--",
target.host,
shlex.join(("sudo", "-n", "/bin/sh", "-c", BOOTSTRAP)),
source=bootstrap_archive(settings),
label=(
f"Install the remote {name} node. "
"Check administrator SSH, sudo and the node logs"
),
timeout=3600,
)
def prepare_node(settings):
name = settings["role"]
_, modern_mail = platform_settings()
packages = ["rspamd", "redis-server"] if name == "mail" else []
if name == "mail" and settings["tls"] == "acme":
packages.append("certbot")
engine.run(
"/bin/sh",
engine.ASSETS / "install-node.sh",
name,
label=f"Install the {name} node packages and receiver",
timeout=2400,
env={"DEBIAN_FRONTEND": "noninteractive"},
)
if name == "dns":
roles.configure_dns()
else:
target = SimpleNamespace(
host=settings["hostname"],
**{field: settings[field] for field in ("certificate", "key")},
)
engine.install_packages(packages)
if settings["tls"] == "acme":
certificates.issue(
target.host,
settings["email"],
("postfix.service", "dovecot.service"),
)
certificate(
{"certificate": target.certificate, "key": target.key}, "mail"
)
roles.configure_mail(target, modern_mail)
def install_on_node(settings):
name = settings["role"]
if name not in roles.WORKERS:
raise InstallError("Choose a supported node role.")
engine.root_directory(NODE_STATE, mode=0o700)
state_file = NODE_STATE / f"{name}.json"
requested = {
field: settings[field]
for field in (
"hostname",
"tls",
"certificate",
"key",
)
}
if os.path.lexists(state_file):
engine.root_file(state_file, 0o600)
state = json.loads(state_file.read_text())
if requested != state["configuration"]:
raise InstallError("Use the settings of the configured node.")
else:
state = {"configuration": requested, "complete": False}
engine.put_file(state_file, json.dumps(state), mode=0o600)
if not state["complete"]:
prepare_node(settings)
node_setup = engine.BINDIR / "coulobre-node-setup"
engine.run(
node_setup, "check-receiver", name, label=f"Check the {name} receiver"
)
if not state["complete"]:
state["complete"] = True
engine.put_file(state_file, json.dumps(state), mode=0o600, update=True)
with TemporaryDirectory(prefix="coulobre-panel-key-") as directory:
key = Path(directory) / "panel.pub"
key.write_text(settings["panel_key"])
engine.run(
node_setup,
"authorize-panel",
name,
key,
label=f"Authorize the panel for {name}",
)
if __name__ == "__main__":
if os.geteuid() != 0:
raise SystemExit("Run the node installer as root.")
try:
install_on_node(json.loads(Path("node-settings.json").read_text()))
except (OSError, ValueError, InstallError) as error:
raise SystemExit(str(error)) from None
+18 -3
View File
@@ -3,7 +3,7 @@ import os
from pathlib import Path
from . import engine
from .config import InstallError
from .config import REMOTE_MODES, InstallError
WORKERS = {
"dns": (
@@ -119,6 +119,8 @@ def configure_dns():
def configure_mail(target, modern):
from . import submission
vmail = engine.identity("coulobre-vmail", home="/srv/coulobre-mail")
dovecot = engine.group("dovecot")
ensure_table(Path("/etc/postfix/coulobre-domains"), mode=0o644)
@@ -182,7 +184,11 @@ def configure_mail(target, modern):
uid=vmail.pw_uid,
)
replace_stock_config(
Path("/etc/dovecot/dovecot.conf"), "dovecot-core", dovecot_config
Path("/etc/dovecot/dovecot.conf"),
"dovecot-core",
dovecot_config.rstrip()
+ "\n\n"
+ (engine.ASSETS / "dovecot/submission-auth.conf.example").read_text(),
)
engine.run("doveconf", "-n", label="Validate the Dovecot configuration")
engine.run(
@@ -191,6 +197,8 @@ def configure_mail(target, modern):
*(f"{key}={value}" for key, value in config.items()),
label="Configure Postfix mailbox delivery",
)
engine.systemctl("enable", "--now", "redis-server.service")
submission.configure()
engine.run("postfix", "check", label="Validate the Postfix configuration")
engine.systemctl("enable", "--now", "postfix.service", "dovecot.service")
engine.systemctl("restart", "postfix.service", "dovecot.service")
@@ -198,7 +206,7 @@ def configure_mail(target, modern):
def configure_role(installer, name, target):
group, worker, receiver, unit = WORKERS[name]
if target.mode == "remote":
if target.mode in REMOTE_MODES:
node_setup = engine.BINDIR / "coulobre-node-setup"
engine.run(
node_setup,
@@ -206,6 +214,13 @@ def configure_role(installer, name, target):
name,
label=f"Prepare the panel's public key for the {name} node",
)
if target.mode == "remote-install":
from . import remote
installer.progress(
f"Installing the remote {name} node at {target.host}."
)
remote.install(name, target, installer.plan.admin_email)
installer.progress(
f"Checking the remote {name} node. Panel key: "
f"/etc/coulobre-remote/{name}/id_ed25519.pub"
+171
View File
@@ -0,0 +1,171 @@
import argparse
import grp
import json
import os
import subprocess
from pathlib import Path
from . import engine, roles
from .config import InstallError, address, platform_settings
BIND = Path("/etc/bind")
KEY_PATH = BIND / "coulobre-transfer.key"
def configuration(role, peer):
from coulobre.dns_catalog import CATALOG, KEY, PATH
server = f'{peer} key "{KEY}";'
if role == "primary":
options = (
f' allow-transfer {{ key "{KEY}"; }};\n'
f" also-notify {{ {server} }};\n"
)
zone = (
f'zone "{CATALOG}" {{\n'
f' type primary; file "{PATH}";\n'
f' allow-query {{ key "{KEY}"; }};\n'
"};\n"
)
else:
options = (
" allow-transfer { none; };\n"
f' allow-notify {{ key "{KEY}"; }};\n'
f' catalog-zones {{ zone "{CATALOG}" '
f"default-primaries {{ {server} }} "
'zone-directory "/var/cache/bind" min-update-interval 5; };\n'
)
zone = (
f'zone "{CATALOG}" {{\n'
f" type secondary; primaries {{ {server} }};\n"
' file "/var/cache/bind/coulobre-catalog";\n'
" allow-query { none; };\n"
"};\n"
)
base = roles.BIND_CONFIG.replace(
" allow-transfer { none; };\n", options
)
return f'include "{KEY_PATH}";\n' + base + zone
def seed_catalog():
from coulobre.dns_catalog import PATH, render_catalog
from coulobre.dns_node_apply import (
ZONE_DIRECTORY,
check_registration,
file_serial,
zone_configuration,
)
from coulobre.domain_names import canonical_domain
from coulobre.node_files import read_root_file
engine.root_directory(PATH.parent)
if PATH.exists():
engine.root_file(PATH, 0o644)
return
members = set()
for path in ZONE_DIRECTORY.iterdir():
if not path.is_file() or path.name.startswith("."):
continue
domain = canonical_domain(path.name)
file_serial(domain, read_root_file(path, mode=0o644))
if check_registration(domain, zone_configuration(path)):
members.add(domain)
engine.put_file(PATH, render_catalog(1, members))
def setup(role, peer):
from coulobre.dns_catalog import PATH
from coulobre.dns_node_apply import ZONE_DIRECTORY
from coulobre.node_files import locked_root_directory
with locked_root_directory(ZONE_DIRECTORY):
seeded = PATH.exists()
try:
install_configuration(role, peer)
except (OSError, ValueError, InstallError):
if not seeded and role == "primary":
PATH.unlink(missing_ok=True)
raise
def install_configuration(role, peer):
root = BIND / "named.conf"
engine.root_file(root, 0o644)
current = root.read_text()
wanted = configuration(role, peer)
if current not in (roles.BIND_CONFIG, wanted):
raise InstallError(
"Use a dedicated Coulobre-managed DNS configuration."
)
engine.root_file(KEY_PATH, 0o640)
if KEY_PATH.stat().st_gid != grp.getgrnam("bind").gr_gid:
raise InstallError("Give the bind group read access to the TSIG key.")
if role == "primary":
seed_catalog()
else:
from coulobre.dns_node_apply import ZONE_DIRECTORY
if any(
path.is_file() and not path.name.startswith(".")
for path in ZONE_DIRECTORY.iterdir()
):
raise InstallError(
"Use a separate DNS host without managed primary zones."
)
engine.put_file(root, wanted, group=root.stat().st_gid, update=True)
try:
engine.run(
"named-checkconf", label="Validate the DNS catalog configuration"
)
engine.run(
"rndc",
"-s",
"127.0.0.1",
"reconfig",
label="Load the DNS catalog configuration",
)
except InstallError:
engine.put_file(root, current, group=root.stat().st_gid, update=True)
raise
def main():
parser = argparse.ArgumentParser(
description="Configure a Coulobre DNS catalog node."
)
parser.add_argument("role", choices=("primary", "secondary"))
parser.add_argument(
"peer", help="The other node address used for DNS transfers"
)
args = parser.parse_args()
try:
if os.geteuid() != 0:
raise InstallError("Run DNS catalog setup as root.")
platform_settings()
peer = address(args.peer, "the other DNS node")
addresses = json.loads(
engine.run("ip", "-j", "address", label="Check DNS node addresses")
)
if any(
peer == item.get("local")
for interface in addresses
for item in interface.get("addr_info", ())
):
raise InstallError("Choose a DNS peer on a different host.")
if args.role == "secondary" and (
BIND / "named.conf"
).read_text() != configuration(args.role, peer):
roles.configure_dns()
setup(args.role, peer)
except (
InstallError,
OSError,
ValueError,
subprocess.SubprocessError,
) as error:
parser.exit(1, f"Coulobre DNS catalog: {error}\n")
if __name__ == "__main__":
main()
+148
View File
@@ -0,0 +1,148 @@
import os
import pwd
import stat
import time
from pathlib import Path
from . import engine
from .config import InstallError
RSPAMD = Path("/etc/rspamd")
MILTER_DIRECTORY = Path("/var/spool/postfix/coulobre-rspamd")
def prepare_milter_directory(signer_uid):
postfix = engine.group("postfix")
engine.root_directory(MILTER_DIRECTORY.parent)
if not os.path.lexists(MILTER_DIRECTORY):
MILTER_DIRECTORY.mkdir(mode=0o750)
os.chown(MILTER_DIRECTORY, signer_uid, postfix.gr_gid)
MILTER_DIRECTORY.chmod(0o2750)
info = MILTER_DIRECTORY.lstat()
if not stat.S_ISDIR(info.st_mode) or (
info.st_uid,
info.st_gid,
stat.S_IMODE(info.st_mode),
) != (signer_uid, postfix.gr_gid, 0o2750):
raise InstallError(
"Check the ownership of the submission socket directory."
)
def wait_for_milter():
path = MILTER_DIRECTORY / "submit.sock"
for _ in range(90):
try:
if stat.S_ISSOCK(path.lstat().st_mode):
return
except FileNotFoundError:
pass
time.sleep(0.5)
raise InstallError("The Rspamd submission socket did not start.")
def configure():
bindings = engine.run(
"redis-cli",
"--raw",
"-h",
"127.0.0.1",
"CONFIG",
"GET",
"bind",
label="Check the local rate-limit cache",
).split()
if (
len(bindings) < 2
or bindings[0] != "bind"
or any(
address.lstrip("-") not in {"127.0.0.1", "::1"}
for address in bindings[1:]
)
):
raise InstallError("Bind the rate-limit cache to loopback.")
configs = {
"override.d/dkim_signing.conf": "dkim_signing.conf.example",
"override.d/worker-normal.inc": "worker-disabled.inc.example",
"override.d/worker-controller.inc": "worker-disabled.inc.example",
"override.d/worker-proxy.inc": "worker-submission.inc",
}
for path, filename in configs.items():
engine.put_file(
RSPAMD / path, (engine.ASSETS / "rspamd" / filename).read_text()
)
engine.put_file(
RSPAMD / "local.d/settings.conf",
"coulobre_submission {\n"
" authenticated = true;\n apply {\n"
' symbols_enabled = ["DKIM_SIGNED", "RATELIMIT_CHECK", '
'"RATELIMIT_UPDATE"];\n'
" }\n}\n",
)
rate_file = RSPAMD / "local.d/ratelimit.conf"
if not os.path.lexists(rate_file):
engine.put_file(
rate_file,
(
'servers = "127.0.0.1:6379";\n'
"rates {\n user {\n bucket {\n"
' burst = 30;\n rate = "120 / 1h";\n'
" }\n }\n}\n"
),
)
engine.root_file(rate_file, 0o644)
keys = RSPAMD / "coulobre-dkim"
signer = engine.group("_rspamd")
if not os.path.lexists(keys):
keys.mkdir(mode=0o750)
os.chown(keys, 0, signer.gr_gid)
engine.root_directory(keys)
if (
keys.stat().st_gid != signer.gr_gid
or keys.stat().st_mode & 0o777 != 0o750
):
raise InstallError(
"Set the DKIM directory to mode 0750 and the Rspamd group."
)
prepare_milter_directory(pwd.getpwnam("_rspamd").pw_uid)
engine.put_file(
Path("/etc/postfix/coulobre-submission-logins"),
"/^([a-zA-Z0-9_.-]+@[a-zA-Z0-9.-]+)$/ $1\n",
)
engine.run(
"rspamadm",
"configtest",
label="Validate the signing and rate-limit configuration",
)
engine.systemctl("enable", "--now", "rspamd.service")
engine.systemctl("restart", "rspamd.service")
wait_for_milter()
engine.run(
"postconf",
"-M",
"submission/inet=submission inet n - y - - smtpd",
label="Enable the TLS submission service",
)
login_map = "regexp:/etc/postfix/coulobre-submission-logins"
sender_check = "reject_authenticated_sender_login_mismatch"
milter = "{unix:coulobre-rspamd/submit.sock,default_action=tempfail}"
options = {
"smtpd_tls_security_level": "encrypt",
"smtpd_tls_auth_only": "yes",
"smtpd_sasl_auth_enable": "yes",
"smtpd_sasl_type": "dovecot",
"smtpd_sasl_path": "private/auth",
"smtpd_relay_restrictions": "permit_sasl_authenticated,reject",
"smtpd_sender_login_maps": login_map,
"smtpd_sender_restrictions": sender_check,
"smtpd_milters": milter,
}
engine.run(
"postconf",
"-P",
*(
f"submission/inet/{name}={value}"
for name, value in options.items()
),
label="Configure authenticated submission and DKIM",
)
+34 -13
View File
@@ -9,7 +9,7 @@ from threading import Thread
from urllib.parse import parse_qs
from .cli import number
from .config import InstallError, parse_plan, port
from .config import REMOTE_MODES, InstallError, parse_plan, port
from .engine import Installer
COOKIE = "coulobre_installer"
@@ -19,6 +19,7 @@ FORM = """<form method="post" action="/review">
<label>Hostname<input name="hostname" autocomplete="off" required></label>
<label>Access<select name="access">
<option value="tls">HTTPS on this server</option>
<option value="acme">HTTPS with Let's Encrypt</option>
<option value="proxy">Trusted external HTTPS proxy</option></select></label>
<label>Panel certificate path<input name="certificate"></label>
<label>Panel private key path<input name="key"></label>
@@ -45,21 +46,33 @@ border-radius:.3rem;padding:.75rem 1.1rem;font:inherit} summary{cursor:pointer}
def role_form(name):
title = name.upper() if name == "dns" else "Mail"
local = (
'<label>Mail hostname<input name="mail_local_host"></label>'
'<label>Mail certificate path<input name="mail_certificate"></label>'
'<label>Mail private key path<input name="mail_key"></label>'
"<label>Public mail hostname"
'<input name="mail_local_host"></label>'
'<label>Mail TLS<select name="mail_tls">'
'<option value="provided">Existing certificate</option>'
'<option value="acme">Let&#39;s Encrypt</option></select></label>'
"<label>Certificate path on the mail host"
'<input name="mail_certificate"></label>'
"<label>Private key path on the mail host"
'<input name="mail_key"></label>'
if name == "mail"
else ""
)
return f"""<fieldset><legend>{title}</legend>
<label>Role<select name="{name}_mode"><option value="off">Disabled</option>
<option value="local">Local service</option>
<option value="remote">Separate Coulobre node</option></select></label>
<option value="remote">Connect an existing Coulobre node</option>
<option value="remote-install">Install and connect a Coulobre node</option>
</select></label>
{local}
<details><summary>Separate node settings</summary>
<label>SSH hostname or address<input name="{name}_host"></label>
<label>SSH port<input name="{name}_port" type="number" value="22"></label>
<label>Verified SSH host public key file<input name="{name}_host_key"></label>
<label>SSH administrator username for installation
<input name="{name}_ssh_user"></label>
<label>SSH administrator key file for installation
<input name="{name}_ssh_identity"></label>
</details></fieldset>"""
@@ -89,7 +102,7 @@ def form_plan(fields):
for name in ("dns", "mail"):
mode = fields.get(f"{name}_mode", "off")
target = data[name] = {"mode": mode}
if mode == "remote":
if mode in REMOTE_MODES:
target.update(
host=fields.get(f"{name}_host", ""),
host_key=fields.get(f"{name}_host_key", ""),
@@ -97,12 +110,20 @@ def form_plan(fields):
fields.get(f"{name}_port") or "22", f"the {name} node"
),
)
elif name == "mail" and mode == "local":
target.update(
host=fields.get("mail_local_host", ""),
certificate=fields.get("mail_certificate", ""),
key=fields.get("mail_key", ""),
)
if mode == "remote-install":
target.update(
ssh_user=fields.get(f"{name}_ssh_user", ""),
ssh_identity=fields.get(f"{name}_ssh_identity", ""),
)
if name == "mail" and mode in {"local", "remote-install"}:
field = "host" if mode == "local" else "mail_hostname"
target[field] = fields.get("mail_local_host", "")
target["tls"] = fields.get("mail_tls", "provided")
if target["tls"] == "provided":
target.update(
certificate=fields.get("mail_certificate", ""),
key=fields.get("mail_key", ""),
)
return parse_plan(data)
@@ -236,7 +257,7 @@ class WizardHandler(BaseHTTPRequestHandler):
data = parse_qs(
self.rfile.read(size).decode("utf-8"),
keep_blank_values=True,
max_num_fields=25,
max_num_fields=32,
errors="strict",
)
if any(len(values) != 1 for values in data.values()):
+6
View File
@@ -0,0 +1,6 @@
bind_socket = "/var/spool/postfix/coulobre-rspamd/submit.sock mode=0660";
milter = true;
upstream "local" {
default = true;
self_scan = true;
}
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
if [ "${1:-}" = secondary ] && [ ! -f /etc/bind/named.conf ]; then
./deploy/install-node.sh dns
fi
exec /opt/coulobre/bin/python -m deploy.panel_installer.secondary "$@"
@@ -0,0 +1,6 @@
[Unit]
Requires=coulobre-website-usage.socket
After=coulobre-website-usage.socket
[Service]
SupplementaryGroups=coulobre-usage-requests
@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre read-only hosted website usage socket
[Socket]
ListenStream=/run/coulobre-website-usage.sock
SocketUser=root
SocketGroup=coulobre-usage-requests
SocketMode=0660
Accept=yes
MaxConnections=4
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,17 @@
[Unit]
Description=Coulobre hosted website usage request
CollectMode=inactive-or-failed
[Service]
Type=exec
ExecStart=/opt/coulobre/bin/coulobre-website-usage inspect-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
RestrictAddressFamilies=AF_UNIX
RuntimeMaxSec=15s
+2 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "coulobre-panel"
version = "0.8.0rc1"
version = "0.9.0rc1"
description = "A web hosting control panel for hosting providers and resellers."
readme = "README.md"
requires-python = ">=3.12"
@@ -19,6 +19,7 @@ dependencies = [
]
[project.scripts]
coulobre-website-usage = "coulobre.web_node_usage:main"
coulobre-account-backup = "coulobre.account_backup:main"
coulobre-database-node = "coulobre.database_node:main"
coulobre-directadmin = "coulobre.directadmin:main"
+53
View File
@@ -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)
+5
View File
@@ -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):
+71
View File
@@ -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,
)
+56
View File
@@ -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),
),
]
+25
View File
@@ -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,
+166 -2
View File
@@ -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 %}
+18
View File
@@ -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(),
+11
View File
@@ -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 (
+158
View File
@@ -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)
+55
View File
@@ -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
+69
View File
@@ -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()
+9
View File
@@ -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"
)
+6 -1
View File
@@ -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(),
)
+3 -1
View File
@@ -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}.")
+8 -1
View File
@@ -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))
+214
View File
@@ -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