3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Model\Process;
10 use Friendica\Util\DateTimeFormat;
11 use Friendica\Util\Network;
13 require_once 'include/dba.php';
16 * @file src/Core/Worker.php
18 * @brief Contains the class for the worker background job processing
22 * @brief Worker methods
26 private static $up_start;
27 private static $db_duration;
28 private static $last_update;
29 private static $lock_duration;
32 * @brief Processes the tasks that are in the workerqueue table
34 * @param boolean $run_cron Should the cron processes be executed?
37 public static function processQueue($run_cron = true)
41 self::$up_start = microtime(true);
43 // At first check the maximum load. We shouldn't continue with a high load
44 if ($a->isMaxLoadReached()) {
45 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
49 // We now start the process. This is done after the load check since this could increase the load.
52 // Kill stale processes every 5 minutes
53 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
54 if (time() > ($last_cleanup + 300)) {
55 Config::set('system', 'worker_last_cleaned', time());
56 self::killStaleWorkers();
59 // Count active workers and compare them with a maximum value that depends on the load
60 if (self::tooMuchWorkers()) {
61 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
65 // Do we have too few memory?
66 if ($a->isMinMemoryReached()) {
67 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
71 // Possibly there are too much database connections
72 if (self::maxConnectionsReached()) {
73 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
77 // Possibly there are too much database processes that block the system
78 if ($a->isMaxProcessesReached()) {
79 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
83 // Now we start additional cron processes if we should do so
90 // We fetch the next queue entry that is about to be executed
91 while ($r = self::workerProcess($passing_slow)) {
92 // When we are processing jobs with a lower priority, we don't refetch new jobs
93 // Otherwise fast jobs could wait behind slow ones and could be blocked.
94 $refetched = $passing_slow;
96 foreach ($r as $entry) {
97 // Assure that the priority is an integer value
98 $entry['priority'] = (int)$entry['priority'];
100 // The work will be done
101 if (!self::execute($entry)) {
102 logger('Process execution failed, quitting.', LOGGER_DEBUG);
106 // If possible we will fetch new jobs for this worker
107 if (!$refetched && Lock::acquire('worker_process', 0)) {
108 $stamp = (float)microtime(true);
109 $refetched = self::findWorkerProcesses($passing_slow);
110 self::$db_duration += (microtime(true) - $stamp);
111 Lock::release('worker_process');
115 // To avoid the quitting of multiple workers only one worker at a time will execute the check
116 if (Lock::acquire('worker', 0)) {
117 $stamp = (float)microtime(true);
118 // Count active workers and compare them with a maximum value that depends on the load
119 if (self::tooMuchWorkers()) {
120 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
121 Lock::release('worker');
126 if ($a->isMinMemoryReached()) {
127 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
128 Lock::release('worker');
131 Lock::release('worker');
132 self::$db_duration += (microtime(true) - $stamp);
135 // Quit the worker once every 5 minutes
136 if (time() > ($starttime + 300)) {
137 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
142 // Cleaning up. Possibly not needed, but it doesn't harm anything.
143 if (Config::get('system', 'worker_daemon_mode', false)) {
144 self::IPCSetJobState(false);
146 logger("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", LOGGER_DEBUG);
150 * @brief Returns the number of non executed entries in the worker queue
152 * @return integer Number of non executed entries in the worker queue
154 private static function totalEntries()
156 return DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
157 DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
161 * @brief Returns the highest priority in the worker queue that isn't executed
163 * @return integer Number of active worker processes
165 private static function highestPriority()
167 $condition = ["`executed` <= ? AND NOT `done` AND `next_try` < ?", DBA::NULL_DATETIME, DateTimeFormat::utcNow()];
168 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
169 if (DBA::isResult($workerqueue)) {
170 return $workerqueue["priority"];
177 * @brief Returns if a process with the given priority is running
179 * @param integer $priority The priority that should be checked
181 * @return integer Is there a process running with that priority?
183 private static function processWithPriorityActive($priority)
185 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done` AND `next_try` < ?",
186 $priority, DBA::NULL_DATETIME, DateTimeFormat::utcNow()];
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->isMaxProcessesReached()) {
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);
247 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
248 if (DBA::update('workerqueue', ['done' => true], $condition)) {
249 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
251 self::$db_duration = (microtime(true) - $stamp);
256 // The script could be provided as full path or only with the function name
257 if ($include == basename($include)) {
258 $include = "include/".$include.".php";
261 if (!validate_include($include)) {
262 logger("Include file ".$argv[0]." is not valid!");
263 DBA::delete('workerqueue', ['id' => $queue["id"]]);
267 require_once $include;
269 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
271 if (function_exists($funcname)) {
272 // We constantly update the "executed" date every minute to avoid being killed too soon
273 if (!isset(self::$last_update)) {
274 self::$last_update = strtotime($queue["executed"]);
277 $age = (time() - self::$last_update) / 60;
278 self::$last_update = time();
281 $stamp = (float)microtime(true);
282 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
283 self::$db_duration += (microtime(true) - $stamp);
286 self::execFunction($queue, $funcname, $argv, false);
288 $stamp = (float)microtime(true);
289 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
290 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
292 self::$db_duration = (microtime(true) - $stamp);
294 logger("Function ".$funcname." does not exist");
295 DBA::delete('workerqueue', ['id' => $queue["id"]]);
302 * @brief Execute a function from the queue
304 * @param array $queue Workerqueue entry
305 * @param string $funcname name of the function
306 * @param array $argv Array of values to be passed to the function
307 * @param boolean $method_call boolean
310 private static function execFunction($queue, $funcname, $argv, $method_call)
316 $argc = count($argv);
318 $new_process_id = System::processID("wrk");
320 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
322 $stamp = (float)microtime(true);
324 // We use the callstack here to analyze the performance of executed worker entries.
325 // For this reason the variables have to be initialized.
326 if (Config::get("system", "profiler")) {
327 $a->performance["start"] = microtime(true);
328 $a->performance["database"] = 0;
329 $a->performance["database_write"] = 0;
330 $a->performance["cache"] = 0;
331 $a->performance["cache_write"] = 0;
332 $a->performance["network"] = 0;
333 $a->performance["file"] = 0;
334 $a->performance["rendering"] = 0;
335 $a->performance["parser"] = 0;
336 $a->performance["marktime"] = 0;
337 $a->performance["markstart"] = microtime(true);
341 // For better logging create a new process id for every worker call
342 // But preserve the old one for the worker
343 $old_process_id = $a->process_id;
344 $a->process_id = $new_process_id;
347 $up_duration = number_format(microtime(true) - self::$up_start, 3);
349 // Reset global data to avoid interferences
353 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
355 $funcname($argv, $argc);
358 $a->process_id = $old_process_id;
361 $duration = (microtime(true) - $stamp);
363 self::$up_start = microtime(true);
365 /* With these values we can analyze how effective the worker is.
366 * The database and rest time should be low since this is the unproductive time.
367 * The execution time is the productive time.
368 * By changing parameters like the maximum number of workers we can check the effectivness.
371 'DB: '.number_format(self::$db_duration, 2).
372 ' - Lock: '.number_format(self::$lock_duration, 2).
373 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
374 ' - Execution: '.number_format($duration, 2),
378 self::$lock_duration = 0;
380 if ($duration > 3600) {
381 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
382 } elseif ($duration > 600) {
383 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
384 } elseif ($duration > 300) {
385 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
386 } elseif ($duration > 120) {
387 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
390 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
392 // Write down the performance values into the log
393 if (Config::get("system", "profiler")) {
394 $duration = microtime(true)-$a->performance["start"];
397 if (Config::get("rendertime", "callstack")) {
398 if (isset($a->callstack["database"])) {
399 $o .= "\nDatabase Read:\n";
400 foreach ($a->callstack["database"] as $func => $time) {
401 $time = round($time, 3);
403 $o .= $func.": ".$time."\n";
407 if (isset($a->callstack["database_write"])) {
408 $o .= "\nDatabase Write:\n";
409 foreach ($a->callstack["database_write"] as $func => $time) {
410 $time = round($time, 3);
412 $o .= $func.": ".$time."\n";
416 if (isset($a->callstack["dache"])) {
417 $o .= "\nCache Read:\n";
418 foreach ($a->callstack["dache"] as $func => $time) {
419 $time = round($time, 3);
421 $o .= $func.": ".$time."\n";
425 if (isset($a->callstack["dache_write"])) {
426 $o .= "\nCache Write:\n";
427 foreach ($a->callstack["dache_write"] as $func => $time) {
428 $time = round($time, 3);
430 $o .= $func.": ".$time."\n";
434 if (isset($a->callstack["network"])) {
435 $o .= "\nNetwork:\n";
436 foreach ($a->callstack["network"] as $func => $time) {
437 $time = round($time, 3);
439 $o .= $func.": ".$time."\n";
446 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
447 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
448 number_format($a->performance["database"] - $a->performance["database_write"], 2),
449 number_format($a->performance["database_write"], 2),
450 number_format($a->performance["cache"], 2),
451 number_format($a->performance["cache_write"], 2),
452 number_format($a->performance["network"], 2),
453 number_format($a->performance["file"], 2),
454 number_format($duration - ($a->performance["database"]
455 + $a->performance["cache"] + $a->performance["cache_write"]
456 + $a->performance["network"] + $a->performance["file"]), 2),
457 number_format($duration, 2)
463 $cooldown = Config::get("system", "worker_cooldown", 0);
466 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
472 * @brief Checks if the number of database connections has reached a critical limit.
474 * @return bool Are more than 3/4 of the maximum connections used?
476 private static function maxConnectionsReached()
478 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
479 $max = Config::get("system", "max_connections");
481 // Fetch the percentage level where the worker will get active
482 $maxlevel = Config::get("system", "max_connections_level", 75);
485 // the maximum number of possible user connections can be a system variable
486 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
487 if (DBA::isResult($r)) {
490 // Or it can be granted. This overrides the system variable
491 $r = DBA::p('SHOW GRANTS');
492 while ($grants = DBA::fetch($r)) {
493 $grant = array_pop($grants);
494 if (stristr($grant, "GRANT USAGE ON")) {
495 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
503 // If $max is set we will use the processlist to determine the current number of connections
504 // The processlist only shows entries of the current user
506 $r = DBA::p('SHOW PROCESSLIST');
507 $used = DBA::numRows($r);
510 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
512 $level = ($used / $max) * 100;
514 if ($level >= $maxlevel) {
515 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
520 // We will now check for the system values.
521 // This limit could be reached although the user limits are fine.
522 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
523 if (!DBA::isResult($r)) {
526 $max = intval($r["Value"]);
530 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
531 if (!DBA::isResult($r)) {
534 $used = intval($r["Value"]);
538 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
540 $level = $used / $max * 100;
542 if ($level < $maxlevel) {
545 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
550 * @brief fix the queue entry if the worker process died
553 private static function killStaleWorkers()
555 $entries = DBA::select(
557 ['id', 'pid', 'executed', 'priority', 'parameter'],
558 ['`executed` > ? AND NOT `done` AND `pid` != 0', DBA::NULL_DATETIME],
559 ['order' => ['priority', 'created']]
562 while ($entry = DBA::fetch($entries)) {
563 if (!posix_kill($entry["pid"], 0)) {
566 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
567 ['id' => $entry["id"]]
570 // Kill long running processes
571 // Check if the priority is in a valid range
572 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
573 $entry["priority"] = PRIORITY_MEDIUM;
576 // Define the maximum durations
577 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
578 $max_duration = $max_duration_defaults[$entry["priority"]];
580 $argv = json_decode($entry["parameter"], true);
581 $argv[0] = basename($argv[0]);
583 // How long is the process already running?
584 $duration = (time() - strtotime($entry["executed"])) / 60;
585 if ($duration > $max_duration) {
586 logger("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
587 posix_kill($entry["pid"], SIGTERM);
589 // We killed the stale process.
590 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
591 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
592 $new_priority = $entry["priority"];
593 if ($entry["priority"] == PRIORITY_HIGH) {
594 $new_priority = PRIORITY_MEDIUM;
595 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
596 $new_priority = PRIORITY_LOW;
597 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
598 $new_priority = PRIORITY_NEGLIGIBLE;
602 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
603 ['id' => $entry["id"]]
606 logger("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
613 * @brief Checks if the number of active workers exceeds the given limits
615 * @return bool Are there too much workers running?
617 public static function tooMuchWorkers()
619 $queues = Config::get("system", "worker_queues", 4);
621 $maxqueues = $queues;
623 $active = self::activeWorkers();
625 // Decrease the number of workers at higher load
626 $load = System::currentLoad();
628 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
630 /* Default exponent 3 causes queues to rapidly decrease as load increases.
631 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
632 * For some environments, this rapid decrease is not needed.
633 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
635 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
636 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
637 $queues = intval(ceil($slope * $maxqueues));
641 if (Config::get('system', 'worker_debug')) {
642 // Create a list of queue entries grouped by their priority
645 // Adding all processes with no workerqueue entry
647 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
648 (SELECT id FROM `workerqueue`
649 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
653 if ($process = DBA::fetch($processes)) {
654 $listitem[0] = "0:".$process["running"];
656 DBA::close($processes);
658 // Now adding all processes with workerqueue entries
659 $entries = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
660 while ($entry = DBA::fetch($entries)) {
661 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
662 if ($process = DBA::fetch($processes)) {
663 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
665 DBA::close($processes);
667 DBA::close($entries);
669 $intervals = [1, 10, 60];
670 $jobs_per_minute = [];
671 foreach ($intervals as $interval) {
672 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
673 if ($job = DBA::fetch($jobs)) {
674 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
678 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
681 $entries = self::totalEntries();
683 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
684 $top_priority = self::highestPriority();
685 $high_running = self::processWithPriorityActive($top_priority);
687 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
688 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
689 $queues = $active + 1;
693 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
695 // Are there fewer workers running as possible? Then fork a new one.
696 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
697 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
698 if (Config::get('system', 'worker_daemon_mode', false)) {
699 self::IPCSetJobState(true);
706 // if there are too much worker, we don't spawn a new one.
707 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
708 self::IPCSetJobState(false);
711 return $active > $queues;
715 * @brief Returns the number of active worker processes
717 * @return integer Number of active worker processes
719 private static function activeWorkers()
721 return DBA::count('process', ['command' => 'Worker.php']);
725 * @brief Check if we should pass some slow processes
727 * When the active processes of the highest priority are using more than 2/3
728 * of all processes, we let pass slower processes.
730 * @param string $highest_priority Returns the currently highest priority
731 * @return bool We let pass a slower process than $highest_priority
733 private static function passingSlow(&$highest_priority)
735 $highest_priority = 0;
740 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
743 // No active processes at all? Fine
744 if (!DBA::isResult($r)) {
748 while ($line = DBA::fetch($r)) {
749 $priorities[] = $line["priority"];
754 if (count($priorities) == 0) {
757 $highest_priority = min($priorities);
759 // The highest process is already the slowest one?
761 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
765 foreach ($priorities as $priority) {
766 if ($priority == $highest_priority) {
770 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
771 $passing_slow = (($high/count($priorities)) > (2/3));
774 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
776 return $passing_slow;
780 * @brief Find and claim the next worker process for us
782 * @param boolean $passing_slow Returns if we had passed low priority processes
783 * @return boolean Have we found something?
785 private static function findWorkerProcesses(&$passing_slow)
789 // Check if we should pass some low priority process
790 $highest_priority = 0;
792 $passing_slow = false;
794 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
795 // We decrease the limit with the number of entries left in the queue
796 $worker_queues = Config::get("system", "worker_queues", 4);
797 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
798 $lower_job_limit = $worker_queues * $queue_length * 2;
799 $jobs = self::totalEntries();
803 $slope = $queue_length / pow($lower_job_limit, $exponent);
804 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
806 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
808 if (self::passingSlow($highest_priority)) {
809 // Are there waiting processes with a higher priority than the currently highest?
810 $result = DBA::select(
813 ["`executed` <= ? AND `priority` < ? AND NOT `done` AND `next_try` < ?",
814 DBA::NULL_DATETIME, $highest_priority, DateTimeFormat::utcNow()],
815 ['limit' => $limit, 'order' => ['priority', 'created']]
818 while ($id = DBA::fetch($result)) {
823 $found = (count($ids) > 0);
826 // Give slower processes some processing time
827 $result = DBA::select(
830 ["`executed` <= ? AND `priority` > ? AND NOT `done` AND `next_try` < ?",
831 DBA::NULL_DATETIME, $highest_priority, DateTimeFormat::utcNow()],
832 ['limit' => $limit, 'order' => ['priority', 'created']]
835 while ($id = DBA::fetch($result)) {
840 $found = (count($ids) > 0);
841 $passing_slow = $found;
845 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
847 $result = DBA::select(
850 ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
851 DBA::NULL_DATETIME, DateTimeFormat::utcNow()],
852 ['limit' => $limit, 'order' => ['priority', 'created']]
855 while ($id = DBA::fetch($result)) {
860 $found = (count($ids) > 0);
864 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
865 array_unshift($ids, $condition);
866 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
873 * @brief Returns the next worker process
875 * @param boolean $passing_slow Returns if we had passed low priority processes
876 * @return string SQL statement
878 public static function workerProcess(&$passing_slow)
880 $stamp = (float)microtime(true);
882 // There can already be jobs for us in the queue.
883 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
884 if (DBA::isResult($r)) {
885 self::$db_duration += (microtime(true) - $stamp);
886 return DBA::toArray($r);
890 $stamp = (float)microtime(true);
891 if (!Lock::acquire('worker_process')) {
894 self::$lock_duration = (microtime(true) - $stamp);
896 $stamp = (float)microtime(true);
897 $found = self::findWorkerProcesses($passing_slow);
898 self::$db_duration += (microtime(true) - $stamp);
900 Lock::release('worker_process');
903 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
904 return DBA::toArray($r);
910 * @brief Removes a workerqueue entry from the current process
913 public static function unclaimProcess()
917 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
921 * @brief Call the front end worker
924 public static function callWorker()
926 if (!Config::get("system", "frontend_worker")) {
930 $url = System::baseUrl()."/worker";
931 Network::fetchUrl($url, false, $redirects, 1);
935 * @brief Call the front end worker if there aren't any active
938 public static function executeIfIdle()
940 if (!Config::get("system", "frontend_worker")) {
944 // Do we have "proc_open"? Then we can fork the worker
945 if (function_exists("proc_open")) {
946 // When was the last time that we called the worker?
947 // Less than one minute? Then we quit
948 if ((time() - Config::get("system", "worker_started")) < 60) {
952 Config::set("system", "worker_started", time());
954 // Do we have enough running workers? Then we quit here.
955 if (self::tooMuchWorkers()) {
956 // Cleaning dead processes
957 self::killStaleWorkers();
958 Process::deleteInactive();
965 logger('Call worker', LOGGER_DEBUG);
970 // We cannot execute background processes.
971 // We now run the processes from the frontend.
972 // This won't work with long running processes.
975 self::clearProcesses();
977 $workers = self::activeWorkers();
985 * @brief Removes long running worker processes
988 public static function clearProcesses()
990 $timeout = Config::get("system", "frontend_worker_timeout", 10);
992 /// @todo We should clean up the corresponding workerqueue entries as well
993 $condition = ["`created` < ? AND `command` = 'worker.php'",
994 DateTimeFormat::utc("now - ".$timeout." minutes")];
995 DBA::delete('process', $condition);
999 * @brief Runs the cron processes
1002 private static function runCron()
1004 logger('Add cron entries', LOGGER_DEBUG);
1006 // Check for spooled items
1007 self::add(PRIORITY_HIGH, "SpoolPost");
1009 // Run the cron job that calls all other jobs
1010 self::add(PRIORITY_MEDIUM, "Cron");
1012 // Cleaning dead processes
1013 self::killStaleWorkers();
1017 * @brief Spawns a new worker
1020 public static function spawnWorker($do_cron = false)
1022 $command = 'bin/worker.php';
1024 $args = ['no_cron' => !$do_cron];
1026 get_app()->proc_run($command, $args);
1028 // after spawning we have to remove the flag.
1029 if (Config::get('system', 'worker_daemon_mode', false)) {
1030 self::IPCSetJobState(false);
1035 * @brief Adds tasks to the worker queue
1037 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1039 * next args are passed as $cmd command line
1040 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1041 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1043 * @note $cmd and string args are surrounded with ""
1048 * @return boolean "false" if proc_run couldn't be executed
1050 public static function add($cmd)
1052 $args = func_get_args();
1054 if (!count($args)) {
1058 $arr = ['args' => $args, 'run_cmd' => true];
1060 Addon::callHooks("proc_run", $arr);
1061 if (!$arr['run_cmd'] || !count($args)) {
1065 $priority = PRIORITY_MEDIUM;
1066 $dont_fork = Config::get("system", "worker_dont_fork", false);
1067 $created = DateTimeFormat::utcNow();
1069 $run_parameter = array_shift($args);
1071 if (is_int($run_parameter)) {
1072 $priority = $run_parameter;
1073 } elseif (is_array($run_parameter)) {
1074 if (isset($run_parameter['priority'])) {
1075 $priority = $run_parameter['priority'];
1077 if (isset($run_parameter['created'])) {
1078 $created = $run_parameter['created'];
1080 if (isset($run_parameter['dont_fork'])) {
1081 $dont_fork = $run_parameter['dont_fork'];
1085 $parameters = json_encode($args);
1086 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1088 // Quit if there was a database error - a precaution for the update process to 3.5.3
1089 if (DBA::errorNo() != 0) {
1094 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1097 // Should we quit and wait for the worker to be called as a cronjob?
1102 // If there is a lock then we don't have to check for too much worker
1103 if (!Lock::acquire('worker', 0)) {
1107 // If there are already enough workers running, don't fork another one
1108 $quit = self::tooMuchWorkers();
1109 Lock::release('worker');
1115 // We tell the daemon that a new job entry exists
1116 if (Config::get('system', 'worker_daemon_mode', false)) {
1117 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1121 // Now call the worker to execute the jobs that we just added to the queue
1122 self::spawnWorker();
1128 * Defers the current worker entry
1130 public static function defer()
1132 if (empty(BaseObject::getApp()->queue)) {
1136 $queue = BaseObject::getApp()->queue;
1138 $retrial = $queue['retrial'];
1141 if ($retrial > 14) {
1142 logger('Id ' . $id . ' had been tried 14 times. We stop now.', LOGGER_DEBUG);
1146 // Calculate the delay until the next trial
1147 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1148 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1150 logger('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next, LOGGER_DEBUG);
1152 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0];
1153 DBA::update('workerqueue', $fields, ['id' => $id]);
1157 * Log active processes into the "process" table
1159 * @brief Log active processes into the "process" table
1161 public static function startProcess()
1163 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1165 $command = basename($trace[0]['file']);
1167 Process::deleteInactive();
1169 Process::insert($command);
1173 * Remove the active process from the "process" table
1175 * @brief Remove the active process from the "process" table
1178 public static function endProcess()
1180 return Process::deleteByPid();
1184 * Set the flag if some job is waiting
1186 * @brief Set the flag if some job is waiting
1187 * @param boolean $jobs Is there a waiting job?
1189 public static function IPCSetJobState($jobs)
1191 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1195 * Checks if some worker job waits to be executed
1197 * @brief Checks if some worker job waits to be executed
1200 public static function IPCJobsExists()
1202 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1204 // When we don't have a row, no job is running
1205 if (!DBA::isResult($row)) {
1209 return (bool)$row['jobs'];