Schedule website jobs with hosting plan limits and run tracking

This commit is contained in:
parkel committed 2026-11-22 15:38:27 +01:00
1 parent c944f9cb23
commit 92fea45f84
9 files changed
+544 -1

No files matched your search

@@ -253,6 +253,9 @@ def request_retirement(account_id, policy, confirmation, digest, actor):
account.retired_at = retirement.requested_at
account.customer = account.reseller = None
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)
if schedule is not None:
schedule.enabled = False
@@ -191,5 +191,8 @@ def apply_website_operation(website):
"website retirement",
identity=request.identity(),
)
website.websitescheduledjob_set.update(
enabled=False, next_run_at=None, dispatched_at=None
)
return {"retired_at": timezone.now()}
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.web_node import MAX_STORAGE_LIMIT_MIB, WebSite
from coulobre.website_job import MAX_JOB_COMMAND_LENGTH
from .fields import DomainNameField
@@ -267,6 +268,13 @@ class HostingPlan(models.Model):
validators=[MinValueValidator(1)],
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(
blank=True,
null=True,
@@ -397,6 +405,7 @@ class HostingAccount(models.Model):
class Meta:
permissions = [
("manage_website_files", "Can manage hosted website files"),
("manage_website_jobs", "Can manage scheduled website jobs"),
]
constraints = [
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):
account = models.OneToOneField(
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 celery import shared_task
@@ -62,6 +62,7 @@ from .models import (
WebProvisioningPlan,
WebsiteAlias,
WebsiteRestoreJob,
WebsiteScheduledJob,
)
from .node_client import (
NodeReplyError,
@@ -88,6 +89,17 @@ from .php_settings import plan_php_versions
from .service_changes import apply_service_change
from .sftp import site_is_active
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)
ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
@@ -962,3 +974,40 @@ def provision_independent_website(job_id):
apply_website_operation,
"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)
@@ -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.")
+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,
)
+7
View File
@@ -208,6 +208,7 @@ except ValueError as error:
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "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_DATABASE_PROVISIONING = (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1"
@@ -376,6 +377,12 @@ if LOCAL_WEB_HTTPS:
"schedule": 5.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:
CELERY_BEAT_SCHEDULE["dispatch-web-sftp"] = {
"task": "coulobre.hosting.tasks.dispatch_web_sftp",