Files
coulobre/src/coulobre/web_node_runtime.py
T

199 lines
7.1 KiB
Python

import fcntl
import os
from dataclasses import replace
from pathlib import Path
from tempfile import TemporaryDirectory
from . import web_node_apply as web
from .node_files import (
read_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
from .php_runtime import DEFAULT_PHP_RUNTIME, installed_php_versions
from .web_node_aliases import alias_directory, alias_paths, read_alias
from .web_node_php import (
read_managed_php_pool,
reload_php_pool,
)
from .web_node_tls import https_paths, render_https_configuration
def switch_php_version(site, version):
if os.geteuid() != 0:
raise ValueError(
"Change the website PHP series as root on the web node."
)
with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(site)
current = web.SitePaths.for_site(site)
if version not in installed_php_versions():
raise ValueError(
f"Install stable PHP {version} FPM on the web node."
)
if current.socket.name == f"{site.service_user}.sock" and (
current.routed or current.runtime.version != version
):
current = route_legacy_site(site, current)
web.check_installation(site, current)
if current.routed:
# The previous request may have switched the route already.
remove_inactive_pools(site, current)
if current.runtime.version == version:
return version
target = web.SitePaths.for_site(site, version=version)
require_root_directory(target.pool.parent)
web.check_services(target.runtime)
switch_pool(site, current, target)
return version
def change_route(paths):
with TemporaryDirectory(dir=paths.route.parent) as directory:
staged = Path(directory) / "socket"
staged.symlink_to(paths.socket)
staged.replace(paths.route)
def route_legacy_site(site, paths):
for directory in (
paths.account,
paths.apache.parent,
paths.enabled.parent,
):
require_root_directory(directory)
legacy = replace(paths, routed=False)
managed = [(paths.apache, paths.enabled, site, False)]
https, enabled = https_paths(paths)
managed.append((https, enabled, site, True))
directory = alias_directory()
if os.path.lexists(directory):
require_root_directory(directory)
for marker in directory.glob("*.json"):
alias = read_alias(marker)
if alias.site == site:
managed.append((*alias_paths(alias), alias, False))
managed.append((*alias_paths(alias, https=True), alias, True))
changes = []
for config, link, resource, tls in managed:
if os.path.lexists(link):
web.check_site_link(link, Path("../sites-available") / config.name)
if not os.path.lexists(config):
if os.path.lexists(link) or config == paths.apache:
raise ValueError(f"Missing managed configuration at {config}.")
continue
before, after = (
(
render_https_configuration(resource, socket_path=socket)
if tls
else resource.render("apache", socket_path=socket)
)
for socket in (legacy.socket, paths.route)
)
actual = read_root_file(config)
from .web_redirects import compatible_configs
if actual not in compatible_configs(before, after):
raise ValueError(f"Existing configuration differs at {config}.")
if actual != after:
changes.append((config, actual, after))
routed = replace(paths, routed=True)
if not paths.routed:
change_route(routed)
updated = []
try:
for path, before, after in changes:
updated.append((path, before))
replace_configuration(path, after)
reload_apache()
except (OSError, ValueError, KeyboardInterrupt):
for path, before in reversed(updated):
replace_configuration(path, before)
if not paths.routed:
paths.route.unlink()
reload_apache()
raise
return routed
def reload_apache():
web.run("/usr/sbin/apache2ctl", "configtest")
web.run("/usr/sbin/service", "apache2", "reload")
def switch_pool(site, current, target):
previous, settings = read_managed_php_pool(
site, current.pool, socket_path=current.socket
)
desired = site.render(
"php-fpm", php_settings=settings, socket_path=target.socket
)
if os.path.lexists(target.pool):
read_managed_php_pool(site, target.pool, socket_path=target.socket)
replace_configuration(target.pool, desired)
else:
if os.path.lexists(target.socket):
raise ValueError(f"Unexpected PHP socket at {target.socket}.")
write_new_file(target.pool, desired, mode=0o644)
target_reload = False
try:
web.run(target.runtime.binary, "--test")
target_reload = True
reload_php_pool(target)
change_route(target)
current.pool.unlink()
remove_pool_from_service(current)
except (OSError, ValueError, KeyboardInterrupt) as error:
try:
if current.route.readlink() == target.socket:
if not os.path.lexists(current.pool):
write_new_file(current.pool, previous, mode=0o644)
web.run(current.runtime.binary, "--test")
reload_php_pool(current)
change_route(current)
target.pool.unlink(missing_ok=True)
if target_reload:
remove_pool_from_service(target)
except (OSError, ValueError) as recovery:
raise ValueError(
f"{error}\nPHP-FPM rollback failed. {recovery}"
) from error
raise
def remove_pool_from_service(paths):
web.run(paths.runtime.binary, "--test")
web.run("/usr/sbin/service", paths.runtime.service, "reload")
def remove_inactive_pools(site, current):
legacy = DEFAULT_PHP_RUNTIME.version
legacy_socket = Path(site.configuration()["socket_path"])
for version in installed_php_versions():
if version == current.runtime.version:
continue
paths = web.SitePaths.for_site(site, version=version)
if os.path.lexists(paths.pool):
require_root_directory(paths.pool.parent)
content = read_root_file(paths.pool)
listen = f"listen = {legacy_socket}\n"
if version == legacy and listen in content.splitlines(
keepends=True
):
paths = replace(paths, socket=legacy_socket)
read_managed_php_pool(site, paths.pool, socket_path=paths.socket)
paths.pool.unlink()
try:
remove_pool_from_service(paths)
except (OSError, ValueError, KeyboardInterrupt):
write_new_file(paths.pool, content, mode=0o644)
raise
elif os.path.lexists(paths.socket) or (
version == legacy and os.path.lexists(legacy_socket)
):
remove_pool_from_service(paths)