diff --git a/src/coulobre/hosting/templates/hosting/php-fpm-pool.conf b/src/coulobre/hosting/templates/hosting/php-fpm-pool.conf index 63c2b08..dd0b2b3 100644 --- a/src/coulobre/hosting/templates/hosting/php-fpm-pool.conf +++ b/src/coulobre/hosting/templates/hosting/php-fpm-pool.conf @@ -6,6 +6,6 @@ listen.owner = www-data listen.group = www-data listen.mode = 0660 pm = ondemand -pm.max_children = 2 +pm.max_children = $max_children clear_env = yes security.limit_extensions = .php diff --git a/src/coulobre/php_pool_settings.py b/src/coulobre/php_pool_settings.py new file mode 100644 index 0000000..5c8abd0 --- /dev/null +++ b/src/coulobre/php_pool_settings.py @@ -0,0 +1,103 @@ +import json +from dataclasses import asdict, dataclass + +DEFAULT_MAX_CHILDREN = 2 +PHP_SETTINGS_COMMENT = "; Coulobre PHP settings " +PHP_SETTING_BOUNDS = { + "memory_limit_mib": (16, 4096), + "upload_limit_mib": (1, 512), + "request_timeout_seconds": (1, 600), + "max_children": (1, 32), +} + + +class PhpPoolSettingsError(ValueError): + def __init__(self, field, message): + super().__init__(message) + self.field = field + + +@dataclass(frozen=True) +class PhpPoolSettings: + memory_limit_mib: int | None = None + upload_limit_mib: int | None = None + request_timeout_seconds: int | None = None + max_children: int | None = None + + def __post_init__(self): + for field, (minimum, maximum) in PHP_SETTING_BOUNDS.items(): + value = getattr(self, field) + if value is not None and ( + type(value) is not int or not minimum <= value <= maximum + ): + raise PhpPoolSettingsError( + field, + f"Enter a whole number between {minimum} and {maximum}.", + ) + if ( + self.memory_limit_mib is not None + and self.post_limit_mib is not None + and self.memory_limit_mib < self.post_limit_mib + ): + raise PhpPoolSettingsError( + "memory_limit_mib", + "Set the memory limit at least 1 MiB above the upload limit.", + ) + + @property + def post_limit_mib(self): + return ( + self.upload_limit_mib + 1 + if self.upload_limit_mib is not None + else None + ) + + @property + def worker_limit(self): + return self.max_children or DEFAULT_MAX_CHILDREN + + @property + def has_overrides(self): + return any(value is not None for value in self.manifest().values()) + + @classmethod + def from_manifest(cls, options): + if ( + not isinstance(options, dict) + or options.keys() != PHP_SETTING_BOUNDS.keys() + ): + raise ValueError("Expected the supported PHP pool settings.") + return cls(**options) + + def manifest(self): + return asdict(self) + + def render_overrides(self): + if not self.has_overrides: + return "" + lines = [ + PHP_SETTINGS_COMMENT + + json.dumps(self.manifest(), separators=(",", ":")) + ] + if self.memory_limit_mib is not None: + lines.append( + f"php_admin_value[memory_limit] = {self.memory_limit_mib}M" + ) + if self.upload_limit_mib is not None: + lines.extend( + ( + "php_admin_value[upload_max_filesize] = " + f"{self.upload_limit_mib}M", + f"php_admin_value[post_max_size] = {self.post_limit_mib}M", + ) + ) + if self.request_timeout_seconds is not None: + timeout = self.request_timeout_seconds + lines.extend( + ( + f"php_admin_value[max_execution_time] = {timeout}", + f"request_terminate_timeout = {timeout}s", + "request_terminate_timeout_track_finished = yes", + ) + ) + return "\n".join(lines) + "\n" diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 1c55388..e5649be 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -10,6 +10,7 @@ from string import Template from .directadmin import DOCUMENT_ROOTS from .domain_names import canonical_domain from .node_requests import serve_apply_request +from .php_pool_settings import PhpPoolSettings MANIFEST_VERSION = 1 MAX_STORAGE_BYTES = 2**63 - 1 @@ -70,7 +71,13 @@ class WebSite: } def render( - self, configuration, *, port=80, tls_settings="", server_name=None + self, + configuration, + *, + port=80, + tls_settings="", + server_name=None, + php_settings=None, ): resource = files("coulobre.hosting").joinpath( "templates", "hosting", CONFIGURATIONS[configuration] @@ -78,7 +85,14 @@ class WebSite: values = self.configuration() if server_name is not None: values["domain"] = canonical_domain(server_name) - return Template(resource.read_text(encoding="utf-8")).substitute( + template = Template(resource.read_text(encoding="utf-8")) + if configuration == "php-fpm": + options = php_settings or PhpPoolSettings() + return ( + template.substitute(values, max_children=options.worker_limit) + + options.render_overrides() + ) + return template.substitute( values, port=port, tls_settings=tls_settings ) @@ -178,6 +192,27 @@ class WebQuotaRequest: } +@dataclass(frozen=True) +class WebPhpRequest: + site: WebSite + php_settings: PhpPoolSettings + operation: str + + def __post_init__(self): + if self.operation not in ( + "activate_with_php_settings", + "set_php_settings", + ): + raise ValueError("Expected a PHP pool operation.") + + def manifest(self): + return { + "operation": self.operation, + "site": self.site.manifest(), + "php_settings": self.php_settings.manifest(), + } + + def parse_web_request(data): if ( isinstance(data, dict) @@ -193,6 +228,16 @@ def parse_web_request(data): return WebQuotaRequest( WebSite.from_manifest(data["site"]), data["limit_mib"] ) + if isinstance(data, dict) and data.keys() == { + "operation", + "site", + "php_settings", + }: + return WebPhpRequest( + WebSite.from_manifest(data["site"]), + PhpPoolSettings.from_manifest(data["php_settings"]), + data["operation"], + ) if isinstance(data, dict) and data.keys() == {"operation", "alias"}: return WebAliasRequest( WebAlias.from_manifest(data["alias"]), data["operation"] @@ -212,6 +257,18 @@ def apply_web_request(request): apply_website_limit(request) return None + if isinstance(request, WebPhpRequest): + from .web_node_apply import apply_site + from .web_node_php import update_php_pool + + if request.operation == "activate_with_php_settings": + applied = apply_site( + request.site, php_settings=request.php_settings + ) + else: + applied = update_php_pool(request.site, request.php_settings) + return {"applied_php_settings": applied.manifest()} + if isinstance(request, WebAliasRequest): from .web_node_aliases import activate_alias, remove_alias diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index b0020fc..964dab1 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -62,7 +62,7 @@ def locked_web_node(mode): yield -def apply_site(site): +def apply_site(site, *, php_settings=None): if os.geteuid() != 0: raise ValueError("Run apply as root on the web node.") @@ -75,10 +75,10 @@ def apply_site(site): with (STATE_DIRECTORY / "apply.lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX) - install_site(site) + return install_site(site, php_settings=php_settings) -def install_site(site): +def install_site(site, *, php_settings=None): user = site.configuration()["service_user"] paths = SitePaths.for_site(site) owned_paths = ( @@ -93,8 +93,13 @@ def install_site(site): uid, web_gid = ensure_system_account(user, paths.account) require_root_directory(paths.account, create_mode=0o755) ensure_public_directory(paths.account / "public", uid, web_gid) - install_configurations( - site, paths.apache, paths.enabled, paths.pool, paths.socket + return install_configurations( + site, + paths.apache, + paths.enabled, + paths.pool, + paths.socket, + php_settings=php_settings, ) @@ -149,6 +154,8 @@ def site_storage(site): def check_installation(site, paths): + from .web_node_php import read_managed_php_pool + for directory in ( paths.account, APACHE_AVAILABLE, @@ -161,7 +168,7 @@ def check_installation(site, paths): uid, gid = check_system_account(user, paths.account) check_public_directory(paths.account / "public", uid, gid) check_configuration(paths.apache, site.render("apache")) - check_configuration(paths.pool, site.render("php-fpm")) + read_managed_php_pool(site, paths.pool) check_site_link( paths.enabled, Path("../sites-available") / paths.apache.name ) @@ -296,10 +303,21 @@ def check_public_directory(path, uid, gid): raise ValueError(f"Unexpected ownership or mode for {path}.") -def install_configurations(site, apache, enabled, pool, socket): +def install_configurations( + site, apache, enabled, pool, socket, *, php_settings=None +): + from .php_pool_settings import PhpPoolSettings + from .web_node_php import read_managed_php_pool + with configuration_installation() as (created, reload_attempts): install_configuration(apache, site.render("apache"), created) - install_configuration(pool, site.render("php-fpm"), created) + if os.path.lexists(pool): + _, applied = read_managed_php_pool(site, pool) + else: + applied = php_settings or PhpPoolSettings() + install_configuration( + pool, site.render("php-fpm", php_settings=applied), created + ) enable_apache_site(apache, enabled, created) run("/usr/sbin/php-fpm8.5", "--test") @@ -309,6 +327,7 @@ def install_configurations(site, apache, enabled, pool, socket): wait_for_socket(socket) reload_attempts.append("apache2") run("/usr/sbin/service", "apache2", "reload") + return applied def install_configuration(path, content, created): diff --git a/src/coulobre/web_node_php.py b/src/coulobre/web_node_php.py new file mode 100644 index 0000000..be1e346 --- /dev/null +++ b/src/coulobre/web_node_php.py @@ -0,0 +1,82 @@ +import fcntl +import json +import os +from pathlib import Path +from tempfile import NamedTemporaryFile + +from . import web_node_apply as web +from .node_files import read_root_file +from .php_pool_settings import PHP_SETTINGS_COMMENT, PhpPoolSettings + + +def read_managed_php_pool(site, path): + content = read_root_file(path) + _, marker, options = content.partition("\n" + PHP_SETTINGS_COMMENT) + try: + if marker: + manifest = json.loads(options.split("\n", 1)[0]) + settings = PhpPoolSettings.from_manifest(manifest) + else: + settings = PhpPoolSettings() + except (ValueError, RecursionError): + raise ValueError( + f"Existing configuration differs at {path}." + ) from None + if content != site.render("php-fpm", php_settings=settings): + raise ValueError(f"Existing configuration differs at {path}.") + return content, settings + + +def update_php_pool(site, settings): + if os.geteuid() != 0: + raise ValueError("Update PHP pool settings as root on the web node.") + paths = web.SitePaths.for_site(site) + with web.locked_web_node(fcntl.LOCK_EX): + web.check_reservation(site) + web.check_installation(site, paths) + old, _ = read_managed_php_pool(site, paths.pool) + wanted = site.render("php-fpm", php_settings=settings) + change_php_pool(paths, old, wanted) + return settings + + +def change_php_pool(paths, old, wanted): + changed = old != wanted + if changed: + replace_pool_file(paths.pool, wanted) + reload_attempted = False + try: + web.run("/usr/sbin/php-fpm8.5", "--test") + reload_attempted = True + reload_php_pool(paths.socket) + except (OSError, ValueError, KeyboardInterrupt) as error: + try: + if changed: + replace_pool_file(paths.pool, old) + if reload_attempted: + reload_php_pool(paths.socket) + except (OSError, ValueError) as recovery: + raise ValueError( + f"{error}\nPHP-FPM rollback failed. {recovery}" + ) from error + raise + + +def replace_pool_file(path, content): + with NamedTemporaryFile( + mode="w", encoding="utf-8", dir=path.parent, delete=False + ) as temporary: + staged = Path(temporary.name) + try: + temporary.write(content) + temporary.flush() + os.fchmod(temporary.fileno(), 0o644) + os.fsync(temporary.fileno()) + staged.replace(path) + finally: + staged.unlink(missing_ok=True) + + +def reload_php_pool(socket): + web.run("/usr/sbin/service", web.PHP_SERVICE, "reload") + web.wait_for_socket(socket)