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_debug')) {
661 // Create a list of queue entries grouped by their priority
664 // Adding all processes with no workerqueue entry
666 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
667 (SELECT id FROM `workerqueue`
668 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
672 if ($process = DBA::fetch($processes)) {
673 $listitem[0] = "0:".$process["running"];
675 DBA::close($processes);
677 // Now adding all processes with workerqueue entries
678 $entries = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
679 while ($entry = DBA::fetch($entries)) {
680 $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` = ?",
681 DateTimeFormat::utcNow(), $entry["priority"]);
682 if ($process = DBA::fetch($processes)) {
683 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
685 DBA::close($processes);
687 DBA::close($entries);
689 $intervals = [1, 10, 60];
690 $jobs_per_minute = [];
691 foreach ($intervals as $interval) {
692 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
693 if ($job = DBA::fetch($jobs)) {
694 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
698 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
701 $entries = self::totalEntries();
702 $deferred = self::deferredEntries();
704 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
705 $top_priority = self::highestPriority();
706 $high_running = self::processWithPriorityActive($top_priority);
708 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
709 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
710 $queues = $active + 1;
714 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $entries . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
716 // Are there fewer workers running as possible? Then fork a new one.
717 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
718 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
719 if (Config::get('system', 'worker_daemon_mode', false)) {
720 self::IPCSetJobState(true);
727 // if there are too much worker, we don't spawn a new one.
728 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
729 self::IPCSetJobState(false);
732 return $active > $queues;
736 * @brief Returns the number of active worker processes
738 * @return integer Number of active worker processes
741 private static function activeWorkers()
743 return DBA::count('process', ['command' => 'Worker.php']);
747 * @brief Check if we should pass some slow processes
749 * When the active processes of the highest priority are using more than 2/3
750 * of all processes, we let pass slower processes.
752 * @param string $highest_priority Returns the currently highest priority
753 * @return bool We let pass a slower process than $highest_priority
756 private static function passingSlow(&$highest_priority)
758 $highest_priority = 0;
763 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
766 // No active processes at all? Fine
767 if (!DBA::isResult($r)) {
771 while ($line = DBA::fetch($r)) {
772 $priorities[] = $line["priority"];
777 if (count($priorities) == 0) {
780 $highest_priority = min($priorities);
782 // The highest process is already the slowest one?
784 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
788 foreach ($priorities as $priority) {
789 if ($priority == $highest_priority) {
793 Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
794 $passing_slow = (($high/count($priorities)) > (2/3));
797 Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
799 return $passing_slow;
803 * @brief Find and claim the next worker process for us
805 * @param boolean $passing_slow Returns if we had passed low priority processes
806 * @return boolean Have we found something?
807 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
809 private static function findWorkerProcesses(&$passing_slow)
813 // Check if we should pass some low priority process
814 $highest_priority = 0;
816 $passing_slow = false;
818 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
819 // We decrease the limit with the number of entries left in the queue
820 $worker_queues = Config::get("system", "worker_queues", 4);
821 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
822 $lower_job_limit = $worker_queues * $queue_length * 2;
823 $jobs = self::totalEntries();
824 $deferred = self::deferredEntries();
828 $slope = $queue_length / pow($lower_job_limit, $exponent);
829 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
831 Logger::log('Deferred: ' . $deferred . ' - Total: ' . $jobs . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
833 if (self::passingSlow($highest_priority)) {
834 // Are there waiting processes with a higher priority than the currently highest?
835 $result = DBA::select(
838 ["`executed` <= ? AND `priority` < ? AND NOT `done` AND `next_try` < ?",
839 DBA::NULL_DATETIME, $highest_priority, DateTimeFormat::utcNow()],
840 ['limit' => $limit, 'order' => ['priority', 'created']]
843 while ($id = DBA::fetch($result)) {
848 $found = (count($ids) > 0);
851 // Give slower processes some processing time
852 $result = DBA::select(
855 ["`executed` <= ? AND `priority` > ? AND NOT `done` AND `next_try` < ?",
856 DBA::NULL_DATETIME, $highest_priority, DateTimeFormat::utcNow()],
857 ['limit' => $limit, 'order' => ['priority', 'created']]
860 while ($id = DBA::fetch($result)) {
865 $found = (count($ids) > 0);
866 $passing_slow = $found;
870 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
872 $result = DBA::select(
875 ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
876 DBA::NULL_DATETIME, DateTimeFormat::utcNow()],
877 ['limit' => $limit, 'order' => ['priority', 'created']]
880 while ($id = DBA::fetch($result)) {
885 $found = (count($ids) > 0);
889 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
890 array_unshift($ids, $condition);
891 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
898 * @brief Returns the next worker process
900 * @param boolean $passing_slow Returns if we had passed low priority processes
901 * @return string SQL statement
902 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
904 public static function workerProcess(&$passing_slow)
906 $stamp = (float)microtime(true);
908 // There can already be jobs for us in the queue.
909 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
910 if (DBA::isResult($r)) {
911 self::$db_duration += (microtime(true) - $stamp);
912 return DBA::toArray($r);
916 $stamp = (float)microtime(true);
917 if (!Lock::acquire('worker_process')) {
920 self::$lock_duration = (microtime(true) - $stamp);
922 $stamp = (float)microtime(true);
923 $found = self::findWorkerProcesses($passing_slow);
924 self::$db_duration += (microtime(true) - $stamp);
926 Lock::release('worker_process');
929 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
930 return DBA::toArray($r);
936 * @brief Removes a workerqueue entry from the current process
940 public static function unclaimProcess()
944 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
948 * @brief Call the front end worker
950 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
952 public static function callWorker()
954 if (!Config::get("system", "frontend_worker")) {
958 $url = System::baseUrl()."/worker";
959 Network::fetchUrl($url, false, $redirects, 1);
963 * @brief Call the front end worker if there aren't any active
965 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
967 public static function executeIfIdle()
969 if (!Config::get("system", "frontend_worker")) {
973 // Do we have "proc_open"? Then we can fork the worker
974 if (function_exists("proc_open")) {
975 // When was the last time that we called the worker?
976 // Less than one minute? Then we quit
977 if ((time() - Config::get("system", "worker_started")) < 60) {
981 Config::set("system", "worker_started", time());
983 // Do we have enough running workers? Then we quit here.
984 if (self::tooMuchWorkers()) {
985 // Cleaning dead processes
986 self::killStaleWorkers();
987 Process::deleteInactive();
994 Logger::log('Call worker', Logger::DEBUG);
999 // We cannot execute background processes.
1000 // We now run the processes from the frontend.
1001 // This won't work with long running processes.
1004 self::clearProcesses();
1006 $workers = self::activeWorkers();
1008 if ($workers == 0) {
1014 * @brief Removes long running worker processes
1016 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1018 public static function clearProcesses()
1020 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1022 /// @todo We should clean up the corresponding workerqueue entries as well
1023 $condition = ["`created` < ? AND `command` = 'worker.php'",
1024 DateTimeFormat::utc("now - ".$timeout." minutes")];
1025 DBA::delete('process', $condition);
1029 * @brief Runs the cron processes
1031 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1033 private static function runCron()
1035 Logger::log('Add cron entries', Logger::DEBUG);
1037 // Check for spooled items
1038 self::add(PRIORITY_HIGH, "SpoolPost");
1040 // Run the cron job that calls all other jobs
1041 self::add(PRIORITY_MEDIUM, "Cron");
1043 // Cleaning dead processes
1044 self::killStaleWorkers();
1048 * @brief Spawns a new worker
1049 * @param bool $do_cron
1051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1053 public static function spawnWorker($do_cron = false)
1055 $command = 'bin/worker.php';
1057 $args = ['no_cron' => !$do_cron];
1059 get_app()->proc_run($command, $args);
1061 // after spawning we have to remove the flag.
1062 if (Config::get('system', 'worker_daemon_mode', false)) {
1063 self::IPCSetJobState(false);
1068 * @brief Adds tasks to the worker queue
1070 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1072 * next args are passed as $cmd command line
1073 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1074 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1076 * @return boolean "false" if proc_run couldn't be executed
1077 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1078 * @note $cmd and string args are surrounded with ""
1084 public static function add($cmd)
1086 $args = func_get_args();
1088 if (!count($args)) {
1092 $arr = ['args' => $args, 'run_cmd' => true];
1094 Hook::callAll("proc_run", $arr);
1095 if (!$arr['run_cmd'] || !count($args)) {
1099 $priority = PRIORITY_MEDIUM;
1100 $dont_fork = Config::get("system", "worker_dont_fork", false);
1101 $created = DateTimeFormat::utcNow();
1103 $run_parameter = array_shift($args);
1105 if (is_int($run_parameter)) {
1106 $priority = $run_parameter;
1107 } elseif (is_array($run_parameter)) {
1108 if (isset($run_parameter['priority'])) {
1109 $priority = $run_parameter['priority'];
1111 if (isset($run_parameter['created'])) {
1112 $created = $run_parameter['created'];
1114 if (isset($run_parameter['dont_fork'])) {
1115 $dont_fork = $run_parameter['dont_fork'];
1119 $parameters = json_encode($args);
1120 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1122 // Quit if there was a database error - a precaution for the update process to 3.5.3
1123 if (DBA::errorNo() != 0) {
1128 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1131 // Should we quit and wait for the worker to be called as a cronjob?
1136 // If there is a lock then we don't have to check for too much worker
1137 if (!Lock::acquire('worker', 0)) {
1141 // If there are already enough workers running, don't fork another one
1142 $quit = self::tooMuchWorkers();
1143 Lock::release('worker');
1149 // We tell the daemon that a new job entry exists
1150 if (Config::get('system', 'worker_daemon_mode', false)) {
1151 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1155 // Now call the worker to execute the jobs that we just added to the queue
1156 self::spawnWorker();
1162 * Defers the current worker entry
1164 public static function defer()
1166 if (empty(BaseObject::getApp()->queue)) {
1170 $queue = BaseObject::getApp()->queue;
1172 $retrial = $queue['retrial'];
1175 if ($retrial > 14) {
1176 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1180 // Calculate the delay until the next trial
1181 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1182 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1184 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next, Logger::DEBUG);
1186 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0];
1187 DBA::update('workerqueue', $fields, ['id' => $id]);
1191 * Log active processes into the "process" table
1193 * @brief Log active processes into the "process" table
1195 public static function startProcess()
1197 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1199 $command = basename($trace[0]['file']);
1201 Process::deleteInactive();
1203 Process::insert($command);
1207 * Remove the active process from the "process" table
1209 * @brief Remove the active process from the "process" table
1211 * @throws \Exception
1213 public static function endProcess()
1215 return Process::deleteByPid();
1219 * Set the flag if some job is waiting
1221 * @brief Set the flag if some job is waiting
1222 * @param boolean $jobs Is there a waiting job?
1223 * @throws \Exception
1225 public static function IPCSetJobState($jobs)
1227 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1231 * Checks if some worker job waits to be executed
1233 * @brief Checks if some worker job waits to be executed
1235 * @throws \Exception
1237 public static function IPCJobsExists()
1239 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1241 // When we don't have a row, no job is running
1242 if (!DBA::isResult($row)) {
1246 return (bool)$row['jobs'];