Cron and runs outside it (DB 4.4.2): old crontab lines that run job scripts on their own, like those the install script left in /etc/cron.d/itflow before 26.08, are listed on Maintenance > Cron, Debug and in Cron Watch's email (cronStrayLines()); such a run without a terminal steps aside while cron.php is running, and one cron.php finds holding the lock is recorded on the job (cron_job_outside_at) and said as started by something other than cron.php instead of fallen behind; a lock file the dispatcher can't open fails only that job with the file to delete instead of ending the cycle; cron started as root becomes the user that owns ITFlow's files first (cronLockRunAsOwner()); 26.12.5 changelog and CONTRIBUTING.md

This commit is contained in:
johnnyq
2026-12-02 18:58:46 -05:00
parent 9e74c0240a
commit 0c7b521f57
10 changed files with 436 additions and 19 deletions

View File

@@ -6,7 +6,10 @@ This file documents all notable changes made to ITFlow.
### Upgrading to 26.12.5
Update from Maintenance > Update as usual. There are no database changes.
Update from Maintenance > Update as usual. This release has one database change, 4.4.2, which keeps when a cron job was last started by something other than cron.php.
- If ITFlow was installed with the install script before 26.08, `/etc/cron.d/itflow` may still have a line for each job besides the `cron.php` one - the 26.08 upgrade asked for them to come out. Maintenance > Cron now lists any it finds, with the file and line. Take them out: `cron.php` runs every job. Until then they step aside while `cron.php` is running, so nothing runs twice.
- Cron started as root - a crontab line for root, or `php cron/cron.php` typed in a root shell - now runs as the user that owns ITFlow's files, so what it makes is that user's.
### New Features & Updates
@@ -15,12 +18,15 @@ Update from Maintenance > Update as usual. There are no database changes.
### Bug Fixes
- A cron job that an old cron line also ran - the line for the Ticket Email Parser or the Mail Queue left in `/etc/cron.d/itflow` by the install script before 26.08 - no longer looks stopped. The old line's run took the job's lock, so `cron.php` passed it by: its last run on Maintenance > Cron stayed days old and Cron Watch emailed that it had fallen behind, while its work got done - and turning it off didn't stop it. Now the old line's run steps aside while `cron.php` is running, Maintenance > Cron lists the lines to take out, with the file and line, and so do Debug and Cron Watch's email. A line ITFlow can't see - in a user's own crontab - is still found from its runs, and said with where to look.
- A cron job whose lock file was made by a run as root no longer stops cron. The web server's user can't open such a file, and every job after it in the list stopped, every minute, without a word - Cron Watch with them - until the server restarted. Now that job fails, saying which file to delete, and the rest run. Cron started as root now becomes the user that owns ITFlow's files first, so it doesn't leave such files - or uploads, backups and git files the web server can't use - behind.
- AI Triage no longer runs every minute when AI triage is off in Settings > Tickets or there's no AI model to ask - before, it ran anyway and showed **Completed** every minute with nothing done.
### Developer Updates
- `getActiveAgentUserCount()` (`functions/app.php`) leaves out `users.user_service_account = 1` with `serviceAccountsOutSql()`, so `getAgentSeatsTaken()`, `agentUserLimitReached()` and the managed report's `agents.active` do too (the report's list still carries them, with `service` set). `admin/post/users.php` skips `agentUserLimitReached()` for an API / service account in `add_user`, `activate_user`, `restore_user` and `bulk_activate_users`, and `edit_user` refuses turning an active one into an agent at the limit before changing anything (`serviceAccountLeavingNeedsSeat()`, `functions/service_account.php`). Admin > Users keeps New User open at the limit when service accounts are available, and the New User window says one can still be added.
- Cron jobs can declare `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why the job has nothing to do on this install or `''` (`cronJobNotInUse()`, which counts a check that throws as in use; `cronJobSettings()` reads the settings the checks need once a request). `cron/cron.php` reads every job's row and Run Now flag once a cycle and skips a job not in use before its lock and claim - registering its row the first time (`cronJobRegister()`, split out of `cronJobClaim()`) - unless it is asked to Run Now. `cronHealthJobs()` leaves such jobs out, so Cron Watch neither waits on nor flags them, and `admin/cron.php` shows them in a new `unused` state. Checks added for `manager_checkin`, `mail_queue`, `sms_queue`, `rmm_sync`, `rmm_alerts`, `ticket_email_parser`, `ai_triage`, `managed_instances`, `payment_provider_fees` and `update_check`, each the same condition its script stops on. `aiTriageNotInUse()` (`functions/ai_ticket.php`) is new, and `cron/ai_triage.php` now stops on it too. CONTRIBUTING.md has the rule.
- Cron and runs outside it (database 4.4.2, `cron_jobs.cron_job_outside_at`): `cron/includes/cron_lock.php` gains `cronLockFile()`, `cronLockHolder()`, `cronLockFileProblem()`, `cronLockDispatchBeat()`, `cronLockOutsideFile()`, `cronLockAttended()` and `cronLockRunAsOwner()`, run first: started as root on an install whose `cron/cron.php` is another user's, it calls `posix_initgroups()`, `posix_setgid()` and `posix_setuid()` to become that user, or exits saying how to run it. `cronLockAcquire($path, $stamp)` returns null for a lock file it can't open (it used to `die()`, ending the dispatch at that job), and writes `direct` or `terminal` into the file while a run on its own holds it. The dispatcher touches the heartbeat file each cycle; a run on its own without a terminal on STDIN (`stream_isatty()`) while it is under 180 seconds old exits 0, quietly, and touches its `.outside` file. The dispatcher records that file's time, or a lock found held by a `direct` run, as `cron_job_outside_at` (`cronJobNoteOutside()`, at most every ten minutes), and fails a job whose lock can't be opened with `cronLockFileProblem()` as its error (`cronJobLockFailed()`, logged to App Logs once). `functions/cron_health.php`: `cronStrayLines()` reads `/etc/crontab` and the `/etc/cron.d` files cron would read for lines that run this install's job scripts on their own (anything in `cron/` but `cron.php`, and the old `scripts/cron*.php` and `cron_*.php`), `cronStrayText()`, `cronStrayWhat()`, `cronOutsideJobs()` (the last `CRON_HEALTH_OUTSIDE_HOURS`, 26), `cronOutsideReady()` and `cronFilesOwner()`; `cronHealthProblems()` adds a `stray` problem and an `outside` one per job the lines don't cover, and doesn't call a job overdue while it is run outside. `health.php` leaves both kinds out, so an uptime monitor doesn't go red for them. Maintenance > Cron has a card for the lines (`data-cron-stray`, `data-cron-stray-line`) and a note on each job run outside (`data-cron-outside`); Debug's Background jobs adds Old cron lines. CONTRIBUTING.md has the rule.
## [26.12.4]

View File

@@ -110,6 +110,8 @@ A job can also ship switched off with `'enabled' => 0` in the registry. The row
A job whose work hangs on a feature that can be off or not set up - texting, an RMM provider, AI triage, a mailbox - declares `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why it has nothing to do or `''` when it has. The dispatcher then doesn't lock, claim or load it at all, Maintenance > Cron shows it as **Not in use** with the reason, and Cron Watch doesn't expect it to run. Make it the same check the script stops on - cheap, and the database only, never the network - so leaving the job out never leaves its work undone; the script keeps its own check, for Run Now and for running it by hand.
A job's script can still be run on its own - `php cron/mail_queue.php`, from **Copy the Command to Run It** - and before 26.08 each one had a crontab line of its own, which some installs keep. Such a run without a terminal while `cron.php` has run in the last three minutes steps aside: the dispatcher runs the job, on its schedule and under its switch, and records that something else tried (`cron_job_outside_at`), and Maintenance > Cron, Debug and Cron Watch name the lines in `/etc/crontab` and `/etc/cron.d` to take out. Run from a terminal, a script always runs. Started as root, cron becomes the user that owns ITFlow's files before it makes anything (`cronLockRunAsOwner()`), and a lock file the dispatcher can't open fails only that job. Don't take any of that away: a lock file left by another user used to stop every job after it, silently, until the server restarted.
`config_enable_cron` is a second, coarser switch that sits above the per-job ones. It is **not** enforced by the dispatcher — every job checks it in its own header and stops itself with `cronJobStop()`. A new job has to make that check too; one that skips it keeps running on an install that believes cron is off, which is exactly the trap `ticket_email_parser` and `ticket_sla` sat in until 26.08.
Be precise about what it does, because it is easy to oversell. It is **not** a guard on restored data: a full backup dumps the `settings` table, so a restored copy comes back with `config_enable_cron = 1` alongside every enabled `cron_jobs` row, exactly as production had them. What it gives you is one reversible bit — the fastest way to stop an install acting on live data once you have noticed, and the only way to stop everything without editing seven rows.

