Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,13 @@ WordPress Request Worker Process (Workerman)
|
Timer triggers at scheduled time
|
Claim job (INSERT IGNORE lock)
|
Batch by site_id
|
+------------------------------+
Claim job (INSERT IGNORE lock)
|
Batch by site_id
|
Acquire per-site WP-Cron execution lease
|
+------------------------------+
| Subprocess: execute-job.php |
| Bootstrap WP for site |
| For each job in batch: |
Expand All @@ -222,9 +224,9 @@ WordPress Request Worker Process (Workerman)
2. The plugin intercepts the schedule call and sends a JSON payload to the worker via Unix socket.
3. The worker sets a Workerman timer for the job's exact timestamp.
4. When the timer triggers, the worker atomically claims the job via `INSERT IGNORE` into a lock table (prevents duplicate execution across workers).
5. Claimed jobs are batched by `site_id` and flushed to a subprocess every second.
5. Claimed jobs are batched by `site_id` and flushed to a subprocess every second. WP-Cron batches acquire a shared per-site lease so separate worker processes cannot update one site's cron option concurrently.
6. The subprocess (`execute-job.php`) bootstraps WordPress for the target site's domain, executes each job with a per-job SIGALRM timeout, logs results to the `qw_job_log` table, and exits.
7. The worker polls subprocesses for completion and logs batch results.
7. The worker polls subprocesses for completion, refreshes active site leases, and logs batch results.
8. A periodic database rescan catches any jobs that arrived before the worker started or bypassed socket notification.

## Troubleshooting
Expand Down
11 changes: 9 additions & 2 deletions src/class-job-payload.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,18 @@ public static function from_as_action(int $action_id): ?self

