3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
7 use Friendica\Database\DBA;
8 use Friendica\Model\Process;
9 use Friendica\Util\DateTimeFormat;
10 use Friendica\Util\Network;
12 require_once 'include/dba.php';
15 * @file src/Core/Worker.php
17 * @brief Contains the class for the worker background job processing
21 * @brief Worker methods
25 private static $up_start;
26 private static $db_duration;
27 private static $last_update;
28 private static $lock_duration;
31 * @brief Processes the tasks that are in the workerqueue table
33 * @param boolean $run_cron Should the cron processes be executed?
36 public static function processQueue($run_cron = true)
40 self::$up_start = microtime(true);
42 // At first check the maximum load. We shouldn't continue with a high load
43 if ($a->isMaxLoadReached()) {
44 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
48 // We now start the process. This is done after the load check since this could increase the load.
51 // Kill stale processes every 5 minutes
52 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
53 if (time() > ($last_cleanup + 300)) {
54 Config::set('system', 'worker_last_cleaned', time());
55 self::killStaleWorkers();
58 // Count active workers and compare them with a maximum value that depends on the load
59 if (self::tooMuchWorkers()) {
60 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
64 // Do we have too few memory?
65 if ($a->min_memory_reached()) {
66 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
70 // Possibly there are too much database connections
71 if (self::maxConnectionsReached()) {
72 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
76 // Possibly there are too much database processes that block the system
77 if ($a->isMaxProcessesReached()) {
78 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
82 // Now we start additional cron processes if we should do so
89 // We fetch the next queue entry that is about to be executed
90 while ($r = self::workerProcess($passing_slow)) {
91 // When we are processing jobs with a lower priority, we don't refetch new jobs
92 // Otherwise fast jobs could wait behind slow ones and could be blocked.
93 $refetched = $passing_slow;
95 foreach ($r as $entry) {
96 // Assure that the priority is an integer value
97 $entry['priority'] = (int)$entry['priority'];
99 // The work will be done
100 if (!self::execute($entry)) {
101 logger('Process execution failed, quitting.', LOGGER_DEBUG);
105 // If possible we will fetch new jobs for this worker
106 if (!$refetched && Lock::acquire('worker_process', 0)) {
107 $stamp = (float)microtime(true);
108 $refetched = self::findWorkerProcesses($passing_slow);
109 self::$db_duration += (microtime(true) - $stamp);
110 Lock::release('worker_process');
114 // To avoid the quitting of multiple workers only one worker at a time will execute the check
115 if (Lock::acquire('worker', 0)) {
116 $stamp = (float)microtime(true);
117 // Count active workers and compare them with a maximum value that depends on the load
118 if (self::tooMuchWorkers()) {
119 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
124 if ($a->min_memory_reached()) {
125 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
128 Lock::release('worker');
129 self::$db_duration += (microtime(true) - $stamp);
132 // Quit the worker once every 5 minutes
133 if (time() > ($starttime + 300)) {
134 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
139 // Cleaning up. Possibly not needed, but it doesn't harm anything.
140 if (Config::get('system', 'worker_daemon_mode', false)) {
141 self::IPCSetJobState(false);
143 logger("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", 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 return DBA::count('workerqueue', ["`executed` <= ? AND NOT `done`", NULL_DATE]);
157 * @brief Returns the highest priority in the worker queue that isn't executed
159 * @return integer Number of active worker processes
161 private static function highestPriority()
163 $condition = ["`executed` <= ? AND NOT `done`", NULL_DATE];
164 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
165 if (DBA::isResult($workerqueue)) {
166 return $workerqueue["priority"];
173 * @brief Returns if a process with the given priority is running
175 * @param integer $priority The priority that should be checked
177 * @return integer Is there a process running with that priority?
179 private static function processWithPriorityActive($priority)
181 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE];
182 return DBA::exists('workerqueue', $condition);
186 * @brief Execute a worker entry
188 * @param array $queue Workerqueue entry
190 * @return boolean "true" if further processing should be stopped
192 public static function execute($queue)
198 // Quit when in maintenance
199 if (Config::get('system', 'maintenance', false, true)) {
200 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
204 // Constantly check the number of parallel database processes
205 if ($a->isMaxProcessesReached()) {
206 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
210 // Constantly check the number of available database connections to let the frontend be accessible at any time
211 if (self::maxConnectionsReached()) {
212 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
216 $argv = json_decode($queue["parameter"], true);
218 // Check for existance and validity of the include file
221 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
222 // We constantly update the "executed" date every minute to avoid being killed too soon
223 if (!isset(self::$last_update)) {
224 self::$last_update = strtotime($queue["executed"]);
227 $age = (time() - self::$last_update) / 60;
228 self::$last_update = time();
231 $stamp = (float)microtime(true);
232 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
233 self::$db_duration += (microtime(true) - $stamp);
238 self::execFunction($queue, $include, $argv, true);
240 $stamp = (float)microtime(true);
241 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
242 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
244 self::$db_duration = (microtime(true) - $stamp);
249 // The script could be provided as full path or only with the function name
250 if ($include == basename($include)) {
251 $include = "include/".$include.".php";
254 if (!validate_include($include)) {
255 logger("Include file ".$argv[0]." is not valid!");
256 DBA::delete('workerqueue', ['id' => $queue["id"]]);
260 require_once $include;
262 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
264 if (function_exists($funcname)) {
265 // We constantly update the "executed" date every minute to avoid being killed too soon
266 if (!isset(self::$last_update)) {
267 self::$last_update = strtotime($queue["executed"]);
270 $age = (time() - self::$last_update) / 60;
271 self::$last_update = time();
274 $stamp = (float)microtime(true);
275 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
276 self::$db_duration += (microtime(true) - $stamp);
279 self::execFunction($queue, $funcname, $argv, false);
281 $stamp = (float)microtime(true);
282 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
283 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
285 self::$db_duration = (microtime(true) - $stamp);
287 logger("Function ".$funcname." does not exist");
288 DBA::delete('workerqueue', ['id' => $queue["id"]]);
295 * @brief Execute a function from the queue
297 * @param array $queue Workerqueue entry
298 * @param string $funcname name of the function
299 * @param array $argv Array of values to be passed to the function
300 * @param boolean $method_call boolean
303 private static function execFunction($queue, $funcname, $argv, $method_call)
309 $argc = count($argv);
311 $new_process_id = System::processID("wrk");
313 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
315 $stamp = (float)microtime(true);
317 // We use the callstack here to analyze the performance of executed worker entries.
318 // For this reason the variables have to be initialized.
319 if (Config::get("system", "profiler")) {
320 $a->performance["start"] = microtime(true);
321 $a->performance["database"] = 0;
322 $a->performance["database_write"] = 0;
323 $a->performance["cache"] = 0;
324 $a->performance["cache_write"] = 0;
325 $a->performance["network"] = 0;
326 $a->performance["file"] = 0;
327 $a->performance["rendering"] = 0;
328 $a->performance["parser"] = 0;
329 $a->performance["marktime"] = 0;
330 $a->performance["markstart"] = microtime(true);
334 // For better logging create a new process id for every worker call
335 // But preserve the old one for the worker
336 $old_process_id = $a->process_id;
337 $a->process_id = $new_process_id;
340 $up_duration = number_format(microtime(true) - self::$up_start, 3);
342 // Reset global data to avoid interferences
346 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
348 $funcname($argv, $argc);
351 $a->process_id = $old_process_id;
354 $duration = (microtime(true) - $stamp);
356 self::$up_start = microtime(true);
358 /* With these values we can analyze how effective the worker is.
359 * The database and rest time should be low since this is the unproductive time.
360 * The execution time is the productive time.
361 * By changing parameters like the maximum number of workers we can check the effectivness.
364 'DB: '.number_format(self::$db_duration, 2).
365 ' - Lock: '.number_format(self::$lock_duration, 2).
366 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
367 ' - Execution: '.number_format($duration, 2),
371 self::$lock_duration = 0;
373 if ($duration > 3600) {
374 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
375 } elseif ($duration > 600) {
376 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
377 } elseif ($duration > 300) {
378 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
379 } elseif ($duration > 120) {
380 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
383 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
385 // Write down the performance values into the log
386 if (Config::get("system", "profiler")) {
387 $duration = microtime(true)-$a->performance["start"];
390 if (Config::get("rendertime", "callstack")) {
391 if (isset($a->callstack["database"])) {
392 $o .= "\nDatabase Read:\n";
393 foreach ($a->callstack["database"] as $func => $time) {
394 $time = round($time, 3);
396 $o .= $func.": ".$time."\n";
400 if (isset($a->callstack["database_write"])) {
401 $o .= "\nDatabase Write:\n";
402 foreach ($a->callstack["database_write"] as $func => $time) {
403 $time = round($time, 3);
405 $o .= $func.": ".$time."\n";
409 if (isset($a->callstack["dache"])) {
410 $o .= "\nCache Read:\n";
411 foreach ($a->callstack["dache"] as $func => $time) {
412 $time = round($time, 3);
414 $o .= $func.": ".$time."\n";
418 if (isset($a->callstack["dache_write"])) {
419 $o .= "\nCache Write:\n";
420 foreach ($a->callstack["dache_write"] as $func => $time) {
421 $time = round($time, 3);
423 $o .= $func.": ".$time."\n";
427 if (isset($a->callstack["network"])) {
428 $o .= "\nNetwork:\n";
429 foreach ($a->callstack["network"] as $func => $time) {
430 $time = round($time, 3);
432 $o .= $func.": ".$time."\n";
439 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
440 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
441 number_format($a->performance["database"] - $a->performance["database_write"], 2),
442 number_format($a->performance["database_write"], 2),
443 number_format($a->performance["cache"], 2),
444 number_format($a->performance["cache_write"], 2),
445 number_format($a->performance["network"], 2),
446 number_format($a->performance["file"], 2),
447 number_format($duration - ($a->performance["database"]
448 + $a->performance["cache"] + $a->performance["cache_write"]
449 + $a->performance["network"] + $a->performance["file"]), 2),
450 number_format($duration, 2)
456 $cooldown = Config::get("system", "worker_cooldown", 0);
459 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
465 * @brief Checks if the number of database connections has reached a critical limit.
467 * @return bool Are more than 3/4 of the maximum connections used?
469 private static function maxConnectionsReached()
471 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
472 $max = Config::get("system", "max_connections");
474 // Fetch the percentage level where the worker will get active
475 $maxlevel = Config::get("system", "max_connections_level", 75);
478 // the maximum number of possible user connections can be a system variable
479 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
480 if (DBA::isResult($r)) {
483 // Or it can be granted. This overrides the system variable
484 $r = DBA::p('SHOW GRANTS');
485 while ($grants = DBA::fetch($r)) {
486 $grant = array_pop($grants);
487 if (stristr($grant, "GRANT USAGE ON")) {
488 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
496 // If $max is set we will use the processlist to determine the current number of connections
497 // The processlist only shows entries of the current user
499 $r = DBA::p('SHOW PROCESSLIST');
500 $used = DBA::numRows($r);
503 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
505 $level = ($used / $max) * 100;
507 if ($level >= $maxlevel) {
508 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
513 // We will now check for the system values.
514 // This limit could be reached although the user limits are fine.
515 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
516 if (!DBA::isResult($r)) {
519 $max = intval($r["Value"]);
523 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
524 if (!DBA::isResult($r)) {
527 $used = intval($r["Value"]);
531 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
533 $level = $used / $max * 100;
535 if ($level < $maxlevel) {
538 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
543 * @brief fix the queue entry if the worker process died
546 private static function killStaleWorkers()
548 $entries = DBA::select(
550 ['id', 'pid', 'executed', 'priority', 'parameter'],
551 ['`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE],
552 ['order' => ['priority', 'created']]
555 while ($entry = DBA::fetch($entries)) {
556 if (!posix_kill($entry["pid"], 0)) {
559 ['executed' => NULL_DATE, 'pid' => 0],
560 ['id' => $entry["id"]]
563 // Kill long running processes
564 // Check if the priority is in a valid range
565 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
566 $entry["priority"] = PRIORITY_MEDIUM;
569 // Define the maximum durations
570 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
571 $max_duration = $max_duration_defaults[$entry["priority"]];
573 $argv = json_decode($entry["parameter"], true);
574 $argv[0] = basename($argv[0]);
576 // How long is the process already running?
577 $duration = (time() - strtotime($entry["executed"])) / 60;
578 if ($duration > $max_duration) {
579 logger("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
580 posix_kill($entry["pid"], SIGTERM);
582 // We killed the stale process.
583 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
584 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
585 $new_priority = $entry["priority"];
586 if ($entry["priority"] == PRIORITY_HIGH) {
587 $new_priority = PRIORITY_MEDIUM;
588 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
589 $new_priority = PRIORITY_LOW;
590 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
591 $new_priority = PRIORITY_NEGLIGIBLE;
595 ['executed' => NULL_DATE, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
596 ['id' => $entry["id"]]
599 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);
606 * @brief Checks if the number of active workers exceeds the given limits
608 * @return bool Are there too much workers running?
610 public static function tooMuchWorkers()
612 $queues = Config::get("system", "worker_queues", 4);
614 $maxqueues = $queues;
616 $active = self::activeWorkers();
618 // Decrease the number of workers at higher load
619 $load = current_load();
621 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
623 /* Default exponent 3 causes queues to rapidly decrease as load increases.
624 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
625 * For some environments, this rapid decrease is not needed.
626 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
628 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
629 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
630 $queues = intval(ceil($slope * $maxqueues));
634 if (Config::get('system', 'worker_debug')) {
635 // Create a list of queue entries grouped by their priority
638 // Adding all processes with no workerqueue entry
640 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
641 (SELECT id FROM `workerqueue`
642 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
646 if ($process = DBA::fetch($processes)) {
647 $listitem[0] = "0:".$process["running"];
649 DBA::close($processes);
651 // Now adding all processes with workerqueue entries
652 $entries = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
653 while ($entry = DBA::fetch($entries)) {
654 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
655 if ($process = DBA::fetch($processes)) {
656 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
658 DBA::close($processes);
660 DBA::close($entries);
662 $intervals = [1, 10, 60];
663 $jobs_per_minute = [];
664 foreach ($intervals as $interval) {
665 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
666 if ($job = DBA::fetch($jobs)) {
667 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
671 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
674 $entries = self::totalEntries();
676 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
677 $top_priority = self::highestPriority();
678 $high_running = self::processWithPriorityActive($top_priority);
680 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
681 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
682 $queues = $active + 1;
686 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
688 // Are there fewer workers running as possible? Then fork a new one.
689 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
690 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
691 if (Config::get('system', 'worker_daemon_mode', false)) {
692 self::IPCSetJobState(true);
699 // if there are too much worker, we don't spawn a new one.
700 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
701 self::IPCSetJobState(false);
704 return $active > $queues;
708 * @brief Returns the number of active worker processes
710 * @return integer Number of active worker processes
712 private static function activeWorkers()
714 return DBA::count('process', ['command' => 'Worker.php']);
718 * @brief Check if we should pass some slow processes
720 * When the active processes of the highest priority are using more than 2/3
721 * of all processes, we let pass slower processes.
723 * @param string $highest_priority Returns the currently highest priority
724 * @return bool We let pass a slower process than $highest_priority
726 private static function passingSlow(&$highest_priority)
728 $highest_priority = 0;
733 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
736 // No active processes at all? Fine
737 if (!DBA::isResult($r)) {
741 while ($line = DBA::fetch($r)) {
742 $priorities[] = $line["priority"];
747 if (count($priorities) == 0) {
750 $highest_priority = min($priorities);
752 // The highest process is already the slowest one?
754 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
758 foreach ($priorities as $priority) {
759 if ($priority == $highest_priority) {
763 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
764 $passing_slow = (($high/count($priorities)) > (2/3));
767 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
769 return $passing_slow;
773 * @brief Find and claim the next worker process for us
775 * @param boolean $passing_slow Returns if we had passed low priority processes
776 * @return boolean Have we found something?
778 private static function findWorkerProcesses(&$passing_slow)
782 // Check if we should pass some low priority process
783 $highest_priority = 0;
785 $passing_slow = false;
787 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
788 // We decrease the limit with the number of entries left in the queue
789 $worker_queues = Config::get("system", "worker_queues", 4);
790 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
791 $lower_job_limit = $worker_queues * $queue_length * 2;
792 $jobs = self::totalEntries();
796 $slope = $queue_length / pow($lower_job_limit, $exponent);
797 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
799 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
801 if (self::passingSlow($highest_priority)) {
802 // Are there waiting processes with a higher priority than the currently highest?
803 $result = DBA::select(
806 ["`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority],
807 ['limit' => $limit, 'order' => ['priority', 'created']]
810 while ($id = DBA::fetch($result)) {
815 $found = (count($ids) > 0);
818 // Give slower processes some processing time
819 $result = DBA::select(
822 ["`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority],
823 ['limit' => $limit, 'order' => ['priority', 'created']]
826 while ($id = DBA::fetch($result)) {
831 $found = (count($ids) > 0);
832 $passing_slow = $found;
836 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
838 $result = DBA::select(
841 ["`executed` <= ? AND NOT `done`", NULL_DATE],
842 ['limit' => $limit, 'order' => ['priority', 'created']]
845 while ($id = DBA::fetch($result)) {
850 $found = (count($ids) > 0);
854 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
855 array_unshift($ids, $condition);
856 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
863 * @brief Returns the next worker process
865 * @param boolean $passing_slow Returns if we had passed low priority processes
866 * @return string SQL statement
868 public static function workerProcess(&$passing_slow)
870 $stamp = (float)microtime(true);
872 // There can already be jobs for us in the queue.
873 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
874 if (DBA::isResult($r)) {
875 self::$db_duration += (microtime(true) - $stamp);
876 return DBA::toArray($r);
880 $stamp = (float)microtime(true);
881 if (!Lock::acquire('worker_process')) {
884 self::$lock_duration = (microtime(true) - $stamp);
886 $stamp = (float)microtime(true);
887 $found = self::findWorkerProcesses($passing_slow);
888 self::$db_duration += (microtime(true) - $stamp);
890 Lock::release('worker_process');
893 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
894 return DBA::toArray($r);
900 * @brief Removes a workerqueue entry from the current process
903 public static function unclaimProcess()
907 DBA::update('workerqueue', ['executed' => NULL_DATE, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
911 * @brief Call the front end worker
914 public static function callWorker()
916 if (!Config::get("system", "frontend_worker")) {
920 $url = System::baseUrl()."/worker";
921 Network::fetchUrl($url, false, $redirects, 1);
925 * @brief Call the front end worker if there aren't any active
928 public static function executeIfIdle()
930 if (!Config::get("system", "frontend_worker")) {
934 // Do we have "proc_open"? Then we can fork the worker
935 if (function_exists("proc_open")) {
936 // When was the last time that we called the worker?
937 // Less than one minute? Then we quit
938 if ((time() - Config::get("system", "worker_started")) < 60) {
942 Config::set("system", "worker_started", time());
944 // Do we have enough running workers? Then we quit here.
945 if (self::tooMuchWorkers()) {
946 // Cleaning dead processes
947 self::killStaleWorkers();
948 Process::deleteInactive();
955 logger('Call worker', LOGGER_DEBUG);
960 // We cannot execute background processes.
961 // We now run the processes from the frontend.
962 // This won't work with long running processes.
965 self::clearProcesses();
967 $workers = self::activeWorkers();
975 * @brief Removes long running worker processes
978 public static function clearProcesses()
980 $timeout = Config::get("system", "frontend_worker_timeout", 10);
982 /// @todo We should clean up the corresponding workerqueue entries as well
983 $condition = ["`created` < ? AND `command` = 'worker.php'",
984 DateTimeFormat::utc("now - ".$timeout." minutes")];
985 DBA::delete('process', $condition);
989 * @brief Runs the cron processes
992 private static function runCron()
994 logger('Add cron entries', LOGGER_DEBUG);
996 // Check for spooled items
997 self::add(PRIORITY_HIGH, "SpoolPost");
999 // Run the cron job that calls all other jobs
1000 self::add(PRIORITY_MEDIUM, "Cron");
1002 // Cleaning dead processes
1003 self::killStaleWorkers();
1007 * @brief Spawns a new worker
1010 public static function spawnWorker($do_cron = false)
1012 $command = 'bin/worker.php';
1014 $args = ['no_cron' => !$do_cron];
1016 get_app()->proc_run($command, $args);
1018 // after spawning we have to remove the flag.
1019 if (Config::get('system', 'worker_daemon_mode', false)) {
1020 self::IPCSetJobState(false);
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 // Should we quit and wait for the worker to be called as a cronjob?
1092 // If there is a lock then we don't have to check for too much worker
1093 if (!Lock::acquire('worker', 0)) {
1097 // If there are already enough workers running, don't fork another one
1098 $quit = self::tooMuchWorkers();
1099 Lock::release('worker');
1105 // We tell the daemon that a new job entry exists
1106 if (Config::get('system', 'worker_daemon_mode', false)) {
1107 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
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 (!DBA::isResult($row)) {
1170 return (bool)$row['jobs'];