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 STATE_STARTUP = 1; // Worker is in startup. This takes most time.
35 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
36 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
37 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
39 const FAST_COMMANDS = ['APDelivery', 'Delivery'];
41 const LOCK_PROCESS = 'worker_process';
42 const LOCK_WORKER = 'worker';
44 private static $up_start;
45 private static $db_duration = 0;
46 private static $db_duration_count = 0;
47 private static $db_duration_write = 0;
48 private static $db_duration_stat = 0;
49 private static $lock_duration = 0;
50 private static $last_update;
51 private static $state;
53 private static $process;
56 * Processes the tasks that are in the workerqueue table
58 * @param boolean $run_cron Should the cron processes be executed?
59 * @param Process $process The current running process
61 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
63 public static function processQueue(bool $run_cron, Process $process)
65 self::$up_start = microtime(true);
67 // At first check the maximum load. We shouldn't continue with a high load
68 if (DI::system()->isMaxLoadReached()) {
69 Logger::notice('Pre check: maximum load reached, quitting.');
73 // We now start the process. This is done after the load check since this could increase the load.
74 self::$process = $process;
76 // Kill stale processes every 5 minutes
77 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
78 if (time() > ($last_cleanup + 300)) {
79 DI::config()->set('system', 'worker_last_cleaned', time());
80 Worker\Cron::killStaleWorkers();
83 // Check if the system is ready
84 if (!self::isReady()) {
88 // Now we start additional cron processes if we should do so
93 $last_check = $starttime = time();
94 self::$state = self::STATE_STARTUP;
96 // We fetch the next queue entry that is about to be executed
97 while ($r = self::workerProcess()) {
98 if (Worker\IPC::JobsExists(getmypid())) {
99 Worker\IPC::DeleteJobState(getmypid());
102 // Don't refetch when a worker fetches tasks for multiple workers
103 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
104 foreach ($r as $entry) {
105 // The work will be done
106 if (!self::execute($entry)) {
107 Logger::notice('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 ((time() > $last_check + 5) && !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::notice('Active worker limit reached, quitting.');
130 DI::lock()->release(self::LOCK_WORKER);
135 if (DI::system()->isMinMemoryReached()) {
136 Logger::warning('Memory limit reached, quitting.');
137 DI::lock()->release(self::LOCK_WORKER);
140 DI::lock()->release(self::LOCK_WORKER);
142 $last_check = time();
145 // Quit the worker once every cron interval
146 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
147 Logger::info('Process lifetime reached, respawning.');
148 self::unclaimProcess($process);
149 if (Worker\Daemon::isMode()) {
150 Worker\IPC::SetJobState(true);
158 // Cleaning up. Possibly not needed, but it doesn't harm anything.
159 if (Worker\Daemon::isMode()) {
160 Worker\IPC::SetJobState(false);
162 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
166 * Checks if the system is ready.
168 * Several system parameters like memory, connections and processes are checked.
172 public static function isReady(): bool
174 // Count active workers and compare them with a maximum value that depends on the load
175 if (self::tooMuchWorkers()) {
176 Logger::notice('Active worker limit reached, quitting.');
180 // Do we have too few memory?
181 if (DI::system()->isMinMemoryReached()) {
182 Logger::warning('Memory limit reached, quitting.');
186 // Possibly there are too much database connections
187 if (self::maxConnectionsReached()) {
188 Logger::warning('Maximum connections reached, quitting.');
192 // Possibly there are too much database processes that block the system
193 if (DI::system()->isMaxProcessesReached()) {
194 Logger::warning('Maximum processes reached, quitting.');
202 * Check if non executed tasks do exist in the worker queue
204 * @return boolean Returns "true" if tasks are existing
207 public static function entriesExists(): bool
209 $stamp = (float)microtime(true);
210 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
211 self::$db_duration += (microtime(true) - $stamp);
216 * Returns the number of deferred entries in the worker queue
218 * @return integer Number of deferred entries in the worker queue
221 private static function deferredEntries(): int
223 $stamp = (float)microtime(true);
224 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
225 self::$db_duration += (microtime(true) - $stamp);
226 self::$db_duration_count += (microtime(true) - $stamp);
231 * Returns the number of non executed entries in the worker queue
233 * @return integer Number of non executed entries in the worker queue
236 private static function totalEntries(): int
238 $stamp = (float)microtime(true);
239 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
240 self::$db_duration += (microtime(true) - $stamp);
241 self::$db_duration_count += (microtime(true) - $stamp);
246 * Returns the highest priority in the worker queue that isn't executed
248 * @return integer Number of active worker processes
251 private static function highestPriority(): int
253 $stamp = (float)microtime(true);
254 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
255 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
256 self::$db_duration += (microtime(true) - $stamp);
257 if (DBA::isResult($workerqueue)) {
258 return $workerqueue['priority'];
265 * Returns if a process with the given priority is running
267 * @param integer $priority The priority that should be checked
269 * @return integer Is there a process running with that priority?
272 private static function processWithPriorityActive(int $priority): int
274 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
275 return DBA::exists('workerqueue', $condition);
279 * Checks if the given file is valid to be included
284 private static function validateInclude(&$file): bool
288 $file = realpath($file);
290 if (strpos($file, getcwd()) !== 0) {
294 $file = str_replace(getcwd() . "/", "", $file, $count);
299 if ($orig_file !== $file) {
304 if (strpos($file, "include/") === 0) {
308 if (strpos($file, "addon/") === 0) {
312 // Simply return flag
317 * Execute a worker entry
319 * @param array $queue Workerqueue entry
321 * @return boolean "true" if further processing should be stopped
322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
324 public static function execute(array $queue): bool
328 // Quit when in maintenance
329 if (DI::config()->get('system', 'maintenance', false, true)) {
330 Logger::notice("Maintenance mode - quit process", ['pid' => $mypid]);
334 // Constantly check the number of parallel database processes
335 if (DI::system()->isMaxProcessesReached()) {
336 Logger::warning("Max processes reached for process", ['pid' => $mypid]);
340 // Constantly check the number of available database connections to let the frontend be accessible at any time
341 if (self::maxConnectionsReached()) {
342 Logger::warning("Max connection reached for process", ['pid' => $mypid]);
346 $argv = json_decode($queue['parameter'], true);
347 if (!is_array($argv)) {
351 if (!empty($queue['command'])) {
352 array_unshift($argv, $queue['command']);
356 Logger::warning('Parameter is empty', ['queue' => $queue]);
360 // Check for existance and validity of the include file
363 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
364 // We constantly update the "executed" date every minute to avoid being killed too soon
365 if (!isset(self::$last_update)) {
366 self::$last_update = strtotime($queue["executed"]);
369 $age = (time() - self::$last_update) / 60;
370 self::$last_update = time();
373 $stamp = (float)microtime(true);
374 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
375 self::$db_duration += (microtime(true) - $stamp);
376 self::$db_duration_write += (microtime(true) - $stamp);
381 self::execFunction($queue, $include, $argv, true);
383 $stamp = (float)microtime(true);
384 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
385 if (DBA::update('workerqueue', ['done' => true], $condition)) {
386 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
388 self::$db_duration = (microtime(true) - $stamp);
389 self::$db_duration_write += (microtime(true) - $stamp);
394 // The script could be provided as full path or only with the function name
395 if ($include == basename($include)) {
396 $include = "include/".$include.".php";
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::config()->set('system', '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 * Execute a function from the queue
450 * @param array $queue Workerqueue entry
451 * @param string $funcname name of the function
452 * @param array $argv Array of values to be passed to the function
453 * @param boolean $method_call boolean
455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457 private static function execFunction(array $queue, string $funcname, array $argv, bool $method_call)
461 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
463 Logger::info('Pre execution cooldown.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'cooldown' => $cooldown]);
467 Logger::enableWorker($funcname);
469 Logger::info("Process start.", ['priority' => $queue['priority'], 'id' => $queue["id"]]);
471 $stamp = (float)microtime(true);
473 // We use the callstack here to analyze the performance of executed worker entries.
474 // For this reason the variables have to be initialized.
475 DI::profiler()->reset();
477 $a->setQueue($queue);
479 $up_duration = microtime(true) - self::$up_start;
481 // Reset global data to avoid interferences
484 // Set the workerLogger as new default logger
486 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
488 $funcname($argv, count($argv));
491 Logger::disableWorker();
495 $duration = (microtime(true) - $stamp);
497 /* With these values we can analyze how effective the worker is.
498 * The database and rest time should be low since this is the unproductive time.
499 * The execution time is the productive time.
500 * By changing parameters like the maximum number of workers we can check the effectivness.
502 $dbtotal = round(self::$db_duration, 2);
503 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
504 $dbcount = round(self::$db_duration_count, 2);
505 $dbstat = round(self::$db_duration_stat, 2);
506 $dbwrite = round(self::$db_duration_write, 2);
507 $dblock = round(self::$lock_duration, 2);
508 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
509 $exec = round($duration, 2);
511 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
513 self::$up_start = microtime(true);
514 self::$db_duration = 0;
515 self::$db_duration_count = 0;
516 self::$db_duration_stat = 0;
517 self::$db_duration_write = 0;
518 self::$lock_duration = 0;
520 if ($duration > 3600) {
521 Logger::info('Longer than 1 hour.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
522 } elseif ($duration > 600) {
523 Logger::info('Longer than 10 minutes.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
524 } elseif ($duration > 300) {
525 Logger::info('Longer than 5 minutes.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
526 } elseif ($duration > 120) {
527 Logger::info('Longer than 2 minutes.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
530 Logger::info('Process done.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
532 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
535 Logger::info('Post execution cooldown.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'cooldown' => $cooldown]);
541 * Checks if the number of database connections has reached a critical limit.
543 * @return bool Are more than 3/4 of the maximum connections used?
544 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
546 private static function maxConnectionsReached(): bool
548 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
549 $max = DI::config()->get("system", "max_connections");
551 // Fetch the percentage level where the worker will get active
552 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
555 // the maximum number of possible user connections can be a system variable
556 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
557 if (DBA::isResult($r)) {
560 // Or it can be granted. This overrides the system variable
561 $stamp = (float)microtime(true);
562 $r = DBA::p('SHOW GRANTS');
563 self::$db_duration += (microtime(true) - $stamp);
564 while ($grants = DBA::fetch($r)) {
565 $grant = array_pop($grants);
566 if (stristr($grant, "GRANT USAGE ON")) {
567 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
575 // If $max is set we will use the processlist to determine the current number of connections
576 // The processlist only shows entries of the current user
578 $stamp = (float)microtime(true);
579 $r = DBA::p('SHOW PROCESSLIST');
580 self::$db_duration += (microtime(true) - $stamp);
581 $used = DBA::numRows($r);
584 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
586 $level = ($used / $max) * 100;
588 if ($level >= $maxlevel) {
589 Logger::warning("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
594 // We will now check for the system values.
595 // This limit could be reached although the user limits are fine.
596 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
597 if (!DBA::isResult($r)) {
600 $max = intval($r["Value"]);
604 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
605 if (!DBA::isResult($r)) {
608 $used = intval($r["Value"]);
612 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
614 $level = $used / $max * 100;
616 if ($level < $maxlevel) {
619 Logger::warning("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
625 * Checks if the number of active workers exceeds the given limits
627 * @return bool Are there too much workers running?
628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
630 private static function tooMuchWorkers(): bool
632 $queues = DI::config()->get("system", "worker_queues", 10);
634 $maxqueues = $queues;
636 $active = self::activeWorkers();
638 // Decrease the number of workers at higher load
639 $load = System::currentLoad();
641 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
643 /* Default exponent 3 causes queues to rapidly decrease as load increases.
644 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
645 * For some environments, this rapid decrease is not needed.
646 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
648 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
649 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
650 $queues = intval(ceil($slope * $maxqueues));
654 if (DI::config()->get('system', 'worker_jpm')) {
655 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
656 $jobs_per_minute = [];
657 foreach ($intervals as $interval) {
658 if ($interval == 0) {
661 $interval = (int)$interval;
664 $stamp = (float)microtime(true);
665 $jobs = DBA::count('workerqueue', ["`done` AND `executed` > ?", DateTimeFormat::utc('now - ' . $interval . ' minute')]);
666 self::$db_duration += (microtime(true) - $stamp);
667 self::$db_duration_stat += (microtime(true) - $stamp);
668 $jobs_per_minute[$interval] = number_format($jobs / $interval, 0);
670 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
673 // Create a list of queue entries grouped by their priority
674 $listitem = [0 => ''];
676 $idle_workers = $active;
678 $deferred = self::deferredEntries();
680 if (DI::config()->get('system', 'worker_debug')) {
681 $waiting_processes = 0;
682 // Now adding all processes with workerqueue entries
683 $stamp = (float)microtime(true);
684 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
685 self::$db_duration += (microtime(true) - $stamp);
686 self::$db_duration_stat += (microtime(true) - $stamp);
687 while ($entry = DBA::fetch($jobs)) {
688 $stamp = (float)microtime(true);
689 $running = DBA::count('workerqueue-view', ['priority' => $entry['priority']]);
690 self::$db_duration += (microtime(true) - $stamp);
691 self::$db_duration_stat += (microtime(true) - $stamp);
692 $idle_workers -= $running;
693 $waiting_processes += $entry["entries"];
694 $listitem[$entry['priority']] = $entry['priority'] . ":" . $running . "/" . $entry["entries"];
698 $waiting_processes = self::totalEntries();
699 $stamp = (float)microtime(true);
700 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
701 self::$db_duration += (microtime(true) - $stamp);
702 self::$db_duration_stat += (microtime(true) - $stamp);
704 while ($entry = DBA::fetch($jobs)) {
705 $idle_workers -= $entry["running"];
706 $listitem[$entry['priority']] = $entry['priority'].":".$entry["running"];
711 $waiting_processes -= $deferred;
713 $listitem[0] = "0:" . max(0, $idle_workers);
715 $processlist .= ' ('.implode(', ', $listitem).')';
717 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
718 $top_priority = self::highestPriority();
719 $high_running = self::processWithPriorityActive($top_priority);
721 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
722 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
723 $queues = $active + 1;
727 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
729 // Are there fewer workers running as possible? Then fork a new one.
730 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
731 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
732 if (Worker\Daemon::isMode()) {
733 Worker\IPC::SetJobState(true);
740 // if there are too much worker, we don't spawn a new one.
741 if (Worker\Daemon::isMode() && ($active > $queues)) {
742 Worker\IPC::SetJobState(false);
745 return $active > $queues;
749 * Returns the number of active worker processes
751 * @return integer Number of active worker processes
754 private static function activeWorkers(): int
756 $stamp = (float)microtime(true);
757 $count = DI::process()->countCommand('Worker.php');
758 self::$db_duration += (microtime(true) - $stamp);
759 self::$db_duration_count += (microtime(true) - $stamp);
764 * Returns the number of active worker processes
766 * @return array List of worker process ids
769 private static function getWorkerPIDList(): array
772 $stamp = (float)microtime(true);
774 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
775 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
776 GROUP BY `process`.`pid`");
777 while ($queue = DBA::fetch($queues)) {
778 $ids[$queue['pid']] = $queue['entries'];
782 self::$db_duration += (microtime(true) - $stamp);
783 self::$db_duration_count += (microtime(true) - $stamp);
788 * Returns waiting jobs for the current process id
790 * @return array waiting workerqueue jobs
793 private static function getWaitingJobForPID(): array
795 $stamp = (float)microtime(true);
796 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
797 self::$db_duration += (microtime(true) - $stamp);
798 if (DBA::isResult($r)) {
799 return DBA::toArray($r);
807 * Returns the next jobs that should be executed
809 * @return array array with next jobs
812 private static function nextProcess(int $limit): array
814 $priority = self::nextPriority();
815 if (empty($priority)) {
816 Logger::info('No tasks found');
821 $stamp = (float)microtime(true);
822 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
823 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
824 self::$db_duration += (microtime(true) - $stamp);
825 while ($task = DBA::fetch($tasks)) {
826 $ids[] = $task['id'];
827 // Only continue that loop while we are storing commands that can be processed quickly
828 if (!empty($task['command'])) {
829 $command = $task['command'];
831 $command = json_decode($task['parameter'])[0];
834 if (!in_array($command, self::FAST_COMMANDS)) {
840 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
845 * Returns the priority of the next workerqueue job
847 * @return string|bool priority or FALSE on failure
850 private static function nextPriority()
853 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
854 foreach ($priorities as $priority) {
855 $stamp = (float)microtime(true);
856 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
857 $waiting[$priority] = true;
859 self::$db_duration += (microtime(true) - $stamp);
862 if (!empty($waiting[PRIORITY_CRITICAL])) {
863 return PRIORITY_CRITICAL;
868 $stamp = (float)microtime(true);
869 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
870 self::$db_duration += (microtime(true) - $stamp);
871 while ($process = DBA::fetch($processes)) {
872 $running[$process['priority']] = $process['running'];
873 $running_total += $process['running'];
875 DBA::close($processes);
877 foreach ($priorities as $priority) {
878 if (!empty($waiting[$priority]) && empty($running[$priority])) {
879 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
884 $active = max(self::activeWorkers(), $running_total);
885 $priorities = max(count($waiting), count($running));
889 for ($i = 1; $i <= $priorities; ++$i) {
890 $total += pow($i, $exponent);
894 for ($i = 1; $i <= $priorities; ++$i) {
895 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
899 foreach ($running as $priority => $workers) {
900 if ($workers < $limit[$i++]) {
901 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
906 if (!empty($waiting)) {
907 $priority = array_keys($waiting)[0];
908 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
916 * Find and claim the next worker process for us
919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
921 private static function findWorkerProcesses()
923 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
925 if (DI::config()->get('system', 'worker_multiple_fetch')) {
927 foreach (self::getWorkerPIDList() as $pid => $count) {
928 if ($count <= $fetch_limit) {
935 $limit = $fetch_limit * count($pids);
937 $pids = [getmypid()];
938 $limit = $fetch_limit;
941 $ids = self::nextProcess($limit);
942 $limit -= count($ids);
944 // If there is not enough results we check without priority limit
946 $stamp = (float)microtime(true);
947 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
948 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
949 self::$db_duration += (microtime(true) - $stamp);
951 while ($task = DBA::fetch($tasks)) {
952 $ids[] = $task['id'];
953 // Only continue that loop while we are storing commands that can be processed quickly
954 if (!empty($task['command'])) {
955 $command = $task['command'];
957 $command = json_decode($task['parameter'])[0];
959 if (!in_array($command, self::FAST_COMMANDS)) {
970 // Assign the task ids to the workers
972 foreach (array_unique($ids) as $id) {
977 $worker[$pid][] = $id;
980 $stamp = (float)microtime(true);
981 foreach ($worker as $worker_pid => $worker_ids) {
982 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
983 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
984 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
986 self::$db_duration += (microtime(true) - $stamp);
987 self::$db_duration_write += (microtime(true) - $stamp);
991 * Returns the next worker process
993 * @return array worker processes
994 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996 public static function workerProcess(): array
998 // There can already be jobs for us in the queue.
999 $waiting = self::getWaitingJobForPID();
1000 if (!empty($waiting)) {
1004 $stamp = (float)microtime(true);
1005 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1008 self::$lock_duration += (microtime(true) - $stamp);
1010 self::findWorkerProcesses();
1012 DI::lock()->release(self::LOCK_PROCESS);
1014 return self::getWaitingJobForPID();
1018 * Removes a workerqueue entry from the current process
1020 * @param Process $process the process behind the workerqueue
1023 * @throws \Exception
1025 public static function unclaimProcess(Process $process)
1027 $stamp = (float)microtime(true);
1028 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $process->pid, 'done' => false]);
1029 self::$db_duration += (microtime(true) - $stamp);
1030 self::$db_duration_write += (microtime(true) - $stamp);
1034 * Fork a child process
1036 * @param boolean $do_cron
1039 private static function forkProcess(bool $do_cron)
1041 if (DI::system()->isMinMemoryReached()) {
1042 Logger::warning('Memory limit reached - quitting');
1046 // Children inherit their parent's database connection.
1047 // To avoid problems we disconnect and connect both parent and child
1049 $pid = pcntl_fork();
1052 Logger::warning('Could not spawn worker');
1055 // The parent process continues here
1058 Worker\IPC::SetJobState(true, $pid);
1059 Logger::info('Spawned new worker', ['pid' => $pid]);
1062 while (Worker\IPC::JobsExists($pid) && (++$cycles < 100)) {
1066 Logger::info('Spawned worker is ready', ['pid' => $pid, 'wait_cycles' => $cycles]);
1070 // We now are in the new worker
1074 $process = DI::process()->create(getmypid(), basename(__FILE__));
1077 while (!Worker\IPC::JobsExists($process->pid) && (++$cycles < 100)) {
1081 Logger::info('Worker spawned', ['pid' => $process->pid, 'wait_cycles' => $cycles]);
1083 self::processQueue($do_cron, $process);
1085 self::unclaimProcess($process);
1087 Worker\IPC::SetJobState(false, $process->pid);
1088 DI::process()->delete($process);
1089 Logger::info('Worker ended', ['pid' => $process->pid]);
1094 * Spawns a new worker
1096 * @param bool $do_cron
1098 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1100 public static function spawnWorker(bool $do_cron = false)
1102 if (Worker\Daemon::isMode() && DI::config()->get('system', 'worker_fork')) {
1103 self::forkProcess($do_cron);
1105 DI::system()->run('bin/worker.php', ['no_cron' => !$do_cron]);
1107 if (Worker\Daemon::isMode()) {
1108 Worker\IPC::SetJobState(false);
1113 * Adds tasks to the worker queue
1115 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1117 * next args are passed as $cmd command line
1118 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1119 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1121 * @return int "0" if worker queue entry already existed or there had been an error, otherwise the ID of the worker task
1122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1123 * @note $cmd and string args are surrounded with ""
1129 public static function add(...$args)
1131 if (!count($args)) {
1135 $arr = ['args' => $args, 'run_cmd' => true];
1137 Hook::callAll("proc_run", $arr);
1138 if (!$arr['run_cmd'] || !count($args)) {
1142 $priority = PRIORITY_MEDIUM;
1143 // Don't fork from frontend tasks by default
1144 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1145 $created = DateTimeFormat::utcNow();
1146 $delayed = DBA::NULL_DATETIME;
1147 $force_priority = false;
1149 $run_parameter = array_shift($args);
1151 if (is_int($run_parameter)) {
1152 $priority = $run_parameter;
1153 } elseif (is_array($run_parameter)) {
1154 if (isset($run_parameter['delayed'])) {
1155 $delayed = $run_parameter['delayed'];
1157 if (isset($run_parameter['priority'])) {
1158 $priority = $run_parameter['priority'];
1160 if (isset($run_parameter['created'])) {
1161 $created = $run_parameter['created'];
1163 if (isset($run_parameter['dont_fork'])) {
1164 $dont_fork = $run_parameter['dont_fork'];
1166 if (isset($run_parameter['force_priority'])) {
1167 $force_priority = $run_parameter['force_priority'];
1170 throw new \InvalidArgumentException('Priority number or task parameter array expected as first argument');
1173 $command = array_shift($args);
1174 $parameters = json_encode($args);
1175 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1178 if (!is_int($priority) || !in_array($priority, PRIORITIES)) {
1179 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1180 $priority = PRIORITY_MEDIUM;
1183 // Quit if there was a database error - a precaution for the update process to 3.5.3
1184 if (DBA::errorNo() != 0) {
1189 if (!DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1190 'priority' => $priority, 'next_try' => $delayed])) {
1193 $added = DBA::lastInsertId();
1194 } elseif ($force_priority) {
1195 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1198 // Set the IPC flag to ensure an immediate process execution via daemon
1199 if (Worker\Daemon::isMode()) {
1200 Worker\IPC::SetJobState(true);
1203 Worker\Daemon::checkState();
1205 // Should we quit and wait for the worker to be called as a cronjob?
1210 // If there is a lock then we don't have to check for too much worker
1211 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1215 // If there are already enough workers running, don't fork another one
1216 $quit = self::tooMuchWorkers();
1217 DI::lock()->release(self::LOCK_WORKER);
1223 // Quit on daemon mode
1224 if (Worker\Daemon::isMode()) {
1228 // Now call the worker to execute the jobs that we just added to the queue
1229 self::spawnWorker();
1234 public static function countWorkersByCommand(string $command): int
1236 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1240 * Returns the next retrial level for worker jobs.
1241 * This function will skip levels when jobs are older.
1243 * @param array $queue Worker queue entry
1244 * @param integer $max_level maximum retrial level
1245 * @return integer the next retrial level value
1247 private static function getNextRetrial(array $queue, int $max_level): int
1249 $created = strtotime($queue['created']);
1250 $retrial_time = time() - $created;
1252 $new_retrial = $queue['retrial'] + 1;
1254 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1255 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1257 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1258 $new_retrial = $retrial;
1261 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1262 return $new_retrial;
1266 * Defers the current worker entry
1268 * @return boolean had the entry been deferred?
1269 * @throws \Exception
1271 public static function defer(): bool
1273 $queue = DI::app()->getQueue();
1275 if (empty($queue)) {
1280 $priority = $queue['priority'];
1282 $max_level = DI::config()->get('system', 'worker_defer_limit');
1284 $new_retrial = self::getNextRetrial($queue, $max_level);
1286 if ($new_retrial > $max_level) {
1287 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]);
1291 // Calculate the delay until the next trial
1292 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1293 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1295 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1296 $priority = PRIORITY_MEDIUM;
1297 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1298 $priority = PRIORITY_LOW;
1299 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1300 $priority = PRIORITY_NEGLIGIBLE;
1303 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1305 $stamp = (float)microtime(true);
1306 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1307 DBA::update('workerqueue', $fields, ['id' => $id]);
1308 self::$db_duration += (microtime(true) - $stamp);
1309 self::$db_duration_write += (microtime(true) - $stamp);
1315 * Check if the system is inside the defined maintenance window
1317 * @param bool $check_last_execution Whether check last execution
1320 public static function isInMaintenanceWindow(bool $check_last_execution = false): bool
1322 // Calculate the seconds of the start end end of the maintenance window
1323 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1324 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1326 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1328 if ($check_last_execution) {
1329 // Calculate the window duration
1330 $duration = max($start, $end) - min($start, $end);
1332 // Quit when the last cron execution had been after the previous window
1333 $last_cron = DI::config()->get('system', 'last_cron_daily');
1334 if ($last_cron + $duration > time()) {
1335 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)]);
1340 $current = time() % 86400;
1342 if ($start < $end) {
1343 // Execute if we are inside the window
1344 $execute = ($current >= $start) && ($current <= $end);
1346 // Don't execute if we are outside the window
1347 $execute = !(($current > $end) && ($current < $start));
1351 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)]);
1353 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)]);