3 * @copyright Copyright (C) 2010-2022, 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
34 const PRIORITY_UNDEFINED = PRIORITY_UNDEFINED;
35 const PRIORITY_CRITICAL = PRIORITY_CRITICAL;
36 const PRIORITY_HIGH = PRIORITY_HIGH;
37 const PRIORITY_MEDIUM = PRIORITY_MEDIUM;
38 const PRIORITY_LOW = PRIORITY_LOW;
39 const PRIORITY_NEGLIGIBLE = PRIORITY_NEGLIGIBLE;
41 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
42 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
43 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
44 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
46 const FAST_COMMANDS = ['APDelivery', 'Delivery'];
48 const LOCK_PROCESS = 'worker_process';
49 const LOCK_WORKER = 'worker';
51 private static $up_start;
52 private static $db_duration = 0;
53 private static $db_duration_count = 0;
54 private static $db_duration_write = 0;
55 private static $db_duration_stat = 0;
56 private static $lock_duration = 0;
57 private static $last_update;
58 private static $state;
60 private static $process;
63 * Processes the tasks that are in the workerqueue table
65 * @param boolean $run_cron Should the cron processes be executed?
66 * @param Process $process The current running process
68 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
70 public static function processQueue(bool $run_cron, Process $process)
72 self::$up_start = microtime(true);
74 // At first check the maximum load. We shouldn't continue with a high load
75 if (DI::system()->isMaxLoadReached()) {
76 Logger::notice('Pre check: maximum load reached, quitting.');
80 // We now start the process. This is done after the load check since this could increase the load.
81 self::$process = $process;
83 // Kill stale processes every 5 minutes
84 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
85 if (time() > ($last_cleanup + 300)) {
86 DI::config()->set('system', 'worker_last_cleaned', time());
87 Worker\Cron::killStaleWorkers();
90 // Check if the system is ready
91 if (!self::isReady()) {
95 // Now we start additional cron processes if we should do so
100 $last_check = $starttime = time();
101 self::$state = self::STATE_STARTUP;
103 // We fetch the next queue entry that is about to be executed
104 while ($r = self::workerProcess()) {
105 if (Worker\IPC::JobsExists(getmypid())) {
106 Worker\IPC::DeleteJobState(getmypid());
109 // Don't refetch when a worker fetches tasks for multiple workers
110 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
111 foreach ($r as $entry) {
112 // The work will be done
113 if (!self::execute($entry)) {
114 Logger::warning('Process execution failed, quitting.', ['entry' => $entry]);
118 // Trying to fetch new processes - but only once when successful
119 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
120 self::findWorkerProcesses();
121 DI::lock()->release(self::LOCK_PROCESS);
122 self::$state = self::STATE_REFETCH;
125 self::$state = self::STATE_SHORT_LOOP;
129 // To avoid the quitting of multiple workers only one worker at a time will execute the check
130 if ((time() > $last_check + 5) && !self::getWaitingJobForPID()) {
131 self::$state = self::STATE_LONG_LOOP;
133 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
134 // Count active workers and compare them with a maximum value that depends on the load
135 if (self::tooMuchWorkers()) {
136 Logger::notice('Active worker limit reached, quitting.');
137 DI::lock()->release(self::LOCK_WORKER);
142 if (DI::system()->isMinMemoryReached()) {
143 Logger::warning('Memory limit reached, quitting.');
144 DI::lock()->release(self::LOCK_WORKER);
147 DI::lock()->release(self::LOCK_WORKER);
149 $last_check = time();
152 // Quit the worker once every cron interval
153 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60)) && !self::systemLimitReached()) {
154 Logger::info('Process lifetime reached, respawning.');
155 self::unclaimProcess($process);
156 if (Worker\Daemon::isMode()) {
157 Worker\IPC::SetJobState(true);
165 // Cleaning up. Possibly not needed, but it doesn't harm anything.
166 if (Worker\Daemon::isMode()) {
167 Worker\IPC::SetJobState(false);
169 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
173 * Checks if the system is ready.
175 * Several system parameters like memory, connections and processes are checked.
179 public static function isReady(): bool
181 // Count active workers and compare them with a maximum value that depends on the load
182 if (self::tooMuchWorkers()) {
183 Logger::notice('Active worker limit reached, quitting.');
187 // Do we have too few memory?
188 if (DI::system()->isMinMemoryReached()) {
189 Logger::warning('Memory limit reached, quitting.');
193 // Possibly there are too much database connections
194 if (self::maxConnectionsReached()) {
195 Logger::warning('Maximum connections reached, quitting.');
199 // Possibly there are too much database processes that block the system
200 if (DI::system()->isMaxProcessesReached()) {
201 Logger::warning('Maximum processes reached, quitting.');
209 * Check if non executed tasks do exist in the worker queue
211 * @return boolean Returns "true" if tasks are existing
214 public static function entriesExists(): bool
216 $stamp = (float)microtime(true);
217 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
218 self::$db_duration += (microtime(true) - $stamp);
223 * Returns the number of deferred entries in the worker queue
225 * @return integer Number of deferred entries in the worker queue
228 private static function deferredEntries(): int
230 $stamp = (float)microtime(true);
231 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
232 self::$db_duration += (microtime(true) - $stamp);
233 self::$db_duration_count += (microtime(true) - $stamp);
238 * Returns the number of non executed entries in the worker queue
240 * @return integer Number of non executed entries in the worker queue
243 private static function totalEntries(): int
245 $stamp = (float)microtime(true);
246 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
247 self::$db_duration += (microtime(true) - $stamp);
248 self::$db_duration_count += (microtime(true) - $stamp);
253 * Returns the highest priority in the worker queue that isn't executed
255 * @return integer Number of active worker processes
258 private static function highestPriority(): int
260 $stamp = (float)microtime(true);
261 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
262 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
263 self::$db_duration += (microtime(true) - $stamp);
264 if (DBA::isResult($workerqueue)) {
265 return $workerqueue['priority'];
272 * Returns if a process with the given priority is running
274 * @param integer $priority The priority that should be checked
276 * @return integer Is there a process running with that priority?
279 private static function processWithPriorityActive(int $priority): int
281 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
282 return DBA::exists('workerqueue', $condition);
286 * Checks if the given file is valid to be included
291 private static function validateInclude(&$file): bool
295 $file = realpath($file);
297 if (strpos($file, getcwd()) !== 0) {
301 $file = str_replace(getcwd() . '/', '', $file, $count);
306 if ($orig_file !== $file) {
311 if (strpos($file, 'include/') === 0) {
315 if (strpos($file, 'addon/') === 0) {
319 // Simply return flag
324 * Execute a worker entry
326 * @param array $queue Workerqueue entry
328 * @return boolean "true" if further processing should be stopped
329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331 public static function execute(array $queue): bool
335 // Quit when in maintenance
336 if (DI::config()->get('system', 'maintenance', false, true)) {
337 Logger::notice('Maintenance mode - quit process', ['pid' => $mypid]);
341 // Constantly check the number of parallel database processes
342 if (DI::system()->isMaxProcessesReached()) {
343 Logger::warning('Max processes reached for process', ['pid' => $mypid]);
347 // Constantly check the number of available database connections to let the frontend be accessible at any time
348 if (self::maxConnectionsReached()) {
349 Logger::warning('Max connection reached for process', ['pid' => $mypid]);
353 $argv = json_decode($queue['parameter'], true);
354 if (!is_array($argv)) {
358 if (!empty($queue['command'])) {
359 array_unshift($argv, $queue['command']);
363 Logger::warning('Parameter is empty', ['queue' => $queue]);
367 // Check for existance and validity of the include file
370 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
371 // We constantly update the "executed" date every minute to avoid being killed too soon
372 if (!isset(self::$last_update)) {
373 self::$last_update = strtotime($queue['executed']);
376 $age = (time() - self::$last_update) / 60;
377 self::$last_update = time();
380 $stamp = (float)microtime(true);
381 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
382 self::$db_duration += (microtime(true) - $stamp);
383 self::$db_duration_write += (microtime(true) - $stamp);
388 self::execFunction($queue, $include, $argv, true);
390 $stamp = (float)microtime(true);
391 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
392 if (DBA::update('workerqueue', ['done' => true], $condition)) {
393 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
395 self::$db_duration = (microtime(true) - $stamp);
396 self::$db_duration_write += (microtime(true) - $stamp);
401 // The script could be provided as full path or only with the function name
402 if ($include == basename($include)) {
403 $include = 'include/' . $include . '.php';
406 if (!self::validateInclude($include)) {
407 Logger::warning('Include file is not valid', ['file' => $argv[0]]);
408 $stamp = (float)microtime(true);
409 DBA::delete('workerqueue', ['id' => $queue['id']]);
410 self::$db_duration = (microtime(true) - $stamp);
411 self::$db_duration_write += (microtime(true) - $stamp);
415 require_once $include;
417 $funcname = str_replace('.php', '', basename($argv[0])) .'_run';
419 if (function_exists($funcname)) {
420 // We constantly update the "executed" date every minute to avoid being killed too soon
421 if (!isset(self::$last_update)) {
422 self::$last_update = strtotime($queue['executed']);
425 $age = (time() - self::$last_update) / 60;
426 self::$last_update = time();
429 $stamp = (float)microtime(true);
430 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
431 self::$db_duration += (microtime(true) - $stamp);
432 self::$db_duration_write += (microtime(true) - $stamp);
435 self::execFunction($queue, $funcname, $argv, false);
437 $stamp = (float)microtime(true);
438 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue['id']])) {
439 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
441 self::$db_duration = (microtime(true) - $stamp);
442 self::$db_duration_write += (microtime(true) - $stamp);
444 Logger::warning('Function does not exist', ['function' => $funcname]);
445 $stamp = (float)microtime(true);
446 DBA::delete('workerqueue', ['id' => $queue['id']]);
447 self::$db_duration = (microtime(true) - $stamp);
448 self::$db_duration_write += (microtime(true) - $stamp);
455 * Checks if system limits are reached.
459 private static function systemLimitReached(): bool
461 $load_cooldown = DI::config()->get('system', 'worker_load_cooldown');
462 $processes_cooldown = DI::config()->get('system', 'worker_processes_cooldown');
464 if (($load_cooldown == 0) && ($processes_cooldown == 0)) {
468 $load = System::getLoadAvg();
473 if (($load_cooldown > 0) && ($load['average1'] > $load_cooldown)) {
477 if (($processes_cooldown > 0) && ($load['scheduled'] > $processes_cooldown)) {
485 * Slow the execution down if the system load is too high
489 public static function coolDown()
491 $cooldown = DI::config()->get('system', 'worker_cooldown', 0);
493 Logger::debug('Wait for cooldown.', ['cooldown' => $cooldown]);
495 usleep($cooldown * 1000000);
501 $load_cooldown = DI::config()->get('system', 'worker_load_cooldown');
502 $processes_cooldown = DI::config()->get('system', 'worker_processes_cooldown');
504 if (($load_cooldown == 0) && ($processes_cooldown == 0)) {
510 while ($load = System::getLoadAvg()) {
511 if (($load_cooldown > 0) && ($load['average1'] > $load_cooldown)) {
513 Logger::notice('Load induced pre execution cooldown.', ['max' => $load_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
519 if (($processes_cooldown > 0) && ($load['scheduled'] > $processes_cooldown)) {
521 Logger::notice('Process induced pre execution cooldown.', ['max' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
531 Logger::notice('Cooldown ended.', ['max-load' => $load_cooldown, 'max-processes' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
536 * Execute a function from the queue
538 * @param array $queue Workerqueue entry
539 * @param string $funcname name of the function
540 * @param array $argv Array of values to be passed to the function
541 * @param boolean $method_call boolean
543 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
545 private static function execFunction(array $queue, string $funcname, array $argv, bool $method_call)
551 Logger::enableWorker($funcname);
553 Logger::info('Process start.', ['priority' => $queue['priority'], 'id' => $queue['id']]);
555 $stamp = (float)microtime(true);
557 // We use the callstack here to analyze the performance of executed worker entries.
558 // For this reason the variables have to be initialized.
559 DI::profiler()->reset();
561 $a->setQueue($queue);
563 $up_duration = microtime(true) - self::$up_start;
565 // Reset global data to avoid interferences
568 // Set the workerLogger as new default logger
570 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
572 $funcname($argv, count($argv));
575 Logger::disableWorker();
579 $duration = (microtime(true) - $stamp);
581 /* With these values we can analyze how effective the worker is.
582 * The database and rest time should be low since this is the unproductive time.
583 * The execution time is the productive time.
584 * By changing parameters like the maximum number of workers we can check the effectivness.
586 $dbtotal = round(self::$db_duration, 2);
587 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
588 $dbcount = round(self::$db_duration_count, 2);
589 $dbstat = round(self::$db_duration_stat, 2);
590 $dbwrite = round(self::$db_duration_write, 2);
591 $dblock = round(self::$lock_duration, 2);
592 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
593 $exec = round($duration, 2);
595 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
599 self::$up_start = microtime(true);
600 self::$db_duration = 0;
601 self::$db_duration_count = 0;
602 self::$db_duration_stat = 0;
603 self::$db_duration_write = 0;
604 self::$lock_duration = 0;
606 if ($duration > 3600) {
607 Logger::info('Longer than 1 hour.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
608 } elseif ($duration > 600) {
609 Logger::info('Longer than 10 minutes.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
610 } elseif ($duration > 300) {
611 Logger::info('Longer than 5 minutes.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
612 } elseif ($duration > 120) {
613 Logger::info('Longer than 2 minutes.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
616 Logger::info('Process done.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration, 3)]);
618 DI::profiler()->saveLog(DI::logger(), 'ID ' . $queue['id'] . ': ' . $funcname);
622 * Checks if the number of database connections has reached a critical limit.
624 * @return bool Are more than 3/4 of the maximum connections used?
625 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
627 private static function maxConnectionsReached(): bool
629 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
630 $max = DI::config()->get('system', 'max_connections');
632 // Fetch the percentage level where the worker will get active
633 $maxlevel = DI::config()->get('system', 'max_connections_level', 75);
636 // the maximum number of possible user connections can be a system variable
637 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
638 if (DBA::isResult($r)) {
641 // Or it can be granted. This overrides the system variable
642 $stamp = (float)microtime(true);
643 $r = DBA::p('SHOW GRANTS');
644 self::$db_duration += (microtime(true) - $stamp);
645 while ($grants = DBA::fetch($r)) {
646 $grant = array_pop($grants);
647 if (stristr($grant, "GRANT USAGE ON")) {
648 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
656 // If $max is set we will use the processlist to determine the current number of connections
657 // The processlist only shows entries of the current user
659 $stamp = (float)microtime(true);
660 $r = DBA::p('SHOW PROCESSLIST');
661 self::$db_duration += (microtime(true) - $stamp);
662 $used = DBA::numRows($r);
665 Logger::info('Connection usage (user values)', ['usage' => $used, 'max' => $max]);
667 $level = ($used / $max) * 100;
669 if ($level >= $maxlevel) {
670 Logger::warning('Maximum level (' . $maxlevel . '%) of user connections reached: ' . $used .'/' . $max);
675 // We will now check for the system values.
676 // This limit could be reached although the user limits are fine.
677 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
678 if (!DBA::isResult($r)) {
681 $max = intval($r['Value']);
685 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
686 if (!DBA::isResult($r)) {
689 $used = intval($r['Value']);
693 Logger::info('Connection usage (system values)', ['used' => $used, 'max' => $max]);
695 $level = $used / $max * 100;
697 if ($level < $maxlevel) {
700 Logger::warning('Maximum level (' . $level . '%) of system connections reached: ' . $used . '/' . $max);
706 * Checks if the number of active workers exceeds the given limits
708 * @return bool Are there too much workers running?
709 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
711 private static function tooMuchWorkers(): bool
713 $queues = DI::config()->get('system', 'worker_queues', 10);
715 $maxqueues = $queues;
717 $active = self::activeWorkers();
719 // Decrease the number of workers at higher load
720 $load = System::currentLoad();
722 $maxsysload = intval(DI::config()->get('system', 'maxloadavg', 20));
724 /* Default exponent 3 causes queues to rapidly decrease as load increases.
725 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
726 * For some environments, this rapid decrease is not needed.
727 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
729 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
730 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
731 $queues = intval(ceil($slope * $maxqueues));
735 if (DI::config()->get('system', 'worker_jpm')) {
736 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
737 $jobs_per_minute = [];
738 foreach ($intervals as $interval) {
739 if ($interval == 0) {
742 $interval = (int)$interval;
745 $stamp = (float)microtime(true);
746 $jobs = DBA::count('workerqueue', ["`done` AND `executed` > ?", DateTimeFormat::utc('now - ' . $interval . ' minute')]);
747 self::$db_duration += (microtime(true) - $stamp);
748 self::$db_duration_stat += (microtime(true) - $stamp);
749 $jobs_per_minute[$interval] = number_format($jobs / $interval, 0);
751 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
754 // Create a list of queue entries grouped by their priority
755 $listitem = [0 => ''];
757 $idle_workers = $active;
759 $deferred = self::deferredEntries();
761 if (DI::config()->get('system', 'worker_debug')) {
762 $waiting_processes = 0;
763 // Now adding all processes with workerqueue entries
764 $stamp = (float)microtime(true);
765 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
766 self::$db_duration += (microtime(true) - $stamp);
767 self::$db_duration_stat += (microtime(true) - $stamp);
768 while ($entry = DBA::fetch($jobs)) {
769 $stamp = (float)microtime(true);
770 $running = DBA::count('workerqueue-view', ['priority' => $entry['priority']]);
771 self::$db_duration += (microtime(true) - $stamp);
772 self::$db_duration_stat += (microtime(true) - $stamp);
773 $idle_workers -= $running;
774 $waiting_processes += $entry['entries'];
775 $listitem[$entry['priority']] = $entry['priority'] . ':' . $running . '/' . $entry['entries'];
779 $waiting_processes = self::totalEntries();
780 $stamp = (float)microtime(true);
781 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
782 self::$db_duration += (microtime(true) - $stamp);
783 self::$db_duration_stat += (microtime(true) - $stamp);
785 while ($entry = DBA::fetch($jobs)) {
786 $idle_workers -= $entry['running'];
787 $listitem[$entry['priority']] = $entry['priority'] . ':' . $entry['running'];
792 $waiting_processes -= $deferred;
794 $listitem[0] = '0:' . max(0, $idle_workers);
796 $processlist .= ' ('.implode(', ', $listitem).')';
798 if (DI::config()->get('system', 'worker_fastlane', false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
799 $top_priority = self::highestPriority();
800 $high_running = self::processWithPriorityActive($top_priority);
802 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
803 Logger::info('Jobs with a higher priority are waiting but none is executed. Open a fastlane.', ['priority' => $top_priority]);
804 $queues = $active + 1;
808 Logger::notice('Load: ' . $load . '/' . $maxsysload . ' - processes: ' . $deferred . '/' . $active . '/' . $waiting_processes . $processlist . ' - maximum: ' . $queues . '/' . $maxqueues);
810 // Are there fewer workers running as possible? Then fork a new one.
811 if (!DI::config()->get('system', 'worker_dont_fork', false) && ($queues > ($active + 1)) && self::entriesExists() && !self::systemLimitReached()) {
812 Logger::info('There are fewer workers as possible, fork a new worker.', ['active' => $active, 'queues' => $queues]);
813 if (Worker\Daemon::isMode()) {
814 Worker\IPC::SetJobState(true);
821 // if there are too much worker, we don't spawn a new one.
822 if (Worker\Daemon::isMode() && ($active > $queues)) {
823 Worker\IPC::SetJobState(false);
826 return $active > $queues;
830 * Returns the number of active worker processes
832 * @return integer Number of active worker processes
835 private static function activeWorkers(): int
837 $stamp = (float)microtime(true);
838 $count = DI::process()->countCommand('Worker.php');
839 self::$db_duration += (microtime(true) - $stamp);
840 self::$db_duration_count += (microtime(true) - $stamp);
845 * Returns the number of active worker processes
847 * @return array List of worker process ids
850 private static function getWorkerPIDList(): array
853 $stamp = (float)microtime(true);
855 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
856 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
857 GROUP BY `process`.`pid`");
858 while ($queue = DBA::fetch($queues)) {
859 $ids[$queue['pid']] = $queue['entries'];
863 self::$db_duration += (microtime(true) - $stamp);
864 self::$db_duration_count += (microtime(true) - $stamp);
869 * Returns waiting jobs for the current process id
871 * @return array|bool waiting workerqueue jobs or FALSE on failture
874 private static function getWaitingJobForPID()
876 $stamp = (float)microtime(true);
877 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
878 self::$db_duration += (microtime(true) - $stamp);
879 if (DBA::isResult($r)) {
880 return DBA::toArray($r);
888 * Returns the next jobs that should be executed
890 * @return array array with next jobs
893 private static function nextProcess(int $limit): array
895 $priority = self::nextPriority();
896 if (empty($priority)) {
897 Logger::info('No tasks found');
902 $stamp = (float)microtime(true);
903 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
904 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
905 self::$db_duration += (microtime(true) - $stamp);
906 while ($task = DBA::fetch($tasks)) {
907 $ids[] = $task['id'];
908 // Only continue that loop while we are storing commands that can be processed quickly
909 if (!empty($task['command'])) {
910 $command = $task['command'];
912 $command = json_decode($task['parameter'])[0];
915 if (!in_array($command, self::FAST_COMMANDS)) {
921 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
926 * Returns the priority of the next workerqueue job
928 * @return string|bool priority or FALSE on failure
931 private static function nextPriority()
934 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
935 foreach ($priorities as $priority) {
936 $stamp = (float)microtime(true);
937 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
938 $waiting[$priority] = true;
940 self::$db_duration += (microtime(true) - $stamp);
943 if (!empty($waiting[PRIORITY_CRITICAL])) {
944 return PRIORITY_CRITICAL;
949 $stamp = (float)microtime(true);
950 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
951 self::$db_duration += (microtime(true) - $stamp);
952 while ($process = DBA::fetch($processes)) {
953 $running[$process['priority']] = $process['running'];
954 $running_total += $process['running'];
956 DBA::close($processes);
958 foreach ($priorities as $priority) {
959 if (!empty($waiting[$priority]) && empty($running[$priority])) {
960 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
965 $active = max(self::activeWorkers(), $running_total);
966 $priorities = max(count($waiting), count($running));
970 for ($i = 1; $i <= $priorities; ++$i) {
971 $total += pow($i, $exponent);
975 for ($i = 1; $i <= $priorities; ++$i) {
976 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
980 foreach ($running as $priority => $workers) {
981 if ($workers < $limit[$i++]) {
982 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
987 if (!empty($waiting)) {
988 $priority = array_keys($waiting)[0];
989 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
997 * Find and claim the next worker process for us
1000 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1002 private static function findWorkerProcesses()
1004 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
1006 if (DI::config()->get('system', 'worker_multiple_fetch')) {
1008 foreach (self::getWorkerPIDList() as $pid => $count) {
1009 if ($count <= $fetch_limit) {
1016 $limit = $fetch_limit * count($pids);
1018 $pids = [getmypid()];
1019 $limit = $fetch_limit;
1022 $ids = self::nextProcess($limit);
1023 $limit -= count($ids);
1025 // If there is not enough results we check without priority limit
1027 $stamp = (float)microtime(true);
1028 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
1029 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
1030 self::$db_duration += (microtime(true) - $stamp);
1032 while ($task = DBA::fetch($tasks)) {
1033 $ids[] = $task['id'];
1034 // Only continue that loop while we are storing commands that can be processed quickly
1035 if (!empty($task['command'])) {
1036 $command = $task['command'];
1038 $command = json_decode($task['parameter'])[0];
1040 if (!in_array($command, self::FAST_COMMANDS)) {
1051 // Assign the task ids to the workers
1053 foreach (array_unique($ids) as $id) {
1056 $pid = reset($pids);
1058 $worker[$pid][] = $id;
1061 $stamp = (float)microtime(true);
1062 foreach ($worker as $worker_pid => $worker_ids) {
1063 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1064 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1065 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1067 self::$db_duration += (microtime(true) - $stamp);
1068 self::$db_duration_write += (microtime(true) - $stamp);
1072 * Returns the next worker process
1074 * @return array worker processes
1075 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1077 public static function workerProcess(): array
1079 // There can already be jobs for us in the queue.
1080 $waiting = self::getWaitingJobForPID();
1081 if (!empty($waiting)) {
1085 $stamp = (float)microtime(true);
1086 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1089 self::$lock_duration += (microtime(true) - $stamp);
1091 self::findWorkerProcesses();
1093 DI::lock()->release(self::LOCK_PROCESS);
1095 // Prevents "Return value of Friendica\Core\Worker::workerProcess() must be of the type array, bool returned"
1096 $process = self::getWaitingJobForPID();
1097 return (is_array($process) ? $process : []);
1101 * Removes a workerqueue entry from the current process
1103 * @param Process $process the process behind the workerqueue
1106 * @throws \Exception
1108 public static function unclaimProcess(Process $process)
1110 $stamp = (float)microtime(true);
1111 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $process->pid, 'done' => false]);
1112 self::$db_duration += (microtime(true) - $stamp);
1113 self::$db_duration_write += (microtime(true) - $stamp);
1117 * Fork a child process
1119 * @param boolean $do_cron
1122 private static function forkProcess(bool $do_cron)
1124 if (DI::system()->isMinMemoryReached()) {
1125 Logger::warning('Memory limit reached - quitting');
1129 // Children inherit their parent's database connection.
1130 // To avoid problems we disconnect and connect both parent and child
1132 $pid = pcntl_fork();
1135 Logger::warning('Could not spawn worker');
1138 // The parent process continues here
1141 Worker\IPC::SetJobState(true, $pid);
1142 Logger::info('Spawned new worker', ['pid' => $pid]);
1145 while (Worker\IPC::JobsExists($pid) && (++$cycles < 100)) {
1149 Logger::info('Spawned worker is ready', ['pid' => $pid, 'wait_cycles' => $cycles]);
1153 // We now are in the new worker
1157 $process = DI::process()->create(getmypid(), basename(__FILE__));
1160 while (!Worker\IPC::JobsExists($process->pid) && (++$cycles < 100)) {
1164 Logger::info('Worker spawned', ['pid' => $process->pid, 'wait_cycles' => $cycles]);
1166 self::processQueue($do_cron, $process);
1168 self::unclaimProcess($process);
1170 Worker\IPC::SetJobState(false, $process->pid);
1171 DI::process()->delete($process);
1172 Logger::info('Worker ended', ['pid' => $process->pid]);
1177 * Spawns a new worker
1179 * @param bool $do_cron
1181 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1183 public static function spawnWorker(bool $do_cron = false)
1185 if (Worker\Daemon::isMode() && DI::config()->get('system', 'worker_fork')) {
1186 self::forkProcess($do_cron);
1188 DI::system()->run('bin/worker.php', ['no_cron' => !$do_cron]);
1190 if (Worker\Daemon::isMode()) {
1191 Worker\IPC::SetJobState(false);
1196 * Adds tasks to the worker queue
1198 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1200 * next args are passed as $cmd command line
1201 * or: Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::DELETION, $drop_id);
1202 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), 'Delivery', $post_id);
1204 * @return int '0' if worker queue entry already existed or there had been an error, otherwise the ID of the worker task
1205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1206 * @note $cmd and string args are surrounded with ''
1212 public static function add(...$args)
1214 if (!count($args)) {
1218 $arr = ['args' => $args, 'run_cmd' => true];
1220 Hook::callAll('proc_run', $arr);
1221 if (!$arr['run_cmd'] || !count($args)) {
1225 $priority = PRIORITY_MEDIUM;
1226 // Don't fork from frontend tasks by default
1227 $dont_fork = DI::config()->get('system', 'worker_dont_fork', false) || !DI::mode()->isBackend();
1228 $created = DateTimeFormat::utcNow();
1229 $delayed = DBA::NULL_DATETIME;
1230 $force_priority = false;
1232 $run_parameter = array_shift($args);
1234 if (is_int($run_parameter)) {
1235 $priority = $run_parameter;
1236 } elseif (is_array($run_parameter)) {
1237 if (isset($run_parameter['delayed'])) {
1238 $delayed = $run_parameter['delayed'];
1240 if (isset($run_parameter['priority'])) {
1241 $priority = $run_parameter['priority'];
1243 if (isset($run_parameter['created'])) {
1244 $created = $run_parameter['created'];
1246 if (isset($run_parameter['dont_fork'])) {
1247 $dont_fork = $run_parameter['dont_fork'];
1249 if (isset($run_parameter['force_priority'])) {
1250 $force_priority = $run_parameter['force_priority'];
1253 throw new \InvalidArgumentException('Priority number or task parameter array expected as first argument');
1256 $command = array_shift($args);
1257 $parameters = json_encode($args);
1258 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1261 if (!is_int($priority) || !in_array($priority, PRIORITIES)) {
1262 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1263 $priority = PRIORITY_MEDIUM;
1266 // Quit if there was a database error - a precaution for the update process to 3.5.3
1267 if (DBA::errorNo() != 0) {
1272 if (!DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1273 'priority' => $priority, 'next_try' => $delayed])) {
1276 $added = DBA::lastInsertId();
1277 } elseif ($force_priority) {
1278 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1281 // Set the IPC flag to ensure an immediate process execution via daemon
1282 if (Worker\Daemon::isMode()) {
1283 Worker\IPC::SetJobState(true);
1286 Worker\Daemon::checkState();
1288 // Should we quit and wait for the worker to be called as a cronjob?
1289 if ($dont_fork || self::systemLimitReached()) {
1293 // If there is a lock then we don't have to check for too much worker
1294 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1298 // If there are already enough workers running, don't fork another one
1299 $quit = self::tooMuchWorkers();
1300 DI::lock()->release(self::LOCK_WORKER);
1306 // Quit on daemon mode
1307 if (Worker\Daemon::isMode()) {
1311 // Now call the worker to execute the jobs that we just added to the queue
1312 self::spawnWorker();
1317 public static function countWorkersByCommand(string $command): int
1319 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1323 * Returns the next retrial level for worker jobs.
1324 * This function will skip levels when jobs are older.
1326 * @param array $queue Worker queue entry
1327 * @param integer $max_level maximum retrial level
1328 * @return integer the next retrial level value
1330 private static function getNextRetrial(array $queue, int $max_level): int
1332 $created = strtotime($queue['created']);
1333 $retrial_time = time() - $created;
1335 $new_retrial = $queue['retrial'] + 1;
1337 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1338 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1340 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1341 $new_retrial = $retrial;
1344 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1345 return $new_retrial;
1349 * Defers the current worker entry
1351 * @return boolean had the entry been deferred?
1352 * @throws \Exception
1354 public static function defer(): bool
1356 $queue = DI::app()->getQueue();
1358 if (empty($queue)) {
1363 $priority = $queue['priority'];
1365 $max_level = DI::config()->get('system', 'worker_defer_limit');
1367 $new_retrial = self::getNextRetrial($queue, $max_level);
1369 if ($new_retrial > $max_level) {
1370 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]);
1374 // Calculate the delay until the next trial
1375 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1376 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1378 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1379 $priority = PRIORITY_MEDIUM;
1380 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1381 $priority = PRIORITY_LOW;
1382 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1383 $priority = PRIORITY_NEGLIGIBLE;
1386 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1388 $stamp = (float)microtime(true);
1389 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1390 DBA::update('workerqueue', $fields, ['id' => $id]);
1391 self::$db_duration += (microtime(true) - $stamp);
1392 self::$db_duration_write += (microtime(true) - $stamp);
1398 * Check if the system is inside the defined maintenance window
1400 * @param bool $check_last_execution Whether check last execution
1403 public static function isInMaintenanceWindow(bool $check_last_execution = false): bool
1405 // Calculate the seconds of the start end end of the maintenance window
1406 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1407 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1409 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1411 if ($check_last_execution) {
1412 // Calculate the window duration
1413 $duration = max($start, $end) - min($start, $end);
1415 // Quit when the last cron execution had been after the previous window
1416 $last_cron = DI::config()->get('system', 'last_cron_daily');
1417 if ($last_cron + $duration > time()) {
1418 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)]);
1423 $current = time() % 86400;
1425 if ($start < $end) {
1426 // Execute if we are inside the window
1427 $execute = ($current >= $start) && ($current <= $end);
1429 // Don't execute if we are outside the window
1430 $execute = !(($current > $end) && ($current < $start));
1434 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)]);
1436 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)]);