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?
34 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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::log('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::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
64 // Do we have too few memory?
65 if ($a->isMinMemoryReached()) {
66 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
70 // Possibly there are too much database connections
71 if (self::maxConnectionsReached()) {
72 Logger::log('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::log('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::log('Process execution failed, quitting.', Logger::DEBUG);
105 // If possible we will fetch new jobs for this worker
107 $entries = self::totalEntries();
108 $deferred = self::deferredEntries();
109 if (Lock::acquire('worker_process', 0)) {
110 $stamp = (float)microtime(true);
111 $refetched = self::findWorkerProcesses($passing_slow, $entries, $deferred);
112 self::$db_duration += (microtime(true) - $stamp);
113 Lock::release('worker_process');
118 // To avoid the quitting of multiple workers only one worker at a time will execute the check
119 if (Lock::acquire('worker', 0)) {
120 $stamp = (float)microtime(true);
121 // Count active workers and compare them with a maximum value that depends on the load
122 if (self::tooMuchWorkers()) {
123 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
124 Lock::release('worker');
129 if ($a->isMinMemoryReached()) {
130 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
131 Lock::release('worker');
134 Lock::release('worker');
135 self::$db_duration += (microtime(true) - $stamp);
138 // Quit the worker once every 5 minutes
139 if (time() > ($starttime + 300)) {
140 Logger::log('Process lifetime reached, quitting.', Logger::DEBUG);
145 // Cleaning up. Possibly not needed, but it doesn't harm anything.
146 if (Config::get('system', 'worker_daemon_mode', false)) {
147 self::IPCSetJobState(false);
149 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
153 * @brief Returns the number of deferred entries in the worker queue
155 * @return integer Number of deferred entries in the worker queue
158 private static function deferredEntries()
160 return DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` > ?", DateTimeFormat::utcNow()]);
164 * @brief Returns the number of non executed entries in the worker queue
166 * @return integer Number of non executed entries in the worker queue
169 private static function totalEntries()
171 return DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
175 * @brief Returns the highest priority in the worker queue that isn't executed
177 * @return integer Number of active worker processes
180 private static function highestPriority()
182 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
183 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
184 if (DBA::isResult($workerqueue)) {
185 return $workerqueue["priority"];
192 * @brief Returns if a process with the given priority is running
194 * @param integer $priority The priority that should be checked
196 * @return integer Is there a process running with that priority?
199 private static function processWithPriorityActive($priority)
201 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
202 return DBA::exists('workerqueue', $condition);
206 * @brief Execute a worker entry
208 * @param array $queue Workerqueue entry
210 * @return boolean "true" if further processing should be stopped
211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
213 public static function execute($queue)
219 // Quit when in maintenance
220 if (Config::get('system', 'maintenance', false, true)) {
221 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
225 // Constantly check the number of parallel database processes
226 if ($a->isMaxProcessesReached()) {
227 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
231 // Constantly check the number of available database connections to let the frontend be accessible at any time
232 if (self::maxConnectionsReached()) {
233 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
237 $argv = json_decode($queue["parameter"], true);
239 // Check for existance and validity of the include file
242 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
243 // We constantly update the "executed" date every minute to avoid being killed too soon
244 if (!isset(self::$last_update)) {
245 self::$last_update = strtotime($queue["executed"]);
248 $age = (time() - self::$last_update) / 60;
249 self::$last_update = time();
252 $stamp = (float)microtime(true);
253 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
254 self::$db_duration += (microtime(true) - $stamp);
259 self::execFunction($queue, $include, $argv, true);
261 $stamp = (float)microtime(true);
263 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
264 if (DBA::update('workerqueue', ['done' => true], $condition)) {
265 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
267 self::$db_duration = (microtime(true) - $stamp);
272 // The script could be provided as full path or only with the function name
273 if ($include == basename($include)) {
274 $include = "include/".$include.".php";
277 if (!validate_include($include)) {
278 Logger::log("Include file ".$argv[0]." is not valid!");
279 DBA::delete('workerqueue', ['id' => $queue["id"]]);
283 require_once $include;
285 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
287 if (function_exists($funcname)) {
288 // We constantly update the "executed" date every minute to avoid being killed too soon
289 if (!isset(self::$last_update)) {
290 self::$last_update = strtotime($queue["executed"]);
293 $age = (time() - self::$last_update) / 60;
294 self::$last_update = time();
297 $stamp = (float)microtime(true);
298 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
299 self::$db_duration += (microtime(true) - $stamp);
302 self::execFunction($queue, $funcname, $argv, false);
304 $stamp = (float)microtime(true);
305 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
306 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
308 self::$db_duration = (microtime(true) - $stamp);
310 Logger::log("Function ".$funcname." does not exist");
311 DBA::delete('workerqueue', ['id' => $queue["id"]]);
318 * @brief Execute a function from the queue
320 * @param array $queue Workerqueue entry
321 * @param string $funcname name of the function
322 * @param array $argv Array of values to be passed to the function
323 * @param boolean $method_call boolean
325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
327 private static function execFunction($queue, $funcname, $argv, $method_call)
333 $argc = count($argv);
335 $new_process_id = System::processID("wrk");
337 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
339 $stamp = (float)microtime(true);
341 // We use the callstack here to analyze the performance of executed worker entries.
342 // For this reason the variables have to be initialized.
343 if (Config::get("system", "profiler")) {
344 $a->performance["start"] = microtime(true);
345 $a->performance["database"] = 0;
346 $a->performance["database_write"] = 0;
347 $a->performance["cache"] = 0;
348 $a->performance["cache_write"] = 0;
349 $a->performance["network"] = 0;
350 $a->performance["file"] = 0;
351 $a->performance["rendering"] = 0;
352 $a->performance["parser"] = 0;
353 $a->performance["marktime"] = 0;
354 $a->performance["markstart"] = microtime(true);
358 // For better logging create a new process id for every worker call
359 // But preserve the old one for the worker
360 $old_process_id = $a->process_id;
361 $a->process_id = $new_process_id;
364 $up_duration = number_format(microtime(true) - self::$up_start, 3);
366 // Reset global data to avoid interferences
370 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
372 $funcname($argv, $argc);
375 $a->process_id = $old_process_id;
378 $duration = (microtime(true) - $stamp);
380 self::$up_start = microtime(true);
382 /* With these values we can analyze how effective the worker is.
383 * The database and rest time should be low since this is the unproductive time.
384 * The execution time is the productive time.
385 * By changing parameters like the maximum number of workers we can check the effectivness.
388 'DB: '.number_format(self::$db_duration, 2).
389 ' - Lock: '.number_format(self::$lock_duration, 2).
390 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
391 ' - Execution: '.number_format($duration, 2),
395 self::$lock_duration = 0;
397 if ($duration > 3600) {
398 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
399 } elseif ($duration > 600) {
400 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
401 } elseif ($duration > 300) {
402 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
403 } elseif ($duration > 120) {
404 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
407 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
409 // Write down the performance values into the log
410 if (Config::get("system", "profiler")) {
411 $duration = microtime(true)-$a->performance["start"];
414 if (Config::get("rendertime", "callstack")) {
415 if (isset($a->callstack["database"])) {
416 $o .= "\nDatabase Read:\n";
417 foreach ($a->callstack["database"] as $func => $time) {
418 $time = round($time, 3);
420 $o .= $func.": ".$time."\n";
424 if (isset($a->callstack["database_write"])) {
425 $o .= "\nDatabase Write:\n";
426 foreach ($a->callstack["database_write"] as $func => $time) {
427 $time = round($time, 3);
429 $o .= $func.": ".$time."\n";
433 if (isset($a->callstack["dache"])) {
434 $o .= "\nCache Read:\n";
435 foreach ($a->callstack["dache"] as $func => $time) {
436 $time = round($time, 3);
438 $o .= $func.": ".$time."\n";
442 if (isset($a->callstack["dache_write"])) {
443 $o .= "\nCache Write:\n";
444 foreach ($a->callstack["dache_write"] as $func => $time) {
445 $time = round($time, 3);
447 $o .= $func.": ".$time."\n";
451 if (isset($a->callstack["network"])) {
452 $o .= "\nNetwork:\n";
453 foreach ($a->callstack["network"] as $func => $time) {
454 $time = round($time, 3);
456 $o .= $func.": ".$time."\n";
463 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
464 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
465 number_format($a->performance["database"] - $a->performance["database_write"], 2),
466 number_format($a->performance["database_write"], 2),
467 number_format($a->performance["cache"], 2),
468 number_format($a->performance["cache_write"], 2),
469 number_format($a->performance["network"], 2),
470 number_format($a->performance["file"], 2),
471 number_format($duration - ($a->performance["database"]
472 + $a->performance["cache"] + $a->performance["cache_write"]
473 + $a->performance["network"] + $a->performance["file"]), 2),
474 number_format($duration, 2)
480 $cooldown = Config::get("system", "worker_cooldown", 0);
483 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
489 * @brief Checks if the number of database connections has reached a critical limit.
491 * @return bool Are more than 3/4 of the maximum connections used?
492 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
494 private static function maxConnectionsReached()
496 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
497 $max = Config::get("system", "max_connections");
499 // Fetch the percentage level where the worker will get active
500 $maxlevel = Config::get("system", "max_connections_level", 75);
503 // the maximum number of possible user connections can be a system variable
504 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
505 if (DBA::isResult($r)) {
508 // Or it can be granted. This overrides the system variable
509 $r = DBA::p('SHOW GRANTS');
510 while ($grants = DBA::fetch($r)) {
511 $grant = array_pop($grants);
512 if (stristr($grant, "GRANT USAGE ON")) {
513 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
521 // If $max is set we will use the processlist to determine the current number of connections
522 // The processlist only shows entries of the current user
524 $r = DBA::p('SHOW PROCESSLIST');
525 $used = DBA::numRows($r);
528 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
530 $level = ($used / $max) * 100;
532 if ($level >= $maxlevel) {
533 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
538 // We will now check for the system values.
539 // This limit could be reached although the user limits are fine.
540 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
541 if (!DBA::isResult($r)) {
544 $max = intval($r["Value"]);
548 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
549 if (!DBA::isResult($r)) {
552 $used = intval($r["Value"]);
556 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
558 $level = $used / $max * 100;
560 if ($level < $maxlevel) {
563 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
568 * @brief fix the queue entry if the worker process died
572 private static function killStaleWorkers()
574 $entries = DBA::select(
576 ['id', 'pid', 'executed', 'priority', 'parameter'],
577 ['NOT `done` AND `pid` != 0'],
578 ['order' => ['priority', 'created']]
581 while ($entry = DBA::fetch($entries)) {
582 if (!posix_kill($entry["pid"], 0)) {
585 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
586 ['id' => $entry["id"]]
589 // Kill long running processes
590 // Check if the priority is in a valid range
591 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
592 $entry["priority"] = PRIORITY_MEDIUM;
595 // Define the maximum durations
596 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
597 $max_duration = $max_duration_defaults[$entry["priority"]];
599 $argv = json_decode($entry["parameter"], true);
600 $argv[0] = basename($argv[0]);
602 // How long is the process already running?
603 $duration = (time() - strtotime($entry["executed"])) / 60;
604 if ($duration > $max_duration) {
605 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
606 posix_kill($entry["pid"], SIGTERM);
608 // We killed the stale process.
609 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
610 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
611 $new_priority = $entry["priority"];
612 if ($entry["priority"] == PRIORITY_HIGH) {
613 $new_priority = PRIORITY_MEDIUM;
614 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
615 $new_priority = PRIORITY_LOW;
616 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
617 $new_priority = PRIORITY_NEGLIGIBLE;
621 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
622 ['id' => $entry["id"]]
625 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);
632 * @brief Checks if the number of active workers exceeds the given limits
634 * @return bool Are there too much workers running?
635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 public static function tooMuchWorkers()
639 $queues = Config::get("system", "worker_queues", 4);
641 $maxqueues = $queues;
643 $active = self::activeWorkers();
645 // Decrease the number of workers at higher load
646 $load = System::currentLoad();
648 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
650 /* Default exponent 3 causes queues to rapidly decrease as load increases.
651 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
652 * For some environments, this rapid decrease is not needed.
653 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
655 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
656 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
657 $queues = intval(ceil($slope * $maxqueues));
661 if (Config::get('system', 'worker_jpm')) {
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 ? MINUTE", $interval);
666 if ($job = DBA::fetch($jobs)) {
667 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
671 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
674 if (Config::get('system', 'worker_debug')) {
675 // Create a list of queue entries grouped by their priority
676 $listitem = [0 => ''];
678 $idle_workers = $active;
680 // Now adding all processes with workerqueue entries
681 $entries = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
682 while ($entry = DBA::fetch($entries)) {
683 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
684 if ($process = DBA::fetch($processes)) {
685 $idle_workers -= $process["running"];
686 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
688 DBA::close($processes);
690 DBA::close($entries);
692 $listitem[0] = "0:" . max(0, $idle_workers);
694 $processlist .= ' ('.implode(', ', $listitem).')';
697 $deferred = self::deferredEntries();
698 $entries = max(self::totalEntries() - $deferred, 0);
700 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
701 $top_priority = self::highestPriority();
702 $high_running = self::processWithPriorityActive($top_priority);
704 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
705 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
706 $queues = $active + 1;
710 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $entries . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
712 // Are there fewer workers running as possible? Then fork a new one.
713 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
714 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
715 if (Config::get('system', 'worker_daemon_mode', false)) {
716 self::IPCSetJobState(true);
723 // if there are too much worker, we don't spawn a new one.
724 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
725 self::IPCSetJobState(false);
728 return $active > $queues;
732 * @brief Returns the number of active worker processes
734 * @return integer Number of active worker processes
737 private static function activeWorkers()
739 return DBA::count('process', ['command' => 'Worker.php']);
743 * @brief Check if we should pass some slow processes
745 * When the active processes of the highest priority are using more than 2/3
746 * of all processes, we let pass slower processes.
748 * @param string $highest_priority Returns the currently highest priority
749 * @return bool We let pass a slower process than $highest_priority
752 private static function passingSlow(&$highest_priority)
754 $highest_priority = 0;
759 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
762 // No active processes at all? Fine
763 if (!DBA::isResult($r)) {
767 while ($line = DBA::fetch($r)) {
768 $priorities[] = $line["priority"];
773 if (count($priorities) == 0) {
776 $highest_priority = min($priorities);
778 // The highest process is already the slowest one?
780 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
784 foreach ($priorities as $priority) {
785 if ($priority == $highest_priority) {
789 Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
790 $passing_slow = (($high/count($priorities)) > (2/3));
793 Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
795 return $passing_slow;
799 * @brief Find and claim the next worker process for us
801 * @param boolean $passing_slow Returns if we had passed low priority processes
802 * @param integer $entries Total number of queue entries
803 * @param integer $deferred Number of deferred queue entries
804 * @return boolean Have we found something?
805 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
807 private static function findWorkerProcesses(&$passing_slow, $entries, $deferred)
811 // Check if we should pass some low priority process
812 $highest_priority = 0;
814 $passing_slow = false;
816 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
817 // We decrease the limit with the number of entries left in the queue
818 $worker_queues = Config::get("system", "worker_queues", 4);
819 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
820 $lower_job_limit = $worker_queues * $queue_length * 2;
821 $entries = max($entries - $deferred, 0);
825 $slope = $queue_length / pow($lower_job_limit, $exponent);
826 $limit = min($queue_length, ceil($slope * pow($entries, $exponent)));
828 Logger::log('Deferred: ' . $deferred . ' - Total: ' . $entries . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
830 if (self::passingSlow($highest_priority)) {
831 // Are there waiting processes with a higher priority than the currently highest?
832 $result = DBA::select(
835 ["`pid` = 0 AND `priority` < ? AND NOT `done` AND `next_try` < ?",
836 $highest_priority, DateTimeFormat::utcNow()],
837 ['limit' => $limit, 'order' => ['priority', 'created']]
840 while ($id = DBA::fetch($result)) {
845 $found = (count($ids) > 0);
848 // Give slower processes some processing time
849 $result = DBA::select(
852 ["`pid` = 0 AND `priority` > ? AND NOT `done` AND `next_try` < ?",
853 $highest_priority, DateTimeFormat::utcNow()],
854 ['limit' => $limit, 'order' => ['priority', 'created']]
857 while ($id = DBA::fetch($result)) {
862 $found = (count($ids) > 0);
863 $passing_slow = $found;
867 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
869 $result = DBA::select(
872 ["`pid` = 0 AND NOT `done` AND `next_try` < ?",
873 DateTimeFormat::utcNow()],
874 ['limit' => $limit, 'order' => ['priority', 'created']]
877 while ($id = DBA::fetch($result)) {
882 $found = (count($ids) > 0);
886 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
887 array_unshift($ids, $condition);
888 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
895 * @brief Returns the next worker process
897 * @param boolean $passing_slow Returns if we had passed low priority processes
898 * @return string SQL statement
899 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
901 public static function workerProcess(&$passing_slow)
903 $stamp = (float)microtime(true);
905 // There can already be jobs for us in the queue.
906 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
907 if (DBA::isResult($r)) {
908 self::$db_duration += (microtime(true) - $stamp);
909 return DBA::toArray($r);
913 $stamp = (float)microtime(true);
915 // Counting the rows outside the lock reduces the lock time
916 $entries = self::totalEntries();
917 $deferred = self::deferredEntries();
919 if (!Lock::acquire('worker_process')) {
922 self::$lock_duration = (microtime(true) - $stamp);
924 $stamp = (float)microtime(true);
925 $found = self::findWorkerProcesses($passing_slow, $entries, $deferred);
926 self::$db_duration += (microtime(true) - $stamp);
928 Lock::release('worker_process');
931 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
932 return DBA::toArray($r);
938 * @brief Removes a workerqueue entry from the current process
942 public static function unclaimProcess()
946 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
950 * @brief Call the front end worker
952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954 public static function callWorker()
956 if (!Config::get("system", "frontend_worker")) {
960 $url = System::baseUrl()."/worker";
961 Network::fetchUrl($url, false, $redirects, 1);
965 * @brief Call the front end worker if there aren't any active
967 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
969 public static function executeIfIdle()
971 if (!Config::get("system", "frontend_worker")) {
975 // Do we have "proc_open"? Then we can fork the worker
976 if (function_exists("proc_open")) {
977 // When was the last time that we called the worker?
978 // Less than one minute? Then we quit
979 if ((time() - Config::get("system", "worker_started")) < 60) {
983 Config::set("system", "worker_started", time());
985 // Do we have enough running workers? Then we quit here.
986 if (self::tooMuchWorkers()) {
987 // Cleaning dead processes
988 self::killStaleWorkers();
989 Process::deleteInactive();
996 Logger::log('Call worker', Logger::DEBUG);
1001 // We cannot execute background processes.
1002 // We now run the processes from the frontend.
1003 // This won't work with long running processes.
1006 self::clearProcesses();
1008 $workers = self::activeWorkers();
1010 if ($workers == 0) {
1016 * @brief Removes long running worker processes
1018 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1020 public static function clearProcesses()
1022 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1024 /// @todo We should clean up the corresponding workerqueue entries as well
1025 $condition = ["`created` < ? AND `command` = 'worker.php'",
1026 DateTimeFormat::utc("now - ".$timeout." minutes")];
1027 DBA::delete('process', $condition);
1031 * @brief Runs the cron processes
1033 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1035 private static function runCron()
1037 Logger::log('Add cron entries', Logger::DEBUG);
1039 // Check for spooled items
1040 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1042 // Run the cron job that calls all other jobs
1043 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1045 // Cleaning dead processes
1046 self::killStaleWorkers();
1050 * @brief Spawns a new worker
1051 * @param bool $do_cron
1053 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1055 public static function spawnWorker($do_cron = false)
1057 $command = 'bin/worker.php';
1059 $args = ['no_cron' => !$do_cron];
1061 get_app()->proc_run($command, $args);
1063 // after spawning we have to remove the flag.
1064 if (Config::get('system', 'worker_daemon_mode', false)) {
1065 self::IPCSetJobState(false);
1070 * @brief Adds tasks to the worker queue
1072 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1074 * next args are passed as $cmd command line
1075 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1076 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1078 * @return boolean "false" if proc_run couldn't be executed
1079 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1080 * @note $cmd and string args are surrounded with ""
1086 public static function add($cmd)
1088 $args = func_get_args();
1090 if (!count($args)) {
1094 $arr = ['args' => $args, 'run_cmd' => true];
1096 Hook::callAll("proc_run", $arr);
1097 if (!$arr['run_cmd'] || !count($args)) {
1101 $priority = PRIORITY_MEDIUM;
1102 $dont_fork = Config::get("system", "worker_dont_fork", false);
1103 $created = DateTimeFormat::utcNow();
1104 $force_priority = false;
1106 $run_parameter = array_shift($args);
1108 if (is_int($run_parameter)) {
1109 $priority = $run_parameter;
1110 } elseif (is_array($run_parameter)) {
1111 if (isset($run_parameter['priority'])) {
1112 $priority = $run_parameter['priority'];
1114 if (isset($run_parameter['created'])) {
1115 $created = $run_parameter['created'];
1117 if (isset($run_parameter['dont_fork'])) {
1118 $dont_fork = $run_parameter['dont_fork'];
1120 if (isset($run_parameter['force_priority'])) {
1121 $force_priority = $run_parameter['force_priority'];
1125 $parameters = json_encode($args);
1126 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1128 // Quit if there was a database error - a precaution for the update process to 3.5.3
1129 if (DBA::errorNo() != 0) {
1134 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1135 } elseif ($force_priority) {
1136 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1139 // Should we quit and wait for the worker to be called as a cronjob?
1144 // If there is a lock then we don't have to check for too much worker
1145 if (!Lock::acquire('worker', 0)) {
1149 // If there are already enough workers running, don't fork another one
1150 $quit = self::tooMuchWorkers();
1151 Lock::release('worker');
1157 // We tell the daemon that a new job entry exists
1158 if (Config::get('system', 'worker_daemon_mode', false)) {
1159 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1163 // Now call the worker to execute the jobs that we just added to the queue
1164 self::spawnWorker();
1170 * Defers the current worker entry
1172 public static function defer()
1174 if (empty(BaseObject::getApp()->queue)) {
1178 $queue = BaseObject::getApp()->queue;
1180 $retrial = $queue['retrial'];
1182 $priority = $queue['priority'];
1184 if ($retrial > 14) {
1185 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1189 // Calculate the delay until the next trial
1190 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1191 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1193 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1194 $priority = PRIORITY_MEDIUM;
1195 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1196 $priority = PRIORITY_LOW;
1197 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1198 $priority = PRIORITY_NEGLIGIBLE;
1201 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1203 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1204 DBA::update('workerqueue', $fields, ['id' => $id]);
1208 * Log active processes into the "process" table
1210 * @brief Log active processes into the "process" table
1212 public static function startProcess()
1214 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1216 $command = basename($trace[0]['file']);
1218 Process::deleteInactive();
1220 Process::insert($command);
1224 * Remove the active process from the "process" table
1226 * @brief Remove the active process from the "process" table
1228 * @throws \Exception
1230 public static function endProcess()
1232 return Process::deleteByPid();
1236 * Set the flag if some job is waiting
1238 * @brief Set the flag if some job is waiting
1239 * @param boolean $jobs Is there a waiting job?
1240 * @throws \Exception
1242 public static function IPCSetJobState($jobs)
1244 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1248 * Checks if some worker job waits to be executed
1250 * @brief Checks if some worker job waits to be executed
1252 * @throws \Exception
1254 public static function IPCJobsExists()
1256 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1258 // When we don't have a row, no job is running
1259 if (!DBA::isResult($row)) {
1263 return (bool)$row['jobs'];