3 * @copyright Copyright (C) 2010-2023, the Friendica project
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;
24 use Friendica\Core\Worker\Entity\Process;
25 use Friendica\Database\DBA;
27 use Friendica\Util\DateTimeFormat;
30 * Contains the class for the worker background job processing
37 * Process priority for the worker
40 const PRIORITY_UNDEFINED = 0;
41 const PRIORITY_CRITICAL = 10;
42 const PRIORITY_HIGH = 20;
43 const PRIORITY_MEDIUM = 30;
44 const PRIORITY_LOW = 40;
45 const PRIORITY_NEGLIGIBLE = 50;
46 const PRIORITIES = [self::PRIORITY_CRITICAL, self::PRIORITY_HIGH, self::PRIORITY_MEDIUM, self::PRIORITY_LOW, self::PRIORITY_NEGLIGIBLE];
49 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
50 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
51 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
52 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
54 const FAST_COMMANDS = ['APDelivery', 'Delivery'];
56 const LOCK_PROCESS = 'worker_process';
57 const LOCK_WORKER = 'worker';
59 private static $up_start;
60 private static $db_duration = 0;
61 private static $db_duration_count = 0;
62 private static $db_duration_write = 0;
63 private static $db_duration_stat = 0;
64 private static $lock_duration = 0;
65 private static $last_update;
66 private static $state;
68 private static $process;
71 * Processes the tasks that are in the workerqueue table
73 * @param boolean $run_cron Should the cron processes be executed?
74 * @param Process $process The current running process
76 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
78 public static function processQueue(bool $run_cron, Process $process)
80 self::$up_start = microtime(true);
82 // At first check the maximum load. We shouldn't continue with a high load
83 if (DI::system()->isMaxLoadReached()) {
84 Logger::notice('Pre check: maximum load reached, quitting.');
88 // We now start the process. This is done after the load check since this could increase the load.
89 self::$process = $process;
91 // Kill stale processes every 5 minutes
92 $last_cleanup = DI::keyValue()->get('worker_last_cleaned') ?? 0;
93 if (time() > ($last_cleanup + 300)) {
94 DI::keyValue()->set( 'worker_last_cleaned', time());
95 Worker\Cron::killStaleWorkers();
98 // Check if the system is ready
99 if (!self::isReady()) {
103 // Now we start additional cron processes if we should do so
108 $last_check = $starttime = time();
109 self::$state = self::STATE_STARTUP;
111 // We fetch the next queue entry that is about to be executed
112 while ($r = self::workerProcess()) {
113 if (Worker\IPC::JobsExists(getmypid())) {
114 Worker\IPC::DeleteJobState(getmypid());
117 // Don't refetch when a worker fetches tasks for multiple workers
118 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
119 foreach ($r as $entry) {
120 // The work will be done
121 if (!self::execute($entry)) {
122 Logger::warning('Process execution failed, quitting.', ['entry' => $entry]);
126 // Trying to fetch new processes - but only once when successful
127 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
128 self::findWorkerProcesses();
129 DI::lock()->release(self::LOCK_PROCESS);
130 self::$state = self::STATE_REFETCH;
133 self::$state = self::STATE_SHORT_LOOP;
137 // To avoid the quitting of multiple workers only one worker at a time will execute the check
138 if ((time() > $last_check + 5) && !self::getWaitingJobForPID()) {
139 self::$state = self::STATE_LONG_LOOP;
141 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
142 // Count active workers and compare them with a maximum value that depends on the load
143 if (self::tooMuchWorkers()) {
144 Logger::info('Active worker limit reached, quitting.');
145 DI::lock()->release(self::LOCK_WORKER);
150 if (DI::system()->isMinMemoryReached()) {
151 Logger::warning('Memory limit reached, quitting.');
152 DI::lock()->release(self::LOCK_WORKER);
155 DI::lock()->release(self::LOCK_WORKER);
157 $last_check = time();
160 // Quit the worker once every cron interval
161 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60)) && !self::systemLimitReached()) {
162 Logger::info('Process lifetime reached, respawning.');
163 self::unclaimProcess($process);
164 if (Worker\Daemon::isMode()) {
165 Worker\IPC::SetJobState(true);
173 // Cleaning up. Possibly not needed, but it doesn't harm anything.
174 if (Worker\Daemon::isMode()) {
175 Worker\IPC::SetJobState(false);
177 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
181 * Checks if the system is ready.
183 * Several system parameters like memory, connections and processes are checked.
187 public static function isReady(): bool
189 // Count active workers and compare them with a maximum value that depends on the load
190 if (self::tooMuchWorkers()) {
191 Logger::info('Active worker limit reached, quitting.');
195 // Do we have too few memory?
196 if (DI::system()->isMinMemoryReached()) {
197 Logger::warning('Memory limit reached, quitting.');
201 // Possibly there are too much database connections
202 if (self::maxConnectionsReached()) {
203 Logger::warning('Maximum connections reached, quitting.');
207 // Possibly there are too much database processes that block the system
208 if (DI::system()->isMaxProcessesReached()) {
209 Logger::warning('Maximum processes reached, quitting.');
217 * Check if non executed tasks do exist in the worker queue
219 * @return boolean Returns "true" if tasks are existing
222 public static function entriesExists(): bool
224 $stamp = (float)microtime(true);
225 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
226 self::$db_duration += (microtime(true) - $stamp);
231 * Returns the number of deferred entries in the worker queue
233 * @return integer Number of deferred entries in the worker queue
236 private static function deferredEntries(): int
238 $stamp = (float)microtime(true);
239 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
240 self::$db_duration += (microtime(true) - $stamp);
241 self::$db_duration_count += (microtime(true) - $stamp);
246 * Returns the number of non executed entries in the worker queue
248 * @return integer Number of non executed entries in the worker queue
251 private static function totalEntries(): int
253 $stamp = (float)microtime(true);
254 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
255 self::$db_duration += (microtime(true) - $stamp);
256 self::$db_duration_count += (microtime(true) - $stamp);
261 * Returns the highest priority in the worker queue that isn't executed
263 * @return integer Number of active worker processes
266 private static function highestPriority(): int
268 $stamp = (float)microtime(true);
269 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
270 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
271 self::$db_duration += (microtime(true) - $stamp);
272 if (DBA::isResult($workerqueue)) {
273 return $workerqueue['priority'];
280 * Returns if a process with the given priority is running
282 * @param integer $priority The priority that should be checked
284 * @return integer Is there a process running with that priority?
287 private static function processWithPriorityActive(int $priority): int
289 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
290 return DBA::exists('workerqueue', $condition);
294 * Checks if the given file is valid to be included
299 private static function validateInclude(&$file): bool
303 $file = realpath($file);
305 if (strpos($file, getcwd()) !== 0) {
309 $file = str_replace(getcwd() . '/', '', $file, $count);
314 if ($orig_file !== $file) {
318 return (strpos($file, 'addon/') === 0);
322 * Execute a worker entry
324 * @param array $queue Workerqueue entry
326 * @return boolean "true" if further processing should be stopped
327 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
329 public static function execute(array $queue): bool
333 // Quit when in maintenance
334 if (DI::config()->get('system', 'maintenance', false)) {
335 Logger::notice('Maintenance mode - quit process', ['pid' => $mypid]);
339 // Constantly check the number of parallel database processes
340 if (DI::system()->isMaxProcessesReached()) {
341 Logger::warning('Max processes reached for process', ['pid' => $mypid]);
345 // Constantly check the number of available database connections to let the frontend be accessible at any time
346 if (self::maxConnectionsReached()) {
347 Logger::warning('Max connection reached for process', ['pid' => $mypid]);
351 $argv = json_decode($queue['parameter'], true);
352 if (!is_array($argv)) {
356 if (!empty($queue['command'])) {
357 array_unshift($argv, $queue['command']);
361 Logger::warning('Parameter is empty', ['queue' => $queue]);
365 // Check for existence and validity of the include file
368 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
369 // We constantly update the "executed" date every minute to avoid being killed too soon
370 if (!isset(self::$last_update)) {
371 self::$last_update = strtotime($queue['executed']);
374 $age = (time() - self::$last_update) / 60;
375 self::$last_update = time();
378 $stamp = (float)microtime(true);
379 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
380 self::$db_duration += (microtime(true) - $stamp);
381 self::$db_duration_write += (microtime(true) - $stamp);
386 self::execFunction($queue, $include, $argv, true);
388 $stamp = (float)microtime(true);
389 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
390 if (DBA::update('workerqueue', ['done' => true], $condition)) {
391 DI::keyValue()->set('last_worker_execution', DateTimeFormat::utcNow());
393 self::$db_duration = (microtime(true) - $stamp);
394 self::$db_duration_write += (microtime(true) - $stamp);
399 if (!self::validateInclude($include)) {
400 Logger::warning('Include file is not valid', ['file' => $argv[0]]);
401 $stamp = (float)microtime(true);
402 DBA::delete('workerqueue', ['id' => $queue['id']]);
403 self::$db_duration = (microtime(true) - $stamp);
404 self::$db_duration_write += (microtime(true) - $stamp);
408 require_once $include;
410 $funcname = str_replace('.php', '', basename($argv[0])) .'_run';
412 if (function_exists($funcname)) {
413 // We constantly update the "executed" date every minute to avoid being killed too soon
414 if (!isset(self::$last_update)) {
415 self::$last_update = strtotime($queue['executed']);
418 $age = (time() - self::$last_update) / 60;
419 self::$last_update = time();
422 $stamp = (float)microtime(true);
423 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
424 self::$db_duration += (microtime(true) - $stamp);
425 self::$db_duration_write += (microtime(true) - $stamp);
428 self::execFunction($queue, $funcname, $argv, false);
430 $stamp = (float)microtime(true);
431 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue['id']])) {
432 DI::keyValue()->set('last_worker_execution', DateTimeFormat::utcNow());
434 self::$db_duration = (microtime(true) - $stamp);
435 self::$db_duration_write += (microtime(true) - $stamp);
437 Logger::warning('Function does not exist', ['function' => $funcname]);
438 $stamp = (float)microtime(true);
439 DBA::delete('workerqueue', ['id' => $queue['id']]);
440 self::$db_duration = (microtime(true) - $stamp);
441 self::$db_duration_write += (microtime(true) - $stamp);
448 * Checks if system limits are reached.
452 private static function systemLimitReached(): bool
454 $load_cooldown = DI::config()->get('system', 'worker_load_cooldown');
455 $processes_cooldown = DI::config()->get('system', 'worker_processes_cooldown');
457 if ($load_cooldown == 0) {
458 $load_cooldown = DI::config()->get('system', 'maxloadavg');
461 if (($load_cooldown == 0) && ($processes_cooldown == 0)) {
465 $load = System::getLoadAvg($processes_cooldown != 0);
470 if (($load_cooldown > 0) && ($load['average1'] > $load_cooldown)) {
474 if (($processes_cooldown > 0) && ($load['scheduled'] > $processes_cooldown)) {
482 * Slow the execution down if the system load is too high
486 public static function coolDown()
488 $cooldown = DI::config()->get('system', 'worker_cooldown', 0);
490 Logger::debug('Wait for cooldown.', ['cooldown' => $cooldown]);
492 usleep($cooldown * 1000000);
498 $load_cooldown = DI::config()->get('system', 'worker_load_cooldown');
499 $processes_cooldown = DI::config()->get('system', 'worker_processes_cooldown');
501 if ($load_cooldown == 0) {
502 $load_cooldown = DI::config()->get('system', 'maxloadavg');
505 if (($load_cooldown == 0) && ($processes_cooldown == 0)) {
511 while ($load = System::getLoadAvg($processes_cooldown != 0)) {
512 if (($load_cooldown > 0) && ($load['average1'] > $load_cooldown)) {
514 Logger::info('Load induced pre execution cooldown.', ['max' => $load_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
520 if (($processes_cooldown > 0) && ($load['scheduled'] > $processes_cooldown)) {
522 Logger::info('Process induced pre execution cooldown.', ['max' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
532 Logger::info('Cooldown ended.', ['max-load' => $load_cooldown, 'max-processes' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
537 * Execute a function from the queue
539 * @param array $queue Workerqueue entry
540 * @param string $funcname name of the function
541 * @param array $argv Array of values to be passed to the function
542 * @param boolean $method_call boolean
544 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
546 private static function execFunction(array $queue, string $funcname, array $argv, bool $method_call)
552 Logger::enableWorker($funcname);
554 Logger::info('Process start.', ['priority' => $queue['priority'], 'id' => $queue['id']]);
556 $stamp = (float)microtime(true);
558 // We use the callstack here to analyze the performance of executed worker entries.
559 // For this reason the variables have to be initialized.
560 DI::profiler()->reset();
562 $a->setQueue($queue);
564 $up_duration = microtime(true) - self::$up_start;
566 // Reset global data to avoid interferences
569 // Set the workerLogger as new default logger
572 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
573 } catch (\TypeError $e) {
574 // No need to defer a worker queue entry if the arguments are invalid
575 Logger::notice('Wrong worker arguments', ['class' => $funcname, 'argv' => $argv, 'queue' => $queue, 'message' => $e->getMessage()]);
576 } catch (\Throwable $e) {
577 Logger::error('Uncaught exception in worker execution', ['class' => get_class($e), 'message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile() . ':' . $e->getLine(), 'trace' => $e->getTraceAsString(), 'previous' => $e->getPrevious()]);
581 $funcname($argv, count($argv));
584 Logger::disableWorker();
588 $duration = (microtime(true) - $stamp);
590 /* With these values we can analyze how effective the worker is.
591 * The database and rest time should be low since this is the unproductive time.
592 * The execution time is the productive time.
593 * By changing parameters like the maximum number of workers we can check the effectiveness.
595 $dbtotal = round(self::$db_duration, 2);
596 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
597 $dbcount = round(self::$db_duration_count, 2);
598 $dbstat = round(self::$db_duration_stat, 2);
599 $dbwrite = round(self::$db_duration_write, 2);
600 $dblock = round(self::$lock_duration, 2);
601 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
602 $exec = round($duration, 2);
604 Logger::info('Performance:', ['function' => $funcname, 'state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
608 self::$up_start = microtime(true);
609 self::$db_duration = 0;
610 self::$db_duration_count = 0;
611 self::$db_duration_stat = 0;
612 self::$db_duration_write = 0;
613 self::$lock_duration = 0;
615 if ($duration > 3600) {
616 Logger::info('Longer than 1 hour.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
617 } elseif ($duration > 600) {
618 Logger::info('Longer than 10 minutes.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
619 } elseif ($duration > 300) {
620 Logger::info('Longer than 5 minutes.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
621 } elseif ($duration > 120) {
622 Logger::info('Longer than 2 minutes.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
625 Logger::info('Process done.', ['function' => $funcname, 'priority' => $queue['priority'], 'retrial' => $queue['retrial'], 'id' => $queue['id'], 'duration' => round($duration, 3)]);
627 DI::profiler()->saveLog(DI::logger(), 'ID ' . $queue['id'] . ': ' . $funcname);
631 * Checks if the number of database connections has reached a critical limit.
633 * @return bool Are more than 3/4 of the maximum connections used?
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
636 private static function maxConnectionsReached(): bool
638 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
639 $max = DI::config()->get('system', 'max_connections');
641 // Fetch the percentage level where the worker will get active
642 $maxlevel = DI::config()->get('system', 'max_connections_level', 75);
645 // the maximum number of possible user connections can be a system variable
646 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
647 if (DBA::isResult($r)) {
650 // Or it can be granted. This overrides the system variable
651 $stamp = (float)microtime(true);
652 $r = DBA::p('SHOW GRANTS');
653 self::$db_duration += (microtime(true) - $stamp);
654 while ($grants = DBA::fetch($r)) {
655 $grant = array_pop($grants);
656 if (stristr($grant, "GRANT USAGE ON")) {
657 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
665 $stamp = (float)microtime(true);
668 $data = DBA::p("SHOW PROCESSLIST");
669 while ($row = DBA::fetch($data)) {
670 if ($row['Command'] != 'Sleep') {
677 self::$db_duration += (microtime(true) - $stamp);
679 // If $max is set we will use the processlist to determine the current number of connections
680 // The processlist only shows entries of the current user
682 Logger::info('Connection usage (user values)', ['working' => $used, 'sleeping' => $sleep, 'max' => $max]);
684 $level = ($used / $max) * 100;
686 if ($level >= $maxlevel) {
687 Logger::warning('Maximum level (' . $maxlevel . '%) of user connections reached: ' . $used .'/' . $max);
692 // We will now check for the system values.
693 // This limit could be reached although the user limits are fine.
694 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
695 if (!DBA::isResult($r)) {
698 $max = intval($r['Value']);
702 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
703 if (!DBA::isResult($r)) {
706 $used = max($used, intval($r['Value'])) - $sleep;
710 Logger::info('Connection usage (system values)', ['working' => $used, 'sleeping' => $sleep, 'max' => $max]);
712 $level = $used / $max * 100;
714 if ($level < $maxlevel) {
717 Logger::warning('Maximum level (' . $level . '%) of system connections reached: ' . $used . '/' . $max);
723 * Checks if the number of active workers exceeds the given limits
725 * @return bool Are there too much workers running?
726 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
728 private static function tooMuchWorkers(): bool
730 $queues = DI::config()->get('system', 'worker_queues', 10);
732 $maxqueues = $queues;
734 $active = self::activeWorkers();
736 // Decrease the number of workers at higher load
737 $load = System::currentLoad();
739 $maxsysload = intval(DI::config()->get('system', 'maxloadavg', 20));
741 /* Default exponent 3 causes queues to rapidly decrease as load increases.
742 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
743 * For some environments, this rapid decrease is not needed.
744 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
746 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
747 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
748 $queues = intval(ceil($slope * $maxqueues));
752 if (DI::config()->get('system', 'worker_jpm')) {
753 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
754 $jobs_per_minute = [];
755 foreach ($intervals as $interval) {
756 if ($interval == 0) {
759 $interval = (int)$interval;
762 $stamp = (float)microtime(true);
763 $jobs = DBA::count('workerqueue', ["`done` AND `executed` > ?", DateTimeFormat::utc('now - ' . $interval . ' minute')]);
764 self::$db_duration += (microtime(true) - $stamp);
765 self::$db_duration_stat += (microtime(true) - $stamp);
766 $jobs_per_minute[$interval] = number_format($jobs / $interval, 0);
768 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
771 // Create a list of queue entries grouped by their priority
772 $listitem = [0 => ''];
774 $idle_workers = $active;
776 $deferred = self::deferredEntries();
778 if (DI::config()->get('system', 'worker_debug')) {
779 $waiting_processes = 0;
780 // Now adding all processes with workerqueue entries
781 $stamp = (float)microtime(true);
782 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
783 self::$db_duration += (microtime(true) - $stamp);
784 self::$db_duration_stat += (microtime(true) - $stamp);
785 while ($entry = DBA::fetch($jobs)) {
786 $stamp = (float)microtime(true);
787 $running = DBA::count('workerqueue-view', ['priority' => $entry['priority']]);
788 self::$db_duration += (microtime(true) - $stamp);
789 self::$db_duration_stat += (microtime(true) - $stamp);
790 $idle_workers -= $running;
791 $waiting_processes += $entry['entries'];
792 $listitem[$entry['priority']] = $entry['priority'] . ':' . $running . '/' . $entry['entries'];
796 $waiting_processes = self::totalEntries();
797 $stamp = (float)microtime(true);
798 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
799 self::$db_duration += (microtime(true) - $stamp);
800 self::$db_duration_stat += (microtime(true) - $stamp);
802 while ($entry = DBA::fetch($jobs)) {
803 $idle_workers -= $entry['running'];
804 $listitem[$entry['priority']] = $entry['priority'] . ':' . $entry['running'];
809 $waiting_processes -= $deferred;
811 $listitem[0] = '0:' . max(0, $idle_workers);
813 $processlist .= ' ('.implode(', ', $listitem).')';
815 if (DI::config()->get('system', 'worker_fastlane', false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
816 $top_priority = self::highestPriority();
817 $high_running = self::processWithPriorityActive($top_priority);
819 if (!$high_running && ($top_priority > self::PRIORITY_UNDEFINED) && ($top_priority < self::PRIORITY_NEGLIGIBLE)) {
820 Logger::info('Jobs with a higher priority are waiting but none is executed. Open a fastlane.', ['priority' => $top_priority]);
821 $queues = $active + 1;
825 Logger::info('Load: ' . $load . '/' . $maxsysload . ' - processes: ' . $deferred . '/' . $active . '/' . $waiting_processes . $processlist . ' - maximum: ' . $queues . '/' . $maxqueues);
827 // Are there fewer workers running as possible? Then fork a new one.
828 if (!DI::config()->get('system', 'worker_dont_fork', false) && ($queues > ($active + 1)) && self::entriesExists() && !self::systemLimitReached()) {
829 Logger::info('There are fewer workers as possible, fork a new worker.', ['active' => $active, 'queues' => $queues]);
830 if (Worker\Daemon::isMode()) {
831 Worker\IPC::SetJobState(true);
838 // if there are too much worker, we don't spawn a new one.
839 if (Worker\Daemon::isMode() && ($active > $queues)) {
840 Worker\IPC::SetJobState(false);
843 return $active > $queues;
847 * Returns the number of active worker processes
849 * @return integer Number of active worker processes
852 private static function activeWorkers(): int
854 $stamp = (float)microtime(true);
855 $count = DI::process()->countCommand('Worker.php');
856 self::$db_duration += (microtime(true) - $stamp);
857 self::$db_duration_count += (microtime(true) - $stamp);
862 * Returns the number of active worker processes
864 * @return array List of worker process ids
867 private static function getWorkerPIDList(): array
870 $stamp = (float)microtime(true);
872 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
873 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
874 GROUP BY `process`.`pid`");
875 while ($queue = DBA::fetch($queues)) {
876 $ids[$queue['pid']] = $queue['entries'];
880 self::$db_duration += (microtime(true) - $stamp);
881 self::$db_duration_count += (microtime(true) - $stamp);
886 * Returns waiting jobs for the current process id
888 * @return array|bool waiting workerqueue jobs or FALSE on failure
891 private static function getWaitingJobForPID()
893 $stamp = (float)microtime(true);
894 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
895 self::$db_duration += (microtime(true) - $stamp);
896 if (DBA::isResult($r)) {
897 return DBA::toArray($r);
905 * Returns the next jobs that should be executed
907 * @return array array with next jobs
910 private static function nextProcess(int $limit): array
912 $priority = self::nextPriority();
913 if (empty($priority)) {
914 Logger::info('No tasks found');
919 $stamp = (float)microtime(true);
920 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
921 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
922 self::$db_duration += (microtime(true) - $stamp);
923 while ($task = DBA::fetch($tasks)) {
924 $ids[] = $task['id'];
925 // Only continue that loop while we are storing commands that can be processed quickly
926 if (!empty($task['command'])) {
927 $command = $task['command'];
929 $command = json_decode($task['parameter'])[0];
932 if (!in_array($command, self::FAST_COMMANDS)) {
938 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
943 * Returns the priority of the next workerqueue job
945 * @return string|bool priority or FALSE on failure
948 private static function nextPriority()
951 $priorities = [self::PRIORITY_CRITICAL, self::PRIORITY_HIGH, self::PRIORITY_MEDIUM, self::PRIORITY_LOW, self::PRIORITY_NEGLIGIBLE];
952 foreach ($priorities as $priority) {
953 $stamp = (float)microtime(true);
954 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
955 $waiting[$priority] = true;
957 self::$db_duration += (microtime(true) - $stamp);
960 if (!empty($waiting[self::PRIORITY_CRITICAL])) {
961 return self::PRIORITY_CRITICAL;
966 $stamp = (float)microtime(true);
967 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
968 self::$db_duration += (microtime(true) - $stamp);
969 while ($process = DBA::fetch($processes)) {
970 $running[$process['priority']] = $process['running'];
971 $running_total += $process['running'];
973 DBA::close($processes);
975 foreach ($priorities as $priority) {
976 if (!empty($waiting[$priority]) && empty($running[$priority])) {
977 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
982 $active = max(self::activeWorkers(), $running_total);
983 $priorities = max(count($waiting), count($running));
987 for ($i = 1; $i <= $priorities; ++$i) {
988 $total += pow($i, $exponent);
992 for ($i = 1; $i <= $priorities; ++$i) {
993 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
997 foreach ($running as $priority => $workers) {
998 if ($workers < $limit[$i++]) {
999 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
1004 if (!empty($waiting)) {
1005 $priority = array_keys($waiting)[0];
1006 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
1014 * Find and claim the next worker process for us
1017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1019 private static function findWorkerProcesses()
1021 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
1023 if (DI::config()->get('system', 'worker_multiple_fetch')) {
1025 foreach (self::getWorkerPIDList() as $pid => $count) {
1026 if ($count <= $fetch_limit) {
1033 $limit = $fetch_limit * count($pids);
1035 $pids = [getmypid()];
1036 $limit = $fetch_limit;
1039 $ids = self::nextProcess($limit);
1040 $limit -= count($ids);
1042 // If there is not enough results we check without priority limit
1044 $stamp = (float)microtime(true);
1045 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
1046 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
1047 self::$db_duration += (microtime(true) - $stamp);
1049 while ($task = DBA::fetch($tasks)) {
1050 $ids[] = $task['id'];
1051 // Only continue that loop while we are storing commands that can be processed quickly
1052 if (!empty($task['command'])) {
1053 $command = $task['command'];
1055 $command = json_decode($task['parameter'])[0];
1057 if (!in_array($command, self::FAST_COMMANDS)) {
1068 // Assign the task ids to the workers
1070 foreach (array_unique($ids) as $id) {
1073 $pid = reset($pids);
1075 $worker[$pid][] = $id;
1078 $stamp = (float)microtime(true);
1079 foreach ($worker as $worker_pid => $worker_ids) {
1080 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1081 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1082 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1084 self::$db_duration += (microtime(true) - $stamp);
1085 self::$db_duration_write += (microtime(true) - $stamp);
1089 * Returns the next worker process
1091 * @return array worker processes
1092 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1094 public static function workerProcess(): array
1096 // There can already be jobs for us in the queue.
1097 $waiting = self::getWaitingJobForPID();
1098 if (!empty($waiting)) {
1102 $stamp = (float)microtime(true);
1103 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1106 self::$lock_duration += (microtime(true) - $stamp);
1108 self::findWorkerProcesses();
1110 DI::lock()->release(self::LOCK_PROCESS);
1112 // Prevents "Return value of Friendica\Core\Worker::workerProcess() must be of the type array, bool returned"
1113 $process = self::getWaitingJobForPID();
1114 return (is_array($process) ? $process : []);
1118 * Removes a workerqueue entry from the current process
1120 * @param Process $process the process behind the workerqueue
1123 * @throws \Exception
1125 public static function unclaimProcess(Process $process)
1127 $stamp = (float)microtime(true);
1128 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $process->pid, 'done' => false]);
1129 self::$db_duration += (microtime(true) - $stamp);
1130 self::$db_duration_write += (microtime(true) - $stamp);
1134 * Fork a child process
1136 * @param boolean $do_cron
1139 private static function forkProcess(bool $do_cron)
1141 if (DI::system()->isMinMemoryReached()) {
1142 Logger::warning('Memory limit reached - quitting');
1146 // Children inherit their parent's database connection.
1147 // To avoid problems we disconnect and connect both parent and child
1149 $pid = pcntl_fork();
1152 Logger::warning('Could not spawn worker');
1155 // The parent process continues here
1158 Worker\IPC::SetJobState(true, $pid);
1159 Logger::info('Spawned new worker', ['pid' => $pid]);
1162 while (Worker\IPC::JobsExists($pid) && (++$cycles < 100)) {
1166 Logger::info('Spawned worker is ready', ['pid' => $pid, 'wait_cycles' => $cycles]);
1170 // We now are in the new worker
1174 $process = DI::process()->create(getmypid(), basename(__FILE__));
1177 while (!Worker\IPC::JobsExists($process->pid) && (++$cycles < 100)) {
1181 Logger::info('Worker spawned', ['pid' => $process->pid, 'wait_cycles' => $cycles]);
1183 self::processQueue($do_cron, $process);
1185 self::unclaimProcess($process);
1187 Worker\IPC::SetJobState(false, $process->pid);
1188 DI::process()->delete($process);
1189 Logger::info('Worker ended', ['pid' => $process->pid]);
1194 * Spawns a new worker
1196 * @param bool $do_cron
1198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1200 public static function spawnWorker(bool $do_cron = false)
1202 if (Worker\Daemon::isMode() && DI::config()->get('system', 'worker_fork')) {
1203 self::forkProcess($do_cron);
1205 DI::system()->run('bin/worker.php', ['no_cron' => !$do_cron]);
1207 if (Worker\Daemon::isMode()) {
1208 Worker\IPC::SetJobState(false);
1213 * Adds tasks to the worker queue
1215 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1217 * next args are passed as $cmd command line
1218 * or: Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::DELETION, $drop_id);
1219 * or: Worker::add(array('priority' => Worker::PRIORITY_HIGH, 'dont_fork' => true), 'Delivery', $post_id);
1221 * @return int '0' if worker queue entry already existed or there had been an error, otherwise the ID of the worker task
1222 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1223 * @note $cmd and string args are surrounded with ''
1229 public static function add(...$args)
1231 if (!count($args)) {
1235 $arr = ['args' => $args, 'run_cmd' => true];
1237 Hook::callAll('proc_run', $arr);
1238 if (!$arr['run_cmd'] || !count($args)) {
1242 $priority = self::PRIORITY_MEDIUM;
1243 // Don't fork from frontend tasks by default
1244 $dont_fork = DI::config()->get('system', 'worker_dont_fork', false) || !DI::mode()->isBackend();
1245 $created = DateTimeFormat::utcNow();
1246 $delayed = DBA::NULL_DATETIME;
1247 $force_priority = false;
1249 $run_parameter = array_shift($args);
1251 if (is_int($run_parameter)) {
1252 $priority = $run_parameter;
1253 } elseif (is_array($run_parameter)) {
1254 if (isset($run_parameter['delayed'])) {
1255 $delayed = $run_parameter['delayed'];
1257 if (isset($run_parameter['priority'])) {
1258 $priority = $run_parameter['priority'];
1260 if (isset($run_parameter['created'])) {
1261 $created = $run_parameter['created'];
1263 if (isset($run_parameter['dont_fork'])) {
1264 $dont_fork = $run_parameter['dont_fork'];
1266 if (isset($run_parameter['force_priority'])) {
1267 $force_priority = $run_parameter['force_priority'];
1270 throw new \InvalidArgumentException('Priority number or task parameter array expected as first argument');
1273 $command = array_shift($args);
1274 $parameters = json_encode($args);
1275 $queue = DBA::selectFirst('workerqueue', ['id', 'priority'], ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1278 if (!is_int($priority) || !in_array($priority, self::PRIORITIES)) {
1279 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1280 $priority = self::PRIORITY_MEDIUM;
1283 // Quit if there was a database error - a precaution for the update process to 3.5.3
1284 if (DBA::errorNo() != 0) {
1288 if (empty($queue)) {
1289 if (!DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1290 'priority' => $priority, 'next_try' => $delayed])) {
1293 $added = DBA::lastInsertId();
1294 } elseif ($force_priority) {
1295 $ret = DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1296 if ($ret && ($priority != $queue['priority'])) {
1297 $added = $queue['id'];
1301 // Set the IPC flag to ensure an immediate process execution via daemon
1302 if (Worker\Daemon::isMode()) {
1303 Worker\IPC::SetJobState(true);
1306 Worker\Daemon::checkState();
1308 // Should we quit and wait for the worker to be called as a cronjob?
1309 if ($dont_fork || self::systemLimitReached()) {
1313 // If there is a lock then we don't have to check for too much worker
1314 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1318 // If there are already enough workers running, don't fork another one
1319 $quit = self::tooMuchWorkers();
1320 DI::lock()->release(self::LOCK_WORKER);
1326 // Quit on daemon mode, except the priority is critical (like for db updates)
1327 if (Worker\Daemon::isMode() && $priority !== self::PRIORITY_CRITICAL) {
1331 // Now call the worker to execute the jobs that we just added to the queue
1332 self::spawnWorker();
1337 public static function countWorkersByCommand(string $command): int
1339 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1343 * Returns the next retrial level for worker jobs.
1344 * This function will skip levels when jobs are older.
1346 * @param array $queue Worker queue entry
1347 * @param integer $max_level maximum retrial level
1348 * @return integer the next retrial level value
1350 private static function getNextRetrial(array $queue, int $max_level): int
1352 $created = strtotime($queue['created']);
1353 $retrial_time = time() - $created;
1355 $new_retrial = $queue['retrial'] + 1;
1357 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1358 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1360 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1361 $new_retrial = $retrial;
1364 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1365 return $new_retrial;
1369 * Get the number of retrials for the current worker task
1373 public static function getRetrial(): int
1375 $queue = DI::app()->getQueue();
1376 return $queue['retrial'] ?? 0;
1380 * Defers the current worker entry
1382 * @return boolean had the entry been deferred?
1383 * @throws \Exception
1385 public static function defer(): bool
1387 $queue = DI::app()->getQueue();
1389 if (empty($queue)) {
1394 $priority = $queue['priority'];
1396 $max_level = DI::config()->get('system', 'worker_defer_limit');
1398 $new_retrial = self::getNextRetrial($queue, $max_level);
1400 if ($new_retrial > $max_level) {
1401 Logger::notice('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]);
1405 // Calculate the delay until the next trial
1406 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1407 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1409 if (($priority < self::PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1410 $priority = self::PRIORITY_MEDIUM;
1411 } elseif (($priority < self::PRIORITY_LOW) && ($new_retrial > 6)) {
1412 $priority = self::PRIORITY_LOW;
1413 } elseif (($priority < self::PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1414 $priority = self::PRIORITY_NEGLIGIBLE;
1417 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1419 $stamp = (float)microtime(true);
1420 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1421 DBA::update('workerqueue', $fields, ['id' => $id]);
1422 self::$db_duration += (microtime(true) - $stamp);
1423 self::$db_duration_write += (microtime(true) - $stamp);
1429 * Check if the system is inside the defined maintenance window
1431 * @param bool $check_last_execution Whether check last execution
1434 public static function isInMaintenanceWindow(bool $check_last_execution = false): bool
1436 // Calculate the seconds of the start and end of the maintenance window
1437 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1438 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1440 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1442 if ($check_last_execution) {
1443 // Calculate the window duration
1444 $duration = max($start, $end) - min($start, $end);
1446 // Quit when the last cron execution had been after the previous window
1447 $last_cron = DI::keyValue()->get('last_cron_daily');
1448 if ($last_cron + $duration > time()) {
1449 Logger::info('The Daily cron had been executed recently', ['last' => date(DateTimeFormat::MYSQL, $last_cron), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1454 $current = time() % 86400;
1456 if ($start < $end) {
1457 // Execute if we are inside the window
1458 $execute = ($current >= $start) && ($current <= $end);
1460 // Don't execute if we are outside the window
1461 $execute = !(($current > $end) && ($current < $start));
1465 Logger::info('We are inside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1467 Logger::info('We are outside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);