Files
itflow/cron/includes/cron_lock.php

256 lines
11 KiB
PHP

<?php
/*
* ITFlow - Cron runtime: single-run guard and dispatcher support
*
* Required by each cron script immediately after its CLI check and before config.php,
* with the caller setting $cron_lock_script = __FILE__ first.
*
* Cron work is not safe to run twice at once: autopay charges cards, the mail queue
* sends client email, the parser creates tickets. If a run is still going when the next
* one fires, those actions can happen twice. The lock name is derived from the calling
* script's full path, so it is unique per script and per install - separate ITFlow
* instances on one host never block each other, and neither do two different cron
* scripts belonging to the same install.
*
* flock is used rather than a lock file whose presence is checked, because checking for
* a file and then creating it is not atomic - two runs starting together can both find
* it absent. flock is also released by the kernel however the process exits, so a killed
* run leaves nothing stale behind and no age heuristic is needed to clean up after it.
*
* Contention is not logged: mail_queue and the email parser run every minute, so hitting
* a run that is still going is expected, not a fault worth reporting. A lock file that
* cannot be opened at all is a real misconfiguration and does report loudly.
*
* TWO WAYS A CRON SCRIPT RUNS
*
* Directly (php cron/mail_queue.php): the guard at the bottom of this file takes the
* lock and holds it for the life of the process, exactly as it always has.
*
* Under the dispatcher (cron/cron.php): the dispatcher takes each job's lock itself,
* runs the job, and releases it before moving on, so a long job does not hold up the
* short ones on the next minute's dispatch. The guard below is skipped in that case -
* the lock is already held for this job, and the jobs share one PHP process, so a lock
* held for the life of the process would be a lock held for the whole cycle.
*
* Because the dispatcher shares one process across jobs, a job must never exit() to end
* itself early - that would take the rest of the cycle down with it. cronJobStop() is
* the replacement: it exits when the script was run directly and unwinds back to the
* dispatcher when it wasn't.
*
* RUNS OUTSIDE THE DISPATCHER
*
* Before 26.08 each job had a crontab line of its own, and an install that kept one - the
* install script wrote them to /etc/cron.d/itflow - runs that job twice a minute: once on
* its own, once by cron.php. The run on its own held the lock, so the dispatcher passed the
* job by, its row never changed, Maintenance > Cron showed it last running days ago and
* Cron Watch said it had fallen behind - while its work got done, and its Off switch was
* ignored. So now:
* - the dispatcher touches a heartbeat file each cycle (cronLockDispatchBeat()), and a run
* on its own with no terminal - cron, a timer - while it is fresh steps aside: cron.php
* runs the job, on its schedule. It leaves a mark (cronLockOutsideFile()) the dispatcher
* records on the job's row, and Maintenance > Cron and Cron Watch say so. An install
* with only its old lines and no cron.php line runs them as before, and a job run by
* hand from a terminal always runs.
* - a run on its own writes "direct" into its lock file, so a dispatcher that finds the
* lock taken can tell who has it.
*
* RUN AS ROOT
*
* A run as root left its lock files, and whatever else it wrote, owned by root. The web
* server's user can't open a lock file root made in /tmp, and every later run of that job
* - and, before 26.12.5, the whole cycle behind it - stopped there until the server was
* restarted. Started as root, cron now becomes the user that owns ITFlow's files first
* (cronLockRunAsOwner()); and a lock file that can't be opened fails that one job, saying
* which file to delete (cronLockAcquire()'s null).
*/
/*
* Thrown by cronJobStop() when a job ends itself early under the dispatcher. Carries the
* message and exit code the script would have exited with, so the dispatcher can record
* why the job stopped.
*/
class CronJobStopped extends Exception
{
}
/*
* End the current cron job early. Direct runs exit exactly as they did before; dispatched
* runs unwind to the dispatcher, which records the reason and carries on with the next job.
*/
function cronJobStop(string $message = '', int $exit_code = 0): void
{
if (defined('ITFLOW_CRON_DISPATCHER')) {
throw new CronJobStopped($message, $exit_code);
}
if ($message !== '') {
echo $message;
}
exit($exit_code);
}
/*
* A cron script's lock file. $script_path must be the script's own __FILE__ (or the same
* resolved path when the dispatcher takes it on the job's behalf), because that path is
* what the lock is named after.
*/
function cronLockFile(string $script_path): string
{
return sys_get_temp_dir() . '/itflow_cron_' . md5($script_path) . '.lock';
}
/*
* Take the single-run lock for a cron script. Returns the open handle on success, false
* when another run holds the lock, or null when the lock file can't be opened at all - one
* another user made, usually root (cronLockFileProblem() says what to do). The handle must
* stay open for as long as the lock is wanted - closing it releases the lock.
*
* $stamp is written into the file while the lock is held: "direct" for a run on its own,
* '' for the dispatcher - so whoever finds the lock taken can tell who has it.
*/
function cronLockAcquire(string $script_path, string $stamp = '')
{
$lock_file = cronLockFile($script_path);
$lock_handle = @fopen($lock_file, 'c');
if ($lock_handle === false) {
return null;
}
if (!flock($lock_handle, LOCK_EX | LOCK_NB)) {
// Closing our own handle does not disturb the lock the other run holds on theirs
fclose($lock_handle);
return false;
}
// Ours now - say whose, for anyone who finds it taken (a stamp left by a run before goes)
@ftruncate($lock_handle, 0);
if ($stamp !== '') {
@fwrite($lock_handle, $stamp);
@fflush($lock_handle);
}
return $lock_handle;
}
/* Who holds a lock found taken: 'direct' (unattended), 'terminal' (run by hand) or '' (the dispatcher, or unknown). */
function cronLockHolder(string $script_path): string
{
$stamp = trim((string) @file_get_contents(cronLockFile($script_path), false, null, 0, 100));
return in_array($stamp, ['direct', 'terminal'], true) ? $stamp : '';
}
/* Why a lock file can't be opened, and what to do about it - for the job's error. */
function cronLockFileProblem(string $script_path): string
{
$lock_file = cronLockFile($script_path);
$owner = @fileowner($lock_file);
$name = $owner !== false && function_exists('posix_getpwuid') ? (posix_getpwuid($owner)['name'] ?? "user $owner") : '';
if ($owner === false) {
return "Can't make its lock file, $lock_file - check that the temp folder can be written to, and open_basedir.";
}
return "Can't open its lock file, $lock_file" . ($name !== '' ? " - it belongs to $name, from a run as that user" : '')
. ". Delete it - it's only a lock: sudo rm $lock_file - or restart the server. Cron runs as the user that owns ITFlow's files from now on.";
}
/* The heartbeat the dispatcher touches each cycle, for runs on their own to find (one per install). */
function cronLockDispatchBeat(): string
{
return sys_get_temp_dir() . '/itflow_cron_dispatch_' . md5(dirname(__DIR__, 2)) . '.beat';
}
/* The mark a run on its own leaves when it steps aside or holds the lock - its mtime is when. */
function cronLockOutsideFile(string $script_path): string
{
return sys_get_temp_dir() . '/itflow_cron_' . md5($script_path) . '.outside';
}
/* Whether a person started this - a terminal on its input. Cron, timers and scripts have none. */
function cronLockAttended(): bool
{
return defined('STDIN') && function_exists('stream_isatty') && @stream_isatty(STDIN);
}
/*
* Started as root on an install whose files are another user's: become that user, so nothing
* this run makes - lock files, uploads, backups, git's own files - ends up root's, where the
* web server and the next run can't use it. Root's own install (files owned by root) runs as
* root, as before. An owner with no account here - a container's bind mount, say - is taken
* with the files' group. If it can't be done, or there are no posix functions to do it with,
* the run carries on as root, as it did before 26.12.5, and says so: stopping cron there would
* be worse than the files it leaves.
*/
function cronLockRunAsOwner(): void
{
if (!function_exists('posix_geteuid') || posix_geteuid() !== 0) {
return;
}
$owner = @fileowner(dirname(__DIR__) . '/cron.php');
if ($owner === false || $owner === 0) {
return;
}
$user = posix_getpwuid($owner) ?: null;
$group = $user ? intval($user['gid']) : @filegroup(dirname(__DIR__) . '/cron.php');
$name = $user['name'] ?? "user $owner";
$switched = $group !== false
&& (!$user || @posix_initgroups($user['name'], $group))
&& @posix_setgid($group)
&& @posix_setuid($owner)
&& posix_geteuid() === $owner;
if (!$switched) {
fwrite(STDERR, "Cron was started as root and couldn't become $name, the user that owns ITFlow's files, so it runs as root - run it as that user: sudo -u $name php " . ($_SERVER['argv'][0] ?? 'cron/cron.php') . "\n");
}
}
// First, before anything here can make a file
cronLockRunAsOwner();
/*
* Release a lock taken by cronLockAcquire(). Only the dispatcher needs this - a direct run
* holds its lock until the process ends and the kernel drops it.
*/
function cronLockRelease($lock_handle): void
{
if (is_resource($lock_handle)) {
flock($lock_handle, LOCK_UN);
fclose($lock_handle);
}
}
// Single-run guard for scripts run directly. Skipped under the dispatcher, which locks
// each job itself - see the note above.
if (!defined('ITFLOW_CRON_DISPATCHER')) {
if (!isset($cron_lock_script)) {
die("Cron scripts must set \$cron_lock_script = __FILE__ before requiring cron/includes/cron_lock.php.\n");
}
$cron_lock_attended = cronLockAttended();
// Unattended - a crontab line from before 26.08, say - while cron.php is running: cron.php runs this
// job on its schedule, so this run steps aside, and leaves a mark for Maintenance > Cron to say so
$cron_lock_beat = @filemtime(cronLockDispatchBeat());
if (!$cron_lock_attended && $cron_lock_beat && time() - $cron_lock_beat < 180) {
@touch(cronLockOutsideFile($cron_lock_script));
exit(0);
}
$cron_lock_handle = cronLockAcquire($cron_lock_script, $cron_lock_attended ? 'terminal' : 'direct');
if ($cron_lock_handle === null) {
echo cronLockFileProblem($cron_lock_script) . "\n";
exit(1);
}
if ($cron_lock_handle === false) {
// Exit silently. On a per-minute schedule, finding a previous run still going is
// normal operation rather than an error, and anything written to stdout here would
// be mailed to the crontab owner every single minute for the length of that run.
exit(0);
}
// The handle is deliberately left open: the lock is held for the life of the process.
}