Give independent websites separate node and archive identities

This commit is contained in:
parkel committed 2026-11-22 12:06:10 +01:00
1 parent 526106b7a0
commit bd88b64ca6
8 files changed
+170 -46

No files matched your search

+41 -2
View File
@@ -18,6 +18,7 @@ from .web_node import WebSite
BASE_MANIFEST_VERSION = 1 BASE_MANIFEST_VERSION = 1
MAIL_MANIFEST_VERSION = 2 MAIL_MANIFEST_VERSION = 2
MULTI_SITE_MANIFEST_VERSION = 3
MANIFEST_KIND = "coulobre_account_backup" MANIFEST_KIND = "coulobre_account_backup"
MANIFEST_NAME = "manifest.json" MANIFEST_NAME = "manifest.json"
MAX_MANIFEST_BYTES = 1024 * 1024 MAX_MANIFEST_BYTES = 1024 * 1024
@@ -29,8 +30,27 @@ class AccountBackup:
website: WebSite website: WebSite
databases: tuple[DatabaseSpec, ...] databases: tuple[DatabaseSpec, ...]
mailboxes: tuple[MailboxSpec, ...] | None = None mailboxes: tuple[MailboxSpec, ...] | None = None
additional_websites: tuple[WebSite, ...] = ()
def __post_init__(self): def __post_init__(self):
if self.website.site_id is not None:
raise ValueError(
"The primary website must use its account identity."
)
sites = {self.website.domain}
site_ids = set()
for site in self.additional_websites:
if (
site.account_id != self.website.account_id
or site.site_id is None
):
raise ValueError(
"All websites must belong to the backup account."
)
if site.domain in sites or site.site_id in site_ids:
raise ValueError("The account backup lists a website twice.")
sites.add(site.domain)
site_ids.add(site.site_id)
names = set() names = set()
for database in self.databases: for database in self.databases:
if database.account_id != self.website.account_id: if database.account_id != self.website.account_id:
@@ -57,6 +77,11 @@ class AccountBackup:
manifest["mailboxes"] = [ manifest["mailboxes"] = [
mailbox.manifest() for mailbox in self.mailboxes mailbox.manifest() for mailbox in self.mailboxes
] ]
if self.additional_websites:
manifest["version"] = MULTI_SITE_MANIFEST_VERSION
manifest["additional_websites"] = [
site.manifest() for site in self.additional_websites
]
return manifest return manifest
@classmethod @classmethod
@@ -67,30 +92,44 @@ class AccountBackup:
if type(version) is not int or version not in ( if type(version) is not int or version not in (
BASE_MANIFEST_VERSION, BASE_MANIFEST_VERSION,
MAIL_MANIFEST_VERSION, MAIL_MANIFEST_VERSION,
MULTI_SITE_MANIFEST_VERSION,
): ):
raise ValueError("Unsupported account backup manifest version.") raise ValueError("Unsupported account backup manifest version.")
fields = {"version", "kind", "website", "databases"} fields = {"version", "kind", "website", "databases"}
if version == MAIL_MANIFEST_VERSION: if version == MULTI_SITE_MANIFEST_VERSION:
fields.add("additional_websites")
if version == MAIL_MANIFEST_VERSION or (
version == MULTI_SITE_MANIFEST_VERSION and "mailboxes" in data
):
fields.add("mailboxes") fields.add("mailboxes")
if data.keys() != fields or not isinstance(data["databases"], list): if data.keys() != fields or not isinstance(data["databases"], list):
raise ValueError("Expected a Coulobre account backup manifest.") raise ValueError("Expected a Coulobre account backup manifest.")
mailboxes = None mailboxes = None
if version == MAIL_MANIFEST_VERSION: if "mailboxes" in fields:
if not isinstance(data["mailboxes"], list): if not isinstance(data["mailboxes"], list):
raise ValueError("Expected a list of mailbox manifests.") raise ValueError("Expected a list of mailbox manifests.")
mailboxes = tuple( mailboxes = tuple(
MailboxSpec.from_manifest(item) for item in data["mailboxes"] MailboxSpec.from_manifest(item) for item in data["mailboxes"]
) )
sites = data.get("additional_websites", [])
if not isinstance(sites, list):
raise ValueError(
"Expected a list of additional website manifests."
)
return cls( return cls(
WebSite.from_manifest(data["website"]), WebSite.from_manifest(data["website"]),
tuple( tuple(
DatabaseSpec.from_manifest(item) for item in data["databases"] DatabaseSpec.from_manifest(item) for item in data["databases"]
), ),
mailboxes, mailboxes,
tuple(WebSite.from_manifest(site) for site in sites),
) )
def components(self): def components(self):
yield self.website, "website.json", "website.tar.gz" yield self.website, "website.json", "website.tar.gz"
for site in self.additional_websites:
name = f"websites/{site.node_key}"
yield site, f"{name}.json", f"{name}.tar.gz"
for database in self.databases: for database in self.databases:
name = f"database-{database.suffix}" name = f"database-{database.suffix}"
yield database, f"{name}.json", f"{name}.sql.gz" yield database, f"{name}.json", f"{name}.sql.gz"
+41 -17
View File
@@ -16,6 +16,7 @@ from .php_runtime import validate_php_version, validate_php_versions
from .service_access import ServiceAccessRequest, parse_service_request from .service_access import ServiceAccessRequest, parse_service_request
MANIFEST_VERSION = 1 MANIFEST_VERSION = 1
INDEPENDENT_SITE_VERSION = 2
MAX_STORAGE_BYTES = 2**63 - 1 MAX_STORAGE_BYTES = 2**63 - 1
MAX_STORAGE_LIMIT_MIB = 2**31 - 1 MAX_STORAGE_LIMIT_MIB = 2**31 - 1
CONFIGURATIONS = { CONFIGURATIONS = {
@@ -28,6 +29,7 @@ CONFIGURATIONS = {
class WebSite: class WebSite:
account_id: int account_id: int
domain: str domain: str
site_id: int | None = None
def __post_init__(self): def __post_init__(self):
if ( if (
@@ -37,40 +39,62 @@ class WebSite:
raise ValueError( raise ValueError(
"The account ID must be a positive 64-bit integer." "The account ID must be a positive 64-bit integer."
) )
if self.site_id is not None and (
type(self.site_id) is not int or not 1 <= self.site_id <= 2**63 - 1
):
raise ValueError("The site ID must be a positive 64-bit integer.")
if not isinstance(self.domain, str): if not isinstance(self.domain, str):
raise ValueError("The domain must be a string.") raise ValueError("The domain must be a string.")
object.__setattr__(self, "domain", canonical_domain(self.domain)) object.__setattr__(self, "domain", canonical_domain(self.domain))
@property
def node_key(self):
return (
str(self.account_id)
if self.site_id is None
else f"s{self.site_id}"
)
@property
def service_user(self):
return f"coulobre-{self.node_key}"
@classmethod @classmethod
def from_manifest(cls, data): def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != { if not isinstance(data, dict):
"version", raise ValueError("Expected a website manifest.")
"account_id", version = data.get("version")
"domain", if type(version) is not int or version not in (
}: MANIFEST_VERSION,
raise ValueError( INDEPENDENT_SITE_VERSION,
"Expected a manifest with version, account_id, and domain." ):
)
version = data["version"]
if type(version) is not int or version != MANIFEST_VERSION:
raise ValueError("Unsupported web deployment manifest version.") raise ValueError("Unsupported web deployment manifest version.")
return cls(data["account_id"], data["domain"]) fields = {"version", "account_id", "domain"}
if version == INDEPENDENT_SITE_VERSION:
fields.add("site_id")
if data.keys() != fields or (
version == INDEPENDENT_SITE_VERSION and data["site_id"] is None
):
raise ValueError("Expected a website manifest.")
return cls(data["account_id"], data["domain"], data.get("site_id"))
def manifest(self): def manifest(self):
return { data = {
"version": MANIFEST_VERSION, "version": MANIFEST_VERSION,
"account_id": self.account_id, "account_id": self.account_id,
"domain": self.domain, "domain": self.domain,
} }
if self.site_id is not None:
data.update(version=INDEPENDENT_SITE_VERSION, site_id=self.site_id)
return data
def configuration(self): def configuration(self):
service_user = f"coulobre-{self.account_id}"
return { return {
"account_id": self.account_id, "account_id": self.account_id,
"domain": self.domain, "domain": self.domain,
"service_user": service_user, "service_user": self.service_user,
"document_root": f"/srv/coulobre/web/{self.account_id}/public", "document_root": f"/srv/coulobre/web/{self.node_key}/public",
"socket_path": f"/run/php/{service_user}.sock", "socket_path": f"/run/php/{self.service_user}.sock",
} }
def render( def render(
@@ -119,7 +143,7 @@ class WebAlias:
@property @property
def name(self): def name(self):
suffix = sha256(self.domain.encode("ascii")).hexdigest()[:24] suffix = sha256(self.domain.encode("ascii")).hexdigest()[:24]
return f"coulobre-{self.site.account_id}-alias-{suffix}" return f"{self.site.service_user}-alias-{suffix}"
@classmethod @classmethod
def from_manifest(cls, data): def from_manifest(cls, data):
+17 -2
View File
@@ -9,6 +9,14 @@ APACHE_CONFIG = Path("/etc/apache2/conf-enabled")
SSH_CONFIG = Path("/etc/ssh/sshd_config.d") SSH_CONFIG = Path("/etc/ssh/sshd_config.d")
def website_suspension_path(site):
return APACHE_CONFIG / f"coulobre-suspended-{site.node_key}.conf"
def sftp_suspension_path(site):
return SSH_CONFIG / f"01-coulobre-suspended-{site.node_key}.conf"
def set_website_access(site, suspended): def set_website_access(site, suspended):
document_root = site.configuration()["document_root"] document_root = site.configuration()["document_root"]
# The shared ACME webroot is outside the hosted document root. # The shared ACME webroot is outside the hosted document root.
@@ -17,17 +25,24 @@ def set_website_access(site, suspended):
" Require all denied\n" " Require all denied\n"
"</DirectoryMatch>\n" "</DirectoryMatch>\n"
) )
path = APACHE_CONFIG / f"coulobre-suspended-{site.account_id}.conf" path = website_suspension_path(site)
def validate(): def validate():
web.run("/usr/sbin/apache2ctl", "configtest") web.run("/usr/sbin/apache2ctl", "configtest")
set_configuration(site, suspended, path, config, validate, "apache2") set_configuration(site, suspended, path, config, validate, "apache2")
if site.site_id is not None:
from .web_node_sftp import AUTHORIZED_KEYS
if os.path.lexists(
AUTHORIZED_KEYS / site.service_user
) or os.path.lexists(sftp_suspension_path(site)):
set_sftp_access(site, suspended)
def set_sftp_access(site, suspended): def set_sftp_access(site, suspended):
user = site.configuration()["service_user"] user = site.configuration()["service_user"]
path = SSH_CONFIG / f"01-coulobre-suspended-{site.account_id}.conf" path = sftp_suspension_path(site)
def validate(): def validate():
configuration = web.run( configuration = web.run(
+13 -8
View File
@@ -54,7 +54,7 @@ class SitePaths:
def for_site(cls, site, *, version=None, archived_account=None): def for_site(cls, site, *, version=None, archived_account=None):
configuration = site.configuration() configuration = site.configuration()
name = configuration["service_user"] name = configuration["service_user"]
account = WEB_ROOT / str(site.account_id) account = WEB_ROOT / site.node_key
socket = Path(configuration["socket_path"]) socket = Path(configuration["socket_path"])
runtime = DEFAULT_PHP_RUNTIME runtime = DEFAULT_PHP_RUNTIME
route = (archived_account or account) / ".coulobre-php.sock" route = (archived_account or account) / ".coulobre-php.sock"
@@ -132,7 +132,7 @@ def install_site(site, *, php_settings=None, allowed=()):
create_route = not ( create_route = not (
paths.routed paths.routed
or ( or (
os.path.lexists(STATE_DIRECTORY / f"{site.account_id}.json") os.path.lexists(STATE_DIRECTORY / f"{site.node_key}.json")
and (os.path.lexists(paths.apache) or os.path.lexists(paths.pool)) and (os.path.lexists(paths.apache) or os.path.lexists(paths.pool))
) )
) )
@@ -171,7 +171,7 @@ def site_status(site):
require_root_directory(STATE_DIRECTORY) require_root_directory(STATE_DIRECTORY)
except FileNotFoundError: except FileNotFoundError:
return report return report
marker = STATE_DIRECTORY / f"{site.account_id}.json" marker = STATE_DIRECTORY / f"{site.node_key}.json"
if not os.path.lexists(marker): if not os.path.lexists(marker):
return report return report
@@ -195,7 +195,7 @@ def site_status(site):
def check_reservation(site): def check_reservation(site):
marker = STATE_DIRECTORY / f"{site.account_id}.json" marker = STATE_DIRECTORY / f"{site.node_key}.json"
try: try:
saved = json.loads(read_root_file(marker)) saved = json.loads(read_root_file(marker))
except FileNotFoundError: except FileNotFoundError:
@@ -208,7 +208,7 @@ def check_reservation(site):
def site_storage(site): def site_storage(site):
check_reservation(site) check_reservation(site)
account = WEB_ROOT / str(site.account_id) account = WEB_ROOT / site.node_key
require_root_directory(account) require_root_directory(account)
user = site.configuration()["service_user"] user = site.configuration()["service_user"]
uid, gid = check_system_account(user, account) uid, gid = check_system_account(user, account)
@@ -254,7 +254,7 @@ def check_services(runtime):
def reserve_account(site, user, paths): def reserve_account(site, user, paths):
marker = STATE_DIRECTORY / f"{site.account_id}.json" marker = STATE_DIRECTORY / f"{site.node_key}.json"
if os.path.lexists(marker.with_suffix(".retired")): if os.path.lexists(marker.with_suffix(".retired")):
raise ValueError("This website belongs to a retired hosting account.") raise ValueError("This website belongs to a retired hosting account.")
manifest = site.manifest() manifest = site.manifest()
@@ -263,7 +263,7 @@ def reserve_account(site, user, paths):
if existing == marker: if existing == marker:
if saved != manifest: if saved != manifest:
raise ValueError( raise ValueError(
"The account is already reserved with a different " "The website is already reserved with a different "
"manifest." "manifest."
) )
elif saved["domain"] == site.domain: elif saved["domain"] == site.domain:
@@ -271,7 +271,10 @@ def reserve_account(site, user, paths):
"The primary domain is already reserved by another account." "The primary domain is already reserved by another account."
) )
from .web_node_aliases import check_alias_domain_available from .web_node_aliases import (
check_alias_domain_available,
check_apache_hostname_available,
)
check_alias_domain_available(site.domain) check_alias_domain_available(site.domain)
@@ -285,6 +288,8 @@ def reserve_account(site, user, paths):
raise ValueError( raise ValueError(
"The web node already has unmanaged resources for this account." "The web node already has unmanaged resources for this account."
) )
if site.site_id is not None:
check_apache_hostname_available(site.domain)
write_new_file(marker, json.dumps(manifest) + "\n", mode=0o600) write_new_file(marker, json.dumps(manifest) + "\n", mode=0o600)
+49 -11
View File
@@ -30,14 +30,21 @@ def retire_site(request):
retirement = RetirementRecord(web.STATE_DIRECTORY, request) retirement = RetirementRecord(web.STATE_DIRECTORY, request)
if retirement.is_complete: if retirement.is_complete:
return return
reservation = web.STATE_DIRECTORY / f"{site.account_id}.json" reservation = web.STATE_DIRECTORY / f"{site.node_key}.json"
started = retirement.matches(retirement.started) started = retirement.matches(retirement.started)
if (
site.site_id is not None
and not os.path.lexists(reservation)
and not (retirement.directory / "site").is_file()
):
retire_unprovisioned_site(site, reservation, retirement)
return
if os.path.lexists(reservation) or not started: if os.path.lexists(reservation) or not started:
web.check_reservation(site) web.check_reservation(site)
elif not (retirement.directory / "site").is_file(): elif not (retirement.directory / "site").is_file():
raise ValueError("The original website reservation is missing.") raise ValueError("The original website reservation is missing.")
archived_account = web.WEB_ROOT / ".retired" / request.operation_id archived_account = web.WEB_ROOT / ".retired" / request.operation_id
account = web.WEB_ROOT / str(site.account_id) account = web.WEB_ROOT / site.node_key
paths = web.SitePaths.for_site( paths = web.SitePaths.for_site(
site, site,
archived_account=archived_account archived_account=archived_account
@@ -67,13 +74,45 @@ def retire_site(request):
apache = managed_vhosts(site, paths) apache = managed_vhosts(site, paths)
retirement.begin() retirement.begin()
detach_site(site, paths, key_file, apache, retirement) detach_site(site, paths, key_file, apache, retirement)
marker = reservation.with_suffix(".retired") finish_site_retirement(reservation, retirement)
if not os.path.lexists(marker):
write_new_file(marker, retirement.document, mode=0o600)
elif read_root_file(marker, mode=0o600) != retirement.document: def retire_unprovisioned_site(site, reservation, retirement):
raise ValueError("The website has a different retirement record.") paths = web.SitePaths.for_site(site)
archive_path(reservation, retirement.directory / "site") https, enabled = https_paths(paths)
retirement.finish() if (
web.current_user(site.service_user)
or web.current_group(site.service_user)
or any(
os.path.lexists(path)
for path in (
paths.account,
paths.apache,
paths.enabled,
paths.pool,
paths.socket,
https,
enabled,
AUTHORIZED_KEYS / site.service_user,
)
)
):
raise ValueError(
"The web node has unmanaged resources for this website."
)
check_aliases(site)
retirement.begin()
finish_site_retirement(reservation, retirement)
def finish_site_retirement(reservation, retirement):
marker = reservation.with_suffix(".retired")
if not os.path.lexists(marker):
write_new_file(marker, retirement.document, mode=0o600)
elif read_root_file(marker, mode=0o600) != retirement.document:
raise ValueError("The website has a different retirement record.")
archive_path(reservation, retirement.directory / "site")
retirement.finish()
def check_aliases(site): def check_aliases(site):
@@ -82,8 +121,7 @@ def check_aliases(site):
return return
require_root_directory(directory) require_root_directory(directory)
if any( if any(
read_alias(marker).site.account_id == site.account_id read_alias(marker).site == site for marker in directory.glob("*.json")
for marker in directory.glob("*.json")
): ):
raise ValueError( raise ValueError(
"Remove the managed website aliases before retiring the site." "Remove the managed website aliases before retiring the site."
+1 -1
View File
@@ -32,7 +32,7 @@ def switch_php_version(site, version):
raise ValueError( raise ValueError(
f"Install stable PHP {version} FPM on the web node." f"Install stable PHP {version} FPM on the web node."
) )
if current.socket.name == f"coulobre-{site.account_id}.sock" and ( if current.socket.name == f"{site.service_user}.sock" and (
current.routed or current.runtime.version != version current.routed or current.runtime.version != version
): ):
current = route_legacy_site(site, current) current = route_legacy_site(site, current)
+7
View File
@@ -37,6 +37,13 @@ def apply_sftp_keys(request):
target = AUTHORIZED_KEYS / user target = AUTHORIZED_KEYS / user
with locked_web_node(fcntl.LOCK_EX): with locked_web_node(fcntl.LOCK_EX):
if site.site_id is not None:
from .web_node_access import website_suspension_path
if os.path.lexists(website_suspension_path(site)):
raise ValueError(
"Resume the website before changing SFTP keys."
)
check_reservation(site) check_reservation(site)
if os.path.lexists(target): if os.path.lexists(target):
check_root_file(target, mode=0o644) check_root_file(target, mode=0o644)
+1 -5
View File
@@ -158,11 +158,7 @@ def https_paths(paths):
def certbot_lineage(site): def certbot_lineage(site):
name = ( name = site.name if isinstance(site, WebAlias) else site.service_user
site.name
if isinstance(site, WebAlias)
else f"coulobre-{site.account_id}"
)
return CERTBOT_ROOT / "live" / name return CERTBOT_ROOT / "live" / name