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
106 if (!$refetched && Lock::acquire('worker_process', 0)) {
107 $stamp = (float)microtime(true);
108 $refetched = self::findWorkerProcesses($passing_slow);
109 self::$db_duration += (microtime(true) - $stamp);
110 Lock::release('worker_process');
114 // To avoid the quitting of multiple workers only one worker at a time will execute the check
115 if (Lock::acquire('worker', 0)) {
116 $stamp = (float)microtime(true);
117 // Count active workers and compare them with a maximum value that depends on the load
118 if (self::tooMuchWorkers()) {
119 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
120 Lock::release('worker');
125 if ($a->isMinMemoryReached()) {
126 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
127 Lock::release('worker');
130 Lock::release('worker');
131 self::$db_duration += (microtime(true) - $stamp);
134 // Quit the worker once every 5 minutes
135 if (time() > ($starttime + 300)) {
136 Logger::log('Process lifetime reached, quitting.', Logger::DEBUG);
141 // Cleaning up. Possibly not needed, but it doesn't harm anything.
142 if (Config::get('system', 'worker_daemon_mode', false)) {
143 self::IPCSetJobState(false);
145 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
149 * @brief Returns the number of deferred entries in the worker queue
151 * @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
166 private static function totalEntries()
168 return DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
169 DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
173 * @brief Returns the highest priority in the worker queue that isn't executed
175 * @return integer Number of active worker processes
178 private static function highestPriority()
180 $condition = ["`executed` <= ? AND NOT `done` AND `next_try` < ?", DBA::NULL_DATETIME, DateTimeFormat::utcNow()];
181 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
182 if (DBA::isResult($workerqueue)) {
183 return $workerqueue["priority"];
190 * @brief Returns if a process with the given priority is running
192 * @param integer $priority The priority that should be checked
194 * @return integer Is there a process running with that priority?
197 private static function processWithPriorityActive($priority)
199 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done` AND `next_try` < ?",
200 $priority, DBA::NULL_DATETIME, DateTimeFormat::utcNow()];
201 return DBA::exists('workerqueue', $condition);
205 * @brief Execute a worker entry
207 * @param array $queue Workerqueue entry
209 * @return boolean "true" if further processing should be stopped
210 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
212 public static function execute($queue)
218 // Quit when in maintenance
219 if (Config::get('system', 'maintenance', false, true)) {
220 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
224 // Constantly check the number of parallel database processes
225 if ($a->isMaxProcessesReached()) {
226 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
230 // Constantly check the number of available database connections to let the frontend be accessible at any time
231 if (self::maxConnectionsReached()) {
232 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
236 $argv = json_decode($queue["parameter"], true);
238 // Check for existance and validity of the include file
241 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
242 // We constantly update the "executed" date every minute to avoid being killed too soon
243 if (!isset(self::$last_update)) {
244 self::$last_update = strtotime($queue["executed"]);
247 $age = (time() - self::$last_update) / 60;
248 self::$last_update = time();
251 $stamp = (float)microtime(true);
252 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
253 self::$db_duration += (microtime(true) - $stamp);
258 self::execFunction($queue, $include, $argv, true);
260 $stamp = (float)microtime(true);
262 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
263 if (DBA::update('workerqueue', ['done' => true], $condition)) {
264 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
266 self::$db_duration = (microtime(true) - $stamp);
271 // The script could be provided as full path or only with the function name
272 if ($include == basename($include)) {
273 $include = "include/".$include.".php";
276 if (!validate_include($include)) {
277 Logger::log("Include file ".$argv[0]." is not valid!");
278 DBA::delete('workerqueue', ['id' => $queue["id"]]);
282 require_once $include;
284 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
286 if (function_exists($funcname)) {
287 // We constantly update the "executed" date every minute to avoid being killed too soon
288 if (!isset(self::$last_update)) {
289 self::$last_update = strtotime($queue["executed"]);
292 $age = (time() - self::$last_update) / 60;
293 self::$last_update = time();
296 $stamp = (float)microtime(true);
297 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
298 self::$db_duration += (microtime(true) - $stamp);
301 self::execFunction($queue, $funcname, $argv, false);
303 $stamp = (float)microtime(true);
304 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
305 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
307 self::$db_duration = (microtime(true) - $stamp);
309 Logger::log("Function ".$funcname." does not exist");
310 DBA::delete('workerqueue', ['id' => $queue["id"]]);
317 * @brief Execute a function from the queue
319 * @param array $queue Workerqueue entry
320 * @param string $funcname name of the function
321 * @param array $argv Array of values to be passed to the function
322 * @param boolean $method_call boolean
324 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
326 private static function execFunction($queue, $funcname, $argv, $method_call)
332 $argc = count($argv);
334 $new_process_id = System::processID("wrk");
336 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
338 $stamp = (float)microtime(true);
340 // We use the callstack here to analyze the performance of executed worker entries.
341 // For this reason the variables have to be initialized.
342 if (Config::get("system", "profiler")) {
343 $a->performance["start"] = microtime(true);
344 $a->performance["database"] = 0;
345 $a->performance["database_write"] = 0;
346 $a->performance["cache"] = 0;
347 $a->performance["cache_write"] = 0;
348 $a->performance["network"] = 0;
349 $a->performance["file"] = 0;
350 $a->performance["rendering"] = 0;
351 $a->performance["parser"] = 0;
352 $a->performance["marktime"] = 0;
353 $a->performance["markstart"] = microtime(true);
357 // For better logging create a new process id for every worker call
358 // But preserve the old one for the worker
359 $old_process_id = $a->process_id;
360 $a->process_id = $new_process_id;
363 $up_duration = number_format(microtime(true) - self::$up_start, 3);
365 // Reset global data to avoid interferences
369 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
371 $funcname($argv, $argc);
374 $a->process_id = $old_process_id;
377 $duration = (microtime(true) - $stamp);
379 self::$up_start = microtime(true);
381 /* With these values we can analyze how effective the worker is.
382 * The database and rest time should be low since this is the unproductive time.
383 * The execution time is the productive time.
384 * By changing parameters like the maximum number of workers we can check the effectivness.
387 'DB: '.number_format(self::$db_duration, 2).
388 ' - Lock: '.number_format(self::$lock_duration, 2).
389 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
390 ' - Execution: '.number_format($duration, 2),
394 self::$lock_duration = 0;
396 if ($duration > 3600) {
397 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
398 } elseif ($duration > 600) {
399 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
400 } elseif ($duration > 300) {
401 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
402 } elseif ($duration > 120) {
403 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
406 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
408 // Write down the performance values into the log
409 if (Config::get("system", "profiler")) {
410 $duration = microtime(true)-$a->performance["start"];
413 if (Config::get("rendertime", "callstack")) {
414 if (isset($a->callstack["database"])) {
415 $o .= "\nDatabase Read:\n";
416 foreach ($a->callstack["database"] as $func => $time) {
417 $time = round($time, 3);
419 $o .= $func.": ".$time."\n";
423 if (isset($a->callstack["database_write"])) {
424 $o .= "\nDatabase Write:\n";
425 foreach ($a->callstack["database_write"] as $func => $time) {
426 $time = round($time, 3);
428 $o .= $func.": ".$time."\n";
432 if (isset($a->callstack["dache"])) {
433 $o .= "\nCache Read:\n";
434 foreach ($a->callstack["dache"] as $func => $time) {
435 $time = round($time, 3);
437 $o .= $func.": ".$time."\n";
441 if (isset($a->callstack["dache_write"])) {
442 $o .= "\nCache Write:\n";
443 foreach ($a->callstack["dache_write"] as $func => $time) {
444 $time = round($time, 3);
446 $o .= $func.": ".$time."\n";
450 if (isset($a->callstack["network"])) {
451 $o .= "\nNetwork:\n";
452 foreach ($a->callstack["network"] as $func => $time) {
453 $time = round($time, 3);
455 $o .= $func.": ".$time."\n";
462 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
463 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
464 number_format($a->performance["database"] - $a->performance["database_write"], 2),
465 number_format($a->performance["database_write"], 2),
466 number_format($a->performance["cache"], 2),
467 number_format($a->performance["cache_write"], 2),
468 number_format($a->performance["network"], 2),
469 number_format($a->performance["file"], 2),
470 number_format($duration - ($a->performance["database"]
471 + $a->performance["cache"] + $a->performance["cache_write"]
472 + $a->performance["network"] + $a->performance["file"]), 2),
473 number_format($duration, 2)
479 $cooldown = Config::get("system", "worker_cooldown", 0);
482 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
488 * @brief Checks if the number of database connections has reached a critical limit.
490 * @return bool Are more than 3/4 of the maximum connections used?
491 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
493 private static function maxConnectionsReached()
495 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
496 $max = Config::get("system", "max_connections");
498 // Fetch the percentage level where the worker will get active
499 $maxlevel = Config::get("system", "max_connections_level", 75);
502 // the maximum number of possible user connections can be a system variable
503 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
504 if (DBA::isResult($r)) {
507 // Or it can be granted. This overrides the system variable
508 $r = DBA::p('SHOW GRANTS');
509 while ($grants = DBA::fetch($r)) {
510 $grant = array_pop($grants);
511 if (stristr($grant, "GRANT USAGE ON")) {
512 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
520 // If $max is set we will use the processlist to determine the current number of connections
521 // The processlist only shows entries of the current user
523 $r = DBA::p('SHOW PROCESSLIST');
524 $used = DBA::numRows($r);
527 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
529 $level = ($used / $max) * 100;
531 if ($level >= $maxlevel) {
532 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
537 // We will now check for the system values.
538 // This limit could be reached although the user limits are fine.
539 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
540 if (!DBA::isResult($r)) {
543 $max = intval($r["Value"]);
547 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
548 if (!DBA::isResult($r)) {
551 $used = intval($r["Value"]);
555 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
557 $level = $used / $max * 100;
559 if ($level < $maxlevel) {
562 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
567 * @brief fix the queue entry if the worker process died
571 private static function killStaleWorkers()
573 $entries = DBA::select(
575 ['id', 'pid', 'executed', 'priority', 'parameter'],
576 ['`executed` > ? AND NOT `done` AND `pid` != 0', DBA::NULL_DATETIME],
577 ['order' => ['priority', 'created']]
580 while ($entry = DBA::fetch($entries)) {
581 if (!posix_kill($entry["pid"], 0)) {
584 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
585 ['id' => $entry["id"]]
588 // Kill long running processes
589 // Check if the priority is in a valid range
590 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
591 $entry["priority"] = PRIORITY_MEDIUM;
594 // Define the maximum durations
595 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
596 $max_duration = $max_duration_defaults[$entry["priority"]];
598 $argv = json_decode($entry["parameter"], true);
599 $argv[0] = basename($argv[0]);
601 // How long is the process already running?
602 $duration = (time() - strtotime($entry["executed"])) / 60;
603 if ($duration > $max_duration) {
604 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
605 posix_kill($entry["pid"], SIGTERM);
607 // We killed the stale process.
608 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
609 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
610 $new_priority = $entry["priority"];
611 if ($entry["priority"] == PRIORITY_HIGH) {
612 $new_priority = PRIORITY_MEDIUM;
613 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
614 $new_priority = PRIORITY_LOW;
615 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
616 $new_priority = PRIORITY_NEGLIGIBLE;
620 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
621 ['id' => $entry["id"]]
624 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);
631 * @brief Checks if the number of active workers exceeds the given limits
633 * @return bool Are there too much workers running?
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
636 public static function tooMuchWorkers()
638 $queues = Config::get("system", "worker_queues", 4);
640 $maxqueues = $queues;
642 $active = self::activeWorkers();
644 // Decrease the number of workers at higher load
645 $load = System::currentLoad();
647 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
649 /* Default exponent 3 causes queues to rapidly decrease as load increases.
650 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
651 * For some environments, this rapid decrease is not needed.
652 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
654 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
655 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
656 $queues = intval(ceil($slope * $maxqueues));
660 if (Config::get('system', 'worker_jpm')) {
661 $intervals = [1, 10, 60];
662 $jobs_per_minute = [];
663 foreach ($intervals as $interval) {
664 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
665 if ($job = DBA::fetch($jobs)) {
666 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
670 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
673 if (Config::get('system', 'worker_debug')) {
674 // Create a list of queue entries grouped by their priority
677 // Adding all processes with no workerqueue entry
679 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
680 (SELECT id FROM `workerqueue`
681 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
685 if ($process = DBA::fetch($processes)) {
686 $listitem[0] = "0:".$process["running"];
688 DBA::close($processes);
690 // Now adding all processes with workerqueue entries
691 $entries = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
692 while ($entry = DBA::fetch($entries)) {
693 $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` = ?",
694 DateTimeFormat::utcNow(), $entry["priority"]);
695 if ($process = DBA::fetch($processes)) {
696 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
698 DBA::close($processes);
700 DBA::close($entries);
702 $processlist .= ' ('.implode(', ', $listitem).')';
705 $entries = self::totalEntries();
706 $deferred = self::deferredEntries();
708 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
709 $top_priority = self::highestPriority();
710 $high_running = self::processWithPriorityActive($top_priority);
712 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
713 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
714 $queues = $active + 1;
718 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $entries . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
720 // Are there fewer workers running as possible? Then fork a new one.
721 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
722 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
723 if (Config::get('system', 'worker_daemon_mode', false)) {
724 self::IPCSetJobState(true);
731 // if there are too much worker, we don't spawn a new one.
732 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
733 self::IPCSetJobState(false);
736 return $active > $queues;
740 * @brief Returns the number of active worker processes
742 * @return integer Number of active worker processes
745 private static function activeWorkers()
747 return DBA::count('process', ['command' => 'Worker.php']);
751 * @brief Check if we should pass some slow processes
753 * When the active processes of the highest priority are using more than 2/3
754 * of all processes, we let pass slower processes.
756 * @param string $highest_priority Returns the currently highest priority
757 * @return bool We let pass a slower process than $highest_priority
760 private static function passingSlow(&$highest_priority)
762 $highest_priority = 0;
767 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
770 // No active processes at all? Fine
771 if (!DBA::isResult($r)) {
775 while ($line = DBA::fetch($r)) {
776 $priorities[] = $line["priority"];
781 if (count($priorities) == 0) {
784 $highest_priority = min($priorities);
786 // The highest process is already the slowest one?
788 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
792 foreach ($priorities as $priority) {
793 if ($priority == $highest_priority) {
797 Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
798 $passing_slow = (($high/count($priorities)) > (2/3));
801 Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
803 return $passing_slow;
807 * @brief Find and claim the next worker process for us
809 * @param boolean $passing_slow Returns if we had passed low priority processes
810 * @return boolean Have we found something?
811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 private static function findWorkerProcesses(&$passing_slow)
817 // Check if we should pass some low priority process
818 $highest_priority = 0;
820 $passing_slow = false;
822 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
823 // We decrease the limit with the number of entries left in the queue
824 $worker_queues = Config::get("system", "worker_queues", 4);
825 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
826 $lower_job_limit = $worker_queues * $queue_length * 2;
827 $jobs = self::totalEntries();
828 $deferred = self::deferredEntries();
832 $slope = $queue_length / pow($lower_job_limit, $exponent);
833 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
835 Logger::log('Deferred: ' . $deferred . ' - Total: ' . $jobs . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
837 if (self::passingSlow($highest_priority)) {
838 // Are there waiting processes with a higher priority than the currently highest?
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);
855 // Give slower processes some processing time
856 $result = DBA::select(
859 ["`executed` <= ? AND `priority` > ? AND NOT `done` AND `next_try` < ?",
860 DBA::NULL_DATETIME, $highest_priority, DateTimeFormat::utcNow()],
861 ['limit' => $limit, 'order' => ['priority', 'created']]
864 while ($id = DBA::fetch($result)) {
869 $found = (count($ids) > 0);
870 $passing_slow = $found;
874 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
876 $result = DBA::select(
879 ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
880 DBA::NULL_DATETIME, DateTimeFormat::utcNow()],
881 ['limit' => $limit, 'order' => ['priority', 'created']]
884 while ($id = DBA::fetch($result)) {
889 $found = (count($ids) > 0);
893 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
894 array_unshift($ids, $condition);
895 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
902 * @brief Returns the next worker process
904 * @param boolean $passing_slow Returns if we had passed low priority processes
905 * @return string SQL statement
906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
908 public static function workerProcess(&$passing_slow)
910 $stamp = (float)microtime(true);
912 // There can already be jobs for us in the queue.
913 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
914 if (DBA::isResult($r)) {
915 self::$db_duration += (microtime(true) - $stamp);
916 return DBA::toArray($r);
920 $stamp = (float)microtime(true);
921 if (!Lock::acquire('worker_process')) {
924 self::$lock_duration = (microtime(true) - $stamp);
926 $stamp = (float)microtime(true);
927 $found = self::findWorkerProcesses($passing_slow);
928 self::$db_duration += (microtime(true) - $stamp);
930 Lock::release('worker_process');
933 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
934 return DBA::toArray($r);
940 * @brief Removes a workerqueue entry from the current process
944 public static function unclaimProcess()
948 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
952 * @brief Call the front end worker
954 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
956 public static function callWorker()
958 if (!Config::get("system", "frontend_worker")) {
962 $url = System::baseUrl()."/worker";
963 Network::fetchUrl($url, false, $redirects, 1);
967 * @brief Call the front end worker if there aren't any active
969 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
971 public static function executeIfIdle()
973 if (!Config::get("system", "frontend_worker")) {
977 // Do we have "proc_open"? Then we can fork the worker
978 if (function_exists("proc_open")) {
979 // When was the last time that we called the worker?
980 // Less than one minute? Then we quit
981 if ((time() - Config::get("system", "worker_started")) < 60) {
985 Config::set("system", "worker_started", time());
987 // Do we have enough running workers? Then we quit here.
988 if (self::tooMuchWorkers()) {
989 // Cleaning dead processes
990 self::killStaleWorkers();
991 Process::deleteInactive();
998 Logger::log('Call worker', Logger::DEBUG);
1003 // We cannot execute background processes.
1004 // We now run the processes from the frontend.
1005 // This won't work with long running processes.
1008 self::clearProcesses();
1010 $workers = self::activeWorkers();
1012 if ($workers == 0) {
1018 * @brief Removes long running worker processes
1020 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1022 public static function clearProcesses()
1024 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1026 /// @todo We should clean up the corresponding workerqueue entries as well
1027 $condition = ["`created` < ? AND `command` = 'worker.php'",
1028 DateTimeFormat::utc("now - ".$timeout." minutes")];
1029 DBA::delete('process', $condition);
1033 * @brief Runs the cron processes
1035 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1037 private static function runCron()
1039 Logger::log('Add cron entries', Logger::DEBUG);
1041 // Check for spooled items
1042 self::add(PRIORITY_HIGH, "SpoolPost");
1044 // Run the cron job that calls all other jobs
1045 self::add(PRIORITY_MEDIUM, "Cron");
1047 // Cleaning dead processes
1048 self::killStaleWorkers();
1052 * @brief Spawns a new worker
1053 * @param bool $do_cron
1055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1057 public static function spawnWorker($do_cron = false)
1059 $command = 'bin/worker.php';
1061 $args = ['no_cron' => !$do_cron];
1063 get_app()->proc_run($command, $args);
1065 // after spawning we have to remove the flag.
1066 if (Config::get('system', 'worker_daemon_mode', false)) {
1067 self::IPCSetJobState(false);
1072 * @brief Adds tasks to the worker queue
1074 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1076 * next args are passed as $cmd command line
1077 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1078 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1080 * @return boolean "false" if proc_run couldn't be executed
1081 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1082 * @note $cmd and string args are surrounded with ""
1088 public static function add($cmd)
1090 $args = func_get_args();
1092 if (!count($args)) {
1096 $arr = ['args' => $args, 'run_cmd' => true];
1098 Hook::callAll("proc_run", $arr);
1099 if (!$arr['run_cmd'] || !count($args)) {
1103 $priority = PRIORITY_MEDIUM;
1104 $dont_fork = Config::get("system", "worker_dont_fork", false);
1105 $created = DateTimeFormat::utcNow();
1107 $run_parameter = array_shift($args);
1109 if (is_int($run_parameter)) {
1110 $priority = $run_parameter;
1111 } elseif (is_array($run_parameter)) {
1112 if (isset($run_parameter['priority'])) {
1113 $priority = $run_parameter['priority'];
1115 if (isset($run_parameter['created'])) {
1116 $created = $run_parameter['created'];
1118 if (isset($run_parameter['dont_fork'])) {
1119 $dont_fork = $run_parameter['dont_fork'];
1123 $parameters = json_encode($args);
1124 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1126 // Quit if there was a database error - a precaution for the update process to 3.5.3
1127 if (DBA::errorNo() != 0) {
1132 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1135 // Should we quit and wait for the worker to be called as a cronjob?
1140 // If there is a lock then we don't have to check for too much worker
1141 if (!Lock::acquire('worker', 0)) {
1145 // If there are already enough workers running, don't fork another one
1146 $quit = self::tooMuchWorkers();
1147 Lock::release('worker');
1153 // We tell the daemon that a new job entry exists
1154 if (Config::get('system', 'worker_daemon_mode', false)) {
1155 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1159 // Now call the worker to execute the jobs that we just added to the queue
1160 self::spawnWorker();
1166 * Defers the current worker entry
1168 public static function defer()
1170 if (empty(BaseObject::getApp()->queue)) {
1174 $queue = BaseObject::getApp()->queue;
1176 $retrial = $queue['retrial'];
1179 if ($retrial > 14) {
1180 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1184 // Calculate the delay until the next trial
1185 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1186 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1188 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next, Logger::DEBUG);
1190 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0];
1191 DBA::update('workerqueue', $fields, ['id' => $id]);
1195 * Log active processes into the "process" table
1197 * @brief Log active processes into the "process" table
1199 public static function startProcess()
1201 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1203 $command = basename($trace[0]['file']);
1205 Process::deleteInactive();
1207 Process::insert($command);
1211 * Remove the active process from the "process" table
1213 * @brief Remove the active process from the "process" table
1215 * @throws \Exception
1217 public static function endProcess()
1219 return Process::deleteByPid();
1223 * Set the flag if some job is waiting
1225 * @brief Set the flag if some job is waiting
1226 * @param boolean $jobs Is there a waiting job?
1227 * @throws \Exception
1229 public static function IPCSetJobState($jobs)
1231 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1235 * Checks if some worker job waits to be executed
1237 * @brief Checks if some worker job waits to be executed
1239 * @throws \Exception
1241 public static function IPCJobsExists()
1243 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1245 // When we don't have a row, no job is running
1246 if (!DBA::isResult($row)) {
1250 return (bool)$row['jobs'];