Schedule jobs for hosted websites #104

Merged
parkel merged 5 commits from feature/website-scheduled-jobs into main 2026-11-22 16:04:27 +01:00
5 changed files with 182 additions and 0 deletions
Showing only changes of commit c944f9cb23 - Show all commits

No files matched your search

@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre website job socket
[Socket]
ListenStream=/run/coulobre-website-jobs.sock
SocketUser=root
SocketGroup=coulobre-website-job-requests
SocketMode=0660
Accept=yes
MaxConnections=4
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,30 @@
[Unit]
Description=Coulobre scheduled website job
CollectMode=inactive-or-failed
[Service]
Type=exec
# The system service starts as root and switches to the website user.
WorkingDirectory=/opt/coulobre
ExecStart=/opt/coulobre/bin/coulobre-web-node job-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
CapabilityBoundingSet=CAP_SETUID CAP_SETGID CAP_DAC_READ_SEARCH
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
ProtectProc=invisible
ProtectControlGroups=true
ReadWritePaths=/srv/coulobre/web
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=true
RestrictSUIDSGID=true
MemoryMax=256M
TasksMax=32
CPUQuota=100%
RuntimeMaxSec=75s
TimeoutStopSec=5s
KillMode=control-group
+8
View File
@@ -497,6 +497,9 @@ def main(argv=None):
commands.add_parser(
"files-request", help="Handle a scoped website file operation."
)
commands.add_parser(
"job-request", help="Run a scheduled job as the website user."
)
args = parser.parse_args(argv)
if args.command == "restore-site" and args.replace and args.file is None:
parser.error("--replace requires --file.")
@@ -506,6 +509,11 @@ def main(argv=None):
return serve_website_files()
if args.command == "job-request":
from .web_node_jobs import serve_website_job
return serve_website_job()
if args.command == "apply-request":
return serve_apply_request(
MANIFEST_VERSION,
+74
View File
@@ -0,0 +1,74 @@
import fcntl
import os
import subprocess
import sys
from . import web_node_apply as web
from .node_stream import encode_header, read_header
from .web_node_access import website_suspension_path
from .website_job import JOB_RUNTIME, WebsiteJobRequest
MAX_REQUEST_HEADER = 16 * 1024
def execute_website_job(request):
if os.geteuid() != 0:
raise ValueError("Run the website job receiver as root.")
site = request.site
with web.locked_web_node(fcntl.LOCK_SH):
if os.path.lexists(website_suspension_path(site)):
raise ValueError("The website is suspended.")
public, uid, _ = web.site_storage(site)
account = web.current_user(site.service_user)
if account is None or account.pw_uid != uid or uid == 0:
raise ValueError("The website user is unavailable.")
runtime = web.SitePaths.for_site(site).runtime
try:
process = subprocess.run(
["/bin/sh", "-s"],
input=(request.command + "\n").encode("utf-8"),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
cwd=public,
env={
"PATH": "/usr/local/bin:/usr/bin:/bin",
"HOME": str(public),
"USER": site.service_user,
"LOGNAME": site.service_user,
"LANG": "C.UTF-8",
"TZ": "UTC",
"PHP_CLI": f"/usr/bin/php{runtime.version}",
},
user=uid,
group=account.pw_gid,
extra_groups=[],
umask=0o027,
timeout=JOB_RUNTIME,
check=False,
)
except subprocess.TimeoutExpired:
return {"timed_out": True, "exit_code": None}
return {"timed_out": False, "exit_code": process.returncode}
def serve_website_job():
run_id = ""
try:
request = WebsiteJobRequest.from_manifest(
read_header(
sys.stdin.buffer,
maximum=MAX_REQUEST_HEADER,
label="scheduled website job request",
)
)
run_id = request.run_id
result = execute_website_job(request)
response = {"state": "configured", "problem": None, **result}
except (OSError, ValueError):
response = {
"state": "failed",
"problem": "The web node could not start the website job.",
}
sys.stdout.buffer.write(encode_header({"run_id": run_id, **response}))
sys.stdout.buffer.flush()
return 0
+56
View File
@@ -0,0 +1,56 @@
from dataclasses import dataclass
from uuid import UUID
from .web_node import WebSite
JOB_SOCKET = "/run/coulobre-website-jobs.sock"
JOB_RUNTIME = 60
MAX_JOB_COMMAND_LENGTH = 1000
def validate_command(command):
if (
not isinstance(command, str)
or not command.strip()
or len(command) > MAX_JOB_COMMAND_LENGTH
or any(not char.isprintable() for char in command)
):
raise ValueError("Enter a single-line shell command.")
@dataclass(frozen=True)
class WebsiteJobRequest:
site: WebSite
run_id: str
command: str
def __post_init__(self):
if (
not isinstance(self.run_id, str)
or UUID(self.run_id).hex != self.run_id
):
raise ValueError("Expected a scheduled job run identifier.")
validate_command(self.command)
@classmethod
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or set(data) != {"version", "site", "run_id", "command"}
or type(data["version"]) is not int
or data["version"] != 1
):
raise ValueError("Expected a version 1 scheduled job request.")
return cls(
WebSite.from_manifest(data["site"]),
data["run_id"],
data["command"],
)
def manifest(self):
return {
"version": 1,
"site": self.site.manifest(),
"run_id": self.run_id,
"command": self.command,
}