View File

@@ -65,7 +65,7 @@ $tidy_reason = function ($reason) {
$job_rows = [];
$sql = mysqli_query($mysqli, "SELECT cron_job_daily_at, cron_job_enabled, cron_job_id, cron_job_interval_minutes,
cron_job_last_duration, cron_job_last_error, cron_job_last_error_at, cron_job_last_run_at, cron_job_last_status,
cron_job_name, cron_job_run_now, cron_job_schedule FROM cron_jobs");
cron_job_name, cron_job_run_now, cron_job_schedule" . (cronOutsideReady() ? ', cron_job_outside_at' : '') . " FROM cron_jobs");
while ($job_row = mysqli_fetch_assoc($sql)) {
$job_rows[$job_row['cron_job_name']] = $job_row;
}
@@ -100,6 +100,8 @@ foreach (cronJobRegistry() as $position => $entry) {
'last_error_at' => $job_row['cron_job_last_error_at'] ?? null,
'reason' => '',
'not_in_use' => cronJobNotInUse($entry),
// Run by something other than cron.php lately - an old crontab line (functions/cron_health.php)
'outside_at' => !empty($job_row['cron_job_outside_at']) && strtotime($job_row['cron_job_outside_at']) > time() - CRON_HEALTH_OUTSIDE_HOURS * 3600 ? $job_row['cron_job_outside_at'] : null,
];
$job['schedule_text'] = cronJobScheduleDescription($job['schedule'], $job['interval_minutes'], $job['daily_at']);
$job['every_minute'] = $job['schedule'] !== 'Daily' && $job['interval_minutes'] === 1;
@@ -137,6 +139,10 @@ foreach (cronJobRegistry() as $position => $entry) {
$jobs[$job['name']] = $job;
}
// Old crontab lines that run job scripts on their own, besides cron.php
$stray_lines = cronStrayLines();
$stray_jobs = array_filter(array_column($stray_lines, 'job'));
$jobs_on = array_filter($jobs, function ($job) { return $job['enabled']; });
$jobs_off = count($jobs) - count($jobs_on);
// On, with nothing to do here yet
@@ -344,6 +350,33 @@ $status_looks = [
</div>
</div>
<?php if ($stray_lines) { ?>
<!-- Old crontab lines that run jobs again, outside cron.php (functions/cron_health.php) -->
<div class="card mb-3 border-warning" data-cron-stray>
<div class="card-body">
<div class="d-flex align-items-start gap-3">
<i class="fas fa-fw fa-exclamation-triangle text-warning mt-1" aria-hidden="true"></i>
<div class="flex-grow-1 min-w-0">
<div class="fw-semibold">Old cron lines run some jobs a second time</div>
<p class="text-body-secondary small mb-2">
Before 26.08 each job had a cron line of its own. These are still in the server's cron files and start their jobs on their own, besides
<code>cron.php</code>. While <code>cron.php</code> is running they step aside, so the schedules and switches here hold - but whenever it isn't, they run their jobs outside them. Take them out - <code>cron.php</code> runs every job now:
</p>
<?php foreach ($stray_lines as $stray_line) { ?>
<div class="small mb-2" data-cron-stray-line>
<div><strong><?= escapeHtml($stray_line['file']) ?></strong>, line <?= intval($stray_line['line']) ?> - <?= escapeHtml(cronStrayWhat($stray_line)) ?></div>
<pre class="itflow-command bg-body-tertiary border rounded p-2 mb-0 mt-1 small text-wrap text-break"><code><?= escapeHtml($stray_line['text']) ?></code></pre>
</div>
<?php } ?>
<p class="text-body-secondary small mb-0">
Put <code>#</code> in front of each, or delete the file if every line in it is one of these - with <code>sudo nano</code>, say. Then this goes by itself.
</p>
</div>
</div>
</div>
</div>
<?php } ?>
<!-- Every job: what it does, its schedule, and how its last run went -->
<div class="card mb-3">
<div class="card-header py-3">
@@ -449,6 +482,11 @@ $status_looks = [
<div class="small text-body-secondary mt-1 text-break" data-cron-reason><i class="fas fa-fw fa-info-circle me-1"></i><?= escapeHtml($reason) ?></div>
<?php } ?>
<?php if ($job['outside_at']) { ?>
<div class="small text-warning-emphasis mt-1" data-cron-outside><i class="fas fa-fw fa-exclamation-triangle me-1"></i>Also started by something other than cron.php, last <?= $ago($job['outside_at']) ?> -
<?= in_array($job['name'], $stray_jobs, true) ? 'an old cron line, above.' : 'a crontab line from before 26.08, most likely: look with <code>crontab -l</code>, as root and as ' . escapeHtml(cronFilesOwner()) . '.' ?> Take it out - while cron.php runs, it steps aside.</div>
<?php } ?>
<?php if ($job['last_error'] !== '') { ?>
<div class="d-flex align-items-start gap-2 small rounded bg-danger-subtle text-danger-emphasis p-2 mt-2" data-cron-error>
<i class="fas fa-fw fa-exclamation-triangle mt-1" aria-hidden="true"></i>

View File

@@ -0,0 +1,21 @@
<?php
/*
* ITFlow - Database update to version 4.4.2 (from 4.4.1)
* Included by admin/database_updates.php - do not access directly
*
* cron_jobs.cron_job_outside_at - when the job was last found run by something other than cron.php: a crontab
* line from before 26.08 that runs its script on its own. Such a run steps aside while cron.php is running, or
* holds the job's lock when it isn't, and the dispatcher records it here (cron/cron.php, cron/includes/cron_lock.php);
* Maintenance > Cron and Cron Watch say so (functions/cron_health.php).
*
* Re-runnable: the column is made only where it isn't there.
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
$itflow_cron_outside = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'cron_jobs' AND COLUMN_NAME = 'cron_job_outside_at' LIMIT 1");
if (!$itflow_cron_outside || mysqli_num_rows($itflow_cron_outside) === 0) {
mysqli_query($mysqli, "ALTER TABLE `cron_jobs` ADD `cron_job_outside_at` datetime DEFAULT NULL AFTER `cron_job_last_error_at`");
}

View File

@@ -161,6 +161,51 @@ function cronJobClaim($mysqli, array $job, string $paused = ''): bool
return mysqli_affected_rows($mysqli) === 1;
}
/*
* Note that $job was run by something other than cron.php at $seen (a timestamp) - an old crontab line that
* runs its script on its own (cron/includes/cron_lock.php). Written at most every ten minutes: such a line
* runs every minute, and Maintenance > Cron and Cron Watch only need to know it still does.
*/
function cronJobNoteOutside($mysqli, array $job, int $seen, array &$rows): void
{
if (!cronOutsideReady()) {
return;
}
$last = $rows[$job['name']]['outside_at'] ?? null;
if ($last && strtotime($last) > $seen - 600) {
return;
}
if (!isset($rows[$job['name']])) {
cronJobRegister($mysqli, $job);
}
$at = date('Y-m-d H:i:s', $seen);
mysqli_query($mysqli, "UPDATE cron_jobs SET cron_job_outside_at = '$at' WHERE cron_job_name = '" . escapeSql($job['name']) . "'");
$rows[$job['name']]['outside_at'] = $at;
}
/*
* The job's lock file can't be opened - another user made it, root most likely. The job can't run until it's
* gone, so it fails, saying which file to delete, and the cycle carries on with the next job. Logged when it
* starts, and its error's time kept within the hour while it lasts - not rewritten every minute.
*/
function cronJobLockFailed($mysqli, array $job, string $problem): void
{
cronJobRegister($mysqli, $job);
$name = escapeSql($job['name']);
$error = escapeSql(substr($problem, 0, 1000));
$now = date('Y-m-d H:i:s');
$hour_ago = date('Y-m-d H:i:s', time() - 3600);
mysqli_query($mysqli, "UPDATE cron_jobs SET cron_job_last_status = 'Failed', cron_job_last_error = '$error', cron_job_last_error_at = '$now'
WHERE cron_job_name = '$name' AND NOT (cron_job_last_status <=> 'Failed' AND cron_job_last_error <=> '$error' AND cron_job_last_error_at > '$hour_ago')");
if (mysqli_affected_rows($mysqli) === 1) {
try {
logApp("Cron", "error", "Cron job {$job['name']} can't run: $problem");
} catch (Throwable $e) {
// Logging must never end the cycle it is reporting on
}
}
}
/*
* Record how a job ended. The status is the outcome of the run that just happened; the error
* is sticky and survives later successes, because the run that failed is usually long gone by
@@ -211,6 +256,10 @@ if (backupRestoreInProgress()) {
// "no job was due" apart from "nothing has run this since the server was rebuilt".
mysqli_query($mysqli, "UPDATE settings SET config_cron_last_dispatch_at = '" . date('Y-m-d H:i:s') . "' WHERE company_id = 1");
// And one a job's script run on its own can see without the database - while it's fresh, such a run steps
// aside and leaves this to run the job (cron/includes/cron_lock.php)
@touch(cronLockDispatchBeat());
// Best effort: ask the server not to hang up while a long job is quiet.
if (function_exists('backupDbHoldOpen')) {
backupDbHoldOpen($mysqli);
@@ -235,9 +284,9 @@ $cron_dispatch_stop_cycle = false;
* Maintenance > Cron can change it, and run when somebody asks.
*/
$cron_dispatch_rows = [];
$cron_dispatch_result = mysqli_query($mysqli, "SELECT cron_job_name, cron_job_run_now FROM cron_jobs");
$cron_dispatch_result = mysqli_query($mysqli, "SELECT cron_job_name, cron_job_run_now, " . (cronOutsideReady() ? 'cron_job_outside_at' : 'NULL AS cron_job_outside_at') . " FROM cron_jobs");
while ($cron_dispatch_result && ($cron_dispatch_row = mysqli_fetch_assoc($cron_dispatch_result))) {
$cron_dispatch_rows[$cron_dispatch_row['cron_job_name']] = intval($cron_dispatch_row['cron_job_run_now']);
$cron_dispatch_rows[$cron_dispatch_row['cron_job_name']] = ['run_now' => intval($cron_dispatch_row['cron_job_run_now']), 'outside_at' => $cron_dispatch_row['cron_job_outside_at']];
}
register_shutdown_function(function () use (&$cron_dispatch_running, &$cron_dispatch_started, $mysqli) {
@@ -262,8 +311,14 @@ foreach (cronJobRegistry() as $cron_dispatch_job) {
continue;
}
// A run of its script on its own stepped aside for this one since we last looked - an old crontab line
$cron_dispatch_outside = @filemtime(cronLockOutsideFile($cron_dispatch_path));
if ($cron_dispatch_outside) {
cronJobNoteOutside($mysqli, $cron_dispatch_job, $cron_dispatch_outside, $cron_dispatch_rows);
}
// Nothing to do here - its feature is off or not set up - so it isn't run at all, unless asked to
if (empty($cron_dispatch_rows[$cron_dispatch_job['name']]) && cronJobNotInUse($cron_dispatch_job) !== '') {
if (empty($cron_dispatch_rows[$cron_dispatch_job['name']]['run_now']) && cronJobNotInUse($cron_dispatch_job) !== '') {
if (!isset($cron_dispatch_rows[$cron_dispatch_job['name']])) {
cronJobRegister($mysqli, $cron_dispatch_job);
}
@@ -273,7 +328,17 @@ foreach (cronJobRegistry() as $cron_dispatch_job) {
// Locked before the schedule is consulted: if the previous run of this job is still
// going there is nothing to decide, and its claim already stands.
$cron_dispatch_lock = cronLockAcquire($cron_dispatch_path);
if ($cron_dispatch_lock === null) {
// A lock file another user made - this job fails, saying which, and the rest of the cycle runs
cronJobLockFailed($mysqli, $cron_dispatch_job, cronLockFileProblem($cron_dispatch_path));
continue;
}
if ($cron_dispatch_lock === false) {
// Taken by its script run on its own, unattended - an old crontab line, before this cycle's heartbeat
// was there for it to see - is worth saying; one run by hand, or still going from before, isn't
if (cronLockHolder($cron_dispatch_path) === 'direct') {
cronJobNoteOutside($mysqli, $cron_dispatch_job, time(), $cron_dispatch_rows);
}
continue;
}

View File

@@ -37,6 +37,32 @@
* 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).
*/
/*
@@ -66,20 +92,31 @@ function cronJobStop(string $message = '', int $exit_code = 0): void
}
/*
* Take the single-run lock for a cron script. $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.
*
* Returns the open handle on success, or false when another run holds the lock. The
* handle must stay open for as long as the lock is wanted - closing it releases the lock.
* 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 cronLockAcquire(string $script_path)
function cronLockFile(string $script_path): string
{
$lock_file = sys_get_temp_dir() . '/itflow_cron_' . md5($script_path) . '.lock';
return sys_get_temp_dir() . '/itflow_cron_' . md5($script_path) . '.lock';
}
$lock_handle = fopen($lock_file, 'c');
/*
* 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) {
die("Cannot open the cron lock file at $lock_file - check permissions and open_basedir.\n");
return null;
}
if (!flock($lock_handle, LOCK_EX | LOCK_NB)) {
@@ -88,9 +125,88 @@ function cronLockAcquire(string $script_path)
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.
@@ -111,7 +227,22 @@ if (!defined('ITFLOW_CRON_DISPATCHER')) {
die("Cron scripts must set \$cron_lock_script = __FILE__ before requiring cron/includes/cron_lock.php.\n");
}
$cron_lock_handle = cronLockAcquire($cron_lock_script);
$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

1
db.sql
View File

@@ -1449,6 +1449,7 @@ CREATE TABLE `cron_jobs` (
`cron_job_last_status` varchar(200) DEFAULT NULL,
`cron_job_last_error` text DEFAULT NULL,
`cron_job_last_error_at` datetime DEFAULT NULL,
`cron_job_outside_at` datetime DEFAULT NULL,
PRIMARY KEY (`cron_job_id`),
UNIQUE KEY `cron_job_name` (`cron_job_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

View File

@@ -21,6 +21,8 @@
// A job still running after this many minutes counts as stuck
const CRON_HEALTH_STUCK_MINUTES = 120;
// A job run by something other than cron.php is said so for this long after the last time - a day and a bit, for a nightly line
const CRON_HEALTH_OUTSIDE_HOURS = 26;
// The dispatcher writes its heartbeat every minute - older than this and cron isn't running
const CRON_HEALTH_HEARTBEAT_SECONDS = 300;
@@ -70,7 +72,7 @@ function cronHealthJobs() {
$kept = $mode === 'active' ? null : (MANAGED_KEEP_JOBS[$mode] ?? []);
$rows = [];
$result = mysqli_query($mysqli, "SELECT cron_job_name, cron_job_schedule, cron_job_interval_minutes, cron_job_daily_at, cron_job_last_run_at,
cron_job_last_status, cron_job_last_error, cron_job_last_error_at FROM cron_jobs WHERE cron_job_enabled = 1");
cron_job_last_status, cron_job_last_error, cron_job_last_error_at, " . (cronOutsideReady() ? 'cron_job_outside_at' : 'NULL AS cron_job_outside_at') . " FROM cron_jobs WHERE cron_job_enabled = 1");
while ($row = mysqli_fetch_assoc($result)) {
$rows[$row['cron_job_name']] = $row;
}
@@ -146,6 +148,23 @@ function cronHealthProblems($fresh = false) {
return $problems;
}
// Old crontab lines that run job scripts on their own, and jobs found run that way
$outside = cronOutsideJobs();
$stray = cronStrayLines();
if ($stray) {
$problems[] = ['key' => 'stray:' . md5(json_encode(array_column($stray, 'text'))), 'job' => '', 'label' => 'Cron', 'kind' => 'stray',
'text' => cronStrayText($stray),
'detail' => implode("\n", array_map(function ($line) { return $line['file'] . ' line ' . $line['line'] . ': ' . $line['text']; }, $stray))];
}
$stray_jobs = array_filter(array_column($stray, 'job'));
foreach ($outside as $name => $job) {
if (!in_array($name, $stray_jobs, true)) {
$problems[] = ['key' => "outside:$name", 'job' => $name, 'label' => $job['label'], 'kind' => 'outside', 'detail' => '',
'text' => $job['label'] . ' is started by something other than cron.php too - last ' . timeAgo($job['at'])
. '. A crontab line from before 26.08, most likely - crontab -l, as root and as ' . cronFilesOwner() . '. Take it out: cron.php runs it now.'];
}
}
foreach (cronHealthJobs() as $name => $job) {
$label = $job['label'];
$status = (string) $job['cron_job_last_status'];
@@ -168,7 +187,8 @@ function cronHealthProblems($fresh = false) {
} elseif ($status === 'Running' && time() - strtotime($job['cron_job_last_run_at']) > CRON_HEALTH_STUCK_MINUTES * 60) {
$problems[] = ['key' => "stuck:$name", 'job' => $name, 'label' => $label, 'kind' => 'stuck', 'detail' => '',
'text' => "$label started " . timeAgo($job['cron_job_last_run_at']) . ' and is still running - it may have stopped part way.'];
} elseif ($running && cronHealthOverdue($job)) {
} elseif ($running && cronHealthOverdue($job) && !isset($outside[$name])) {
// Behind because something else runs it is said above, as what it is
// Late only means something while cron is running - otherwise "isn't running" says it all
$problems[] = ['key' => "overdue:$name", 'job' => $name, 'label' => $label, 'kind' => 'overdue', 'detail' => '',
'text' => "$label is behind - it last ran " . timeAgo($job['cron_job_last_run_at']) . '.'];
@@ -341,3 +361,127 @@ function cronHealthUrl() {
global $config_base_url;
return 'https://' . $config_base_url . '/health.php?key=' . cronHealthKey();
}
/** Whether the 4.4.2 update has run - cron_jobs.cron_job_outside_at is there. */
function cronOutsideReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
if (defined('CURRENT_DATABASE_VERSION')) {
$version = CURRENT_DATABASE_VERSION;
} else {
$result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1");
$version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0';
}
$ready = version_compare($version, '4.4.2', '>=');
}
return $ready;
}
/*
* The jobs found run by something other than cron.php in the last CRON_HEALTH_OUTSIDE_HOURS - an old
* crontab line that runs the job's script on its own (cron/includes/cron_lock.php): name => ['label', 'at'].
* Whether the job is on or off - a line that runs a job switched off is the point.
*/
function cronOutsideJobs() {
global $mysqli;
if (!cronOutsideReady()) {
return [];
}
require_once __DIR__ . '/../includes/cron_jobs.php';
$registry = cronJobRegistryByName();
$since = date('Y-m-d H:i:s', time() - CRON_HEALTH_OUTSIDE_HOURS * 3600);
$jobs = [];
$result = mysqli_query($mysqli, "SELECT cron_job_name, cron_job_outside_at FROM cron_jobs WHERE cron_job_outside_at > '$since'");
while ($result && ($row = mysqli_fetch_assoc($result))) {
if (isset($registry[$row['cron_job_name']])) {
$jobs[$row['cron_job_name']] = ['label' => $registry[$row['cron_job_name']]['label'], 'at' => $row['cron_job_outside_at']];
}
}
return $jobs;
}
/*
* Lines in the system's cron files - /etc/crontab and /etc/cron.d - that run one of this install's job scripts
* on its own: a script in cron/ other than cron.php, or the scripts/cron*.php and cron_*.php from before 26.08.
* The install script wrote them to /etc/cron.d/itflow, and since 26.08 cron.php runs every job, so they only run
* the job a second time, outside its schedule and its Off switch. Each: file, line (from 1), text, script (as the
* line names it), job and label (the job it is for), gone (the script isn't there any more - the line only errors).
* A file cron itself skips - a name
* with a dot, like itflow.bak - isn't read, and nor is anything this user can't read (users' own crontabs).
* $files is for tests.
*/
function cronStrayLines(?array $files = null) {
$root = dirname(__DIR__);
$roots = array_values(array_unique(array_filter([$root, (string) realpath($root)])));
if ($files === null) {
$files = ['/etc/crontab'];
foreach ((@scandir('/etc/cron.d') ?: []) as $name) {
if (preg_match('/^[A-Za-z0-9_-]+$/', $name)) {
$files[] = "/etc/cron.d/$name";
}
}
}
require_once __DIR__ . '/../includes/cron_jobs.php';
$by_script = [];
foreach (cronJobRegistry() as $job) {
$by_script[$job['script']] = $job;
}
$found = [];
foreach ($files as $file) {
if (!@is_file($file) || !@is_readable($file)) {
continue;
}
foreach ((@file($file, FILE_IGNORE_NEW_LINES) ?: []) as $i => $text) {
$text = trim($text);
if ($text === '' || $text[0] === '#') {
continue;
}
foreach ($roots as $install) {
// This install's folder - /var/www/itflow/cron/x.php, or cd /var/www/itflow && php cron/x.php - not /var/www/itflow2's
if (!preg_match('#' . preg_quote(rtrim($install, '/'), '#') . '(?=[/\s;&|"\']|$)#', $text)
|| !preg_match('#(?:^|[\s/])(cron/(?!cron\.php\b)[A-Za-z0-9_]+\.php|scripts/cron[A-Za-z0-9_]*\.php|cron_[A-Za-z0-9_]+\.php)#', $text, $match)) {
continue;
}
// cron/mail_queue.php, or what it was called before: scripts/cron_mail_queue.php, cron_mail_queue.php
$script = preg_replace('#^(?:cron/|scripts/)?(?:cron_)?#', '', $match[1]);
$job = $by_script[$script] ?? null;
$found[] = ['file' => $file, 'line' => $i + 1, 'text' => mb_substr($text, 0, 300), 'script' => $match[1],
'job' => $job['name'] ?? '', 'label' => $job['label'] ?? '', 'gone' => !is_file(rtrim($install, '/') . '/' . $match[1])];
break;
}
}
}
return $found;
}
/* What cronStrayLines() found, in a sentence: which file and lines, and what they run. */
function cronStrayText(array $stray) {
$by_file = [];
foreach ($stray as $line) {
$by_file[$line['file']][] = 'line ' . $line['line'] . ' (' . cronStrayWhat($line) . ')';
}
$where = [];
foreach ($by_file as $file => $lines) {
$where[] = $file . ' ' . implode(', ', $lines);
}
return 'Old cron lines run ITFlow\'s jobs on their own, besides cron.php: ' . implode('; ', $where)
. '. Take them out - cron.php runs every job now. While it runs they step aside, but whenever it doesn\'t, they run their jobs outside the schedules and switches on Maintenance > Cron.';
}
/* The user that owns ITFlow's files - who cron should run as. */
function cronFilesOwner() {
$owner = @fileowner(dirname(__DIR__) . '/cron/cron.php');
if ($owner !== false && function_exists('posix_getpwuid')) {
return (string) (posix_getpwuid($owner)['name'] ?? 'the user that owns ITFlow\'s files');
}
return 'the user that owns ITFlow\'s files';
}
/* What a stray line is for: "Mail Queue", or "an old Mail Queue script that no longer exists - it only errors". */
function cronStrayWhat(array $line) {
if (!$line['gone']) {
return $line['label'] !== '' ? $line['label'] : $line['script'];
}
return 'an old ' . ($line['label'] !== '' ? $line['label'] . ' ' : '') . 'script that no longer exists - it only errors';
}

View File

@@ -216,6 +216,11 @@ function healthJobChecks() {
} else {
$items[] = healthItem('Cron', 'ok', 'Last ran ' . healthAgo($heard));
}
// Old crontab lines that run job scripts on their own, besides cron.php (functions/cron_health.php)
$stray = function_exists('cronStrayLines') ? cronStrayLines() : [];
if ($stray) {
$items[] = healthItem('Old cron lines', 'warning', count($stray) . ' still there', escapeHtml(cronStrayText($stray)), 'cron.php', 'Maintenance > Cron');
}
if (empty($settings['config_enable_cron'])) {
$items[] = healthItem('Cron switch', 'danger', 'Off', 'Every job stops itself while it is off. Turn it on, unless this is a copy that mustn\'t email clients or charge cards.', 'cron.php', 'Maintenance > Cron');
}

View File

@@ -39,7 +39,11 @@ if ($health_key === '' || !hash_equals($health_key, $health_given)) {
}
try {
$health_problems = cronHealthProblems();
// Old cron lines that run jobs a second time are for tidying up, not for waking someone - the jobs still run
// (Maintenance > Cron and Cron Watch's email say so)
$health_problems = array_values(array_filter(cronHealthProblems(), function ($problem) {
return !in_array($problem['kind'], ['stray', 'outside'], true);
}));
} catch (Throwable $e) {
http_response_code(503);
exit("PROBLEM\n- The health check could not read the database\n");