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 deferred entries in the worker queue
152 * @return integer Number of deferred entries in the worker queue
154 private static function deferredEntries()
156 return DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` > ?",
157 DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
161 * @brief Returns the number of non executed entries in the worker queue
163 * @return integer Number of non executed entries in the worker queue
165 private static function totalEntries()
167 return DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
168 DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
172 * @brief Returns the highest priority in the worker queue that isn't executed
174 * @return integer Number of active worker processes
176 private static function highestPriority()
178 $condition = ["`executed` <= ? AND NOT `done` AND `next_try` < ?", DBA::NULL_DATETIME, DateTimeFormat::utcNow()];
179 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
180 if (DBA::isResult($workerqueue)) {
181 return $workerqueue["priority"];
188 * @brief Returns if a process with the given priority is running
190 * @param integer $priority The priority that should be checked
192 * @return integer Is there a process running with that priority?
194 private static function processWithPriorityActive($priority)
196 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done` AND `next_try` < ?",
197 $priority, DBA::NULL_DATETIME, DateTimeFormat::utcNow()];
198 return DBA::exists('workerqueue', $condition);
202 * @brief Execute a worker entry
204 * @param array $queue Workerqueue entry
206 * @return boolean "true" if further processing should be stopped
208 public static function execute($queue)
214 // Quit when in maintenance
215 if (Config::get('system', 'maintenance', false, true)) {
216 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
220 // Constantly check the number of parallel database processes
221 if ($a->isMaxProcessesReached()) {
222 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
226 // Constantly check the number of available database connections to let the frontend be accessible at any time
227 if (self::maxConnectionsReached()) {
228 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
232 $argv = json_decode($queue["parameter"], true);
234 // Check for existance and validity of the include file
237 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
238 // We constantly update the "executed" date every minute to avoid being killed too soon
239 if (!isset(self::$last_update)) {
240 self::$last_update = strtotime($queue["executed"]);
243 $age = (time() - self::$last_update) / 60;
244 self::$last_update = time();
247 $stamp = (float)microtime(true);
248 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
249 self::$db_duration += (microtime(true) - $stamp);
254 self::execFunction($queue, $include, $argv, true);
256 $stamp = (float)microtime(true);
258 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
259 if (DBA::update('workerqueue', ['done' => true], $condition)) {
260 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
262 self::$db_duration = (microtime(true) - $stamp);
267 // The script could be provided as full path or only with the function name
268 if ($include == basename($include)) {
269 $include = "include/".$include.".php";
272 if (!validate_include($include)) {
273 logger("Include file ".$argv[0]." is not valid!");
274 DBA::delete('workerqueue', ['id' => $queue["id"]]);
278 require_once $include;
280 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
282 if (function_exists($funcname)) {
283 // We constantly update the "executed" date every minute to avoid being killed too soon
284 if (!isset(self::$last_update)) {
285 self::$last_update = strtotime($queue["executed"]);
288 $age = (time() - self::$last_update) / 60;
289 self::$last_update = time();
292 $stamp = (float)microtime(true);
293 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
294 self::$db_duration += (microtime(true) - $stamp);
297 self::execFunction($queue, $funcname, $argv, false);
299 $stamp = (float)microtime(true);
300 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
301 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
303 self::$db_duration = (microtime(true) - $stamp);
305 logger("Function ".$funcname." does not exist");
306 DBA::delete('workerqueue', ['id' => $queue["id"]]);
313 * @brief Execute a function from the queue
315 * @param array $queue Workerqueue entry
316 * @param string $funcname name of the function
317 * @param array $argv Array of values to be passed to the function
318 * @param boolean $method_call boolean
321 private static function execFunction($queue, $funcname, $argv, $method_call)
327 $argc = count($argv);
329 $new_process_id = System::processID("wrk");
331 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
333 $stamp = (float)microtime(true);
335 // We use the callstack here to analyze the performance of executed worker entries.
336 // For this reason the variables have to be initialized.
337 if (Config::get("system", "profiler")) {
338 $a->performance["start"] = microtime(true);
339 $a->performance["database"] = 0;
340 $a->performance["database_write"] = 0;
341 $a->performance["cache"] = 0;
342 $a->performance["cache_write"] = 0;
343 $a->performance["network"] = 0;
344 $a->performance["file"] = 0;
345 $a->performance["rendering"] = 0;
346 $a->performance["parser"] = 0;
347 $a->performance["marktime"] = 0;
348 $a->performance["markstart"] = microtime(true);
352 // For better logging create a new process id for every worker call
353 // But preserve the old one for the worker
354 $old_process_id = $a->process_id;
355 $a->process_id = $new_process_id;
358 $up_duration = number_format(microtime(true) - self::$up_start, 3);
360 // Reset global data to avoid interferences
364 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
366 $funcname($argv, $argc);
369 $a->process_id = $old_process_id;
372 $duration = (microtime(true) - $stamp);
374 self::$up_start = microtime(true);
376 /* With these values we can analyze how effective the worker is.
377 * The database and rest time should be low since this is the unproductive time.
378 * The execution time is the productive time.
379 * By changing parameters like the maximum number of workers we can check the effectivness.
382 'DB: '.number_format(self::$db_duration, 2).
383 ' - Lock: '.number_format(self::$lock_duration, 2).
384 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
385 ' - Execution: '.number_format($duration, 2),
389 self::$lock_duration = 0;
391 if ($duration > 3600) {
392 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
393 } elseif ($duration > 600) {
394 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
395 } elseif ($duration > 300) {
396 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
397 } elseif ($duration > 120) {
398 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
401 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
403 // Write down the performance values into the log
404 if (Config::get("system", "profiler")) {
405 $duration = microtime(true)-$a->performance["start"];
408 if (Config::get("rendertime", "callstack")) {
409 if (isset($a->callstack["database"])) {
410 $o .= "\nDatabase Read:\n";
411 foreach ($a->callstack["database"] as $func => $time) {
412 $time = round($time, 3);
414 $o .= $func.": ".$time."\n";
418 if (isset($a->callstack["database_write"])) {
419 $o .= "\nDatabase Write:\n";
420 foreach ($a->callstack["database_write"] as $func => $time) {
421 $time = round($time, 3);
423 $o .= $func.": ".$time."\n";
427 if (isset($a->callstack["dache"])) {
428 $o .= "\nCache Read:\n";
429 foreach ($a->callstack["dache"] as $func => $time) {
430 $time = round($time, 3);
432 $o .= $func.": ".$time."\n";
436 if (isset($a->callstack["dache_write"])) {
437 $o .= "\nCache Write:\n";
438 foreach ($a->callstack["dache_write"] as $func => $time) {
439 $time = round($time, 3);
441 $o .= $func.": ".$time."\n";
445 if (isset($a->callstack["network"])) {
446 $o .= "\nNetwork:\n";
447 foreach ($a->callstack["network"] as $func => $time) {
448 $time = round($time, 3);
450 $o .= $func.": ".$time."\n";
457 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
458 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
459 number_format($a->performance["database"] - $a->performance["database_write"], 2),
460 number_format($a->performance["database_write"], 2),
461 number_format($a->performance["cache"], 2),
462 number_format($a->performance["cache_write"], 2),
463 number_format($a->performance["network"], 2),
464 number_format($a->performance["file"], 2),
465 number_format($duration - ($a->performance["database"]
466 + $a->performance["cache"] + $a->performance["cache_write"]
467 + $a->performance["network"] + $a->performance["file"]), 2),
468 number_format($duration, 2)
474 $cooldown = Config::get("system", "worker_cooldown", 0);
477 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
483 * @brief Checks if the number of database connections has reached a critical limit.
485 * @return bool Are more than 3/4 of the maximum connections used?
487 private static function maxConnectionsReached()
489 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
490 $max = Config::get("system", "max_connections");
492 // Fetch the percentage level where the worker will get active
493 $maxlevel = Config::get("system", "max_connections_level", 75);
496 // the maximum number of possible user connections can be a system variable
497 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
498 if (DBA::isResult($r)) {
501 // Or it can be granted. This overrides the system variable
502 $r = DBA::p('SHOW GRANTS');
503 while ($grants = DBA::fetch($r)) {
504 $grant = array_pop($grants);
505 if (stristr($grant, "GRANT USAGE ON")) {
506 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
514 // If $max is set we will use the processlist to determine the current number of connections
515 // The processlist only shows entries of the current user
517 $r = DBA::p('SHOW PROCESSLIST');
518 $used = DBA::numRows($r);
521 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
523 $level = ($used / $max) * 100;
525 if ($level >= $maxlevel) {
526 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
531 // We will now check for the system values.
532 // This limit could be reached although the user limits are fine.
533 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
534 if (!DBA::isResult($r)) {
537 $max = intval($r["Value"]);
541 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
542 if (!DBA::isResult($r)) {
545 $used = intval($r["Value"]);
549 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
551 $level = $used / $max * 100;
553 if ($level < $maxlevel) {
556 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
561 * @brief fix the queue entry if the worker process died
564 private static function killStaleWorkers()
566 $entries = DBA::select(
568 ['id', 'pid', 'executed', 'priority', 'parameter'],
569 ['`executed` > ? AND NOT `done` AND `pid` != 0', DBA::NULL_DATETIME],
570 ['order' => ['priority', 'created']]
573 while ($entry = DBA::fetch($entries)) {
574 if (!posix_kill($entry["pid"], 0)) {
577 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
578 ['id' => $entry["id"]]
581 // Kill long running processes
582 // Check if the priority is in a valid range
583 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
584 $entry["priority"] = PRIORITY_MEDIUM;
587 // Define the maximum durations
588 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
589 $max_duration = $max_duration_defaults[$entry["priority"]];
591 $argv = json_decode($entry["parameter"], true);
592 $argv[0] = basename($argv[0]);
594 // How long is the process already running?
595 $duration = (time() - strtotime($entry["executed"])) / 60;
596 if ($duration > $max_duration) {
597 logger("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
598 posix_kill($entry["pid"], SIGTERM);
600 // We killed the stale process.
601 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
602 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
603 $new_priority = $entry["priority"];
604 if ($entry["priority"] == PRIORITY_HIGH) {
605 $new_priority = PRIORITY_MEDIUM;
606 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
607 $new_priority = PRIORITY_LOW;
608 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
609 $new_priority = PRIORITY_NEGLIGIBLE;
613 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
614 ['id' => $entry["id"]]
617 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);
624 * @brief Checks if the number of active workers exceeds the given limits
626 * @return bool Are there too much workers running?
628 public static function tooMuchWorkers()
630 $queues = Config::get("system", "worker_queues", 4);
632 $maxqueues = $queues;
634 $active = self::activeWorkers();
636 // Decrease the number of workers at higher load
637 $load = System::currentLoad();
639 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
641 /* Default exponent 3 causes queues to rapidly decrease as load increases.
642 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
643 * For some environments, this rapid decrease is not needed.
644 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
646 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
647 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
648 $queues = intval(ceil($slope * $maxqueues));
652 if (Config::get('system', 'worker_debug')) {
653 // Create a list of queue entries grouped by their priority
656 // Adding all processes with no workerqueue entry
658 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
659 (SELECT id FROM `workerqueue`
660 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
664 if ($process = DBA::fetch($processes)) {
665 $listitem[0] = "0:".$process["running"];
667 DBA::close($processes);
669 // Now adding all processes with workerqueue entries
670 $entries = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
671 while ($entry = DBA::fetch($entries)) {
672 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
673 if ($process = DBA::fetch($processes)) {
674 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
676 DBA::close($processes);
678 DBA::close($entries);
680 $intervals = [1, 10, 60];
681 $jobs_per_minute = [];
682 foreach ($intervals as $interval) {
683 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
684 if ($job = DBA::fetch($jobs)) {
685 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
689 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
692 $entries = self::totalEntries();
693 $deferred = self::deferredEntries();
695 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
696 $top_priority = self::highestPriority();
697 $high_running = self::processWithPriorityActive($top_priority);
699 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
700 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
701 $queues = $active + 1;
705 logger("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $entries . $processlist . " - maximum: " . $queues . "/" . $maxqueues, LOGGER_DEBUG);
707 // Are there fewer workers running as possible? Then fork a new one.
708 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
709 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
710 if (Config::get('system', 'worker_daemon_mode', false)) {
711 self::IPCSetJobState(true);
718 // if there are too much worker, we don't spawn a new one.
719 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
720 self::IPCSetJobState(false);
723 return $active > $queues;
727 * @brief Returns the number of active worker processes
729 * @return integer Number of active worker processes
731 private static function activeWorkers()
733 return DBA::count('process', ['command' => 'Worker.php']);
737 * @brief Check if we should pass some slow processes
739 * When the active processes of the highest priority are using more than 2/3
740 * of all processes, we let pass slower processes.
742 * @param string $highest_priority Returns the currently highest priority
743 * @return bool We let pass a slower process than $highest_priority
745 private static function passingSlow(&$highest_priority)
747 $highest_priority = 0;
752 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
755 // No active processes at all? Fine
756 if (!DBA::isResult($r)) {
760 while ($line = DBA::fetch($r)) {
761 $priorities[] = $line["priority"];
766 if (count($priorities) == 0) {
769 $highest_priority = min($priorities);
771 // The highest process is already the slowest one?
773 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
777 foreach ($priorities as $priority) {
778 if ($priority == $highest_priority) {
782 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
783 $passing_slow = (($high/count($priorities)) > (2/3));
786 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
788 return $passing_slow;
792 * @brief Find and claim the next worker process for us
794 * @param boolean $passing_slow Returns if we had passed low priority processes
795 * @return boolean Have we found something?
797 private static function findWorkerProcesses(&$passing_slow)
801 // Check if we should pass some low priority process
802 $highest_priority = 0;
804 $passing_slow = false;
806 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
807 // We decrease the limit with the number of entries left in the queue
808 $worker_queues = Config::get("system", "worker_queues", 4);
809 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
810 $lower_job_limit = $worker_queues * $queue_length * 2;
811 $jobs = self::totalEntries();
812 $deferred = self::deferredEntries();
816 $slope = $queue_length / pow($lower_job_limit, $exponent);
817 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
819 logger('Deferred: ' . $deferred . ' - Total: ' . $jobs . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, LOGGER_DEBUG);
821 if (self::passingSlow($highest_priority)) {
822 // Are there waiting processes with a higher priority than the currently highest?
823 $result = DBA::select(
826 ["`executed` <= ? AND `priority` < ? AND NOT `done` AND `next_try` < ?",
827 DBA::NULL_DATETIME, $highest_priority, DateTimeFormat::utcNow()],
828 ['limit' => $limit, 'order' => ['priority', 'created']]
831 while ($id = DBA::fetch($result)) {
836 $found = (count($ids) > 0);
839 // Give slower processes some processing time
840 $result = DBA::select(
843 ["`executed` <= ? AND `priority` > ? AND NOT `done` AND `next_try` < ?",
844 DBA::NULL_DATETIME, $highest_priority, DateTimeFormat::utcNow()],
845 ['limit' => $limit, 'order' => ['priority', 'created']]
848 while ($id = DBA::fetch($result)) {
853 $found = (count($ids) > 0);
854 $passing_slow = $found;
858 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
860 $result = DBA::select(
863 ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
864 DBA::NULL_DATETIME, DateTimeFormat::utcNow()],
865 ['limit' => $limit, 'order' => ['priority', 'created']]
868 while ($id = DBA::fetch($result)) {
873 $found = (count($ids) > 0);
877 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
878 array_unshift($ids, $condition);
879 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
886 * @brief Returns the next worker process
888 * @param boolean $passing_slow Returns if we had passed low priority processes
889 * @return string SQL statement
891 public static function workerProcess(&$passing_slow)
893 $stamp = (float)microtime(true);
895 // There can already be jobs for us in the queue.
896 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
897 if (DBA::isResult($r)) {
898 self::$db_duration += (microtime(true) - $stamp);
899 return DBA::toArray($r);
903 $stamp = (float)microtime(true);
904 if (!Lock::acquire('worker_process')) {
907 self::$lock_duration = (microtime(true) - $stamp);
909 $stamp = (float)microtime(true);
910 $found = self::findWorkerProcesses($passing_slow);
911 self::$db_duration += (microtime(true) - $stamp);
913 Lock::release('worker_process');
916 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
917 return DBA::toArray($r);
923 * @brief Removes a workerqueue entry from the current process
926 public static function unclaimProcess()
930 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
934 * @brief Call the front end worker
937 public static function callWorker()
939 if (!Config::get("system", "frontend_worker")) {
943 $url = System::baseUrl()."/worker";
944 Network::fetchUrl($url, false, $redirects, 1);
948 * @brief Call the front end worker if there aren't any active
951 public static function executeIfIdle()
953 if (!Config::get("system", "frontend_worker")) {
957 // Do we have "proc_open"? Then we can fork the worker
958 if (function_exists("proc_open")) {
959 // When was the last time that we called the worker?
960 // Less than one minute? Then we quit
961 if ((time() - Config::get("system", "worker_started")) < 60) {
965 Config::set("system", "worker_started", time());
967 // Do we have enough running workers? Then we quit here.
968 if (self::tooMuchWorkers()) {
969 // Cleaning dead processes
970 self::killStaleWorkers();
971 Process::deleteInactive();
978 logger('Call worker', LOGGER_DEBUG);
983 // We cannot execute background processes.
984 // We now run the processes from the frontend.
985 // This won't work with long running processes.
988 self::clearProcesses();
990 $workers = self::activeWorkers();
998 * @brief Removes long running worker processes
1001 public static function clearProcesses()
1003 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1005 /// @todo We should clean up the corresponding workerqueue entries as well
1006 $condition = ["`created` < ? AND `command` = 'worker.php'",
1007 DateTimeFormat::utc("now - ".$timeout." minutes")];
1008 DBA::delete('process', $condition);
1012 * @brief Runs the cron processes
1015 private static function runCron()
1017 logger('Add cron entries', LOGGER_DEBUG);
1019 // Check for spooled items
1020 self::add(PRIORITY_HIGH, "SpoolPost");
1022 // Run the cron job that calls all other jobs
1023 self::add(PRIORITY_MEDIUM, "Cron");
1025 // Cleaning dead processes
1026 self::killStaleWorkers();
1030 * @brief Spawns a new worker
1033 public static function spawnWorker($do_cron = false)
1035 $command = 'bin/worker.php';
1037 $args = ['no_cron' => !$do_cron];
1039 get_app()->proc_run($command, $args);
1041 // after spawning we have to remove the flag.
1042 if (Config::get('system', 'worker_daemon_mode', false)) {
1043 self::IPCSetJobState(false);
1048 * @brief Adds tasks to the worker queue
1050 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1052 * next args are passed as $cmd command line
1053 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1054 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1056 * @note $cmd and string args are surrounded with ""
1061 * @return boolean "false" if proc_run couldn't be executed
1063 public static function add($cmd)
1065 $args = func_get_args();
1067 if (!count($args)) {
1071 $arr = ['args' => $args, 'run_cmd' => true];
1073 Addon::callHooks("proc_run", $arr);
1074 if (!$arr['run_cmd'] || !count($args)) {
1078 $priority = PRIORITY_MEDIUM;
1079 $dont_fork = Config::get("system", "worker_dont_fork", false);
1080 $created = DateTimeFormat::utcNow();
1082 $run_parameter = array_shift($args);
1084 if (is_int($run_parameter)) {
1085 $priority = $run_parameter;
1086 } elseif (is_array($run_parameter)) {
1087 if (isset($run_parameter['priority'])) {
1088 $priority = $run_parameter['priority'];
1090 if (isset($run_parameter['created'])) {
1091 $created = $run_parameter['created'];
1093 if (isset($run_parameter['dont_fork'])) {
1094 $dont_fork = $run_parameter['dont_fork'];
1098 $parameters = json_encode($args);
1099 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1101 // Quit if there was a database error - a precaution for the update process to 3.5.3
1102 if (DBA::errorNo() != 0) {
1107 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1110 // Should we quit and wait for the worker to be called as a cronjob?
1115 // If there is a lock then we don't have to check for too much worker
1116 if (!Lock::acquire('worker', 0)) {
1120 // If there are already enough workers running, don't fork another one
1121 $quit = self::tooMuchWorkers();
1122 Lock::release('worker');
1128 // We tell the daemon that a new job entry exists
1129 if (Config::get('system', 'worker_daemon_mode', false)) {
1130 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1134 // Now call the worker to execute the jobs that we just added to the queue
1135 self::spawnWorker();
1141 * Defers the current worker entry
1143 public static function defer()
1145 if (empty(BaseObject::getApp()->queue)) {
1149 $queue = BaseObject::getApp()->queue;
1151 $retrial = $queue['retrial'];
1154 if ($retrial > 14) {
1155 logger('Id ' . $id . ' had been tried 14 times. We stop now.', LOGGER_DEBUG);
1159 // Calculate the delay until the next trial
1160 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1161 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1163 logger('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next, LOGGER_DEBUG);
1165 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0];
1166 DBA::update('workerqueue', $fields, ['id' => $id]);
1170 * Log active processes into the "process" table
1172 * @brief Log active processes into the "process" table
1174 public static function startProcess()
1176 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1178 $command = basename($trace[0]['file']);
1180 Process::deleteInactive();
1182 Process::insert($command);
1186 * Remove the active process from the "process" table
1188 * @brief Remove the active process from the "process" table
1191 public static function endProcess()
1193 return Process::deleteByPid();
1197 * Set the flag if some job is waiting
1199 * @brief Set the flag if some job is waiting
1200 * @param boolean $jobs Is there a waiting job?
1202 public static function IPCSetJobState($jobs)
1204 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1208 * Checks if some worker job waits to be executed
1210 * @brief Checks if some worker job waits to be executed
1213 public static function IPCJobsExists()
1215 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1217 // When we don't have a row, no job is running
1218 if (!DBA::isResult($row)) {
1222 return (bool)$row['jobs'];