public function tracking_key(): string
{
if ($this->is_action_scheduler() && $this->action_id > 0) {
return sprintf(
'action_scheduler:%d:%d',
$this->site_id,
$this->action_id
);
}

return sprintf(
'%s:%d:%s:%s:%s:%s:%d',
'%s:%d:%s:%s:%s:%d',
$this->source,
$this->site_id,
md5($this->site_url),
$this->hook,
$this->group,
md5(serialize($this->args)),
Expand Down
192 changes: 176 additions & 16 deletions src/class-worker-process.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
*/
class Worker_Process
{
private const QW_CRON_SITE_LOCK_TTL_SECONDS = 360;
private const QW_CRON_SITE_LOCK_REFRESH_SECONDS = 60;

/** @var string Absolute path to wp-load.php */
private string $wp_load;

Expand Down Expand Up @@ -49,7 +52,7 @@ class Worker_Process
/** @var array<string, Job_Payload> tracking_key => payload */
private array $pending_timer_payloads = [];

/** @var list<array{process: resource, pipes: array, payloads: list<Job_Payload>, started: int, stdout: string, stderr: string, lane: string}> */
/** @var list<array{process: resource, pipes: array, payloads: list<Job_Payload>, started: int, stdout: string, stderr: string, lane: string, cron_site_lock_owner: string, cron_site_lock_refreshed: int}> */
private array $running_processes = [];

/** @var array<string, array<int, list<Job_Payload>>> lane => site_id => [payload, ...] */
Expand Down Expand Up @@ -333,7 +336,12 @@ private function execute_action_scheduler_job(Job_Payload $payload): void
/**
* Spawn a subprocess to execute a batch of jobs (all same site).
*/
private function spawn_batch(array $payloads, int $worker_id, string $lane = 'wp_cron'): void
private function spawn_batch(
array $payloads,
int $worker_id,
string $lane = 'wp_cron',
string $cron_site_lock_owner = ''
): bool
{
$json_array = array_map(
fn($p) => array_merge(json_decode($p->to_json(), true), ['lane' => $lane]),
Expand All @@ -355,7 +363,10 @@ private function spawn_batch(array $payloads, int $worker_id, string $lane = 'wp
count($payloads),
$payloads[0]->site_id
));
return;
if ($cron_site_lock_owner !== '') {
$this->release_cron_site_lock($payloads[0]->site_id, $cron_site_lock_owner);
}
return false;
}

// Write JSON payload to stdin, then close
Expand All @@ -366,13 +377,15 @@ private function spawn_batch(array $payloads, int $worker_id, string $lane = 'wp

$this->running_jobs++;
$this->running_processes[] = [
'process' => $process,
'pipes' => $pipes,
'payloads' => $payloads,
'started' => time(),
'stdout' => '',
'stderr' => '',
'lane' => $lane,
'process' => $process,
'pipes' => $pipes,
'payloads' => $payloads,
'started' => time(),
'stdout' => '',
'stderr' => '',
'lane' => $lane,
'cron_site_lock_owner' => $cron_site_lock_owner,
'cron_site_lock_refreshed' => time(),
];

$hooks = array_map(fn($p) => $p->hook, $payloads);
Expand All @@ -388,6 +401,8 @@ private function spawn_batch(array $payloads, int $worker_id, string $lane = 'wp
$priority_summary,
implode(', ', array_unique($hooks))
));

return true;
}

/**
Expand All @@ -407,10 +422,17 @@ private function flush_batches(): void
if ($this->running_process_count($lane) >= $this->cron_lane_max_concurrent($lane)) {
break;
}
$site_lock_owner = $this->claim_cron_site_lock((int) $site_id);
if ($site_lock_owner === null) {
continue;
}
$this->sort_payloads_by_priority($this->pending_batch[$lane][$site_id]);
$batch = array_splice($this->pending_batch[$lane][$site_id], 0, $this->cron_lane_max_batch_size($lane));
// Worker ID isn't critical for batch flush logging; use 0
$this->spawn_batch($batch, 0, $lane);
if (!$this->spawn_batch($batch, 0, $lane, $site_lock_owner)) {
array_splice($this->pending_batch[$lane][$site_id], 0, 0, $batch);
continue;
}
if (empty($this->pending_batch[$lane][$site_id])) {
unset($this->pending_batch[$lane][$site_id]);
}
Expand Down Expand Up @@ -479,7 +501,10 @@ private function flush_action_scheduler_batches(): void
}
$this->sort_payloads_by_priority($this->pending_as_batch[$lane][$site_id]);
$batch = array_splice($this->pending_as_batch[$lane][$site_id], 0, $this->lane_max_batch_size($lane));
$this->spawn_batch($batch, 0, $lane);
if (!$this->spawn_batch($batch, 0, $lane)) {
array_splice($this->pending_as_batch[$lane][$site_id], 0, 0, $batch);
continue;
}
if (empty($this->pending_as_batch[$lane][$site_id])) {
unset($this->pending_as_batch[$lane][$site_id]);
}
Expand Down Expand Up @@ -708,6 +733,26 @@ private function running_process_count(string $lane): int
private function poll_processes(int $worker_id): void
{
foreach ($this->running_processes as $i => $proc) {
$cron_site_lock_owner = $proc['cron_site_lock_owner'];
$lock_refreshed = $proc['cron_site_lock_refreshed'];
if ($cron_site_lock_owner !== '' && time() - $lock_refreshed >= self::QW_CRON_SITE_LOCK_REFRESH_SECONDS) {
if ($this->refresh_cron_site_lock($proc['payloads'][0]->site_id, $cron_site_lock_owner)) {
$this->running_processes[$i]['cron_site_lock_refreshed'] = time();
} else {
$this->terminate_and_reap_process($proc);
Worker::log(sprintf(
'[W%d][LOCK][LOST] Batch: %d jobs on site %d lost its cron site lease',
$worker_id,
count($proc['payloads']),
$proc['payloads'][0]->site_id
));
$this->release_running_cron_site_lock($proc);
unset($this->running_processes[$i]);
$this->running_jobs--;
continue;
}
}
Comment thread
superdav42 marked this conversation as resolved.
Resolved

// Read available output
$out = stream_get_contents($proc['pipes'][1]);
if ($out !== false && $out !== '') {
Expand Down Expand Up @@ -765,6 +810,7 @@ private function poll_processes(int $worker_id): void
));
}

$this->release_running_cron_site_lock($proc);
unset($this->running_processes[$i]);
$this->running_jobs--;
continue;
Expand All @@ -774,10 +820,7 @@ private function poll_processes(int $worker_id): void
if (time() - $proc['started'] > $this->batch_timeout) {
$payloads = $proc['payloads'];
$pid = $status['pid'];
proc_terminate($proc['process'], 9);
fclose($proc['pipes'][1]);
fclose($proc['pipes'][2]);
proc_close($proc['process']);
$this->terminate_and_reap_process($proc);

Worker::log(sprintf(
'[W%d][TIMEOUT] Batch: %d jobs on site %d exceeded %ds limit (pid %d)',
Expand All @@ -788,6 +831,7 @@ private function poll_processes(int $worker_id): void
$pid
));

$this->release_running_cron_site_lock($proc);
unset($this->running_processes[$i]);
$this->running_jobs--;
}
Expand All @@ -796,6 +840,17 @@ private function poll_processes(int $worker_id): void
$this->running_processes = array_values($this->running_processes);
}

/**
* Stop an active child process and reap its resources.
*/
private function terminate_and_reap_process(array $proc): void
{
proc_terminate($proc['process'], 9);
fclose($proc['pipes'][1]);
fclose($proc['pipes'][2]);
proc_close($proc['process']);
}

/**
* Scan all multisite blogs for pending WP Cron events and AS actions.
*/
Expand Down Expand Up @@ -1120,6 +1175,102 @@ private function claim_job(string $job_key): bool
return $result === 1;
}

/**
* Claim the network-wide WP-Cron execution lease for a site.
*/
private function claim_cron_site_lock(int $site_id): ?string
{
global $wpdb;

if ($site_id < 1) {
return null;
}

try {
$owner_token = bin2hex(random_bytes(16));
} catch (\Throwable $e) {
Worker::log(sprintf('[LOCK][ERROR] Failed to create a cron site-lock token for site %d: %s', $site_id, $e->getMessage()));
return null;
}

$table = $wpdb->base_prefix . 'qw_cron_site_locks';
$ttl = self::QW_CRON_SITE_LOCK_TTL_SECONDS;
$result = $wpdb->query($wpdb->prepare(
"INSERT INTO `$table` (site_id, owner_token, expires_at) "
. "VALUES (%d, %s, DATE_ADD(NOW(), INTERVAL $ttl SECOND)) "
. 'ON DUPLICATE KEY UPDATE '
. 'owner_token = IF(expires_at < NOW(), VALUES(owner_token), owner_token), '
. 'expires_at = IF(expires_at < NOW(), VALUES(expires_at), expires_at)',
$site_id,
$owner_token
));

if ($result === false) {
return null;
}

// Do not rely on affected-row semantics: clients using FOUND_ROWS can
// report a no-op duplicate-key update as successful.
$current_owner = $wpdb->get_var($wpdb->prepare(
"SELECT owner_token FROM `$table` WHERE site_id = %d",
$site_id
));

return is_string($current_owner) && hash_equals($owner_token, $current_owner) ? $owner_token : null;
}

/**
* Extend a site lease while its subprocess is still running.
*/
private function refresh_cron_site_lock(int $site_id, string $owner_token): bool
{
global $wpdb;

$table = $wpdb->base_prefix . 'qw_cron_site_locks';
$ttl = self::QW_CRON_SITE_LOCK_TTL_SECONDS;
$result = $wpdb->query($wpdb->prepare(
"UPDATE `$table` SET expires_at = DATE_ADD(NOW(), INTERVAL $ttl SECOND) "
. 'WHERE site_id = %d AND owner_token = %s',
$site_id,
$owner_token
));

return $result === 1;
}

/**
* Release a site lease only when this worker still owns it.
*/
private function release_cron_site_lock(int $site_id, string $owner_token): void
{
global $wpdb;

if ($site_id < 1 || $owner_token === '') {
return;
}

$table = $wpdb->base_prefix . 'qw_cron_site_locks';
$wpdb->query($wpdb->prepare(
"DELETE FROM `$table` WHERE site_id = %d AND owner_token = %s",
$site_id,
$owner_token
));
}

/**
* Release the optional WP-Cron lease attached to a subprocess record.
*/
private function release_running_cron_site_lock(array $process): void
{
$owner_token = (string) ($process['cron_site_lock_owner'] ?? '');
$payloads = $process['payloads'] ?? [];
if ($owner_token === '' || empty($payloads)) {
return;
}

$this->release_cron_site_lock($payloads[0]->site_id, $owner_token);
}

/**
* Handle incoming socket commands (status, restart).
*/
Expand Down Expand Up @@ -1423,5 +1574,14 @@ public static function ensure_lock_table(): void
claimed_at DATETIME NOT NULL
) ENGINE=InnoDB"
);

$cron_site_locks = $wpdb->base_prefix . 'qw_cron_site_locks';
$wpdb->query("CREATE TABLE IF NOT EXISTS `$cron_site_locks` (
site_id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
owner_token VARCHAR(64) NOT NULL,
expires_at DATETIME NOT NULL,
KEY expires_at (expires_at)
) ENGINE=InnoDB"
);
}
}
Loading