3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core;
25 use Friendica\Database\DBA;
27 use Friendica\Model\Process;
28 use Friendica\Util\DateTimeFormat;
31 * Contains the class for the worker background job processing
35 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
36 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
37 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
38 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
40 const FAST_COMMANDS = ['APDelivery', 'Delivery', 'CreateShadowEntry'];
42 const LOCK_PROCESS = 'worker_process';
43 const LOCK_WORKER = 'worker';
45 private static $up_start;
46 private static $db_duration = 0;
47 private static $db_duration_count = 0;
48 private static $db_duration_write = 0;
49 private static $db_duration_stat = 0;
50 private static $lock_duration = 0;
51 private static $last_update;
52 private static $state;
55 * Processes the tasks that are in the workerqueue table
57 * @param boolean $run_cron Should the cron processes be executed?
59 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
61 public static function processQueue($run_cron = true)
63 // Ensure that all "strtotime" operations do run timezone independent
64 date_default_timezone_set('UTC');
66 self::$up_start = microtime(true);
68 // At first check the maximum load. We shouldn't continue with a high load
69 if (DI::process()->isMaxLoadReached()) {
70 Logger::info('Pre check: maximum load reached, quitting.');
74 // We now start the process. This is done after the load check since this could increase the load.
77 // Kill stale processes every 5 minutes
78 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
79 if (time() > ($last_cleanup + 300)) {
80 DI::config()->set('system', 'worker_last_cleaned', time());
81 self::killStaleWorkers();
84 // Check if the system is ready
85 if (!self::isReady()) {
89 // Now we start additional cron processes if we should do so
95 self::$state = self::STATE_STARTUP;
97 // We fetch the next queue entry that is about to be executed
98 while ($r = self::workerProcess()) {
99 // Don't refetch when a worker fetches tasks for multiple workers
100 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
101 foreach ($r as $entry) {
102 // Assure that the priority is an integer value
103 $entry['priority'] = (int)$entry['priority'];
105 // The work will be done
106 if (!self::execute($entry)) {
107 Logger::info('Process execution failed, quitting.');
111 // Trying to fetch new processes - but only once when successful
112 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
113 self::findWorkerProcesses();
114 DI::lock()->release(self::LOCK_PROCESS);
115 self::$state = self::STATE_REFETCH;
118 self::$state = self::STATE_SHORT_LOOP;
122 // To avoid the quitting of multiple workers only one worker at a time will execute the check
123 if (!self::getWaitingJobForPID()) {
124 self::$state = self::STATE_LONG_LOOP;
126 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
127 // Count active workers and compare them with a maximum value that depends on the load
128 if (self::tooMuchWorkers()) {
129 Logger::info('Active worker limit reached, quitting.');
130 DI::lock()->release(self::LOCK_WORKER);
135 if (DI::process()->isMinMemoryReached()) {
136 Logger::info('Memory limit reached, quitting.');
137 DI::lock()->release(self::LOCK_WORKER);
140 DI::lock()->release(self::LOCK_WORKER);
144 // Quit the worker once every cron interval
145 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
146 Logger::info('Process lifetime reached, respawning.');
147 self::unclaimProcess();
153 // Cleaning up. Possibly not needed, but it doesn't harm anything.
154 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
155 self::IPCSetJobState(false);
157 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
161 * Checks if the system is ready.
163 * Several system parameters like memory, connections and processes are checked.
167 public static function isReady()
169 // Count active workers and compare them with a maximum value that depends on the load
170 if (self::tooMuchWorkers()) {
171 Logger::info('Active worker limit reached, quitting.');
175 // Do we have too few memory?
176 if (DI::process()->isMinMemoryReached()) {
177 Logger::info('Memory limit reached, quitting.');
181 // Possibly there are too much database connections
182 if (self::maxConnectionsReached()) {
183 Logger::info('Maximum connections reached, quitting.');
187 // Possibly there are too much database processes that block the system
188 if (DI::process()->isMaxProcessesReached()) {
189 Logger::info('Maximum processes reached, quitting.');
197 * Check if non executed tasks do exist in the worker queue
199 * @return boolean Returns "true" if tasks are existing
202 public static function entriesExists()
204 $stamp = (float)microtime(true);
205 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
206 self::$db_duration += (microtime(true) - $stamp);
211 * Returns the number of deferred entries in the worker queue
213 * @return integer Number of deferred entries in the worker queue
216 private static function deferredEntries()
218 $stamp = (float)microtime(true);
219 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
220 self::$db_duration += (microtime(true) - $stamp);
221 self::$db_duration_count += (microtime(true) - $stamp);
226 * Returns the number of non executed entries in the worker queue
228 * @return integer Number of non executed entries in the worker queue
231 private static function totalEntries()
233 $stamp = (float)microtime(true);
234 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
235 self::$db_duration += (microtime(true) - $stamp);
236 self::$db_duration_count += (microtime(true) - $stamp);
241 * Returns the highest priority in the worker queue that isn't executed
243 * @return integer Number of active worker processes
246 private static function highestPriority()
248 $stamp = (float)microtime(true);
249 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
250 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
251 self::$db_duration += (microtime(true) - $stamp);
252 if (DBA::isResult($workerqueue)) {
253 return $workerqueue["priority"];
260 * Returns if a process with the given priority is running
262 * @param integer $priority The priority that should be checked
264 * @return integer Is there a process running with that priority?
267 private static function processWithPriorityActive($priority)
269 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
270 return DBA::exists('workerqueue', $condition);
274 * Execute a worker entry
276 * @param array $queue Workerqueue entry
278 * @return boolean "true" if further processing should be stopped
279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
281 public static function execute($queue)
285 // Quit when in maintenance
286 if (DI::config()->get('system', 'maintenance', false, true)) {
287 Logger::info("Maintenance mode - quit process", ['pid' => $mypid]);
291 // Constantly check the number of parallel database processes
292 if (DI::process()->isMaxProcessesReached()) {
293 Logger::info("Max processes reached for process", ['pid' => $mypid]);
297 // Constantly check the number of available database connections to let the frontend be accessible at any time
298 if (self::maxConnectionsReached()) {
299 Logger::info("Max connection reached for process", ['pid' => $mypid]);
303 $argv = json_decode($queue["parameter"], true);
305 Logger::error('Parameter is empty', ['queue' => $queue]);
309 // Check for existance and validity of the include file
312 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
313 // We constantly update the "executed" date every minute to avoid being killed too soon
314 if (!isset(self::$last_update)) {
315 self::$last_update = strtotime($queue["executed"]);
318 $age = (time() - self::$last_update) / 60;
319 self::$last_update = time();
322 $stamp = (float)microtime(true);
323 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
324 self::$db_duration += (microtime(true) - $stamp);
325 self::$db_duration_write += (microtime(true) - $stamp);
330 self::execFunction($queue, $include, $argv, true);
332 $stamp = (float)microtime(true);
333 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
334 if (DBA::update('workerqueue', ['done' => true], $condition)) {
335 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
337 self::$db_duration = (microtime(true) - $stamp);
338 self::$db_duration_write += (microtime(true) - $stamp);
343 // The script could be provided as full path or only with the function name
344 if ($include == basename($include)) {
345 $include = "include/".$include.".php";
348 if (!validate_include($include)) {
349 Logger::log("Include file ".$argv[0]." is not valid!");
350 $stamp = (float)microtime(true);
351 DBA::delete('workerqueue', ['id' => $queue["id"]]);
352 self::$db_duration = (microtime(true) - $stamp);
353 self::$db_duration_write += (microtime(true) - $stamp);
357 require_once $include;
359 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
361 if (function_exists($funcname)) {
362 // We constantly update the "executed" date every minute to avoid being killed too soon
363 if (!isset(self::$last_update)) {
364 self::$last_update = strtotime($queue["executed"]);
367 $age = (time() - self::$last_update) / 60;
368 self::$last_update = time();
371 $stamp = (float)microtime(true);
372 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
373 self::$db_duration += (microtime(true) - $stamp);
374 self::$db_duration_write += (microtime(true) - $stamp);
377 self::execFunction($queue, $funcname, $argv, false);
379 $stamp = (float)microtime(true);
380 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
381 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
383 self::$db_duration = (microtime(true) - $stamp);
384 self::$db_duration_write += (microtime(true) - $stamp);
386 Logger::log("Function ".$funcname." does not exist");
387 $stamp = (float)microtime(true);
388 DBA::delete('workerqueue', ['id' => $queue["id"]]);
389 self::$db_duration = (microtime(true) - $stamp);
390 self::$db_duration_write += (microtime(true) - $stamp);
397 * Execute a function from the queue
399 * @param array $queue Workerqueue entry
400 * @param string $funcname name of the function
401 * @param array $argv Array of values to be passed to the function
402 * @param boolean $method_call boolean
404 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
406 private static function execFunction($queue, $funcname, $argv, $method_call)
410 Logger::enableWorker($funcname);
412 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
414 $stamp = (float)microtime(true);
416 // We use the callstack here to analyze the performance of executed worker entries.
417 // For this reason the variables have to be initialized.
418 DI::profiler()->reset();
422 $up_duration = microtime(true) - self::$up_start;
424 // Reset global data to avoid interferences
427 // Set the workerLogger as new default logger
429 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
431 $funcname($argv, count($argv));
434 Logger::disableWorker();
438 $duration = (microtime(true) - $stamp);
440 /* With these values we can analyze how effective the worker is.
441 * The database and rest time should be low since this is the unproductive time.
442 * The execution time is the productive time.
443 * By changing parameters like the maximum number of workers we can check the effectivness.
445 $dbtotal = round(self::$db_duration, 2);
446 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
447 $dbcount = round(self::$db_duration_count, 2);
448 $dbstat = round(self::$db_duration_stat, 2);
449 $dbwrite = round(self::$db_duration_write, 2);
450 $dblock = round(self::$lock_duration, 2);
451 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
452 $exec = round($duration, 2);
454 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
456 self::$up_start = microtime(true);
457 self::$db_duration = 0;
458 self::$db_duration_count = 0;
459 self::$db_duration_stat = 0;
460 self::$db_duration_write = 0;
461 self::$lock_duration = 0;
463 if ($duration > 3600) {
464 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
465 } elseif ($duration > 600) {
466 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
467 } elseif ($duration > 300) {
468 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
469 } elseif ($duration > 120) {
470 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
473 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
475 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
477 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
480 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
486 * Checks if the number of database connections has reached a critical limit.
488 * @return bool Are more than 3/4 of the maximum connections used?
489 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
491 private static function maxConnectionsReached()
493 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
494 $max = DI::config()->get("system", "max_connections");
496 // Fetch the percentage level where the worker will get active
497 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
500 // the maximum number of possible user connections can be a system variable
501 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
502 if (DBA::isResult($r)) {
505 // Or it can be granted. This overrides the system variable
506 $stamp = (float)microtime(true);
507 $r = DBA::p('SHOW GRANTS');
508 self::$db_duration += (microtime(true) - $stamp);
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 $stamp = (float)microtime(true);
524 $r = DBA::p('SHOW PROCESSLIST');
525 self::$db_duration += (microtime(true) - $stamp);
526 $used = DBA::numRows($r);
529 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
531 $level = ($used / $max) * 100;
533 if ($level >= $maxlevel) {
534 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
539 // We will now check for the system values.
540 // This limit could be reached although the user limits are fine.
541 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
542 if (!DBA::isResult($r)) {
545 $max = intval($r["Value"]);
549 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
550 if (!DBA::isResult($r)) {
553 $used = intval($r["Value"]);
557 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
559 $level = $used / $max * 100;
561 if ($level < $maxlevel) {
564 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
569 * fix the queue entry if the worker process died
574 private static function killStaleWorkers()
576 $stamp = (float)microtime(true);
577 $entries = DBA::select(
579 ['id', 'pid', 'executed', 'priority', 'parameter'],
580 ['NOT `done` AND `pid` != 0'],
581 ['order' => ['priority', 'created']]
583 self::$db_duration += (microtime(true) - $stamp);
585 while ($entry = DBA::fetch($entries)) {
586 if (!posix_kill($entry["pid"], 0)) {
587 $stamp = (float)microtime(true);
590 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
591 ['id' => $entry["id"]]
593 self::$db_duration += (microtime(true) - $stamp);
594 self::$db_duration_write += (microtime(true) - $stamp);
596 // Kill long running processes
597 // Check if the priority is in a valid range
598 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
599 $entry["priority"] = PRIORITY_MEDIUM;
602 // Define the maximum durations
603 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
604 $max_duration = $max_duration_defaults[$entry["priority"]];
606 $argv = json_decode($entry["parameter"], true);
611 $argv[0] = basename($argv[0]);
613 // How long is the process already running?
614 $duration = (time() - strtotime($entry["executed"])) / 60;
615 if ($duration > $max_duration) {
616 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
617 posix_kill($entry["pid"], SIGTERM);
619 // We killed the stale process.
620 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
621 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
622 $new_priority = $entry["priority"];
623 if ($entry["priority"] == PRIORITY_HIGH) {
624 $new_priority = PRIORITY_MEDIUM;
625 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
626 $new_priority = PRIORITY_LOW;
627 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
628 $new_priority = PRIORITY_NEGLIGIBLE;
630 $stamp = (float)microtime(true);
633 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
634 ['id' => $entry["id"]]
636 self::$db_duration += (microtime(true) - $stamp);
637 self::$db_duration_write += (microtime(true) - $stamp);
639 Logger::info('Process runtime is okay', ['pid' => $entry["pid"], 'duration' => $duration, 'max' => $max_duration, 'command' => substr(json_encode($argv), 0, 50)]);
643 DBA::close($entries);
647 * Checks if the number of active workers exceeds the given limits
649 * @return bool Are there too much workers running?
650 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
652 private static function tooMuchWorkers()
654 $queues = DI::config()->get("system", "worker_queues", 10);
656 $maxqueues = $queues;
658 $active = self::activeWorkers();
660 // Decrease the number of workers at higher load
661 $load = System::currentLoad();
663 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
665 /* Default exponent 3 causes queues to rapidly decrease as load increases.
666 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
667 * For some environments, this rapid decrease is not needed.
668 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
670 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
671 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
672 $queues = intval(ceil($slope * $maxqueues));
676 if (DI::config()->get('system', 'worker_jpm')) {
677 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
678 $jobs_per_minute = [];
679 foreach ($intervals as $interval) {
680 if ($interval == 0) {
683 $interval = (int)$interval;
686 $stamp = (float)microtime(true);
687 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
688 self::$db_duration += (microtime(true) - $stamp);
689 self::$db_duration_stat += (microtime(true) - $stamp);
690 if ($job = DBA::fetch($jobs)) {
691 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
695 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
698 // Create a list of queue entries grouped by their priority
699 $listitem = [0 => ''];
701 $idle_workers = $active;
703 $deferred = self::deferredEntries();
705 if (DI::config()->get('system', 'worker_debug')) {
706 $waiting_processes = 0;
707 // Now adding all processes with workerqueue entries
708 $stamp = (float)microtime(true);
709 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
710 self::$db_duration += (microtime(true) - $stamp);
711 self::$db_duration_stat += (microtime(true) - $stamp);
712 while ($entry = DBA::fetch($jobs)) {
713 $stamp = (float)microtime(true);
714 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
715 self::$db_duration += (microtime(true) - $stamp);
716 self::$db_duration_stat += (microtime(true) - $stamp);
717 if ($process = DBA::fetch($processes)) {
718 $idle_workers -= $process["running"];
719 $waiting_processes += $entry["entries"];
720 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
722 DBA::close($processes);
726 $waiting_processes = self::totalEntries();
727 $stamp = (float)microtime(true);
728 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
729 self::$db_duration += (microtime(true) - $stamp);
730 self::$db_duration_stat += (microtime(true) - $stamp);
732 while ($entry = DBA::fetch($jobs)) {
733 $idle_workers -= $entry["running"];
734 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
739 $waiting_processes -= $deferred;
741 $listitem[0] = "0:" . max(0, $idle_workers);
743 $processlist .= ' ('.implode(', ', $listitem).')';
745 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
746 $top_priority = self::highestPriority();
747 $high_running = self::processWithPriorityActive($top_priority);
749 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
750 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
751 $queues = $active + 1;
755 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
757 // Are there fewer workers running as possible? Then fork a new one.
758 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
759 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
760 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
761 self::IPCSetJobState(true);
768 // if there are too much worker, we don't spawn a new one.
769 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
770 self::IPCSetJobState(false);
773 return $active > $queues;
777 * Returns the number of active worker processes
779 * @return integer Number of active worker processes
782 private static function activeWorkers()
784 $stamp = (float)microtime(true);
785 $count = DBA::count('process', ['command' => 'Worker.php']);
786 self::$db_duration += (microtime(true) - $stamp);
791 * Returns the number of active worker processes
793 * @return array List of worker process ids
796 private static function getWorkerPIDList()
799 $stamp = (float)microtime(true);
801 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
802 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
803 GROUP BY `process`.`pid`");
804 while ($queue = DBA::fetch($queues)) {
805 $ids[$queue['pid']] = $queue['entries'];
809 self::$db_duration += (microtime(true) - $stamp);
814 * Returns waiting jobs for the current process id
816 * @return array waiting workerqueue jobs
819 private static function getWaitingJobForPID()
821 $stamp = (float)microtime(true);
822 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
823 self::$db_duration += (microtime(true) - $stamp);
824 if (DBA::isResult($r)) {
825 return DBA::toArray($r);
833 * Returns the next jobs that should be executed
835 * @return array array with next jobs
838 private static function nextProcess(int $limit)
840 $priority = self::nextPriority();
841 if (empty($priority)) {
842 Logger::info('No tasks found');
847 $stamp = (float)microtime(true);
848 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
849 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
850 self::$db_duration += (microtime(true) - $stamp);
851 while ($task = DBA::fetch($tasks)) {
852 $ids[] = $task['id'];
853 // Only continue that loop while we are storing commands that can be processed quickly
854 $command = json_decode($task['parameter'])[0];
855 if (!in_array($command, self::FAST_COMMANDS)) {
861 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
866 * Returns the priority of the next workerqueue job
868 * @return string priority
871 private static function nextPriority()
874 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
875 foreach ($priorities as $priority) {
876 $stamp = (float)microtime(true);
877 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
878 $waiting[$priority] = true;
880 self::$db_duration += (microtime(true) - $stamp);
883 if (!empty($waiting[PRIORITY_CRITICAL])) {
884 return PRIORITY_CRITICAL;
889 $stamp = (float)microtime(true);
890 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
891 self::$db_duration += (microtime(true) - $stamp);
892 while ($process = DBA::fetch($processes)) {
893 $running[$process['priority']] = $process['running'];
894 $running_total += $process['running'];
896 DBA::close($processes);
898 foreach ($priorities as $priority) {
899 if (!empty($waiting[$priority]) && empty($running[$priority])) {
900 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
905 $active = max(self::activeWorkers(), $running_total);
906 $priorities = max(count($waiting), count($running));
910 for ($i = 1; $i <= $priorities; ++$i) {
911 $total += pow($i, $exponent);
915 for ($i = 1; $i <= $priorities; ++$i) {
916 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
920 foreach ($running as $priority => $workers) {
921 if ($workers < $limit[$i++]) {
922 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
927 if (!empty($waiting)) {
928 $priority = array_keys($waiting)[0];
929 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
937 * Find and claim the next worker process for us
939 * @return boolean Have we found something?
940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
942 private static function findWorkerProcesses()
944 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
946 if (DI::config()->get('system', 'worker_multiple_fetch')) {
948 foreach (self::getWorkerPIDList() as $pid => $count) {
949 if ($count <= $fetch_limit) {
956 $limit = $fetch_limit * count($pids);
958 $pids = [getmypid()];
959 $limit = $fetch_limit;
962 $ids = self::nextProcess($limit);
963 $limit -= count($ids);
965 // If there is not enough results we check without priority limit
967 $stamp = (float)microtime(true);
968 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
969 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
970 self::$db_duration += (microtime(true) - $stamp);
972 while ($task = DBA::fetch($tasks)) {
973 $ids[] = $task['id'];
974 // Only continue that loop while we are storing commands that can be processed quickly
975 $command = json_decode($task['parameter'])[0];
976 if (!in_array($command, self::FAST_COMMANDS)) {
987 // Assign the task ids to the workers
989 foreach (array_unique($ids) as $id) {
994 $worker[$pid][] = $id;
997 $stamp = (float)microtime(true);
998 foreach ($worker as $worker_pid => $worker_ids) {
999 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1000 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1001 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1003 self::$db_duration += (microtime(true) - $stamp);
1004 self::$db_duration_write += (microtime(true) - $stamp);
1008 * Returns the next worker process
1010 * @return array worker processes
1011 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1013 public static function workerProcess()
1015 // There can already be jobs for us in the queue.
1016 $waiting = self::getWaitingJobForPID();
1017 if (!empty($waiting)) {
1021 $stamp = (float)microtime(true);
1022 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1025 self::$lock_duration += (microtime(true) - $stamp);
1027 self::findWorkerProcesses();
1029 DI::lock()->release(self::LOCK_PROCESS);
1031 return self::getWaitingJobForPID();
1035 * Removes a workerqueue entry from the current process
1038 * @throws \Exception
1040 public static function unclaimProcess()
1042 $mypid = getmypid();
1044 $stamp = (float)microtime(true);
1045 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1046 self::$db_duration += (microtime(true) - $stamp);
1047 self::$db_duration_write += (microtime(true) - $stamp);
1051 * Call the front end worker
1054 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1056 public static function callWorker()
1058 if (!DI::config()->get("system", "frontend_worker")) {
1062 $url = DI::baseUrl() . '/worker';
1063 DI::httpRequest()->fetch($url, false, 1);
1067 * Call the front end worker if there aren't any active
1070 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1072 public static function executeIfIdle()
1074 if (!DI::config()->get("system", "frontend_worker")) {
1078 // Do we have "proc_open"? Then we can fork the worker
1079 if (function_exists("proc_open")) {
1080 // When was the last time that we called the worker?
1081 // Less than one minute? Then we quit
1082 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1086 DI::config()->set("system", "worker_started", time());
1088 // Do we have enough running workers? Then we quit here.
1089 if (self::tooMuchWorkers()) {
1090 // Cleaning dead processes
1091 self::killStaleWorkers();
1092 Process::deleteInactive();
1099 Logger::info('Call worker');
1100 self::spawnWorker();
1104 // We cannot execute background processes.
1105 // We now run the processes from the frontend.
1106 // This won't work with long running processes.
1109 self::clearProcesses();
1111 $workers = self::activeWorkers();
1113 if ($workers == 0) {
1119 * Removes long running worker processes
1122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1124 public static function clearProcesses()
1126 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1128 /// @todo We should clean up the corresponding workerqueue entries as well
1129 $stamp = (float)microtime(true);
1130 $condition = ["`created` < ? AND `command` = 'worker.php'",
1131 DateTimeFormat::utc("now - ".$timeout." minutes")];
1132 DBA::delete('process', $condition);
1133 self::$db_duration = (microtime(true) - $stamp);
1134 self::$db_duration_write += (microtime(true) - $stamp);
1138 * Runs the cron processes
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1143 private static function runCron()
1145 Logger::info('Add cron entries');
1147 // Check for spooled items
1148 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1150 // Run the cron job that calls all other jobs
1151 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1153 // Cleaning dead processes
1154 self::killStaleWorkers();
1158 * Spawns a new worker
1160 * @param bool $do_cron
1162 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1164 public static function spawnWorker($do_cron = false)
1166 $command = 'bin/worker.php';
1168 $args = ['no_cron' => !$do_cron];
1171 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), $a->getBasePath());
1172 $process->run($command, $args);
1174 // after spawning we have to remove the flag.
1175 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1176 self::IPCSetJobState(false);
1181 * Adds tasks to the worker queue
1183 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1185 * next args are passed as $cmd command line
1186 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1187 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1189 * @return boolean "false" if worker queue entry already existed or there had been an error
1190 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1191 * @note $cmd and string args are surrounded with ""
1197 public static function add($cmd)
1199 $args = func_get_args();
1201 if (!count($args)) {
1205 $arr = ['args' => $args, 'run_cmd' => true];
1207 Hook::callAll("proc_run", $arr);
1208 if (!$arr['run_cmd'] || !count($args)) {
1212 $priority = PRIORITY_MEDIUM;
1213 // Don't fork from frontend tasks by default
1214 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1215 $created = DateTimeFormat::utcNow();
1216 $force_priority = false;
1218 $run_parameter = array_shift($args);
1220 if (is_int($run_parameter)) {
1221 $priority = $run_parameter;
1222 } elseif (is_array($run_parameter)) {
1223 if (isset($run_parameter['priority'])) {
1224 $priority = $run_parameter['priority'];
1226 if (isset($run_parameter['created'])) {
1227 $created = $run_parameter['created'];
1229 if (isset($run_parameter['dont_fork'])) {
1230 $dont_fork = $run_parameter['dont_fork'];
1232 if (isset($run_parameter['force_priority'])) {
1233 $force_priority = $run_parameter['force_priority'];
1237 $parameters = json_encode($args);
1238 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1241 // Quit if there was a database error - a precaution for the update process to 3.5.3
1242 if (DBA::errorNo() != 0) {
1247 $added = DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1251 } elseif ($force_priority) {
1252 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1255 // Should we quit and wait for the worker to be called as a cronjob?
1260 // If there is a lock then we don't have to check for too much worker
1261 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1265 // If there are already enough workers running, don't fork another one
1266 $quit = self::tooMuchWorkers();
1267 DI::lock()->release(self::LOCK_WORKER);
1273 // We tell the daemon that a new job entry exists
1274 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1275 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1279 // Now call the worker to execute the jobs that we just added to the queue
1280 self::spawnWorker();
1286 * Returns the next retrial level for worker jobs.
1287 * This function will skip levels when jobs are older.
1289 * @param array $queue Worker queue entry
1290 * @param integer $max_level maximum retrial level
1291 * @return integer the next retrial level value
1293 private static function getNextRetrial($queue, $max_level)
1295 $created = strtotime($queue['created']);
1296 $retrial_time = time() - $created;
1298 $new_retrial = $queue['retrial'] + 1;
1300 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1301 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1303 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1304 $new_retrial = $retrial;
1307 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1308 return $new_retrial;
1312 * Defers the current worker entry
1314 * @return boolean had the entry been deferred?
1316 public static function defer()
1318 if (empty(DI::app()->queue)) {
1322 $queue = DI::app()->queue;
1324 $retrial = $queue['retrial'];
1326 $priority = $queue['priority'];
1328 $max_level = DI::config()->get('system', 'worker_defer_limit');
1330 $new_retrial = self::getNextRetrial($queue, $max_level);
1332 if ($new_retrial > $max_level) {
1333 Logger::info('The task exceeded the maximum retry count', ['id' => $id, 'created' => $queue['created'], 'old_prio' => $queue['priority'], 'old_retrial' => $queue['retrial'], 'max_level' => $max_level, 'retrial' => $new_retrial]);
1337 // Calculate the delay until the next trial
1338 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1339 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1341 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1342 $priority = PRIORITY_MEDIUM;
1343 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1344 $priority = PRIORITY_LOW;
1345 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1346 $priority = PRIORITY_NEGLIGIBLE;
1349 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1351 $stamp = (float)microtime(true);
1352 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1353 DBA::update('workerqueue', $fields, ['id' => $id]);
1354 self::$db_duration += (microtime(true) - $stamp);
1355 self::$db_duration_write += (microtime(true) - $stamp);
1361 * Log active processes into the "process" table
1363 public static function startProcess()
1365 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1367 $command = basename($trace[0]['file']);
1369 Process::deleteInactive();
1371 Process::insert($command);
1375 * Remove the active process from the "process" table
1378 * @throws \Exception
1380 public static function endProcess()
1382 return Process::deleteByPid();
1386 * Set the flag if some job is waiting
1388 * @param boolean $jobs Is there a waiting job?
1389 * @throws \Exception
1391 public static function IPCSetJobState($jobs)
1393 $stamp = (float)microtime(true);
1394 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1395 self::$db_duration += (microtime(true) - $stamp);
1396 self::$db_duration_write += (microtime(true) - $stamp);
1400 * Checks if some worker job waits to be executed
1403 * @throws \Exception
1405 public static function IPCJobsExists()
1407 $stamp = (float)microtime(true);
1408 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1409 self::$db_duration += (microtime(true) - $stamp);
1411 // When we don't have a row, no job is running
1412 if (!DBA::isResult($row)) {
1416 return (bool)$row['jobs'];