3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Process;
12 use Friendica\Util\DateTimeFormat;
13 use Friendica\Util\Lock;
14 use Friendica\Util\Network;
17 require_once 'include/dba.php';
20 * @file src/Core/Worker.php
22 * @brief Contains the class for the worker background job processing
26 * @brief Worker methods
30 private static $up_start;
31 private static $db_duration;
32 private static $last_update;
33 private static $lock_duration;
36 * @brief Processes the tasks that are in the workerqueue table
38 * @param boolean $run_cron Should the cron processes be executed?
41 public static function processQueue($run_cron = true)
45 self::$up_start = microtime(true);
47 // At first check the maximum load. We shouldn't continue with a high load
48 if ($a->maxload_reached()) {
49 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
53 // We now start the process. This is done after the load check since this could increase the load.
56 // The daemon doesn't need to fork new workers anymore, since we started a process
57 if (Config::get('system', 'worker_daemon_mode', false)) {
58 self::IPCSetJobState(false);
61 // Kill stale processes every 5 minutes
62 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
63 if (time() > ($last_cleanup + 300)) {
64 Config::set('system', 'worker_last_cleaned', time());
65 self::killStaleWorkers();
68 // Count active workers and compare them with a maximum value that depends on the load
69 if (self::tooMuchWorkers()) {
70 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
74 // Do we have too few memory?
75 if ($a->min_memory_reached()) {
76 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
80 // Possibly there are too much database connections
81 if (self::maxConnectionsReached()) {
82 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
86 // Possibly there are too much database processes that block the system
87 if ($a->max_processes_reached()) {
88 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
92 // Now we start additional cron processes if we should do so
99 // We fetch the next queue entry that is about to be executed
100 while ($r = self::workerProcess($passing_slow)) {
101 // When we are processing jobs with a lower priority, we don't refetch new jobs
102 // Otherwise fast jobs could wait behind slow ones and could be blocked.
103 $refetched = $passing_slow;
105 foreach ($r as $entry) {
106 // Assure that the priority is an integer value
107 $entry['priority'] = (int)$entry['priority'];
109 // The work will be done
110 if (!self::execute($entry)) {
111 logger('Process execution failed, quitting.', LOGGER_DEBUG);
115 // If possible we will fetch new jobs for this worker
116 if (!$refetched && Lock::set('worker_process', 0)) {
117 $stamp = (float)microtime(true);
118 $refetched = self::findWorkerProcesses($passing_slow);
119 self::$db_duration += (microtime(true) - $stamp);
120 Lock::remove('worker_process');
124 // To avoid the quitting of multiple workers only one worker at a time will execute the check
125 if (Lock::set('worker', 0)) {
126 $stamp = (float)microtime(true);
127 // Count active workers and compare them with a maximum value that depends on the load
128 if (self::tooMuchWorkers()) {
129 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
134 if ($a->min_memory_reached()) {
135 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
138 Lock::remove('worker');
139 self::$db_duration += (microtime(true) - $stamp);
142 // Quit the worker once every 5 minutes
143 if (time() > ($starttime + 300)) {
144 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
148 if (Config::get('system', 'worker_daemon_mode', false)) {
149 self::IPCSetJobState(false);
151 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
155 * @brief Returns the number of non executed entries in the worker queue
157 * @return integer Number of non executed entries in the worker queue
159 private static function totalEntries()
161 $s = dba::fetch_first("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done`", NULL_DATE);
162 if (DBM::is_result($s)) {
170 * @brief Returns the highest priority in the worker queue that isn't executed
172 * @return integer Number of active worker processes
174 private static function highestPriority()
176 $condition = ["`executed` <= ? AND NOT `done`", NULL_DATE];
177 $workerqueue = dba::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
178 if (DBM::is_result($workerqueue)) {
179 return $workerqueue["priority"];
186 * @brief Returns if a process with the given priority is running
188 * @param integer $priority The priority that should be checked
190 * @return integer Is there a process running with that priority?
192 private static function processWithPriorityActive($priority)
194 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE];
195 return dba::exists('workerqueue', $condition);
199 * @brief Execute a worker entry
201 * @param array $queue Workerqueue entry
203 * @return boolean "true" if further processing should be stopped
205 public static function execute($queue)
211 // Quit when in maintenance
212 if (Config::get('system', 'maintenance', false, true)) {
213 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
217 // Constantly check the number of parallel database processes
218 if ($a->max_processes_reached()) {
219 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
223 // Constantly check the number of available database connections to let the frontend be accessible at any time
224 if (self::maxConnectionsReached()) {
225 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
229 $argv = json_decode($queue["parameter"], true);
231 // Check for existance and validity of the include file
234 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
235 // We constantly update the "executed" date every minute to avoid being killed too soon
236 if (!isset(self::$last_update)) {
237 self::$last_update = strtotime($queue["executed"]);
240 $age = (time() - self::$last_update) / 60;
241 self::$last_update = time();
244 $stamp = (float)microtime(true);
245 dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
246 self::$db_duration += (microtime(true) - $stamp);
251 self::execFunction($queue, $include, $argv, true);
253 $stamp = (float)microtime(true);
254 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
255 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
257 self::$db_duration = (microtime(true) - $stamp);
262 // The script could be provided as full path or only with the function name
263 if ($include == basename($include)) {
264 $include = "include/".$include.".php";
267 if (!validate_include($include)) {
268 logger("Include file ".$argv[0]." is not valid!");
269 dba::delete('workerqueue', ['id' => $queue["id"]]);
273 require_once $include;
275 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
277 if (function_exists($funcname)) {
278 // We constantly update the "executed" date every minute to avoid being killed too soon
279 if (!isset(self::$last_update)) {
280 self::$last_update = strtotime($queue["executed"]);
283 $age = (time() - self::$last_update) / 60;
284 self::$last_update = time();
287 $stamp = (float)microtime(true);
288 dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
289 self::$db_duration += (microtime(true) - $stamp);
292 self::execFunction($queue, $funcname, $argv, false);
294 $stamp = (float)microtime(true);
295 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
296 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
298 self::$db_duration = (microtime(true) - $stamp);
300 logger("Function ".$funcname." does not exist");
301 dba::delete('workerqueue', ['id' => $queue["id"]]);
308 * @brief Execute a function from the queue
310 * @param array $queue Workerqueue entry
311 * @param string $funcname name of the function
312 * @param array $argv Array of values to be passed to the function
313 * @param boolean $method_call boolean
316 private static function execFunction($queue, $funcname, $argv, $method_call)
322 $argc = count($argv);
324 $new_process_id = uniqid("wrk", true);
326 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
328 $stamp = (float)microtime(true);
330 // We use the callstack here to analyze the performance of executed worker entries.
331 // For this reason the variables have to be initialized.
332 if (Config::get("system", "profiler")) {
333 $a->performance["start"] = microtime(true);
334 $a->performance["database"] = 0;
335 $a->performance["database_write"] = 0;
336 $a->performance["cache"] = 0;
337 $a->performance["cache_write"] = 0;
338 $a->performance["network"] = 0;
339 $a->performance["file"] = 0;
340 $a->performance["rendering"] = 0;
341 $a->performance["parser"] = 0;
342 $a->performance["marktime"] = 0;
343 $a->performance["markstart"] = microtime(true);
347 // For better logging create a new process id for every worker call
348 // But preserve the old one for the worker
349 $old_process_id = $a->process_id;
350 $a->process_id = $new_process_id;
353 $up_duration = number_format(microtime(true) - self::$up_start, 3);
355 // Reset global data to avoid interferences
359 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
361 $funcname($argv, $argc);
364 $a->process_id = $old_process_id;
367 $duration = number_format(microtime(true) - $stamp, 3);
369 self::$up_start = microtime(true);
371 /* With these values we can analyze how effective the worker is.
372 * The database and rest time should be low since this is the unproductive time.
373 * The execution time is the productive time.
374 * By changing parameters like the maximum number of workers we can check the effectivness.
377 'DB: '.number_format(self::$db_duration, 2).
378 ' - Lock: '.number_format(self::$lock_duration, 2).
379 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
380 ' - Execution: '.number_format($duration, 2),
384 self::$lock_duration = 0;
386 if ($duration > 3600) {
387 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
388 } elseif ($duration > 600) {
389 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
390 } elseif ($duration > 300) {
391 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
392 } elseif ($duration > 120) {
393 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
396 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
398 // Write down the performance values into the log
399 if (Config::get("system", "profiler")) {
400 $duration = microtime(true)-$a->performance["start"];
403 if (Config::get("rendertime", "callstack")) {
404 if (isset($a->callstack["database"])) {
405 $o .= "\nDatabase Read:\n";
406 foreach ($a->callstack["database"] as $func => $time) {
407 $time = round($time, 3);
409 $o .= $func.": ".$time."\n";
413 if (isset($a->callstack["database_write"])) {
414 $o .= "\nDatabase Write:\n";
415 foreach ($a->callstack["database_write"] as $func => $time) {
416 $time = round($time, 3);
418 $o .= $func.": ".$time."\n";
422 if (isset($a->callstack["dache"])) {
423 $o .= "\nCache Read:\n";
424 foreach ($a->callstack["dache"] as $func => $time) {
425 $time = round($time, 3);
427 $o .= $func.": ".$time."\n";
431 if (isset($a->callstack["dache_write"])) {
432 $o .= "\nCache Write:\n";
433 foreach ($a->callstack["dache_write"] as $func => $time) {
434 $time = round($time, 3);
436 $o .= $func.": ".$time."\n";
440 if (isset($a->callstack["network"])) {
441 $o .= "\nNetwork:\n";
442 foreach ($a->callstack["network"] as $func => $time) {
443 $time = round($time, 3);
445 $o .= $func.": ".$time."\n";
452 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
453 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
454 number_format($a->performance["database"] - $a->performance["database_write"], 2),
455 number_format($a->performance["database_write"], 2),
456 number_format($a->performance["cache"], 2),
457 number_format($a->performance["cache_write"], 2),
458 number_format($a->performance["network"], 2),
459 number_format($a->performance["file"], 2),
460 number_format($duration - ($a->performance["database"]
461 + $a->performance["cache"] + $a->performance["cache_write"]
462 + $a->performance["network"] + $a->performance["file"]), 2),
463 number_format($duration, 2)
469 $cooldown = Config::get("system", "worker_cooldown", 0);
472 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
478 * @brief Checks if the number of database connections has reached a critical limit.
480 * @return bool Are more than 3/4 of the maximum connections used?
482 private static function maxConnectionsReached()
484 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
485 $max = Config::get("system", "max_connections");
487 // Fetch the percentage level where the worker will get active
488 $maxlevel = Config::get("system", "max_connections_level", 75);
491 // the maximum number of possible user connections can be a system variable
492 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
493 if (DBM::is_result($r)) {
496 // Or it can be granted. This overrides the system variable
497 $r = dba::p('SHOW GRANTS');
498 while ($grants = dba::fetch($r)) {
499 $grant = array_pop($grants);
500 if (stristr($grant, "GRANT USAGE ON")) {
501 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
509 // If $max is set we will use the processlist to determine the current number of connections
510 // The processlist only shows entries of the current user
512 $r = dba::p('SHOW PROCESSLIST');
513 $used = dba::num_rows($r);
516 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
518 $level = ($used / $max) * 100;
520 if ($level >= $maxlevel) {
521 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
526 // We will now check for the system values.
527 // This limit could be reached although the user limits are fine.
528 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
529 if (!DBM::is_result($r)) {
532 $max = intval($r["Value"]);
536 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
537 if (!DBM::is_result($r)) {
540 $used = intval($r["Value"]);
544 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
546 $level = $used / $max * 100;
548 if ($level < $maxlevel) {
551 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
556 * @brief fix the queue entry if the worker process died
559 private static function killStaleWorkers()
561 $entries = dba::select(
563 ['id', 'pid', 'executed', 'priority', 'parameter'],
564 ['`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE],
565 ['order' => ['priority', 'created']]
568 while ($entry = dba::fetch($entries)) {
569 if (!posix_kill($entry["pid"], 0)) {
572 ['executed' => NULL_DATE, 'pid' => 0],
573 ['id' => $entry["id"]]
576 // Kill long running processes
577 // Check if the priority is in a valid range
578 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
579 $entry["priority"] = PRIORITY_MEDIUM;
582 // Define the maximum durations
583 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
584 $max_duration = $max_duration_defaults[$entry["priority"]];
586 $argv = json_decode($entry["parameter"], true);
587 $argv[0] = basename($argv[0]);
589 // How long is the process already running?
590 $duration = (time() - strtotime($entry["executed"])) / 60;
591 if ($duration > $max_duration) {
592 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
593 posix_kill($entry["pid"], SIGTERM);
595 // We killed the stale process.
596 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
597 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
598 $new_priority = $entry["priority"];
599 if ($entry["priority"] == PRIORITY_HIGH) {
600 $new_priority = PRIORITY_MEDIUM;
601 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
602 $new_priority = PRIORITY_LOW;
603 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
604 $new_priority = PRIORITY_NEGLIGIBLE;
608 ['executed' => NULL_DATE, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
609 ['id' => $entry["id"]]
612 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
619 * @brief Checks if the number of active workers exceeds the given limits
621 * @return bool Are there too much workers running?
623 public static function tooMuchWorkers()
625 $queues = Config::get("system", "worker_queues", 4);
627 $maxqueues = $queues;
629 $active = self::activeWorkers();
631 // Decrease the number of workers at higher load
632 $load = current_load();
634 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
636 $maxworkers = $queues;
638 // Some magical mathemathics to reduce the workers
640 $slope = $maxworkers / pow($maxsysload, $exponent);
641 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
644 if (Config::get('system', 'worker_debug')) {
645 // Create a list of queue entries grouped by their priority
648 // Adding all processes with no workerqueue entry
650 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
651 (SELECT id FROM `workerqueue`
652 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
656 if ($process = dba::fetch($processes)) {
657 $listitem[0] = "0:".$process["running"];
659 dba::close($processes);
661 // Now adding all processes with workerqueue entries
662 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
663 while ($entry = dba::fetch($entries)) {
664 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
665 if ($process = dba::fetch($processes)) {
666 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
668 dba::close($processes);
670 dba::close($entries);
672 $intervals = [1, 10, 60];
673 $jobs_per_minute = [];
674 foreach ($intervals as $interval) {
675 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
676 if ($job = dba::fetch($jobs)) {
677 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
681 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
684 $entries = self::totalEntries();
686 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
687 $top_priority = self::highestPriority();
688 $high_running = self::processWithPriorityActive($top_priority);
690 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
691 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
692 $queues = $active + 1;
696 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
698 // Are there fewer workers running as possible? Then fork a new one.
699 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
700 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
705 return $active >= $queues;
709 * @brief Returns the number of active worker processes
711 * @return integer Number of active worker processes
713 private static function activeWorkers()
715 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
717 return $workers["processes"];
721 * @brief Check if we should pass some slow processes
723 * When the active processes of the highest priority are using more than 2/3
724 * of all processes, we let pass slower processes.
726 * @param string $highest_priority Returns the currently highest priority
727 * @return bool We let pass a slower process than $highest_priority
729 private static function passingSlow(&$highest_priority)
731 $highest_priority = 0;
736 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
739 // No active processes at all? Fine
740 if (!DBM::is_result($r)) {
744 while ($line = dba::fetch($r)) {
745 $priorities[] = $line["priority"];
750 if (count($priorities) == 0) {
753 $highest_priority = min($priorities);
755 // The highest process is already the slowest one?
757 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
761 foreach ($priorities as $priority) {
762 if ($priority == $highest_priority) {
766 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
767 $passing_slow = (($high/count($priorities)) > (2/3));
770 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
772 return $passing_slow;
776 * @brief Find and claim the next worker process for us
778 * @param boolean $passing_slow Returns if we had passed low priority processes
779 * @return boolean Have we found something?
781 private static function findWorkerProcesses(&$passing_slow)
785 // Check if we should pass some low priority process
786 $highest_priority = 0;
788 $passing_slow = false;
790 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
791 // We decrease the limit with the number of entries left in the queue
792 $worker_queues = Config::get("system", "worker_queues", 4);
793 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
794 $lower_job_limit = $worker_queues * $queue_length * 2;
795 $jobs = self::totalEntries();
799 $slope = $queue_length / pow($lower_job_limit, $exponent);
800 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
802 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
804 if (self::passingSlow($highest_priority)) {
805 // Are there waiting processes with a higher priority than the currently highest?
806 $result = dba::select(
809 ["`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority],
810 ['limit' => $limit, 'order' => ['priority', 'created']]
813 while ($id = dba::fetch($result)) {
818 $found = (count($ids) > 0);
821 // Give slower processes some processing time
822 $result = dba::select(
825 ["`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority],
826 ['limit' => $limit, 'order' => ['priority', 'created']]
829 while ($id = dba::fetch($result)) {
834 $found = (count($ids) > 0);
835 $passing_slow = $found;
839 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
841 $result = dba::select(
844 ["`executed` <= ? AND NOT `done`", NULL_DATE],
845 ['limit' => $limit, 'order' => ['priority', 'created']]
848 while ($id = dba::fetch($result)) {
853 $found = (count($ids) > 0);
857 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
858 array_unshift($ids, $condition);
859 dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
862 // The daemon doesn't need to fork new workers anymore, since we are inside the worker
863 if (Config::get('system', 'worker_daemon_mode', false)) {
864 self::IPCSetJobState(false);
871 * @brief Returns the next worker process
873 * @param boolean $passing_slow Returns if we had passed low priority processes
874 * @return string SQL statement
876 public static function workerProcess(&$passing_slow)
878 $stamp = (float)microtime(true);
880 // There can already be jobs for us in the queue.
881 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
882 if (DBM::is_result($r)) {
883 self::$db_duration += (microtime(true) - $stamp);
884 return dba::inArray($r);
888 $stamp = (float)microtime(true);
889 if (!Lock::set('worker_process')) {
892 self::$lock_duration = (microtime(true) - $stamp);
894 $stamp = (float)microtime(true);
895 $found = self::findWorkerProcesses($passing_slow);
896 self::$db_duration += (microtime(true) - $stamp);
898 Lock::remove('worker_process');
901 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
902 return dba::inArray($r);
908 * @brief Removes a workerqueue entry from the current process
911 public static function unclaimProcess()
915 dba::update('workerqueue', ['executed' => NULL_DATE, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
919 * @brief Call the front end worker
922 public static function callWorker()
924 if (!Config::get("system", "frontend_worker")) {
928 $url = System::baseUrl()."/worker";
929 Network::fetchUrl($url, false, $redirects, 1);
933 * @brief Call the front end worker if there aren't any active
936 public static function executeIfIdle()
938 if (!Config::get("system", "frontend_worker")) {
942 // Do we have "proc_open"? Then we can fork the worker
943 if (function_exists("proc_open")) {
944 // When was the last time that we called the worker?
945 // Less than one minute? Then we quit
946 if ((time() - Config::get("system", "worker_started")) < 60) {
950 Config::set("system", "worker_started", time());
952 // Do we have enough running workers? Then we quit here.
953 if (self::tooMuchWorkers()) {
954 // Cleaning dead processes
955 self::killStaleWorkers();
956 Process::deleteInactive();
963 logger('Call worker', LOGGER_DEBUG);
968 // We cannot execute background processes.
969 // We now run the processes from the frontend.
970 // This won't work with long running processes.
973 self::clearProcesses();
975 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
977 if ($workers["processes"] == 0) {
983 * @brief Removes long running worker processes
986 public static function clearProcesses()
988 $timeout = Config::get("system", "frontend_worker_timeout", 10);
990 /// @todo We should clean up the corresponding workerqueue entries as well
991 $condition = ["`created` < ? AND `command` = 'worker.php'",
992 DateTimeFormat::utc("now - ".$timeout." minutes")];
993 dba::delete('process', $condition);
997 * @brief Runs the cron processes
1000 private static function runCron()
1002 logger('Add cron entries', LOGGER_DEBUG);
1004 // Check for spooled items
1005 self::add(PRIORITY_HIGH, "SpoolPost");
1007 // Run the cron job that calls all other jobs
1008 self::add(PRIORITY_MEDIUM, "Cron");
1010 // Cleaning dead processes
1011 self::killStaleWorkers();
1015 * @brief Spawns a new worker
1018 public static function spawnWorker()
1020 $args = ["bin/worker.php", "no_cron"];
1021 get_app()->proc_run($args);
1025 * @brief Adds tasks to the worker queue
1027 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1029 * next args are passed as $cmd command line
1030 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1031 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1033 * @note $cmd and string args are surrounded with ""
1038 * @return boolean "false" if proc_run couldn't be executed
1040 public static function add($cmd)
1042 $args = func_get_args();
1044 if (!count($args)) {
1048 $arr = ['args' => $args, 'run_cmd' => true];
1050 Addon::callHooks("proc_run", $arr);
1051 if (!$arr['run_cmd'] || !count($args)) {
1055 $priority = PRIORITY_MEDIUM;
1056 $dont_fork = Config::get("system", "worker_dont_fork", false);
1057 $created = DateTimeFormat::utcNow();
1059 $run_parameter = array_shift($args);
1061 if (is_int($run_parameter)) {
1062 $priority = $run_parameter;
1063 } elseif (is_array($run_parameter)) {
1064 if (isset($run_parameter['priority'])) {
1065 $priority = $run_parameter['priority'];
1067 if (isset($run_parameter['created'])) {
1068 $created = $run_parameter['created'];
1070 if (isset($run_parameter['dont_fork'])) {
1071 $dont_fork = $run_parameter['dont_fork'];
1075 $parameters = json_encode($args);
1076 $found = dba::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1078 // Quit if there was a database error - a precaution for the update process to 3.5.3
1079 if (dba::errorNo() != 0) {
1084 dba::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1087 // We tell the daemon that a new job entry exists
1088 if (Config::get('system', 'worker_daemon_mode', false)) {
1089 self::IPCSetJobState(true);
1093 // Should we quit and wait for the worker to be called as a cronjob?
1098 // If there is a lock then we don't have to check for too much worker
1099 if (!Lock::set('worker', 0)) {
1103 // If there are already enough workers running, don't fork another one
1104 $quit = self::tooMuchWorkers();
1105 Lock::remove('worker');
1111 // Now call the worker to execute the jobs that we just added to the queue
1112 self::spawnWorker();
1118 * Log active processes into the "process" table
1120 * @brief Log active processes into the "process" table
1122 public static function startProcess()
1124 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1126 $command = basename($trace[0]['file']);
1128 Process::deleteInactive();
1130 Process::insert($command);
1134 * Remove the active process from the "process" table
1136 * @brief Remove the active process from the "process" table
1139 public static function endProcess()
1141 return Process::deleteByPid();
1145 * Set the flag if some job is waiting
1147 * @brief Set the flag if some job is waiting
1148 * @param boolean $jobs Is there a waiting job?
1150 public static function IPCSetJobState($jobs)
1152 dba::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1156 * Checks if some worker job waits to be executed
1158 * @brief Checks if some worker job waits to be executed
1161 public static function IPCJobsExists()
1163 $row = dba::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1165 // When we don't have a row, no job is running
1166 if (!DBM::is_result($row)) {
1170 return (bool)$row['jobs'];