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;
14 * @file src/Core/Worker.php
16 * @brief Contains the class for the worker background job processing
20 * @brief Worker methods
24 private static $up_start;
25 private static $db_duration;
26 private static $last_update;
27 private static $lock_duration;
30 * @brief Processes the tasks that are in the workerqueue table
32 * @param boolean $run_cron Should the cron processes be executed?
35 public static function processQueue($run_cron = true)
39 self::$up_start = microtime(true);
41 // At first check the maximum load. We shouldn't continue with a high load
42 if ($a->isMaxLoadReached()) {
43 Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
47 // We now start the process. This is done after the load check since this could increase the load.
50 // Kill stale processes every 5 minutes
51 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
52 if (time() > ($last_cleanup + 300)) {
53 Config::set('system', 'worker_last_cleaned', time());
54 self::killStaleWorkers();
57 // Count active workers and compare them with a maximum value that depends on the load
58 if (self::tooMuchWorkers()) {
59 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
63 // Do we have too few memory?
64 if ($a->isMinMemoryReached()) {
65 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
69 // Possibly there are too much database connections
70 if (self::maxConnectionsReached()) {
71 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
75 // Possibly there are too much database processes that block the system
76 if ($a->isMaxProcessesReached()) {
77 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
81 // Now we start additional cron processes if we should do so
88 // We fetch the next queue entry that is about to be executed
89 while ($r = self::workerProcess($passing_slow)) {
90 // When we are processing jobs with a lower priority, we don't refetch new jobs
91 // Otherwise fast jobs could wait behind slow ones and could be blocked.
92 $refetched = $passing_slow;
94 foreach ($r as $entry) {
95 // Assure that the priority is an integer value
96 $entry['priority'] = (int)$entry['priority'];
98 // The work will be done
99 if (!self::execute($entry)) {
100 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
104 // If possible we will fetch new jobs for this worker
105 if (!$refetched && Lock::acquire('worker_process', 0)) {
106 $stamp = (float)microtime(true);
107 $refetched = self::findWorkerProcesses($passing_slow);
108 self::$db_duration += (microtime(true) - $stamp);
109 Lock::release('worker_process');
113 // To avoid the quitting of multiple workers only one worker at a time will execute the check
114 if (Lock::acquire('worker', 0)) {
115 $stamp = (float)microtime(true);
116 // Count active workers and compare them with a maximum value that depends on the load
117 if (self::tooMuchWorkers()) {
118 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
119 Lock::release('worker');
124 if ($a->isMinMemoryReached()) {
125 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
126 Lock::release('worker');
129 Lock::release('worker');
130 self::$db_duration += (microtime(true) - $stamp);
133 // Quit the worker once every 5 minutes
134 if (time() > ($starttime + 300)) {
135 Logger::log('Process lifetime reached, quitting.', Logger::DEBUG);
140 // Cleaning up. Possibly not needed, but it doesn't harm anything.
141 if (Config::get('system', 'worker_daemon_mode', false)) {
142 self::IPCSetJobState(false);
144 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
148 * @brief Returns the number of deferred entries in the worker queue
150 * @return integer Number of deferred entries in the worker queue
152 private static function deferredEntries()
154 return DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` > ?",
155 DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
159 * @brief Returns the number of non executed entries in the worker queue
161 * @return integer Number of non executed entries in the worker queue
163 private static function totalEntries()
165 return DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
166 DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
170 * @brief Returns the highest priority in the worker queue that isn't executed
172 * @return integer Number of active worker processes
174 private static function highestPriority()
176 $condition = ["`executed` <= ? AND NOT `done` AND `next_try` < ?", DBA::NULL_DATETIME, DateTimeFormat::utcNow()];
177 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
178 if (DBA::isResult($workerqueue)) {
179 return $workerqueue["priority"];
186 * @brief Returns if a process with the given priority is running
188 * @param integer $priority The priority that should be checked
190 * @return integer Is there a process running with that priority?
192 private static function processWithPriorityActive($priority)
194 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done` AND `next_try` < ?",
195 $priority, DBA::NULL_DATETIME, DateTimeFormat::utcNow()];
196 return DBA::exists('workerqueue', $condition);
200 * @brief Execute a worker entry
202 * @param array $queue Workerqueue entry
204 * @return boolean "true" if further processing should be stopped
206 public static function execute($queue)
212 // Quit when in maintenance
213 if (Config::get('system', 'maintenance', false, true)) {
214 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
218 // Constantly check the number of parallel database processes
219 if ($a->isMaxProcessesReached()) {
220 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
224 // Constantly check the number of available database connections to let the frontend be accessible at any time
225 if (self::maxConnectionsReached()) {
226 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
230 $argv = json_decode($queue["parameter"], true);
232 // Check for existance and validity of the include file
235 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
236 // We constantly update the "executed" date every minute to avoid being killed too soon
237 if (!isset(self::$last_update)) {
238 self::$last_update = strtotime($queue["executed"]);
241 $age = (time() - self::$last_update) / 60;
242 self::$last_update = time();
245 $stamp = (float)microtime(true);
246 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
247 self::$db_duration += (microtime(true) - $stamp);
252 self::execFunction($queue, $include, $argv, true);
254 $stamp = (float)microtime(true);
256 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
257 if (DBA::update('workerqueue', ['done' => true], $condition)) {
258 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
260 self::$db_duration = (microtime(true) - $stamp);
265 // The script could be provided as full path or only with the function name
266 if ($include == basename($include)) {
267 $include = "include/".$include.".php";
270 if (!validate_include($include)) {
271 Logger::log("Include file ".$argv[0]." is not valid!");
272 DBA::delete('workerqueue', ['id' => $queue["id"]]);
276 require_once $include;
278 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
280 if (function_exists($funcname)) {
281 // We constantly update the "executed" date every minute to avoid being killed too soon
282 if (!isset(self::$last_update)) {
283 self::$last_update = strtotime($queue["executed"]);
286 $age = (time() - self::$last_update) / 60;
287 self::$last_update = time();
290 $stamp = (float)microtime(true);
291 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
292 self::$db_duration += (microtime(true) - $stamp);
295 self::execFunction($queue, $funcname, $argv, false);
297 $stamp = (float)microtime(true);
298 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
299 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
301 self::$db_duration = (microtime(true) - $stamp);
303 Logger::log("Function ".$funcname." does not exist");
304 DBA::delete('workerqueue', ['id' => $queue["id"]]);
311 * @brief Execute a function from the queue
313 * @param array $queue Workerqueue entry
314 * @param string $funcname name of the function
315 * @param array $argv Array of values to be passed to the function
316 * @param boolean $method_call boolean
319 private static function execFunction($queue, $funcname, $argv, $method_call)
325 $argc = count($argv);
327 $new_process_id = System::processID("wrk");
329 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
331 $stamp = (float)microtime(true);
333 // We use the callstack here to analyze the performance of executed worker entries.
334 // For this reason the variables have to be initialized.
335 if (Config::get("system", "profiler")) {
336 $a->performance["start"] = microtime(true);
337 $a->performance["database"] = 0;
338 $a->performance["database_write"] = 0;
339 $a->performance["cache"] = 0;
340 $a->performance["cache_write"] = 0;
341 $a->performance["network"] = 0;
342 $a->performance["file"] = 0;
343 $a->performance["rendering"] = 0;
344 $a->performance["parser"] = 0;
345 $a->performance["marktime"] = 0;
346 $a->performance["markstart"] = microtime(true);
350 // For better logging create a new process id for every worker call
351 // But preserve the old one for the worker
352 $old_process_id = $a->process_id;
353 $a->process_id = $new_process_id;
356 $up_duration = number_format(microtime(true) - self::$up_start, 3);
358 // Reset global data to avoid interferences
362 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
364 $funcname($argv, $argc);
367 $a->process_id = $old_process_id;
370 $duration = (microtime(true) - $stamp);
372 self::$up_start = microtime(true);
374 /* With these values we can analyze how effective the worker is.
375 * The database and rest time should be low since this is the unproductive time.
376 * The execution time is the productive time.
377 * By changing parameters like the maximum number of workers we can check the effectivness.
380 'DB: '.number_format(self::$db_duration, 2).
381 ' - Lock: '.number_format(self::$lock_duration, 2).
382 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
383 ' - Execution: '.number_format($duration, 2),
387 self::$lock_duration = 0;
389 if ($duration > 3600) {
390 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
391 } elseif ($duration > 600) {
392 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
393 } elseif ($duration > 300) {
394 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
395 } elseif ($duration > 120) {
396 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
399 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
401 // Write down the performance values into the log
402 if (Config::get("system", "profiler")) {
403 $duration = microtime(true)-$a->performance["start"];
406 if (Config::get("rendertime", "callstack")) {
407 if (isset($a->callstack["database"])) {
408 $o .= "\nDatabase Read:\n";
409 foreach ($a->callstack["database"] as $func => $time) {
410 $time = round($time, 3);
412 $o .= $func.": ".$time."\n";
416 if (isset($a->callstack["database_write"])) {
417 $o .= "\nDatabase Write:\n";
418 foreach ($a->callstack["database_write"] as $func => $time) {
419 $time = round($time, 3);
421 $o .= $func.": ".$time."\n";
425 if (isset($a->callstack["dache"])) {
426 $o .= "\nCache Read:\n";
427 foreach ($a->callstack["dache"] as $func => $time) {
428 $time = round($time, 3);
430 $o .= $func.": ".$time."\n";
434 if (isset($a->callstack["dache_write"])) {
435 $o .= "\nCache Write:\n";
436 foreach ($a->callstack["dache_write"] as $func => $time) {
437 $time = round($time, 3);
439 $o .= $func.": ".$time."\n";
443 if (isset($a->callstack["network"])) {
444 $o .= "\nNetwork:\n";
445 foreach ($a->callstack["network"] as $func => $time) {
446 $time = round($time, 3);
448 $o .= $func.": ".$time."\n";
455 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
456 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
457 number_format($a->performance["database"] - $a->performance["database_write"], 2),
458 number_format($a->performance["database_write"], 2),
459 number_format($a->performance["cache"], 2),
460 number_format($a->performance["cache_write"], 2),
461 number_format($a->performance["network"], 2),
462 number_format($a->performance["file"], 2),
463 number_format($duration - ($a->performance["database"]
464 + $a->performance["cache"] + $a->performance["cache_write"]
465 + $a->performance["network"] + $a->performance["file"]), 2),
466 number_format($duration, 2)
472 $cooldown = Config::get("system", "worker_cooldown", 0);
475 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
481 * @brief Checks if the number of database connections has reached a critical limit.
483 * @return bool Are more than 3/4 of the maximum connections used?
485 private static function maxConnectionsReached()
487 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
488 $max = Config::get("system", "max_connections");
490 // Fetch the percentage level where the worker will get active
491 $maxlevel = Config::get("system", "max_connections_level", 75);
494 // the maximum number of possible user connections can be a system variable
495 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
496 if (DBA::isResult($r)) {
499 // Or it can be granted. This overrides the system variable
500 $r = DBA::p('SHOW GRANTS');
501 while ($grants = DBA::fetch($r)) {
502 $grant = array_pop($grants);
503 if (stristr($grant, "GRANT USAGE ON")) {
504 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
512 // If $max is set we will use the processlist to determine the current number of connections
513 // The processlist only shows entries of the current user
515 $r = DBA::p('SHOW PROCESSLIST');
516 $used = DBA::numRows($r);
519 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
521 $level = ($used / $max) * 100;
523 if ($level >= $maxlevel) {
524 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
529 // We will now check for the system values.
530 // This limit could be reached although the user limits are fine.
531 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
532 if (!DBA::isResult($r)) {
535 $max = intval($r["Value"]);
539 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
540 if (!DBA::isResult($r)) {
543 $used = intval($r["Value"]);
547 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
549 $level = $used / $max * 100;
551 if ($level < $maxlevel) {
554 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
559 * @brief fix the queue entry if the worker process died
562 private static function killStaleWorkers()
564 $entries = DBA::select(
566 ['id', 'pid', 'executed', 'priority', 'parameter'],
567 ['`executed` > ? AND NOT `done` AND `pid` != 0', DBA::NULL_DATETIME],
568 ['order' => ['priority', 'created']]
571 while ($entry = DBA::fetch($entries)) {
572 if (!posix_kill($entry["pid"], 0)) {
575 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
576 ['id' => $entry["id"]]
579 // Kill long running processes
580 // Check if the priority is in a valid range
581 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
582 $entry["priority"] = PRIORITY_MEDIUM;
585 // Define the maximum durations
586 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
587 $max_duration = $max_duration_defaults[$entry["priority"]];
589 $argv = json_decode($entry["parameter"], true);
590 $argv[0] = basename($argv[0]);
592 // How long is the process already running?
593 $duration = (time() - strtotime($entry["executed"])) / 60;
594 if ($duration > $max_duration) {
595 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
596 posix_kill($entry["pid"], SIGTERM);
598 // We killed the stale process.
599 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
600 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
601 $new_priority = $entry["priority"];
602 if ($entry["priority"] == PRIORITY_HIGH) {
603 $new_priority = PRIORITY_MEDIUM;
604 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
605 $new_priority = PRIORITY_LOW;
606 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
607 $new_priority = PRIORITY_NEGLIGIBLE;
611 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
612 ['id' => $entry["id"]]
615 Logger::log("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);
622 * @brief Checks if the number of active workers exceeds the given limits
624 * @return bool Are there too much workers running?
626 public static function tooMuchWorkers()
628 $queues = Config::get("system", "worker_queues", 4);
630 $maxqueues = $queues;
632 $active = self::activeWorkers();
634 // Decrease the number of workers at higher load
635 $load = System::currentLoad();
637 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
639 /* Default exponent 3 causes queues to rapidly decrease as load increases.
640 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
641 * For some environments, this rapid decrease is not needed.
642 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
644 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
645 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
646 $queues = intval(ceil($slope * $maxqueues));
650 if (Config::get('system', 'worker_debug')) {
651 // Create a list of queue entries grouped by their priority
654 // Adding all processes with no workerqueue entry
656 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
657 (SELECT id FROM `workerqueue`
658 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
662 if ($process = DBA::fetch($processes)) {
663 $listitem[0] = "0:".$process["running"];
665 DBA::close($processes);
667 // Now adding all processes with workerqueue entries
668 $entries = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
669 while ($entry = DBA::fetch($entries)) {
670 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `next_try` < ? AND `priority` = ?",
671 DateTimeFormat::utcNow(), $entry["priority"]);
672 if ($process = DBA::fetch($processes)) {
673 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
675 DBA::close($processes);
677 DBA::close($entries);
679 $intervals = [1, 10, 60];
680 $jobs_per_minute = [];
681 foreach ($intervals as $interval) {
682 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
683 if ($job = DBA::fetch($jobs)) {
684 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
688 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
691 $entries = self::totalEntries();
692 $deferred = self::deferredEntries();
694 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
695 $top_priority = self::highestPriority();
696 $high_running = self::processWithPriorityActive($top_priority);
698 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
699 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
700 $queues = $active + 1;
704 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $entries . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
706 // Are there fewer workers running as possible? Then fork a new one.
707 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
708 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
709 if (Config::get('system', 'worker_daemon_mode', false)) {
710 self::IPCSetJobState(true);
717 // if there are too much worker, we don't spawn a new one.
718 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
719 self::IPCSetJobState(false);
722 return $active > $queues;
726 * @brief Returns the number of active worker processes
728 * @return integer Number of active worker processes
730 private static function activeWorkers()
732 return DBA::count('process', ['command' => 'Worker.php']);
736 * @brief Check if we should pass some slow processes
738 * When the active processes of the highest priority are using more than 2/3
739 * of all processes, we let pass slower processes.
741 * @param string $highest_priority Returns the currently highest priority
742 * @return bool We let pass a slower process than $highest_priority
744 private static function passingSlow(&$highest_priority)
746 $highest_priority = 0;
751 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
754 // No active processes at all? Fine
755 if (!DBA::isResult($r)) {
759 while ($line = DBA::fetch($r)) {
760 $priorities[] = $line["priority"];
765 if (count($priorities) == 0) {
768 $highest_priority = min($priorities);
770 // The highest process is already the slowest one?
772 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
776 foreach ($priorities as $priority) {
777 if ($priority == $highest_priority) {
781 Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
782 $passing_slow = (($high/count($priorities)) > (2/3));
785 Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
787 return $passing_slow;
791 * @brief Find and claim the next worker process for us
793 * @param boolean $passing_slow Returns if we had passed low priority processes
794 * @return boolean Have we found something?
796 private static function findWorkerProcesses(&$passing_slow)
800 // Check if we should pass some low priority process
801 $highest_priority = 0;
803 $passing_slow = false;
805 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
806 // We decrease the limit with the number of entries left in the queue
807 $worker_queues = Config::get("system", "worker_queues", 4);
808 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
809 $lower_job_limit = $worker_queues * $queue_length * 2;
810 $jobs = self::totalEntries();
811 $deferred = self::deferredEntries();
815 $slope = $queue_length / pow($lower_job_limit, $exponent);
816 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
818 Logger::log('Deferred: ' . $deferred . ' - Total: ' . $jobs . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
820 if (self::passingSlow($highest_priority)) {
821 // Are there waiting processes with a higher priority than the currently highest?
822 $result = DBA::select(
825 ["`executed` <= ? AND `priority` < ? AND NOT `done` AND `next_try` < ?",
826 DBA::NULL_DATETIME, $highest_priority, DateTimeFormat::utcNow()],
827 ['limit' => $limit, 'order' => ['priority', 'created']]
830 while ($id = DBA::fetch($result)) {
835 $found = (count($ids) > 0);
838 // Give slower processes some processing time
839 $result = DBA::select(
842 ["`executed` <= ? AND `priority` > ? AND NOT `done` AND `next_try` < ?",
843 DBA::NULL_DATETIME, $highest_priority, DateTimeFormat::utcNow()],
844 ['limit' => $limit, 'order' => ['priority', 'created']]
847 while ($id = DBA::fetch($result)) {
852 $found = (count($ids) > 0);
853 $passing_slow = $found;
857 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
859 $result = DBA::select(
862 ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
863 DBA::NULL_DATETIME, DateTimeFormat::utcNow()],
864 ['limit' => $limit, 'order' => ['priority', 'created']]
867 while ($id = DBA::fetch($result)) {
872 $found = (count($ids) > 0);
876 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
877 array_unshift($ids, $condition);
878 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
885 * @brief Returns the next worker process
887 * @param boolean $passing_slow Returns if we had passed low priority processes
888 * @return string SQL statement
890 public static function workerProcess(&$passing_slow)
892 $stamp = (float)microtime(true);
894 // There can already be jobs for us in the queue.
895 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
896 if (DBA::isResult($r)) {
897 self::$db_duration += (microtime(true) - $stamp);
898 return DBA::toArray($r);
902 $stamp = (float)microtime(true);
903 if (!Lock::acquire('worker_process')) {
906 self::$lock_duration = (microtime(true) - $stamp);
908 $stamp = (float)microtime(true);
909 $found = self::findWorkerProcesses($passing_slow);
910 self::$db_duration += (microtime(true) - $stamp);
912 Lock::release('worker_process');
915 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
916 return DBA::toArray($r);
922 * @brief Removes a workerqueue entry from the current process
925 public static function unclaimProcess()
929 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
933 * @brief Call the front end worker
936 public static function callWorker()
938 if (!Config::get("system", "frontend_worker")) {
942 $url = System::baseUrl()."/worker";
943 Network::fetchUrl($url, false, $redirects, 1);
947 * @brief Call the front end worker if there aren't any active
950 public static function executeIfIdle()
952 if (!Config::get("system", "frontend_worker")) {
956 // Do we have "proc_open"? Then we can fork the worker
957 if (function_exists("proc_open")) {
958 // When was the last time that we called the worker?
959 // Less than one minute? Then we quit
960 if ((time() - Config::get("system", "worker_started")) < 60) {
964 Config::set("system", "worker_started", time());
966 // Do we have enough running workers? Then we quit here.
967 if (self::tooMuchWorkers()) {
968 // Cleaning dead processes
969 self::killStaleWorkers();
970 Process::deleteInactive();
977 Logger::log('Call worker', Logger::DEBUG);
982 // We cannot execute background processes.
983 // We now run the processes from the frontend.
984 // This won't work with long running processes.
987 self::clearProcesses();
989 $workers = self::activeWorkers();
997 * @brief Removes long running worker processes
1000 public static function clearProcesses()
1002 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1004 /// @todo We should clean up the corresponding workerqueue entries as well
1005 $condition = ["`created` < ? AND `command` = 'worker.php'",
1006 DateTimeFormat::utc("now - ".$timeout." minutes")];
1007 DBA::delete('process', $condition);
1011 * @brief Runs the cron processes
1014 private static function runCron()
1016 Logger::log('Add cron entries', Logger::DEBUG);
1018 // Check for spooled items
1019 self::add(PRIORITY_HIGH, "SpoolPost");
1021 // Run the cron job that calls all other jobs
1022 self::add(PRIORITY_MEDIUM, "Cron");
1024 // Cleaning dead processes
1025 self::killStaleWorkers();
1029 * @brief Spawns a new worker
1032 public static function spawnWorker($do_cron = false)
1034 $command = 'bin/worker.php';
1036 $args = ['no_cron' => !$do_cron];
1038 get_app()->proc_run($command, $args);
1040 // after spawning we have to remove the flag.
1041 if (Config::get('system', 'worker_daemon_mode', false)) {
1042 self::IPCSetJobState(false);
1047 * @brief Adds tasks to the worker queue
1049 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1051 * next args are passed as $cmd command line
1052 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1053 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1055 * @note $cmd and string args are surrounded with ""
1060 * @return boolean "false" if proc_run couldn't be executed
1062 public static function add($cmd)
1064 $args = func_get_args();
1066 if (!count($args)) {
1070 $arr = ['args' => $args, 'run_cmd' => true];
1072 Hook::callAll("proc_run", $arr);
1073 if (!$arr['run_cmd'] || !count($args)) {
1077 $priority = PRIORITY_MEDIUM;
1078 $dont_fork = Config::get("system", "worker_dont_fork", false);
1079 $created = DateTimeFormat::utcNow();
1081 $run_parameter = array_shift($args);
1083 if (is_int($run_parameter)) {
1084 $priority = $run_parameter;
1085 } elseif (is_array($run_parameter)) {
1086 if (isset($run_parameter['priority'])) {
1087 $priority = $run_parameter['priority'];
1089 if (isset($run_parameter['created'])) {
1090 $created = $run_parameter['created'];
1092 if (isset($run_parameter['dont_fork'])) {
1093 $dont_fork = $run_parameter['dont_fork'];
1097 $parameters = json_encode($args);
1098 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1100 // Quit if there was a database error - a precaution for the update process to 3.5.3
1101 if (DBA::errorNo() != 0) {
1106 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1109 // Should we quit and wait for the worker to be called as a cronjob?
1114 // If there is a lock then we don't have to check for too much worker
1115 if (!Lock::acquire('worker', 0)) {
1119 // If there are already enough workers running, don't fork another one
1120 $quit = self::tooMuchWorkers();
1121 Lock::release('worker');
1127 // We tell the daemon that a new job entry exists
1128 if (Config::get('system', 'worker_daemon_mode', false)) {
1129 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1133 // Now call the worker to execute the jobs that we just added to the queue
1134 self::spawnWorker();
1140 * Defers the current worker entry
1142 public static function defer()
1144 if (empty(BaseObject::getApp()->queue)) {
1148 $queue = BaseObject::getApp()->queue;
1150 $retrial = $queue['retrial'];
1153 if ($retrial > 14) {
1154 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1158 // Calculate the delay until the next trial
1159 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1160 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1162 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next, Logger::DEBUG);
1164 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0];
1165 DBA::update('workerqueue', $fields, ['id' => $id]);
1169 * Log active processes into the "process" table
1171 * @brief Log active processes into the "process" table
1173 public static function startProcess()
1175 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1177 $command = basename($trace[0]['file']);
1179 Process::deleteInactive();
1181 Process::insert($command);
1185 * Remove the active process from the "process" table
1187 * @brief Remove the active process from the "process" table
1190 public static function endProcess()
1192 return Process::deleteByPid();
1196 * Set the flag if some job is waiting
1198 * @brief Set the flag if some job is waiting
1199 * @param boolean $jobs Is there a waiting job?
1201 public static function IPCSetJobState($jobs)
1203 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1207 * Checks if some worker job waits to be executed
1209 * @brief Checks if some worker job waits to be executed
1212 public static function IPCJobsExists()
1214 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1216 // When we don't have a row, no job is running
1217 if (!DBA::isResult($row)) {
1221 return (bool)$row['jobs'];