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 // Kill stale processes every 5 minutes
57 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
58 if (time() > ($last_cleanup + 300)) {
59 Config::set('system', 'poller_last_cleaned', time());
60 self::killStaleWorkers();
63 // Count active workers and compare them with a maximum value that depends on the load
64 if (self::tooMuchWorkers()) {
65 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
69 // Do we have too few memory?
70 if ($a->min_memory_reached()) {
71 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
75 // Possibly there are too much database connections
76 if (self::maxConnectionsReached()) {
77 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
81 // Possibly there are too much database processes that block the system
82 if ($a->max_processes_reached()) {
83 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
87 // Now we start additional cron processes if we should do so
94 // We fetch the next queue entry that is about to be executed
95 while ($r = self::workerProcess($passing_slow)) {
96 // When we are processing jobs with a lower priority, we don't refetch new jobs
97 // Otherwise fast jobs could wait behind slow ones and could be blocked.
98 $refetched = $passing_slow;
100 foreach ($r as $entry) {
101 // Assure that the priority is an integer value
102 $entry['priority'] = (int)$entry['priority'];
104 // The work will be done
105 if (!self::execute($entry)) {
106 logger('Process execution failed, quitting.', LOGGER_DEBUG);
110 // If possible we will fetch new jobs for this worker
111 if (!$refetched && Lock::set('poller_worker_process', 0)) {
112 $stamp = (float)microtime(true);
113 $refetched = self::findWorkerProcesses($passing_slow);
114 self::$db_duration += (microtime(true) - $stamp);
115 Lock::remove('poller_worker_process');
119 // To avoid the quitting of multiple workers only one worker at a time will execute the check
120 if (Lock::set('poller_worker', 0)) {
121 $stamp = (float)microtime(true);
122 // Count active workers and compare them with a maximum value that depends on the load
123 if (self::tooMuchWorkers()) {
124 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
129 if ($a->min_memory_reached()) {
130 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
133 Lock::remove('poller_worker');
134 self::$db_duration += (microtime(true) - $stamp);
137 // Quit the worker once every 5 minutes
138 if (time() > ($starttime + 300)) {
139 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
143 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
147 * @brief Returns the number of non executed entries in the worker queue
149 * @return integer Number of non executed entries in the worker queue
151 private static function totalEntries()
153 $s = dba::fetch_first("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done`", NULL_DATE);
154 if (DBM::is_result($s)) {
162 * @brief Returns the highest priority in the worker queue that isn't executed
164 * @return integer Number of active worker processes
166 private static function highestPriority()
168 $condition = ["`executed` <= ? AND NOT `done`", NULL_DATE];
169 $workerqueue = dba::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
170 if (DBM::is_result($workerqueue)) {
171 return $workerqueue["priority"];
178 * @brief Returns if a process with the given priority is running
180 * @param integer $priority The priority that should be checked
182 * @return integer Is there a process running with that priority?
184 private static function processWithPriorityActive($priority)
186 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE];
187 return dba::exists('workerqueue', $condition);
191 * @brief Execute a worker entry
193 * @param array $queue Workerqueue entry
195 * @return boolean "true" if further processing should be stopped
197 public static function execute($queue)
203 // Quit when in maintenance
204 if (Config::get('system', 'maintenance', false, true)) {
205 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
209 // Constantly check the number of parallel database processes
210 if ($a->max_processes_reached()) {
211 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
215 // Constantly check the number of available database connections to let the frontend be accessible at any time
216 if (self::maxConnectionsReached()) {
217 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
221 $argv = json_decode($queue["parameter"], true);
223 // Check for existance and validity of the include file
226 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
227 // We constantly update the "executed" date every minute to avoid being killed too soon
228 if (!isset(self::$last_update)) {
229 self::$last_update = strtotime($queue["executed"]);
232 $age = (time() - self::$last_update) / 60;
233 self::$last_update = time();
236 $stamp = (float)microtime(true);
237 dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
238 self::$db_duration += (microtime(true) - $stamp);
243 self::execFunction($queue, $include, $argv, true);
245 $stamp = (float)microtime(true);
246 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
247 Config::set('system', 'last_poller_execution', DateTimeFormat::utcNow());
249 self::$db_duration = (microtime(true) - $stamp);
254 // The script could be provided as full path or only with the function name
255 if ($include == basename($include)) {
256 $include = "include/".$include.".php";
259 if (!validate_include($include)) {
260 logger("Include file ".$argv[0]." is not valid!");
261 dba::delete('workerqueue', ['id' => $queue["id"]]);
265 require_once $include;
267 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
269 if (function_exists($funcname)) {
270 // We constantly update the "executed" date every minute to avoid being killed too soon
271 if (!isset(self::$last_update)) {
272 self::$last_update = strtotime($queue["executed"]);
275 $age = (time() - self::$last_update) / 60;
276 self::$last_update = time();
279 $stamp = (float)microtime(true);
280 dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
281 self::$db_duration += (microtime(true) - $stamp);
284 self::execFunction($queue, $funcname, $argv, false);
286 $stamp = (float)microtime(true);
287 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
288 Config::set('system', 'last_poller_execution', DateTimeFormat::utcNow());
290 self::$db_duration = (microtime(true) - $stamp);
292 logger("Function ".$funcname." does not exist");
293 dba::delete('workerqueue', ['id' => $queue["id"]]);
300 * @brief Execute a function from the queue
302 * @param array $queue Workerqueue entry
303 * @param string $funcname name of the function
304 * @param array $argv Array of values to be passed to the function
305 * @param boolean $method_call boolean
308 private static function execFunction($queue, $funcname, $argv, $method_call)
314 $argc = count($argv);
316 $new_process_id = uniqid("wrk", true);
318 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
320 $stamp = (float)microtime(true);
322 // We use the callstack here to analyze the performance of executed worker entries.
323 // For this reason the variables have to be initialized.
324 if (Config::get("system", "profiler")) {
325 $a->performance["start"] = microtime(true);
326 $a->performance["database"] = 0;
327 $a->performance["database_write"] = 0;
328 $a->performance["cache"] = 0;
329 $a->performance["cache_write"] = 0;
330 $a->performance["network"] = 0;
331 $a->performance["file"] = 0;
332 $a->performance["rendering"] = 0;
333 $a->performance["parser"] = 0;
334 $a->performance["marktime"] = 0;
335 $a->performance["markstart"] = microtime(true);
339 // For better logging create a new process id for every worker call
340 // But preserve the old one for the worker
341 $old_process_id = $a->process_id;
342 $a->process_id = $new_process_id;
345 $up_duration = number_format(microtime(true) - self::$up_start, 3);
347 // Reset global data to avoid interferences
351 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
353 $funcname($argv, $argc);
356 $a->process_id = $old_process_id;
359 $duration = number_format(microtime(true) - $stamp, 3);
361 self::$up_start = microtime(true);
363 /* With these values we can analyze how effective the worker is.
364 * The database and rest time should be low since this is the unproductive time.
365 * The execution time is the productive time.
366 * By changing parameters like the maximum number of workers we can check the effectivness.
369 'DB: '.number_format(self::$db_duration, 2).
370 ' - Lock: '.number_format(self::$lock_duration, 2).
371 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
372 ' - Execution: '.number_format($duration, 2),
376 self::$lock_duration = 0;
378 if ($duration > 3600) {
379 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
380 } elseif ($duration > 600) {
381 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
382 } elseif ($duration > 300) {
383 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
384 } elseif ($duration > 120) {
385 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
388 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
390 // Write down the performance values into the log
391 if (Config::get("system", "profiler")) {
392 $duration = microtime(true)-$a->performance["start"];
395 if (Config::get("rendertime", "callstack")) {
396 if (isset($a->callstack["database"])) {
397 $o .= "\nDatabase Read:\n";
398 foreach ($a->callstack["database"] as $func => $time) {
399 $time = round($time, 3);
401 $o .= $func.": ".$time."\n";
405 if (isset($a->callstack["database_write"])) {
406 $o .= "\nDatabase Write:\n";
407 foreach ($a->callstack["database_write"] as $func => $time) {
408 $time = round($time, 3);
410 $o .= $func.": ".$time."\n";
414 if (isset($a->callstack["dache"])) {
415 $o .= "\nCache Read:\n";
416 foreach ($a->callstack["dache"] as $func => $time) {
417 $time = round($time, 3);
419 $o .= $func.": ".$time."\n";
423 if (isset($a->callstack["dache_write"])) {
424 $o .= "\nCache Write:\n";
425 foreach ($a->callstack["dache_write"] as $func => $time) {
426 $time = round($time, 3);
428 $o .= $func.": ".$time."\n";
432 if (isset($a->callstack["network"])) {
433 $o .= "\nNetwork:\n";
434 foreach ($a->callstack["network"] as $func => $time) {
435 $time = round($time, 3);
437 $o .= $func.": ".$time."\n";
444 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
445 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
446 number_format($a->performance["database"] - $a->performance["database_write"], 2),
447 number_format($a->performance["database_write"], 2),
448 number_format($a->performance["cache"], 2),
449 number_format($a->performance["cache_write"], 2),
450 number_format($a->performance["network"], 2),
451 number_format($a->performance["file"], 2),
452 number_format($duration - ($a->performance["database"]
453 + $a->performance["cache"] + $a->performance["cache_write"]
454 + $a->performance["network"] + $a->performance["file"]), 2),
455 number_format($duration, 2)
461 $cooldown = Config::get("system", "worker_cooldown", 0);
464 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
470 * @brief Checks if the number of database connections has reached a critical limit.
472 * @return bool Are more than 3/4 of the maximum connections used?
474 private static function maxConnectionsReached()
476 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
477 $max = Config::get("system", "max_connections");
479 // Fetch the percentage level where the worker will get active
480 $maxlevel = Config::get("system", "max_connections_level", 75);
483 // the maximum number of possible user connections can be a system variable
484 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
485 if (DBM::is_result($r)) {
488 // Or it can be granted. This overrides the system variable
489 $r = dba::p('SHOW GRANTS');
490 while ($grants = dba::fetch($r)) {
491 $grant = array_pop($grants);
492 if (stristr($grant, "GRANT USAGE ON")) {
493 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
501 // If $max is set we will use the processlist to determine the current number of connections
502 // The processlist only shows entries of the current user
504 $r = dba::p('SHOW PROCESSLIST');
505 $used = dba::num_rows($r);
508 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
510 $level = ($used / $max) * 100;
512 if ($level >= $maxlevel) {
513 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
518 // We will now check for the system values.
519 // This limit could be reached although the user limits are fine.
520 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
521 if (!DBM::is_result($r)) {
524 $max = intval($r["Value"]);
528 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
529 if (!DBM::is_result($r)) {
532 $used = intval($r["Value"]);
536 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
538 $level = $used / $max * 100;
540 if ($level < $maxlevel) {
543 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
548 * @brief fix the queue entry if the worker process died
551 private static function killStaleWorkers()
553 $entries = dba::select(
555 ['id', 'pid', 'executed', 'priority', 'parameter'],
556 ['`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE],
557 ['order' => ['priority', 'created']]
560 while ($entry = dba::fetch($entries)) {
561 if (!posix_kill($entry["pid"], 0)) {
564 ['executed' => NULL_DATE, 'pid' => 0],
565 ['id' => $entry["id"]]
568 // Kill long running processes
569 // Check if the priority is in a valid range
570 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
571 $entry["priority"] = PRIORITY_MEDIUM;
574 // Define the maximum durations
575 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
576 $max_duration = $max_duration_defaults[$entry["priority"]];
578 $argv = json_decode($entry["parameter"], true);
579 $argv[0] = basename($argv[0]);
581 // How long is the process already running?
582 $duration = (time() - strtotime($entry["executed"])) / 60;
583 if ($duration > $max_duration) {
584 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
585 posix_kill($entry["pid"], SIGTERM);
587 // We killed the stale process.
588 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
589 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
590 $new_priority = $entry["priority"];
591 if ($entry["priority"] == PRIORITY_HIGH) {
592 $new_priority = PRIORITY_MEDIUM;
593 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
594 $new_priority = PRIORITY_LOW;
595 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
596 $new_priority = PRIORITY_NEGLIGIBLE;
600 ['executed' => NULL_DATE, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
601 ['id' => $entry["id"]]
604 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
611 * @brief Checks if the number of active workers exceeds the given limits
613 * @return bool Are there too much workers running?
615 public static function tooMuchWorkers()
617 $queues = Config::get("system", "worker_queues", 4);
619 $maxqueues = $queues;
621 $active = self::activeWorkers();
623 // Decrease the number of workers at higher load
624 $load = current_load();
626 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
628 $maxworkers = $queues;
630 // Some magical mathemathics to reduce the workers
632 $slope = $maxworkers / pow($maxsysload, $exponent);
633 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
636 if (Config::get('system', 'worker_debug')) {
637 // Create a list of queue entries grouped by their priority
640 // Adding all processes with no workerqueue entry
642 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
643 (SELECT id FROM `workerqueue`
644 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
648 if ($process = dba::fetch($processes)) {
649 $listitem[0] = "0:".$process["running"];
651 dba::close($processes);
653 // Now adding all processes with workerqueue entries
654 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
655 while ($entry = dba::fetch($entries)) {
656 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
657 if ($process = dba::fetch($processes)) {
658 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
660 dba::close($processes);
662 dba::close($entries);
664 $intervals = [1, 10, 60];
665 $jobs_per_minute = [];
666 foreach ($intervals as $interval) {
667 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
668 if ($job = dba::fetch($jobs)) {
669 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
673 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
676 $entries = self::totalEntries();
678 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
679 $top_priority = self::highestPriority();
680 $high_running = self::processWithPriorityActive($top_priority);
682 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
683 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
684 $queues = $active + 1;
688 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
690 // Are there fewer workers running as possible? Then fork a new one.
691 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
692 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
697 return $active >= $queues;
701 * @brief Returns the number of active worker processes
703 * @return integer Number of active worker processes
705 private static function activeWorkers()
707 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
709 return $workers["processes"];
713 * @brief Check if we should pass some slow processes
715 * When the active processes of the highest priority are using more than 2/3
716 * of all processes, we let pass slower processes.
718 * @param string $highest_priority Returns the currently highest priority
719 * @return bool We let pass a slower process than $highest_priority
721 private static function passingSlow(&$highest_priority)
723 $highest_priority = 0;
728 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
731 // No active processes at all? Fine
732 if (!DBM::is_result($r)) {
736 while ($line = dba::fetch($r)) {
737 $priorities[] = $line["priority"];
742 if (count($priorities) == 0) {
745 $highest_priority = min($priorities);
747 // The highest process is already the slowest one?
749 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
753 foreach ($priorities as $priority) {
754 if ($priority == $highest_priority) {
758 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
759 $passing_slow = (($high/count($priorities)) > (2/3));
762 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
764 return $passing_slow;
768 * @brief Find and claim the next worker process for us
770 * @param boolean $passing_slow Returns if we had passed low priority processes
771 * @return boolean Have we found something?
773 private static function findWorkerProcesses(&$passing_slow)
777 // Check if we should pass some low priority process
778 $highest_priority = 0;
780 $passing_slow = false;
782 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
783 // We decrease the limit with the number of entries left in the queue
784 $worker_queues = Config::get("system", "worker_queues", 4);
785 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
786 $lower_job_limit = $worker_queues * $queue_length * 2;
787 $jobs = self::totalEntries();
791 $slope = $queue_length / pow($lower_job_limit, $exponent);
792 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
794 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
796 if (self::passingSlow($highest_priority)) {
797 // Are there waiting processes with a higher priority than the currently highest?
798 $result = dba::select(
801 ["`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority],
802 ['limit' => $limit, 'order' => ['priority', 'created']]
805 while ($id = dba::fetch($result)) {
810 $found = (count($ids) > 0);
813 // Give slower processes some processing time
814 $result = dba::select(
817 ["`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority],
818 ['limit' => $limit, 'order' => ['priority', 'created']]
821 while ($id = dba::fetch($result)) {
826 $found = (count($ids) > 0);
827 $passing_slow = $found;
831 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
833 $result = dba::select(
836 ["`executed` <= ? AND NOT `done`", NULL_DATE],
837 ['limit' => $limit, 'order' => ['priority', 'created']]
840 while ($id = dba::fetch($result)) {
845 $found = (count($ids) > 0);
849 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
850 array_unshift($ids, $condition);
851 dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
858 * @brief Returns the next worker process
860 * @param boolean $passing_slow Returns if we had passed low priority processes
861 * @return string SQL statement
863 public static function workerProcess(&$passing_slow)
865 $stamp = (float)microtime(true);
867 // There can already be jobs for us in the queue.
868 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
869 if (DBM::is_result($r)) {
870 self::$db_duration += (microtime(true) - $stamp);
871 return dba::inArray($r);
875 $stamp = (float)microtime(true);
876 if (!Lock::set('poller_worker_process')) {
879 self::$lock_duration = (microtime(true) - $stamp);
881 $stamp = (float)microtime(true);
882 $found = self::findWorkerProcesses($passing_slow);
883 self::$db_duration += (microtime(true) - $stamp);
885 Lock::remove('poller_worker_process');
888 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
889 return dba::inArray($r);
895 * @brief Removes a workerqueue entry from the current process
898 public static function unclaimProcess()
902 dba::update('workerqueue', ['executed' => NULL_DATE, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
906 * @brief Call the front end worker
909 public static function callWorker()
911 if (!Config::get("system", "frontend_worker")) {
915 $url = System::baseUrl()."/worker";
916 Network::fetchUrl($url, false, $redirects, 1);
920 * @brief Call the front end worker if there aren't any active
923 public static function executeIfIdle()
925 if (!Config::get("system", "frontend_worker")) {
929 // Do we have "proc_open"? Then we can fork the worker
930 if (function_exists("proc_open")) {
931 // When was the last time that we called the worker?
932 // Less than one minute? Then we quit
933 if ((time() - Config::get("system", "worker_started")) < 60) {
937 Config::set("system", "worker_started", time());
939 // Do we have enough running workers? Then we quit here.
940 if (self::tooMuchWorkers()) {
941 // Cleaning dead processes
942 self::killStaleWorkers();
943 Process::deleteInactive();
950 logger('Call worker', LOGGER_DEBUG);
955 // We cannot execute background processes.
956 // We now run the processes from the frontend.
957 // This won't work with long running processes.
960 self::clearProcesses();
962 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
964 if ($workers["processes"] == 0) {
970 * @brief Removes long running worker processes
973 public static function clearProcesses()
975 $timeout = Config::get("system", "frontend_worker_timeout", 10);
977 /// @todo We should clean up the corresponding workerqueue entries as well
978 $condition = ["`created` < ? AND `command` = 'worker.php'",
979 DateTimeFormat::utc("now - ".$timeout." minutes")];
980 dba::delete('process', $condition);
984 * @brief Runs the cron processes
987 private static function runCron()
989 logger('Add cron entries', LOGGER_DEBUG);
991 // Check for spooled items
992 self::add(PRIORITY_HIGH, "SpoolPost");
994 // Run the cron job that calls all other jobs
995 self::add(PRIORITY_MEDIUM, "Cron");
997 // Cleaning dead processes
998 self::killStaleWorkers();
1002 * @brief Spawns a new worker
1005 public static function spawnWorker()
1007 $args = ["bin/worker.php", "no_cron"];
1008 get_app()->proc_run($args);
1012 * @brief Adds tasks to the worker queue
1014 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1016 * next args are passed as $cmd command line
1017 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1018 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1020 * @note $cmd and string args are surrounded with ""
1025 * @return boolean "false" if proc_run couldn't be executed
1027 public static function add($cmd)
1029 $args = func_get_args();
1031 if (!count($args)) {
1035 $arr = ['args' => $args, 'run_cmd' => true];
1037 Addon::callHooks("proc_run", $arr);
1038 if (!$arr['run_cmd'] || !count($args)) {
1042 $priority = PRIORITY_MEDIUM;
1043 $dont_fork = Config::get("system", "worker_dont_fork");
1044 $created = DateTimeFormat::utcNow();
1046 $run_parameter = array_shift($args);
1048 if (is_int($run_parameter)) {
1049 $priority = $run_parameter;
1050 } elseif (is_array($run_parameter)) {
1051 if (isset($run_parameter['priority'])) {
1052 $priority = $run_parameter['priority'];
1054 if (isset($run_parameter['created'])) {
1055 $created = $run_parameter['created'];
1057 if (isset($run_parameter['dont_fork'])) {
1058 $dont_fork = $run_parameter['dont_fork'];
1062 $parameters = json_encode($args);
1063 $found = dba::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1065 // Quit if there was a database error - a precaution for the update process to 3.5.3
1066 if (dba::errorNo() != 0) {
1071 dba::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1074 // Should we quit and wait for the worker to be called as a cronjob?
1079 // If there is a lock then we don't have to check for too much worker
1080 if (!Lock::set('poller_worker', 0)) {
1084 // If there are already enough workers running, don't fork another one
1085 $quit = self::tooMuchWorkers();
1086 Lock::remove('poller_worker');
1092 // Now call the worker to execute the jobs that we just added to the queue
1093 self::spawnWorker();
1099 * Log active processes into the "process" table
1101 * @brief Log active processes into the "process" table
1103 public static function startProcess()
1105 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1107 $command = basename($trace[0]['file']);
1109 Process::deleteInactive();
1111 Process::insert($command);
1115 * Remove the active process from the "process" table
1117 * @brief Remove the active process from the "process" table
1120 public static function endProcess()
1122 return Process::deleteByPid();