Merge pull request 'Schedule jobs for hosted websites' (#104) from feature/website-scheduled-jobs into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s

Reviewed-on: #104
This commit was merged in pull request #104.
This commit is contained in:
parkel committed 2026-11-22 16:04:27 +01:00
commit af58151ee2
26 files changed
+1401 -7

No files matched your search

+1
View File
@@ -23,6 +23,7 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_WEB_HTTPS=1 # COULOBRE_LOCAL_WEB_HTTPS=1
# COULOBRE_LOCAL_WEB_SFTP=1 # COULOBRE_LOCAL_WEB_SFTP=1
# COULOBRE_WEB_FILE_MANAGER=1 # COULOBRE_WEB_FILE_MANAGER=1
# COULOBRE_WEBSITE_JOBS=1
# COULOBRE_LOCAL_DATABASE_PROVISIONING=1 # COULOBRE_LOCAL_DATABASE_PROVISIONING=1
# These two switches also enable provisioners using the SSH service drop-ins. # These two switches also enable provisioners using the SSH service drop-ins.
# COULOBRE_LOCAL_DNS_PUBLISHING=1 # COULOBRE_LOCAL_DNS_PUBLISHING=1
@@ -0,0 +1,26 @@
[Unit]
Description=Coulobre Panel website job worker
Requires=coulobre-website-jobs.socket
Wants=network-online.target
After=network-online.target coulobre-website-jobs.socket mariadb.service rabbitmq-server.service
[Service]
Type=exec
User=coulobre-website-job-worker
Group=coulobre-website-job-worker
SupplementaryGroups=coulobre-website-job-requests
EnvironmentFile=/etc/coulobre/panel.env
WorkingDirectory=/opt/coulobre
UMask=0077
ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-website-jobs --hostname=website-jobs@%H --concurrency=2 --prefetch-multiplier=1
KillMode=mixed
TimeoutStopSec=2min
Restart=on-failure
RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
@@ -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,31 @@
[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
# The receiver also terminates the website user's process on timeout.
CapabilityBoundingSet=CAP_SETUID CAP_SETGID CAP_DAC_READ_SEARCH CAP_KILL
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
+44
View File
@@ -710,6 +710,50 @@ links and files with multiple hard links. Uploads accept one file of up to
Uploads and renames require an unused name in the current folder. A Uploads and renames require an unused name in the current folder. A
separate confirmation is required to delete a file or an empty folder. separate confirmation is required to delete a file or an empty folder.
## Enable scheduled website jobs
The scheduled job worker runs on the same server as the panel and web
node. Install the local socket and Celery worker on that server.
```sh
sudo groupadd --system coulobre-website-job-requests
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
--shell /usr/sbin/nologin coulobre-website-job-worker
sudo install -m 0644 deploy/systemd/coulobre-website-jobs.socket \
deploy/systemd/coulobre-website-jobs@.service \
deploy/systemd/coulobre-website-job-worker.service /etc/systemd/system/
```
Set `COULOBRE_WEBSITE_JOBS=1` in `/etc/coulobre/panel.env`.
```sh
panel_manage migrate --noinput
sudo systemctl daemon-reload
sudo systemctl enable --now coulobre-website-job-worker.service
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
```
Set **Website job limit** to the number of saved jobs allowed per hosting
account. Paused jobs count toward the saved limit. The default is zero.
If you lower a limit, the oldest enabled jobs retain their places until
the account removes or pauses jobs. Add `website-jobs` to the local service
health list if you monitor this worker from the panel.
Customers and their assigned resellers can open **Scheduled jobs** from the
account page. Operators need both **Can view hosting account** and **Can
manage scheduled website jobs**. Pick the primary or an active independent
website. Use five cron fields in UTC. For example, `*/15 * * * *` runs every
15 minutes. Runs must be at least five minutes apart. When both day fields
are restricted, the date must match both.
The job runs as the website's Unix user in its document root with a
60-second deadline. To use the site's selected PHP series, install its PHP
CLI package and enter a command such as `"$PHP_CLI" tasks/refresh.php`.
The panel shows the last result, including the exit code if the node
reported one. Command output is discarded. A run missed by over 90 seconds
is skipped, and a run with an unconfirmed result is never replayed.
Suspended and retired sites are ineligible for new runs.
## Enable HTTPS for hosted websites ## Enable HTTPS for hosted websites
Once a site is active, obtain the website certificate with Certbot on the Once a site is active, obtain the website certificate with Certbot on the
@@ -253,6 +253,9 @@ def request_retirement(account_id, policy, confirmation, digest, actor):
account.retired_at = retirement.requested_at account.retired_at = retirement.requested_at
account.customer = account.reseller = None account.customer = account.reseller = None
account.save(update_fields=["retired_at", "customer", "reseller"]) account.save(update_fields=["retired_at", "customer", "reseller"])
account.website_jobs.update(
enabled=False, next_run_at=None, dispatched_at=None
)
schedule = getattr(account, "backup_schedule", None) schedule = getattr(account, "backup_schedule", None)
if schedule is not None: if schedule is not None:
schedule.enabled = False schedule.enabled = False
+1
View File
@@ -60,6 +60,7 @@ class HostingPlanAdmin(admin.ModelAdmin):
"name", "name",
"description", "description",
"website_limit", "website_limit",
"website_job_limit",
"database_limit", "database_limit",
"mailbox_limit", "mailbox_limit",
"mailbox_quota_mib", "mailbox_quota_mib",
@@ -191,5 +191,8 @@ def apply_website_operation(website):
"website retirement", "website retirement",
identity=request.identity(), identity=request.identity(),
) )
website.websitescheduledjob_set.update(
enabled=False, next_run_at=None, dispatched_at=None
)
return {"retired_at": timezone.now()} return {"retired_at": timezone.now()}
raise ValueError("Unknown website operation.") raise ValueError("Unknown website operation.")
@@ -0,0 +1,114 @@
# Generated by Django 5.2.19 on 2026-11-22 14:34
import django.core.validators
import django.db.models.deletion
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
dependencies = [
("hosting", "0048_website_file_permission"),
]
operations = [
migrations.AlterModelOptions(
name="hostingaccount",
options={
"permissions": [
(
"manage_website_files",
"Can manage hosted website files",
),
(
"manage_website_jobs",
"Can manage scheduled website jobs",
),
]
},
),
migrations.AddField(
model_name="hostingplan",
name="website_job_limit",
field=models.PositiveSmallIntegerField(
default=0,
help_text=(
"Maximum saved jobs per account. "
"Enter 0 to disable scheduling."
),
validators=[django.core.validators.MaxValueValidator(50)],
),
),
migrations.CreateModel(
name="WebsiteScheduledJob",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"domain",
coulobre.hosting.fields.DomainNameField(max_length=253),
),
("name", models.CharField(max_length=120)),
("expression", models.CharField(max_length=120)),
("command", models.CharField(max_length=1000)),
("enabled", models.BooleanField(default=True)),
("next_run_at", models.DateTimeField(blank=True, null=True)),
("dispatched_at", models.DateTimeField(blank=True, null=True)),
("last_run_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
(
"last_result",
models.CharField(
blank=True,
choices=[
("running", "Running"),
("succeeded", "Succeeded"),
("failed", "Failed"),
("timed_out", "Timed out"),
("unconfirmed", "Result unavailable"),
],
max_length=11,
),
),
(
"last_exit_code",
models.SmallIntegerField(blank=True, null=True),
),
("run_token", models.UUIDField(blank=True, null=True)),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="website_jobs",
to="hosting.hostingaccount",
),
),
(
"website",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="hosting.independentwebsite",
),
),
],
options={
"ordering": ("pk",),
"indexes": [
models.Index(
fields=["enabled", "next_run_at"],
name="hosting_web_enabled_552c55_idx",
)
],
},
),
]
+41
View File
@@ -40,6 +40,7 @@ from coulobre.php_pool_settings import (
) )
from coulobre.php_runtime import validate_php_versions from coulobre.php_runtime import validate_php_versions
from coulobre.web_node import MAX_STORAGE_LIMIT_MIB, WebSite from coulobre.web_node import MAX_STORAGE_LIMIT_MIB, WebSite
from coulobre.website_job import MAX_JOB_COMMAND_LENGTH
from .fields import DomainNameField from .fields import DomainNameField
@@ -267,6 +268,13 @@ class HostingPlan(models.Model):
validators=[MinValueValidator(1)], validators=[MinValueValidator(1)],
help_text="Maximum independent websites, including the primary site.", help_text="Maximum independent websites, including the primary site.",
) )
website_job_limit = models.PositiveSmallIntegerField(
default=0,
validators=[MaxValueValidator(50)],
help_text=(
"Maximum saved jobs per account. Enter 0 to disable scheduling."
),
)
database_limit = models.PositiveIntegerField( database_limit = models.PositiveIntegerField(
blank=True, blank=True,
null=True, null=True,
@@ -397,6 +405,7 @@ class HostingAccount(models.Model):
class Meta: class Meta:
permissions = [ permissions = [
("manage_website_files", "Can manage hosted website files"), ("manage_website_files", "Can manage hosted website files"),
("manage_website_jobs", "Can manage scheduled website jobs"),
] ]
constraints = [ constraints = [
models.CheckConstraint( models.CheckConstraint(
@@ -940,6 +949,38 @@ class IndependentWebsite(ProvisioningJob):
) )
class WebsiteScheduledJob(models.Model):
class Result(models.TextChoices):
RUNNING = "running", "Running"
SUCCEEDED = "succeeded", "Succeeded"
FAILED = "failed", "Failed"
TIMED_OUT = "timed_out", "Timed out"
UNCONFIRMED = "unconfirmed", "Result unavailable"
account = models.ForeignKey(
HostingAccount, on_delete=models.CASCADE, related_name="website_jobs"
)
website = models.ForeignKey(
IndependentWebsite, on_delete=models.CASCADE, null=True, blank=True
)
domain = DomainNameField(max_length=253)
name = models.CharField(max_length=120)
expression = models.CharField(max_length=120)
command = models.CharField(max_length=MAX_JOB_COMMAND_LENGTH)
enabled = models.BooleanField(default=True)
next_run_at = models.DateTimeField(null=True, blank=True)
dispatched_at = models.DateTimeField(null=True, blank=True)
last_run_at = models.DateTimeField(null=True, blank=True)
finished_at = models.DateTimeField(null=True, blank=True)
last_result = models.CharField(choices=Result, max_length=11, blank=True)
last_exit_code = models.SmallIntegerField(null=True, blank=True)
run_token = models.UUIDField(null=True, blank=True)
class Meta:
ordering = ("pk",)
indexes = [models.Index(fields=("enabled", "next_run_at"))]
class SiteSFTP(ProvisioningJob): class SiteSFTP(ProvisioningJob):
account = models.OneToOneField( account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="sftp" HostingAccount, on_delete=models.CASCADE, related_name="sftp"
+50 -1
View File
@@ -1,4 +1,4 @@
from datetime import timedelta from datetime import datetime, timedelta
from uuid import UUID from uuid import UUID
from celery import shared_task from celery import shared_task
@@ -62,6 +62,7 @@ from .models import (
WebProvisioningPlan, WebProvisioningPlan,
WebsiteAlias, WebsiteAlias,
WebsiteRestoreJob, WebsiteRestoreJob,
WebsiteScheduledJob,
) )
from .node_client import ( from .node_client import (
NodeReplyError, NodeReplyError,
@@ -88,6 +89,17 @@ from .php_settings import plan_php_versions
from .service_changes import apply_service_change from .service_changes import apply_service_change
from .sftp import site_is_active from .sftp import site_is_active
from .sign_in_limits import current_window from .sign_in_limits import current_window
from .website_jobs import (
JOB_QUEUE,
claim_website_job,
due_website_jobs,
recover_interrupted_runs,
run_website_job,
save_website_job_result,
)
from .website_jobs import (
Result as WebsiteJobResult,
)
REDISPATCH_AFTER = timedelta(minutes=5) REDISPATCH_AFTER = timedelta(minutes=5)
ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60) ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
@@ -962,3 +974,40 @@ def provision_independent_website(job_id):
apply_website_operation, apply_website_operation,
"Could not complete the request to the web node. Try again.", "Could not complete the request to the web node. Try again.",
) )
@shared_task
def dispatch_website_jobs():
if not settings.WEBSITE_JOBS:
return
now = timezone.now()
recover_interrupted_runs(now)
due = due_website_jobs(now).values_list("pk", "account_id", "next_run_at")
for job_id, account_id, next_run in list(due[:100]):
execute_website_job.apply_async(
args=[account_id, job_id, next_run.isoformat()],
queue=JOB_QUEUE,
expires=90,
retry=False,
)
WebsiteScheduledJob.objects.filter(
pk=job_id, next_run_at=next_run
).update(dispatched_at=now)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def execute_website_job(account_id, job_id, scheduled_for):
if not settings.WEBSITE_JOBS:
return
request = claim_website_job(
account_id, job_id, datetime.fromisoformat(scheduled_for)
)
if request is None:
return
try:
result, code = run_website_job(request)
except (OSError, NodeReplyError):
result, code = WebsiteJobResult.UNCONFIRMED, None
except ValueError:
result, code = WebsiteJobResult.FAILED, None
save_website_job_result(job_id, request.run_id, result, code)
@@ -10,7 +10,7 @@
{% include "hosting/account_status.html" %} {% include "hosting/account_status.html" %}
</div> </div>
</div> </div>
{% if primary_file_access 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 %}
<div class="form-actions"> <div class="form-actions">
{% if can_retire_account %} {% if can_retire_account %}
<a class="button secondary" href="{% url 'panel:account_retirement' account.pk %}">Retire account</a> <a class="button secondary" href="{% url 'panel:account_retirement' account.pk %}">Retire account</a>
@@ -18,6 +18,9 @@
{% if primary_file_access %} {% if primary_file_access %}
<a class="button secondary" href="{% url 'panel:website_files' account.pk %}">Website files</a> <a class="button secondary" href="{% url 'panel:website_files' account.pk %}">Website files</a>
{% endif %} {% endif %}
{% if manage_website_jobs %}
<a class="button secondary" href="{% url 'panel:website_jobs' account.pk %}">Scheduled jobs</a>
{% endif %}
{% if manage_sftp %} {% if manage_sftp %}
<a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">SFTP access</a> <a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">SFTP access</a>
{% endif %} {% endif %}
@@ -19,6 +19,7 @@
<th scope="col">Mailbox limit</th> <th scope="col">Mailbox limit</th>
<th scope="col">Storage per new mailbox</th> <th scope="col">Storage per new mailbox</th>
<th scope="col">Default website limit</th> <th scope="col">Default website limit</th>
<th scope="col">Scheduled jobs</th>
<th scope="col">PHP overrides</th> <th scope="col">PHP overrides</th>
</tr> </tr>
</thead> </thead>
@@ -37,6 +38,7 @@
<td>{{ hosting_plan.mailbox_limit|default_if_none:"Unlimited" }}</td> <td>{{ hosting_plan.mailbox_limit|default_if_none:"Unlimited" }}</td>
<td>{% if hosting_plan.mailbox_quota_mib is not None %}{{ hosting_plan.mailbox_quota_mib }} MiB{% else %}Unlimited{% endif %}</td> <td>{% if hosting_plan.mailbox_quota_mib is not None %}{{ hosting_plan.mailbox_quota_mib }} MiB{% else %}Unlimited{% endif %}</td>
<td>{% if hosting_plan.website_storage_limit_mib is not None %}{{ hosting_plan.website_storage_limit_mib }} MiB{% else %}Unlimited{% endif %}</td> <td>{% if hosting_plan.website_storage_limit_mib is not None %}{{ hosting_plan.website_storage_limit_mib }} MiB{% else %}Unlimited{% endif %}</td>
<td>{{ hosting_plan.website_job_limit }}</td>
<td>{% if hosting_plan.get_php_settings.has_overrides %}Configured{% else %}Server defaults{% endif %}</td> <td>{% if hosting_plan.get_php_settings.has_overrides %}Configured{% else %}Server defaults{% endif %}</td>
</tr> </tr>
{% endfor %} {% endfor %}
@@ -0,0 +1,22 @@
{% extends "hosting/base.html" %}
{% block title %}{% if job %}Edit{% else %}Add{% endif %} website job · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ list_url }}">← Scheduled website jobs</a>
<header class="page-heading">
<div>
<h1>{% if job %}Edit{% else %}Add{% endif %} website job</h1>
{% if job %}<p class="heading-meta domain">{{ job.domain }}</p>{% endif %}
</div>
</header>
<section class="surface editor-surface">
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Save job</button>
<a class="button secondary" href="{{ list_url }}">Cancel</a>
{% if job %}<button class="button secondary" name="action" value="remove" type="submit" formnovalidate>Remove job</button>{% endif %}
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,45 @@
{% extends "hosting/base.html" %}
{% block title %}Scheduled website jobs · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>Scheduled website jobs</h1>
<p class="heading-meta">{{ rows|length }} of {{ limit }} saved jobs</p>
</div>
{% if add_job %}
<a class="button primary" href="{% url 'panel:website_job_create' account.pk %}">Add job</a>
{% endif %}
</header>
<section class="surface" aria-label="Scheduled website jobs">
{% if rows %}
<div class="table-scroll">
<table>
<thead>
<tr><th scope="col">Job</th><th scope="col">Website</th><th scope="col">Schedule (UTC)</th><th scope="col">Next run</th><th scope="col">Last result</th></tr>
</thead>
<tbody>
{% for job, available in rows %}
<tr>
<th scope="row"><a class="record-link" href="{% url 'panel:website_job_edit' account.pk job.pk %}">{{ job.name }}</a></th>
<td class="domain">{{ job.domain }}</td>
<td><code>{{ job.expression }}</code></td>
<td>
{% if available and job.next_run_at %}{{ job.next_run_at|date:"j M Y, H:i" }} UTC
{% elif job.enabled %}Unavailable{% else %}Paused{% endif %}
</td>
<td>
{{ job.get_last_result_display|default:"Never run" }}
{% if job.last_exit_code is not None %}(exit {{ job.last_exit_code }}){% endif %}
{% if job.last_run_at %}<br>{{ job.last_run_at|date:"j M Y, H:i" }} UTC{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="empty">No website jobs scheduled.</p>
{% endif %}
</section>
{% endblock %}
+327
View File
@@ -0,0 +1,327 @@
import json
from datetime import UTC, datetime, timedelta
from io import BytesIO, StringIO
from types import SimpleNamespace
from unittest.mock import patch
from uuid import uuid4
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre.web_node import WebSite
from coulobre.web_node_jobs import serve_website_job
from coulobre.website_job import WebsiteJobRequest
from .models import (
Customer,
HostingAccount,
HostingPlan,
IndependentWebsite,
WebActivation,
WebProvisioningPlan,
WebsiteDomain,
WebsiteScheduledJob,
)
from .node_client import encode_manifest
from .tasks import dispatch_website_jobs, execute_website_job
from .website_job_schedule import next_website_run
from .website_jobs import (
JOB_QUEUE,
Result,
claim_website_job,
recover_interrupted_runs,
)
NOW = datetime(2026, 11, 23, 10, 15, tzinfo=UTC)
CLOCK = "django.utils.timezone.now"
class WebsiteJobReceiverTests(SimpleTestCase):
def test_receiver_accepts_the_client_protocol_without_echoing_commands(
self,
):
request = WebsiteJobRequest(
WebSite(42, "example.test"), uuid4().hex, "exit 7"
)
request_body = BytesIO(encode_manifest(request.manifest()))
response = StringIO()
with (
patch("sys.stdin", SimpleNamespace(buffer=request_body)),
patch("sys.stdout", response),
patch(
"coulobre.web_node_jobs.execute_website_job",
return_value={"timed_out": False, "exit_code": 7},
) as execute,
):
self.assertEqual(serve_website_job(), 0)
execute.assert_called_once_with(request)
self.assertEqual(
json.loads(response.getvalue()),
{
"run_id": request.run_id,
"state": "configured",
"problem": None,
"timed_out": False,
"exit_code": 7,
},
)
class WebsiteJobScheduleTests(SimpleTestCase):
def test_utc_schedule_advances_to_the_next_matching_minute(self):
self.assertEqual(
next_website_run("*/15 * * * *", NOW),
NOW + timedelta(minutes=15),
)
self.assertEqual(
next_website_run("0 8 * * mon", NOW),
datetime(2026, 11, 30, 8, tzinfo=UTC),
)
self.assertEqual(
next_website_run("0 0 29 2 *", NOW),
datetime(2028, 2, 29, tzinfo=UTC),
)
self.assertEqual(
next_website_run("0 0 1 * mon", NOW),
datetime(2027, 2, 1, tzinfo=UTC),
)
def test_unsafe_or_impossible_schedules_are_rejected(self):
for value in (
"* * * * *",
"0,58 * * * *",
"*/0 * * * *",
"*/5/5 * * * *",
"0, * * * *",
"61 * * * *",
"0 0 31 2 *",
"@daily",
):
with self.subTest(value=value), self.assertRaises(ValueError):
next_website_run(value, NOW)
@override_settings(WEBSITE_JOBS=True)
class WebsiteJobWorkflowTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.user = users.create_user("site-owner")
cls.operator = users.create_user("operator")
cls.plan = HostingPlan.objects.create(name="Web", website_job_limit=2)
cls.account = HostingAccount.objects.create(
name="Site account",
primary_domain="example.test",
hosting_plan=cls.plan,
customer=Customer.objects.create(user=cls.user),
)
cls.foreign = HostingAccount.objects.create(
name="Another account",
primary_domain="foreign.test",
hosting_plan=cls.plan,
)
activation = WebProvisioningPlan.objects.create(
account=cls.account,
primary_domain=cls.account.primary_domain,
completed_at=timezone.now(),
)
WebActivation.objects.create(
plan=activation, finished_at=timezone.now()
)
for account, tag in ((cls.account, "shop"), (cls.foreign, "foreign")):
reservation = WebsiteDomain.objects.create(
account=account, domain=f"{tag}.example.test"
)
website = IndependentWebsite.objects.create(
reservation=reservation,
activated=True,
finished_at=timezone.now(),
)
if tag == "shop":
cls.site = website
else:
cls.foreign_site = website
cls.jobs_url = reverse("panel:website_jobs", args=[cls.account.pk])
cls.add_url = reverse(
"panel:website_job_create", args=[cls.account.pk]
)
def setUp(self):
self.client.force_login(self.user)
def form(self, **overrides):
return {
"site": "primary",
"name": "Refresh catalogue",
"expression": "*/15 * * * *",
"command": '"$PHP_CLI" refresh.php',
"enabled": "on",
**overrides,
}
def job(self, **overrides):
return self.account.website_jobs.create(
**(
{
"domain": self.account.primary_domain,
"name": "Due job",
"command": "true",
"expression": "*/15 * * * *",
"next_run_at": NOW,
}
| overrides
)
)
def test_customer_can_add_pause_and_remove_a_job_for_its_own_site(self):
self.assertContains(
self.client.get(self.account.get_absolute_url()), "Scheduled jobs"
)
with patch(CLOCK, return_value=NOW):
self.assertRedirects(
self.client.post(self.add_url, self.form(site=self.site.pk)),
self.jobs_url,
)
job = self.account.website_jobs.get()
self.assertEqual(job.website, self.site)
self.assertEqual(job.next_run_at, NOW + timedelta(minutes=15))
self.assertContains(
self.client.get(self.jobs_url), "shop.example.test"
)
edit = reverse(
"panel:website_job_edit", args=[self.account.pk, job.pk]
)
self.assertRedirects(
self.client.post(
edit, self.form(site=self.foreign_site.pk, enabled="")
),
self.jobs_url,
)
job.refresh_from_db()
self.assertEqual(job.website, self.site)
self.assertFalse(job.enabled)
self.assertIsNone(job.next_run_at)
self.assertRedirects(
self.client.post(edit, {"action": "remove"}), self.jobs_url
)
self.assertFalse(self.account.website_jobs.exists())
def test_customer_cannot_access_foreign_accounts_or_choose_foreign_sites(
self,
):
foreign_url = reverse("panel:website_jobs", args=[self.foreign.pk])
self.assertEqual(self.client.get(foreign_url).status_code, 404)
self.assertContains(
self.client.post(
self.add_url, self.form(site=self.foreign_site.pk)
),
"Select a valid choice",
)
self.assertFalse(WebsiteScheduledJob.objects.exists())
def test_holding_paused_jobs_counts_toward_the_plan_limit(self):
self.job()
self.job(enabled=False, next_run_at=None)
self.assertContains(
self.client.post(self.add_url, self.form()),
"has reached its scheduled job limit",
)
self.assertEqual(self.account.website_jobs.count(), 2)
def test_operator_needs_permission_and_feature_is_optional(self):
self.client.force_login(self.operator)
self.operator.user_permissions.add(
Permission.objects.get(codename="view_hostingaccount")
)
self.assertEqual(self.client.get(self.jobs_url).status_code, 403)
self.operator.user_permissions.add(
Permission.objects.get(codename="manage_website_jobs")
)
self.assertEqual(self.client.get(self.jobs_url).status_code, 200)
with self.settings(WEBSITE_JOBS=False):
self.assertEqual(self.client.get(self.jobs_url).status_code, 404)
def test_due_run_is_dispatched_and_only_claimed_once(self):
job = self.job()
with (
patch(CLOCK, return_value=NOW),
patch.object(execute_website_job, "apply_async") as publish,
patch(
"coulobre.hosting.tasks.run_website_job",
return_value=(Result.FAILED, 7),
) as run,
):
dispatch_website_jobs.run()
dispatch_website_jobs.run()
publish.assert_called_once_with(
args=[self.account.pk, job.pk, NOW.isoformat()],
queue=JOB_QUEUE,
expires=90,
retry=False,
)
for _ in range(2):
execute_website_job.run(*publish.call_args.kwargs["args"])
run.assert_called_once()
self.assertEqual(run.call_args.args[0].site.domain, "example.test")
job.refresh_from_db()
self.assertEqual(job.next_run_at, NOW + timedelta(minutes=15))
self.assertEqual(job.last_result, Result.FAILED)
self.assertEqual(job.last_exit_code, 7)
self.assertIsNone(job.run_token)
def test_missed_and_out_of_plan_runs_advance_without_running(self):
old_slot = NOW - timedelta(minutes=15)
missed = self.job(next_run_at=old_slot)
extra = self.job()
self.plan.website_job_limit = 1
self.plan.save(update_fields=["website_job_limit"])
with patch(CLOCK, return_value=NOW):
self.assertIsNone(
claim_website_job(self.account.pk, missed.pk, old_slot)
)
self.assertIsNone(
claim_website_job(self.account.pk, extra.pk, NOW)
)
for job in (missed, extra):
job.refresh_from_db()
self.assertEqual(job.next_run_at, NOW + timedelta(minutes=15))
self.assertIsNone(job.last_run_at)
def test_suspension_or_retirement_prevents_a_run(self):
job = self.job(website=self.site, domain=self.site.spec.domain)
for marker in (
{"suspended": True},
{"suspended": False, "operation": "retire", "finished_at": None},
{"retired_at": NOW, "finished_at": NOW},
):
IndependentWebsite.objects.filter(pk=self.site.pk).update(**marker)
WebsiteScheduledJob.objects.filter(pk=job.pk).update(
next_run_at=NOW
)
with patch(CLOCK, return_value=NOW):
self.assertIsNone(
claim_website_job(self.account.pk, job.pk, NOW)
)
HostingAccount.objects.filter(pk=self.account.pk).update(
services_suspended=True
)
primary = self.job()
with patch(CLOCK, return_value=NOW):
self.assertIsNone(
claim_website_job(self.account.pk, primary.pk, NOW)
)
def test_lost_worker_result_is_marked_unconfirmed_without_replay(self):
job = self.job()
with patch(CLOCK, return_value=NOW):
self.assertIsNotNone(
claim_website_job(self.account.pk, job.pk, NOW)
)
recover_interrupted_runs(NOW + timedelta(minutes=4))
job.refresh_from_db()
self.assertEqual(job.last_result, Result.UNCONFIRMED)
self.assertIsNone(job.run_token)
self.assertEqual(job.next_run_at, NOW + timedelta(minutes=15))
+16
View File
@@ -38,6 +38,7 @@ from .sign_in import (
VerifyFactorView, VerifyFactorView,
) )
from .website_file_views import WebsiteFilesView from .website_file_views import WebsiteFilesView
from .website_job_views import WebsiteJobEditor, WebsiteJobList
app_name = "panel" app_name = "panel"
@@ -88,6 +89,21 @@ urlpatterns = [
WebsiteFilesView.as_view(), WebsiteFilesView.as_view(),
name="website_files", name="website_files",
), ),
path(
"accounts/<int:pk>/website-jobs/",
WebsiteJobList.as_view(),
name="website_jobs",
),
path(
"accounts/<int:pk>/website-jobs/new/",
WebsiteJobEditor.as_view(),
name="website_job_create",
),
path(
"accounts/<int:pk>/website-jobs/<int:job_pk>/",
WebsiteJobEditor.as_view(),
name="website_job_edit",
),
path( path(
"accounts/<int:pk>/websites/<int:site_pk>/files/", "accounts/<int:pk>/websites/<int:site_pk>/files/",
WebsiteFilesView.as_view(), WebsiteFilesView.as_view(),
+18 -5
View File
@@ -162,6 +162,8 @@ from .website_aliases import (
queue_website_alias, queue_website_alias,
) )
from .website_file_views import can_manage_website_files from .website_file_views import can_manage_website_files
from .website_job_views import can_manage_website_jobs
from .website_jobs import website_job_limit
VIEW_ACCOUNTS = "hosting.view_hostingaccount" VIEW_ACCOUNTS = "hosting.view_hostingaccount"
CHANGE_ACCOUNTS = "hosting.change_hostingaccount" CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
@@ -390,6 +392,12 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
and can_manage_website_files(self.request) and can_manage_website_files(self.request)
) )
context["manage_website_files"] = manage_files context["manage_website_files"] = manage_files
context["manage_website_jobs"] = can_manage_website_jobs(
self.request
) and (
website_job_limit(self.object) > 0
or self.object.website_jobs.exists()
)
context["primary_file_access"] = manage_files and site_is_active( context["primary_file_access"] = manage_files and site_is_active(
self.object self.object
) )
@@ -2040,6 +2048,7 @@ class HostingPlanEditor:
"name", "name",
"description", "description",
"website_limit", "website_limit",
"website_job_limit",
"database_limit", "database_limit",
"mailbox_limit", "mailbox_limit",
"mailbox_quota_mib", "mailbox_quota_mib",
@@ -2057,11 +2066,15 @@ class HostingPlanEditor:
def get_form_kwargs(self): def get_form_kwargs(self):
kwargs = super().get_form_kwargs() kwargs = super().get_form_kwargs()
if "data" in kwargs and "website_limit" not in kwargs["data"]: if "data" in kwargs:
data = kwargs["data"].copy() defaults = {"website_limit": 1, "website_job_limit": 0}
instance = kwargs.get("instance") missing = defaults.keys() - kwargs["data"].keys()
data["website_limit"] = instance.website_limit if instance else 1 if missing:
kwargs["data"] = data data = kwargs["data"].copy()
instance = kwargs.get("instance")
for field in missing:
data[field] = getattr(instance, field, defaults[field])
kwargs["data"] = data
return kwargs return kwargs
@@ -0,0 +1,76 @@
import re
from bisect import bisect_right
from calendar import monthrange
from datetime import UTC, datetime
from celery.schedules import ParseException, crontab
MIN_INTERVAL = 5
MINUTES_PER_DAY = 24 * 60
CRON_VALUE = r"(?:[a-zA-Z]+|[0-9]+)"
CRON_PART = re.compile(
rf"(?:\*|{CRON_VALUE}-{CRON_VALUE})(?:/[0-9]+)?|{CRON_VALUE}"
)
def next_website_run(expression, now):
fields = expression.split()
if len(fields) != 5 or not all(
CRON_PART.fullmatch(part)
for field in fields
for part in field.split(",")
):
raise ValueError("Enter five cron fields in UTC.")
minute, hour, day, month, weekday = fields
try:
schedule = crontab(
minute=minute,
hour=hour,
day_of_month=day,
month_of_year=month,
day_of_week=weekday,
)
except (ParseException, ValueError, ZeroDivisionError):
raise ValueError("Enter a valid cron schedule.") from None
times = sorted(
hour * 60 + minute
for hour in schedule.hour
for minute in schedule.minute
)
if not times:
raise ValueError("Enter a valid cron schedule.")
following = times[1:] + [times[0] + MINUTES_PER_DAY]
if any(
end - start < MIN_INTERVAL
for start, end in zip(times, following, strict=True)
):
raise ValueError("Schedule jobs at least five minutes apart.")
now = now.astimezone(UTC)
months = sorted(schedule.month_of_year)
dates = sorted(schedule.day_of_month)
# The Gregorian calendar repeats every 400 years.
for year in range(now.year, min(now.year + 401, 10000)):
for month in months:
if year == now.year and month < now.month:
continue
days_in_month = monthrange(year, month)[1]
for day in dates:
if day > days_in_month:
break
date = datetime(year, month, day, tzinfo=UTC)
if (
date.date() < now.date()
or date.isoweekday() % 7 not in schedule.day_of_week
):
continue
offset = (
bisect_right(times, now.hour * 60 + now.minute)
if date.date() == now.date()
else 0
)
if offset < len(times):
hour, minute = divmod(times[offset], 60)
return date.replace(hour=hour, minute=minute)
raise ValueError("The cron schedule does not match a calendar date.")
+202
View File
@@ -0,0 +1,202 @@
from django import forms
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.views import View
from django.views.decorators.cache import never_cache
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.detail import SingleObjectMixin
from coulobre.website_job import MAX_JOB_COMMAND_LENGTH, validate_command
from .access import TenantScopeMixin, is_tenant
from .independent_websites import check_actor
from .models import HostingAccount
from .resource_requests import lock_hosting_account
from .website_job_schedule import next_website_run
from .website_jobs import (
available_job_sites,
save_website_job,
website_job_limit,
)
MANAGE_JOBS = ("hosting.view_hostingaccount", "hosting.manage_website_jobs")
def can_manage_website_jobs(request):
user = request.user
return (
settings.WEBSITE_JOBS
and getattr(request, "impersonation", None) is None
and (is_tenant(user) or user.has_perms(MANAGE_JOBS))
)
class WebsiteJobForm(forms.Form):
site = forms.ChoiceField(label="Website")
name = forms.CharField(max_length=120)
expression = forms.CharField(
label="Cron schedule (UTC)",
max_length=120,
help_text=(
"Use minute, hour, day of month, month, and day of week. "
"For example, */15 * * * *."
),
)
command = forms.CharField(
max_length=MAX_JOB_COMMAND_LENGTH,
help_text=(
"Runs from the document root. "
'Use "$PHP_CLI" to run the site\'s PHP series.'
),
)
enabled = forms.BooleanField(required=False, initial=True)
def __init__(self, *args, sites, job=None, **kwargs):
super().__init__(*args, **kwargs)
if job is None:
self.fields["site"].choices = [
(key, site.domain) for key, site in sites.items()
]
else:
self.fields.pop("site")
self.initial.update(
name=job.name,
expression=job.expression,
command=job.command,
enabled=job.enabled,
)
def clean_expression(self):
expression = " ".join(self.cleaned_data["expression"].split())
try:
next_website_run(expression, timezone.now())
except ValueError as error:
raise forms.ValidationError(str(error)) from None
return expression
def clean_command(self):
command = self.cleaned_data["command"]
try:
validate_command(command)
except ValueError as error:
raise forms.ValidationError(str(error)) from None
return command
@method_decorator(
[never_cache, sensitive_post_parameters("command")], name="dispatch"
)
class WebsiteJobAccountView(
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, View
):
queryset = HostingAccount.objects.filter(
retired_at__isnull=True
).select_related("hosting_plan")
customer_relation = "customer"
permission_required = MANAGE_JOBS
def dispatch(self, request, *args, **kwargs):
if not settings.WEBSITE_JOBS:
raise Http404
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_manage_website_jobs(self.request)
@cached_property
def account(self):
return self.get_object()
class WebsiteJobList(WebsiteJobAccountView):
def get(self, request, *args, **kwargs):
account = self.account
jobs = list(account.website_jobs.all())
limit = website_job_limit(account)
sites = (
{} if account.services_suspended else available_job_sites(account)
)
active = {(site.site_id, site.domain) for site in sites.values()}
enabled_count = 0
rows = []
for job in jobs:
if job.enabled:
enabled_count += 1
available = (
(job.website_id, job.domain) in active
and job.enabled
and enabled_count <= limit
)
rows.append((job, available))
return render(
request,
"hosting/website_jobs.html",
{
"account": account,
"rows": rows,
"limit": limit,
"add_job": len(jobs) < limit and bool(sites),
},
)
class WebsiteJobEditor(WebsiteJobAccountView):
@cached_property
def job(self):
if "job_pk" not in self.kwargs:
return None
return get_object_or_404(
self.account.website_jobs, pk=self.kwargs["job_pk"]
)
def get(self, request, *args, **kwargs):
return self.edit()
def post(self, request, *args, **kwargs):
return self.edit(request.POST)
def edit(self, data=None):
account, job = self.account, self.job
list_url = reverse("panel:website_jobs", args=[account.pk])
if (
job is not None
and data is not None
and data.get("action") == "remove"
):
with transaction.atomic():
locked = lock_hosting_account(account.pk, customer_id=None)
check_actor(locked, self.request.user)
locked.website_jobs.filter(pk=job.pk).delete()
return redirect(list_url)
sites = available_job_sites(account) if job is None else {}
form = WebsiteJobForm(data, sites=sites, job=job)
if form.is_bound and form.is_valid():
try:
save_website_job(
account.pk,
job.pk if job is not None else None,
form.cleaned_data,
self.request.user,
)
except ValidationError as error:
form.add_error(None, error)
else:
return redirect(list_url)
return render(
self.request,
"hosting/website_job_form.html",
{
"account": account,
"job": job,
"form": form,
"list_url": list_url,
},
)
+224
View File
@@ -0,0 +1,224 @@
from datetime import timedelta
from uuid import uuid4
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from coulobre.web_node import WebSite
from coulobre.website_job import JOB_RUNTIME, JOB_SOCKET, WebsiteJobRequest
from .independent_websites import active_websites, check_actor
from .models import HostingAccount, WebsiteScheduledJob
from .node_client import NodeReplyError, apply_on_local_node
from .resource_requests import lock_hosting_account, require_active_services
from .sftp import site_is_active
from .website_job_schedule import next_website_run
JOB_QUEUE = "coulobre-website-jobs"
DISPATCH_INTERVAL = timedelta(seconds=30)
MISSED_WINDOW = timedelta(seconds=90)
RESULT_DEADLINE = timedelta(minutes=3)
Result = WebsiteScheduledJob.Result
def website_job_limit(account):
plan = account.hosting_plan
return plan.website_job_limit if plan is not None else 0
def available_job_sites(account):
sites = {}
if site_is_active(account):
sites["primary"] = WebSite(account.pk, account.primary_domain)
for website in active_websites(account):
if website_accepts_jobs(website):
sites[str(website.pk)] = website.spec
return sites
def website_accepts_jobs(website):
return not website.suspended and (
website.finished_at is not None
or website.operation
not in (website.Operation.SUSPEND, website.Operation.RETIRE)
)
def job_site(job, account):
if job.website_id is None:
if account.primary_domain == job.domain and site_is_active(account):
return WebSite(account.pk, job.domain)
return None
website = (
active_websites(account)
.filter(pk=job.website_id, reservation__domain=job.domain)
.first()
)
return (
website.spec
if website is not None and website_accepts_jobs(website)
else None
)
@transaction.atomic
def save_website_job(account_id, job_id, values, actor):
account = lock_hosting_account(account_id, customer_id=None)
check_actor(account, actor)
if job_id is None:
require_active_services(account)
if account.website_jobs.count() >= website_job_limit(account):
raise ValidationError(
"This hosting account has reached its scheduled job limit."
)
target = available_job_sites(account).get(values["site"])
if target is None:
raise ValidationError("Choose an active website.")
job = WebsiteScheduledJob(
account=account, website_id=target.site_id, domain=target.domain
)
else:
job = account.website_jobs.filter(pk=job_id).first()
if job is None:
raise ValidationError("This scheduled job was removed.")
enabled = values["enabled"]
if enabled:
require_active_services(account)
if website_job_limit(account) == 0 or job_site(job, account) is None:
raise ValidationError(
"Scheduled jobs are unavailable for this website."
)
expression = values["expression"]
reschedule = job.next_run_at is None or expression != job.expression
job.name = values["name"]
job.expression = expression
job.command = values["command"]
job.enabled = enabled
if not enabled or reschedule:
job.next_run_at = (
next_website_run(expression, timezone.now()) if enabled else None
)
job.dispatched_at = None
if job_id is None:
job.save()
else:
job.save(
update_fields=[
"name",
"expression",
"command",
"enabled",
"next_run_at",
"dispatched_at",
]
)
return job
def due_website_jobs(now):
return (
WebsiteScheduledJob.objects.filter(
enabled=True,
next_run_at__lte=now,
account__retired_at__isnull=True,
account__services_suspended=False,
account__hosting_plan__website_job_limit__gt=0,
)
.filter(
Q(dispatched_at__isnull=True)
| Q(dispatched_at__lte=now - DISPATCH_INTERVAL),
)
.order_by("next_run_at", "pk")
)
@transaction.atomic
def claim_website_job(account_id, job_id, expected_run):
try:
account = lock_hosting_account(account_id, customer_id=None)
except HostingAccount.DoesNotExist:
return None
job = account.website_jobs.filter(
pk=job_id, next_run_at=expected_run, enabled=True
).first()
now = timezone.now()
if job is None or expected_run > now:
return None
try:
require_active_services(account)
except ValidationError:
return None
limit = website_job_limit(account)
if limit == 0:
return None
job.next_run_at = next_website_run(job.expression, now)
job.dispatched_at = None
fields = ["next_run_at", "dispatched_at"]
older_jobs = account.website_jobs.filter(enabled=True, pk__lt=job.pk)
site = job_site(job, account)
request = None
if (
site is not None
and now - expected_run <= MISSED_WINDOW
and job.run_token is None
and older_jobs.count() < limit
):
token = uuid4()
request = WebsiteJobRequest(site, token.hex, job.command)
job.run_token = token
job.last_result = Result.RUNNING
job.last_run_at = now
job.finished_at = None
job.last_exit_code = None
fields.extend(
(
"run_token",
"last_result",
"last_run_at",
"finished_at",
"last_exit_code",
)
)
job.save(update_fields=fields)
return request
def recover_interrupted_runs(now):
WebsiteScheduledJob.objects.filter(
run_token__isnull=False,
last_run_at__lt=now - RESULT_DEADLINE,
).update(run_token=None, last_result=Result.UNCONFIRMED, finished_at=now)
def run_website_job(request):
reply = apply_on_local_node(
request,
JOB_SOCKET,
"web node",
"scheduled website job",
identity={"run_id": request.run_id},
timeout=JOB_RUNTIME + 20,
)
timed_out = reply.get("timed_out")
code = reply.get("exit_code")
if timed_out is True and "exit_code" in reply and code is None:
return Result.TIMED_OUT, None
if (
timed_out is not False
or type(code) is not int
or not -255 <= code <= 255
):
raise NodeReplyError("The web node returned an invalid job result.")
return (Result.SUCCEEDED if code == 0 else Result.FAILED), code
def save_website_job_result(job_id, token, result, code):
WebsiteScheduledJob.objects.filter(pk=job_id, run_token=token).update(
finished_at=timezone.now(),
last_result=result,
last_exit_code=code,
run_token=None,
)
+4
View File
@@ -14,6 +14,10 @@ SERVICES = {
"panel": ("Coulobre Panel", "coulobre-panel.service"), "panel": ("Coulobre Panel", "coulobre-panel.service"),
"worker": ("Coulobre worker", "coulobre-worker.service"), "worker": ("Coulobre worker", "coulobre-worker.service"),
"scheduler": ("Coulobre scheduler", "coulobre-beat.service"), "scheduler": ("Coulobre scheduler", "coulobre-beat.service"),
"website-jobs": (
"Coulobre website job worker",
"coulobre-website-job-worker.service",
),
"apache": ("Apache", "apache2.service"), "apache": ("Apache", "apache2.service"),
"php-fpm": ("PHP-FPM", f"{DEFAULT_PHP_RUNTIME.service}.service"), "php-fpm": ("PHP-FPM", f"{DEFAULT_PHP_RUNTIME.service}.service"),
"mariadb": ("MariaDB", "mariadb.service"), "mariadb": ("MariaDB", "mariadb.service"),
+7
View File
@@ -208,6 +208,7 @@ except ValueError as error:
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1" LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1" LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1" WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1"
WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1"
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1" LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"
LOCAL_DATABASE_PROVISIONING = ( LOCAL_DATABASE_PROVISIONING = (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1" os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1"
@@ -376,6 +377,12 @@ if LOCAL_WEB_HTTPS:
"schedule": 5.0, "schedule": 5.0,
"options": {"expires": 4.0}, "options": {"expires": 4.0},
} }
if WEBSITE_JOBS:
CELERY_BEAT_SCHEDULE["dispatch-website-jobs"] = {
"task": "coulobre.hosting.tasks.dispatch_website_jobs",
"schedule": 15.0,
"options": {"expires": 14.0},
}
if LOCAL_WEB_SFTP: if LOCAL_WEB_SFTP:
CELERY_BEAT_SCHEDULE["dispatch-web-sftp"] = { CELERY_BEAT_SCHEDULE["dispatch-web-sftp"] = {
"task": "coulobre.hosting.tasks.dispatch_web_sftp", "task": "coulobre.hosting.tasks.dispatch_web_sftp",
+8
View File
@@ -497,6 +497,9 @@ def main(argv=None):
commands.add_parser( commands.add_parser(
"files-request", help="Handle a scoped website file operation." "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) args = parser.parse_args(argv)
if args.command == "restore-site" and args.replace and args.file is None: if args.command == "restore-site" and args.replace and args.file is None:
parser.error("--replace requires --file.") parser.error("--replace requires --file.")
@@ -506,6 +509,11 @@ def main(argv=None):
return serve_website_files() 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": if args.command == "apply-request":
return serve_apply_request( return serve_apply_request(
MANIFEST_VERSION, MANIFEST_VERSION,
+61
View File
@@ -0,0 +1,61 @@
import fcntl
import os
import subprocess
from . import web_node_apply as web
from .node_requests import serve_apply_request
from .web_node_access import website_suspension_path
from .website_job import JOB_MANIFEST_VERSION, JOB_RUNTIME, WebsiteJobRequest
MAX_REQUEST_BYTES = 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():
return serve_apply_request(
JOB_MANIFEST_VERSION,
WebsiteJobRequest.from_manifest,
execute_website_job,
limit=MAX_REQUEST_BYTES,
identity=lambda request: {"run_id": request.run_id},
include_result=True,
)
+57
View File
@@ -0,0 +1,57 @@
from dataclasses import dataclass
from uuid import UUID
from .web_node import WebSite
JOB_SOCKET = "/run/coulobre-website-jobs.sock"
JOB_MANIFEST_VERSION = 1
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"] != JOB_MANIFEST_VERSION
):
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": JOB_MANIFEST_VERSION,
"site": self.site.manifest(),
"run_id": self.run_id,
"command": self.command,
}