3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core;
25 use Friendica\Database\DBA;
27 use Friendica\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;
54 * Processes the tasks that are in the workerqueue table
56 * @param boolean $run_cron Should the cron processes be executed?
58 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
60 public static function processQueue($run_cron = true)
62 // Ensure that all "strtotime" operations do run timezone independent
63 date_default_timezone_set('UTC');
65 self::$up_start = microtime(true);
67 // At first check the maximum load. We shouldn't continue with a high load
68 if (DI::process()->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 DI::process()->start();
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 self::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 // Don't refetch when a worker fetches tasks for multiple workers
99 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
100 foreach ($r as $entry) {
101 // Assure that the priority is an integer value
102 $entry['priority'] = (int)$entry['priority'];
104 // The work will be done
105 if (!self::execute($entry)) {
106 Logger::info('Process execution failed, quitting.');
110 // Trying to fetch new processes - but only once when successful
111 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
112 self::findWorkerProcesses();
113 DI::lock()->release(self::LOCK_PROCESS);
114 self::$state = self::STATE_REFETCH;
117 self::$state = self::STATE_SHORT_LOOP;
121 // To avoid the quitting of multiple workers only one worker at a time will execute the check
122 if ((time() > $last_check + 5) && !self::getWaitingJobForPID()) {
123 self::$state = self::STATE_LONG_LOOP;
125 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
126 // Count active workers and compare them with a maximum value that depends on the load
127 if (self::tooMuchWorkers()) {
128 Logger::info('Active worker limit reached, quitting.');
129 DI::lock()->release(self::LOCK_WORKER);
134 if (DI::process()->isMinMemoryReached()) {
135 Logger::notice('Memory limit reached, quitting.');
136 DI::lock()->release(self::LOCK_WORKER);
139 DI::lock()->release(self::LOCK_WORKER);
141 $last_check = time();
144 // Quit the worker once every cron interval
145 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
146 Logger::info('Process lifetime reached, respawning.');
147 self::unclaimProcess();
153 // Cleaning up. Possibly not needed, but it doesn't harm anything.
154 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
155 self::IPCSetJobState(false);
157 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
161 * Checks if the system is ready.
163 * Several system parameters like memory, connections and processes are checked.
167 public static function isReady()
169 // Count active workers and compare them with a maximum value that depends on the load
170 if (self::tooMuchWorkers()) {
171 Logger::info('Active worker limit reached, quitting.');
175 // Do we have too few memory?
176 if (DI::process()->isMinMemoryReached()) {
177 Logger::notice('Memory limit reached, quitting.');
181 // Possibly there are too much database connections
182 if (self::maxConnectionsReached()) {
183 Logger::notice('Maximum connections reached, quitting.');
187 // Possibly there are too much database processes that block the system
188 if (DI::process()->isMaxProcessesReached()) {
189 Logger::notice('Maximum processes reached, quitting.');
197 * Check if non executed tasks do exist in the worker queue
199 * @return boolean Returns "true" if tasks are existing
202 public static function entriesExists()
204 $stamp = (float)microtime(true);
205 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
206 self::$db_duration += (microtime(true) - $stamp);
211 * Returns the number of deferred entries in the worker queue
213 * @return integer Number of deferred entries in the worker queue
216 private static function deferredEntries()
218 $stamp = (float)microtime(true);
219 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
220 self::$db_duration += (microtime(true) - $stamp);
221 self::$db_duration_count += (microtime(true) - $stamp);
226 * Returns the number of non executed entries in the worker queue
228 * @return integer Number of non executed entries in the worker queue
231 private static function totalEntries()
233 $stamp = (float)microtime(true);
234 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
235 self::$db_duration += (microtime(true) - $stamp);
236 self::$db_duration_count += (microtime(true) - $stamp);
241 * Returns the highest priority in the worker queue that isn't executed
243 * @return integer Number of active worker processes
246 private static function highestPriority()
248 $stamp = (float)microtime(true);
249 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
250 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
251 self::$db_duration += (microtime(true) - $stamp);
252 if (DBA::isResult($workerqueue)) {
253 return $workerqueue["priority"];
260 * Returns if a process with the given priority is running
262 * @param integer $priority The priority that should be checked
264 * @return integer Is there a process running with that priority?
267 private static function processWithPriorityActive($priority)
269 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
270 return DBA::exists('workerqueue', $condition);
274 * Execute a worker entry
276 * @param array $queue Workerqueue entry
278 * @return boolean "true" if further processing should be stopped
279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
281 public static function execute($queue)
285 // Quit when in maintenance
286 if (DI::config()->get('system', 'maintenance', false, true)) {
287 Logger::notice("Maintenance mode - quit process", ['pid' => $mypid]);
291 // Constantly check the number of parallel database processes
292 if (DI::process()->isMaxProcessesReached()) {
293 Logger::notice("Max processes reached for process", ['pid' => $mypid]);
297 // Constantly check the number of available database connections to let the frontend be accessible at any time
298 if (self::maxConnectionsReached()) {
299 Logger::notice("Max connection reached for process", ['pid' => $mypid]);
303 $argv = json_decode($queue['parameter'], true);
304 if (!empty($queue['command'])) {
305 array_unshift($argv, $queue['command']);
309 Logger::warning('Parameter is empty', ['queue' => $queue]);
313 // Check for existance and validity of the include file
316 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
317 // We constantly update the "executed" date every minute to avoid being killed too soon
318 if (!isset(self::$last_update)) {
319 self::$last_update = strtotime($queue["executed"]);
322 $age = (time() - self::$last_update) / 60;
323 self::$last_update = time();
326 $stamp = (float)microtime(true);
327 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
328 self::$db_duration += (microtime(true) - $stamp);
329 self::$db_duration_write += (microtime(true) - $stamp);
334 self::execFunction($queue, $include, $argv, true);
336 $stamp = (float)microtime(true);
337 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
338 if (DBA::update('workerqueue', ['done' => true], $condition)) {
339 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
341 self::$db_duration = (microtime(true) - $stamp);
342 self::$db_duration_write += (microtime(true) - $stamp);
347 // The script could be provided as full path or only with the function name
348 if ($include == basename($include)) {
349 $include = "include/".$include.".php";
352 if (!validate_include($include)) {
353 Logger::warning("Include file is not valid", ['file' => $argv[0]]);
354 $stamp = (float)microtime(true);
355 DBA::delete('workerqueue', ['id' => $queue["id"]]);
356 self::$db_duration = (microtime(true) - $stamp);
357 self::$db_duration_write += (microtime(true) - $stamp);
361 require_once $include;
363 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
365 if (function_exists($funcname)) {
366 // We constantly update the "executed" date every minute to avoid being killed too soon
367 if (!isset(self::$last_update)) {
368 self::$last_update = strtotime($queue["executed"]);
371 $age = (time() - self::$last_update) / 60;
372 self::$last_update = time();
375 $stamp = (float)microtime(true);
376 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
377 self::$db_duration += (microtime(true) - $stamp);
378 self::$db_duration_write += (microtime(true) - $stamp);
381 self::execFunction($queue, $funcname, $argv, false);
383 $stamp = (float)microtime(true);
384 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
385 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
387 self::$db_duration = (microtime(true) - $stamp);
388 self::$db_duration_write += (microtime(true) - $stamp);
390 Logger::warning("Function does not exist", ['function' => $funcname]);
391 $stamp = (float)microtime(true);
392 DBA::delete('workerqueue', ['id' => $queue["id"]]);
393 self::$db_duration = (microtime(true) - $stamp);
394 self::$db_duration_write += (microtime(true) - $stamp);
401 * Execute a function from the queue
403 * @param array $queue Workerqueue entry
404 * @param string $funcname name of the function
405 * @param array $argv Array of values to be passed to the function
406 * @param boolean $method_call boolean
408 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
410 private static function execFunction($queue, $funcname, $argv, $method_call)
414 Logger::enableWorker($funcname);
416 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
418 $stamp = (float)microtime(true);
420 // We use the callstack here to analyze the performance of executed worker entries.
421 // For this reason the variables have to be initialized.
422 DI::profiler()->reset();
426 $up_duration = microtime(true) - self::$up_start;
428 // Reset global data to avoid interferences
431 // Set the workerLogger as new default logger
433 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
435 $funcname($argv, count($argv));
438 Logger::disableWorker();
442 $duration = (microtime(true) - $stamp);
444 /* With these values we can analyze how effective the worker is.
445 * The database and rest time should be low since this is the unproductive time.
446 * The execution time is the productive time.
447 * By changing parameters like the maximum number of workers we can check the effectivness.
449 $dbtotal = round(self::$db_duration, 2);
450 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
451 $dbcount = round(self::$db_duration_count, 2);
452 $dbstat = round(self::$db_duration_stat, 2);
453 $dbwrite = round(self::$db_duration_write, 2);
454 $dblock = round(self::$lock_duration, 2);
455 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
456 $exec = round($duration, 2);
458 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
460 self::$up_start = microtime(true);
461 self::$db_duration = 0;
462 self::$db_duration_count = 0;
463 self::$db_duration_stat = 0;
464 self::$db_duration_write = 0;
465 self::$lock_duration = 0;
467 if ($duration > 3600) {
468 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
469 } elseif ($duration > 600) {
470 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
471 } elseif ($duration > 300) {
472 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
473 } elseif ($duration > 120) {
474 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
477 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
479 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
481 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
484 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
490 * Checks if the number of database connections has reached a critical limit.
492 * @return bool Are more than 3/4 of the maximum connections used?
493 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
495 private static function maxConnectionsReached()
497 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
498 $max = DI::config()->get("system", "max_connections");
500 // Fetch the percentage level where the worker will get active
501 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
504 // the maximum number of possible user connections can be a system variable
505 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
506 if (DBA::isResult($r)) {
509 // Or it can be granted. This overrides the system variable
510 $stamp = (float)microtime(true);
511 $r = DBA::p('SHOW GRANTS');
512 self::$db_duration += (microtime(true) - $stamp);
513 while ($grants = DBA::fetch($r)) {
514 $grant = array_pop($grants);
515 if (stristr($grant, "GRANT USAGE ON")) {
516 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
524 // If $max is set we will use the processlist to determine the current number of connections
525 // The processlist only shows entries of the current user
527 $stamp = (float)microtime(true);
528 $r = DBA::p('SHOW PROCESSLIST');
529 self::$db_duration += (microtime(true) - $stamp);
530 $used = DBA::numRows($r);
533 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
535 $level = ($used / $max) * 100;
537 if ($level >= $maxlevel) {
538 Logger::notice("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
543 // We will now check for the system values.
544 // This limit could be reached although the user limits are fine.
545 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
546 if (!DBA::isResult($r)) {
549 $max = intval($r["Value"]);
553 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
554 if (!DBA::isResult($r)) {
557 $used = intval($r["Value"]);
561 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
563 $level = $used / $max * 100;
565 if ($level < $maxlevel) {
568 Logger::notice("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
573 * fix the queue entry if the worker process died
578 private static function killStaleWorkers()
580 $stamp = (float)microtime(true);
581 $entries = DBA::select(
583 ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
584 ['NOT `done` AND `pid` != 0'],
585 ['order' => ['priority', 'retrial', 'created']]
587 self::$db_duration += (microtime(true) - $stamp);
589 while ($entry = DBA::fetch($entries)) {
590 if (!posix_kill($entry["pid"], 0)) {
591 $stamp = (float)microtime(true);
594 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
595 ['id' => $entry["id"]]
597 self::$db_duration += (microtime(true) - $stamp);
598 self::$db_duration_write += (microtime(true) - $stamp);
600 // Kill long running processes
601 // Check if the priority is in a valid range
602 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
603 $entry["priority"] = PRIORITY_MEDIUM;
606 // Define the maximum durations
607 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
608 $max_duration = $max_duration_defaults[$entry["priority"]];
610 $argv = json_decode($entry['parameter'], true);
611 if (!empty($entry['command'])) {
612 $command = $entry['command'];
613 } elseif (!empty($argv)) {
614 $command = array_shift($argv);
619 $command = basename($command);
621 // How long is the process already running?
622 $duration = (time() - strtotime($entry["executed"])) / 60;
623 if ($duration > $max_duration) {
624 Logger::notice('Worker process took too much time - killed', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
625 posix_kill($entry["pid"], SIGTERM);
627 // We killed the stale process.
628 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
629 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
630 $new_priority = $entry["priority"];
631 if ($entry["priority"] == PRIORITY_HIGH) {
632 $new_priority = PRIORITY_MEDIUM;
633 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
634 $new_priority = PRIORITY_LOW;
635 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
636 $new_priority = PRIORITY_NEGLIGIBLE;
638 $stamp = (float)microtime(true);
641 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
642 ['id' => $entry["id"]]
644 self::$db_duration += (microtime(true) - $stamp);
645 self::$db_duration_write += (microtime(true) - $stamp);
647 Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
651 DBA::close($entries);
655 * Checks if the number of active workers exceeds the given limits
657 * @return bool Are there too much workers running?
658 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
660 private static function tooMuchWorkers()
662 $queues = DI::config()->get("system", "worker_queues", 10);
664 $maxqueues = $queues;
666 $active = self::activeWorkers();
668 // Decrease the number of workers at higher load
669 $load = System::currentLoad();
671 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
673 /* Default exponent 3 causes queues to rapidly decrease as load increases.
674 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
675 * For some environments, this rapid decrease is not needed.
676 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
678 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
679 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
680 $queues = intval(ceil($slope * $maxqueues));
684 if (DI::config()->get('system', 'worker_jpm')) {
685 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
686 $jobs_per_minute = [];
687 foreach ($intervals as $interval) {
688 if ($interval == 0) {
691 $interval = (int)$interval;
694 $stamp = (float)microtime(true);
695 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
696 self::$db_duration += (microtime(true) - $stamp);
697 self::$db_duration_stat += (microtime(true) - $stamp);
698 if ($job = DBA::fetch($jobs)) {
699 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
703 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
706 // Create a list of queue entries grouped by their priority
707 $listitem = [0 => ''];
709 $idle_workers = $active;
711 $deferred = self::deferredEntries();
713 if (DI::config()->get('system', 'worker_debug')) {
714 $waiting_processes = 0;
715 // Now adding all processes with workerqueue entries
716 $stamp = (float)microtime(true);
717 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
718 self::$db_duration += (microtime(true) - $stamp);
719 self::$db_duration_stat += (microtime(true) - $stamp);
720 while ($entry = DBA::fetch($jobs)) {
721 $stamp = (float)microtime(true);
722 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
723 self::$db_duration += (microtime(true) - $stamp);
724 self::$db_duration_stat += (microtime(true) - $stamp);
725 if ($process = DBA::fetch($processes)) {
726 $idle_workers -= $process["running"];
727 $waiting_processes += $entry["entries"];
728 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
730 DBA::close($processes);
734 $waiting_processes = self::totalEntries();
735 $stamp = (float)microtime(true);
736 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
737 self::$db_duration += (microtime(true) - $stamp);
738 self::$db_duration_stat += (microtime(true) - $stamp);
740 while ($entry = DBA::fetch($jobs)) {
741 $idle_workers -= $entry["running"];
742 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
747 $waiting_processes -= $deferred;
749 $listitem[0] = "0:" . max(0, $idle_workers);
751 $processlist .= ' ('.implode(', ', $listitem).')';
753 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
754 $top_priority = self::highestPriority();
755 $high_running = self::processWithPriorityActive($top_priority);
757 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
758 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
759 $queues = $active + 1;
763 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
765 // Are there fewer workers running as possible? Then fork a new one.
766 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
767 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
768 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
769 self::IPCSetJobState(true);
776 // if there are too much worker, we don't spawn a new one.
777 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
778 self::IPCSetJobState(false);
781 return $active > $queues;
785 * Returns the number of active worker processes
787 * @return integer Number of active worker processes
790 private static function activeWorkers()
792 $stamp = (float)microtime(true);
793 $count = DBA::count('process', ['command' => 'Worker.php']);
794 self::$db_duration += (microtime(true) - $stamp);
795 self::$db_duration_count += (microtime(true) - $stamp);
800 * Returns the number of active worker processes
802 * @return array List of worker process ids
805 private static function getWorkerPIDList()
808 $stamp = (float)microtime(true);
810 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
811 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
812 GROUP BY `process`.`pid`");
813 while ($queue = DBA::fetch($queues)) {
814 $ids[$queue['pid']] = $queue['entries'];
818 self::$db_duration += (microtime(true) - $stamp);
819 self::$db_duration_count += (microtime(true) - $stamp);
824 * Returns waiting jobs for the current process id
826 * @return array waiting workerqueue jobs
829 private static function getWaitingJobForPID()
831 $stamp = (float)microtime(true);
832 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
833 self::$db_duration += (microtime(true) - $stamp);
834 if (DBA::isResult($r)) {
835 return DBA::toArray($r);
843 * Returns the next jobs that should be executed
845 * @return array array with next jobs
848 private static function nextProcess(int $limit)
850 $priority = self::nextPriority();
851 if (empty($priority)) {
852 Logger::info('No tasks found');
857 $stamp = (float)microtime(true);
858 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
859 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
860 self::$db_duration += (microtime(true) - $stamp);
861 while ($task = DBA::fetch($tasks)) {
862 $ids[] = $task['id'];
863 // Only continue that loop while we are storing commands that can be processed quickly
864 if (!empty($task['command'])) {
865 $command = $task['command'];
867 $command = json_decode($task['parameter'])[0];
870 if (!in_array($command, self::FAST_COMMANDS)) {
876 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
881 * Returns the priority of the next workerqueue job
883 * @return string priority
886 private static function nextPriority()
889 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
890 foreach ($priorities as $priority) {
891 $stamp = (float)microtime(true);
892 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
893 $waiting[$priority] = true;
895 self::$db_duration += (microtime(true) - $stamp);
898 if (!empty($waiting[PRIORITY_CRITICAL])) {
899 return PRIORITY_CRITICAL;
904 $stamp = (float)microtime(true);
905 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
906 self::$db_duration += (microtime(true) - $stamp);
907 while ($process = DBA::fetch($processes)) {
908 $running[$process['priority']] = $process['running'];
909 $running_total += $process['running'];
911 DBA::close($processes);
913 foreach ($priorities as $priority) {
914 if (!empty($waiting[$priority]) && empty($running[$priority])) {
915 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
920 $active = max(self::activeWorkers(), $running_total);
921 $priorities = max(count($waiting), count($running));
925 for ($i = 1; $i <= $priorities; ++$i) {
926 $total += pow($i, $exponent);
930 for ($i = 1; $i <= $priorities; ++$i) {
931 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
935 foreach ($running as $priority => $workers) {
936 if ($workers < $limit[$i++]) {
937 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
942 if (!empty($waiting)) {
943 $priority = array_keys($waiting)[0];
944 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
952 * Find and claim the next worker process for us
954 * @return boolean Have we found something?
955 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
957 private static function findWorkerProcesses()
959 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
961 if (DI::config()->get('system', 'worker_multiple_fetch')) {
963 foreach (self::getWorkerPIDList() as $pid => $count) {
964 if ($count <= $fetch_limit) {
971 $limit = $fetch_limit * count($pids);
973 $pids = [getmypid()];
974 $limit = $fetch_limit;
977 $ids = self::nextProcess($limit);
978 $limit -= count($ids);
980 // If there is not enough results we check without priority limit
982 $stamp = (float)microtime(true);
983 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
984 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
985 self::$db_duration += (microtime(true) - $stamp);
987 while ($task = DBA::fetch($tasks)) {
988 $ids[] = $task['id'];
989 // Only continue that loop while we are storing commands that can be processed quickly
990 if (!empty($task['command'])) {
991 $command = $task['command'];
993 $command = json_decode($task['parameter'])[0];
995 if (!in_array($command, self::FAST_COMMANDS)) {
1006 // Assign the task ids to the workers
1008 foreach (array_unique($ids) as $id) {
1011 $pid = reset($pids);
1013 $worker[$pid][] = $id;
1016 $stamp = (float)microtime(true);
1017 foreach ($worker as $worker_pid => $worker_ids) {
1018 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1019 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1020 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1022 self::$db_duration += (microtime(true) - $stamp);
1023 self::$db_duration_write += (microtime(true) - $stamp);
1027 * Returns the next worker process
1029 * @return array worker processes
1030 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1032 public static function workerProcess()
1034 // There can already be jobs for us in the queue.
1035 $waiting = self::getWaitingJobForPID();
1036 if (!empty($waiting)) {
1040 $stamp = (float)microtime(true);
1041 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1044 self::$lock_duration += (microtime(true) - $stamp);
1046 self::findWorkerProcesses();
1048 DI::lock()->release(self::LOCK_PROCESS);
1050 return self::getWaitingJobForPID();
1054 * Removes a workerqueue entry from the current process
1057 * @throws \Exception
1059 public static function unclaimProcess()
1061 $mypid = getmypid();
1063 $stamp = (float)microtime(true);
1064 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1065 self::$db_duration += (microtime(true) - $stamp);
1066 self::$db_duration_write += (microtime(true) - $stamp);
1070 * Call the front end worker
1073 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1075 public static function callWorker()
1077 if (!DI::config()->get("system", "frontend_worker")) {
1081 $url = DI::baseUrl() . '/worker';
1082 DI::httpRequest()->fetch($url, 1);
1086 * Call the front end worker if there aren't any active
1089 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1091 public static function executeIfIdle()
1093 self::checkDaemonState();
1095 if (!DI::config()->get("system", "frontend_worker")) {
1099 // Do we have "proc_open"? Then we can fork the worker
1100 if (function_exists("proc_open")) {
1101 // When was the last time that we called the worker?
1102 // Less than one minute? Then we quit
1103 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1107 DI::config()->set("system", "worker_started", time());
1109 // Do we have enough running workers? Then we quit here.
1110 if (self::tooMuchWorkers()) {
1111 // Cleaning dead processes
1112 self::killStaleWorkers();
1113 DI::modelProcess()->deleteInactive();
1120 Logger::info('Call worker');
1121 self::spawnWorker();
1125 // We cannot execute background processes.
1126 // We now run the processes from the frontend.
1127 // This won't work with long running processes.
1130 self::clearProcesses();
1132 $workers = self::activeWorkers();
1134 if ($workers == 0) {
1140 * Removes long running worker processes
1143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1145 public static function clearProcesses()
1147 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1149 /// @todo We should clean up the corresponding workerqueue entries as well
1150 $stamp = (float)microtime(true);
1151 $condition = ["`created` < ? AND `command` = 'worker.php'",
1152 DateTimeFormat::utc("now - ".$timeout." minutes")];
1153 DBA::delete('process', $condition);
1154 self::$db_duration = (microtime(true) - $stamp);
1155 self::$db_duration_write += (microtime(true) - $stamp);
1159 * Runs the cron processes
1162 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1164 private static function runCron()
1166 Logger::info('Add cron entries');
1168 // Check for spooled items
1169 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1171 // Run the cron job that calls all other jobs
1172 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1174 // Cleaning dead processes
1175 self::killStaleWorkers();
1179 * Spawns a new worker
1181 * @param bool $do_cron
1183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1185 public static function spawnWorker($do_cron = false)
1187 $command = 'bin/worker.php';
1189 $args = ['no_cron' => !$do_cron];
1192 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), DI::modelProcess(), $a->getBasePath(), getmypid());
1193 $process->run($command, $args);
1195 // after spawning we have to remove the flag.
1196 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1197 self::IPCSetJobState(false);
1202 * Adds tasks to the worker queue
1204 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1206 * next args are passed as $cmd command line
1207 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1208 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1210 * @return boolean "false" if worker queue entry already existed or there had been an error
1211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1212 * @note $cmd and string args are surrounded with ""
1218 public static function add($cmd)
1220 $args = func_get_args();
1222 if (!count($args)) {
1226 $arr = ['args' => $args, 'run_cmd' => true];
1228 Hook::callAll("proc_run", $arr);
1229 if (!$arr['run_cmd'] || !count($args)) {
1233 $priority = PRIORITY_MEDIUM;
1234 // Don't fork from frontend tasks by default
1235 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1236 $created = DateTimeFormat::utcNow();
1237 $delayed = DBA::NULL_DATETIME;
1238 $force_priority = false;
1240 $run_parameter = array_shift($args);
1242 if (is_int($run_parameter)) {
1243 $priority = $run_parameter;
1244 } elseif (is_array($run_parameter)) {
1245 if (isset($run_parameter['delayed'])) {
1246 $delayed = $run_parameter['delayed'];
1248 if (isset($run_parameter['priority'])) {
1249 $priority = $run_parameter['priority'];
1251 if (isset($run_parameter['created'])) {
1252 $created = $run_parameter['created'];
1254 if (isset($run_parameter['dont_fork'])) {
1255 $dont_fork = $run_parameter['dont_fork'];
1257 if (isset($run_parameter['force_priority'])) {
1258 $force_priority = $run_parameter['force_priority'];
1262 $command = array_shift($args);
1263 $parameters = json_encode($args);
1264 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1267 // Quit if there was a database error - a precaution for the update process to 3.5.3
1268 if (DBA::errorNo() != 0) {
1273 $added = DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1274 'priority' => $priority, 'next_try' => $delayed]);
1278 } elseif ($force_priority) {
1279 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1282 // Set the IPC flag to ensure an immediate process execution via daemon
1283 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1284 self::IPCSetJobState(true);
1287 self::checkDaemonState();
1289 // Should we quit and wait for the worker to be called as a cronjob?
1294 // If there is a lock then we don't have to check for too much worker
1295 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1299 // If there are already enough workers running, don't fork another one
1300 $quit = self::tooMuchWorkers();
1301 DI::lock()->release(self::LOCK_WORKER);
1307 // Quit on daemon mode
1308 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1312 // Now call the worker to execute the jobs that we just added to the queue
1313 self::spawnWorker();
1318 public static function countWorkersByCommand(string $command)
1320 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1324 * Returns the next retrial level for worker jobs.
1325 * This function will skip levels when jobs are older.
1327 * @param array $queue Worker queue entry
1328 * @param integer $max_level maximum retrial level
1329 * @return integer the next retrial level value
1331 private static function getNextRetrial($queue, $max_level)
1333 $created = strtotime($queue['created']);
1334 $retrial_time = time() - $created;
1336 $new_retrial = $queue['retrial'] + 1;
1338 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1339 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1341 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1342 $new_retrial = $retrial;
1345 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1346 return $new_retrial;
1350 * Defers the current worker entry
1352 * @return boolean had the entry been deferred?
1354 public static function defer()
1356 if (empty(DI::app()->queue)) {
1360 $queue = DI::app()->queue;
1362 $retrial = $queue['retrial'];
1364 $priority = $queue['priority'];
1366 $max_level = DI::config()->get('system', 'worker_defer_limit');
1368 $new_retrial = self::getNextRetrial($queue, $max_level);
1370 if ($new_retrial > $max_level) {
1371 Logger::info('The task exceeded the maximum retry count', ['id' => $id, 'created' => $queue['created'], 'old_prio' => $queue['priority'], 'old_retrial' => $queue['retrial'], 'max_level' => $max_level, 'retrial' => $new_retrial]);
1375 // Calculate the delay until the next trial
1376 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1377 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1379 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1380 $priority = PRIORITY_MEDIUM;
1381 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1382 $priority = PRIORITY_LOW;
1383 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1384 $priority = PRIORITY_NEGLIGIBLE;
1387 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1389 $stamp = (float)microtime(true);
1390 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1391 DBA::update('workerqueue', $fields, ['id' => $id]);
1392 self::$db_duration += (microtime(true) - $stamp);
1393 self::$db_duration_write += (microtime(true) - $stamp);
1399 * Set the flag if some job is waiting
1401 * @param boolean $jobs Is there a waiting job?
1402 * @throws \Exception
1404 public static function IPCSetJobState($jobs)
1406 $stamp = (float)microtime(true);
1407 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1408 self::$db_duration += (microtime(true) - $stamp);
1409 self::$db_duration_write += (microtime(true) - $stamp);
1413 * Checks if some worker job waits to be executed
1416 * @throws \Exception
1418 public static function IPCJobsExists()
1420 $stamp = (float)microtime(true);
1421 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1422 self::$db_duration += (microtime(true) - $stamp);
1424 // When we don't have a row, no job is running
1425 if (!DBA::isResult($row)) {
1429 return (bool)$row['jobs'];
1433 * Test if the daemon is running. If not, it will be started
1437 private static function checkDaemonState()
1439 if (!DI::config()->get('system', 'daemon_watchdog', false)) {
1443 if (!DI::mode()->isNormal()) {
1447 // Check every minute if the daemon is running
1448 if (DI::config()->get('system', 'last_daemon_check', 0) + 60 > time()) {
1452 DI::config()->set('system', 'last_daemon_check', time());
1454 $pidfile = DI::config()->get('system', 'pidfile');
1455 if (empty($pidfile)) {
1456 // No pid file, no daemon
1460 if (!is_readable($pidfile)) {
1461 // No pid file. We assume that the daemon had been intentionally stopped.
1465 $pid = intval(file_get_contents($pidfile));
1466 if (posix_kill($pid, 0)) {
1467 Logger::info('Daemon process is running', ['pid' => $pid]);
1471 Logger::warning('Daemon process is not running', ['pid' => $pid]);
1473 self::spawnDaemon();
1477 * Spawn a new daemon process
1481 private static function spawnDaemon()
1483 Logger::info('Starting new daemon process');
1484 $command = 'bin/daemon.php';
1486 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), DI::modelProcess(), $a->getBasePath(), getmypid());
1487 $process->run($command, ['start']);
1488 Logger::info('New daemon process started');
1492 * Check if the system is inside the defined maintenance window
1496 public static function isInMaintenanceWindow(bool $check_last_execution = false)
1498 // Calculate the seconds of the start end end of the maintenance window
1499 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1500 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1502 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1504 if ($check_last_execution) {
1505 // Calculate the window duration
1506 $duration = max($start, $end) - min($start, $end);
1508 // Quit when the last cron execution had been after the previous window
1509 $last_cron = DI::config()->get('system', 'last_cron_daily');
1510 if ($last_cron + $duration > time()) {
1511 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)]);
1516 $current = time() % 86400;
1518 if ($start < $end) {
1519 // Execute if we are inside the window
1520 $execute = ($current >= $start) && ($current <= $end);
1522 // Don't execute if we are outside the window
1523 $execute = !(($current > $end) && ($current < $start));
1527 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)]);
1529 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)]);