3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core;
25 use Friendica\Database\DBA;
27 use Friendica\Model\Process;
28 use Friendica\Util\DateTimeFormat;
31 * Contains the class for the worker background job processing
35 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
36 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
37 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
38 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
40 const FAST_COMMANDS = ['APDelivery', 'Delivery', 'CreateShadowEntry'];
42 const LOCK_PROCESS = 'worker_process';
43 const LOCK_WORKER = 'worker';
45 private static $up_start;
46 private static $db_duration = 0;
47 private static $db_duration_count = 0;
48 private static $db_duration_write = 0;
49 private static $db_duration_stat = 0;
50 private static $lock_duration = 0;
51 private static $last_update;
52 private static $state;
55 * Processes the tasks that are in the workerqueue table
57 * @param boolean $run_cron Should the cron processes be executed?
59 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
61 public static function processQueue($run_cron = true)
63 // Ensure that all "strtotime" operations do run timezone independent
64 date_default_timezone_set('UTC');
66 self::$up_start = microtime(true);
68 // At first check the maximum load. We shouldn't continue with a high load
69 if (DI::process()->isMaxLoadReached()) {
70 Logger::info('Pre check: maximum load reached, quitting.');
74 // We now start the process. This is done after the load check since this could increase the load.
77 // Kill stale processes every 5 minutes
78 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
79 if (time() > ($last_cleanup + 300)) {
80 DI::config()->set('system', 'worker_last_cleaned', time());
81 self::killStaleWorkers();
84 // Count active workers and compare them with a maximum value that depends on the load
85 if (self::tooMuchWorkers()) {
86 Logger::info('Pre check: Active worker limit reached, quitting.');
90 // Do we have too few memory?
91 if (DI::process()->isMinMemoryReached()) {
92 Logger::info('Pre check: Memory limit reached, quitting.');
96 // Possibly there are too much database connections
97 if (self::maxConnectionsReached()) {
98 Logger::info('Pre check: maximum connections reached, quitting.');
102 // Possibly there are too much database processes that block the system
103 if (DI::process()->isMaxProcessesReached()) {
104 Logger::info('Pre check: maximum processes reached, quitting.');
108 // Now we start additional cron processes if we should do so
114 self::$state = self::STATE_STARTUP;
116 // We fetch the next queue entry that is about to be executed
117 while ($r = self::workerProcess()) {
119 foreach ($r as $entry) {
120 // Assure that the priority is an integer value
121 $entry['priority'] = (int)$entry['priority'];
123 // The work will be done
124 if (!self::execute($entry)) {
125 Logger::info('Process execution failed, quitting.');
129 // Trying to fetch new processes - but only once when successful
130 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
131 self::findWorkerProcesses();
132 DI::lock()->release(self::LOCK_PROCESS);
133 self::$state = self::STATE_REFETCH;
136 self::$state = self::STATE_SHORT_LOOP;
140 // To avoid the quitting of multiple workers only one worker at a time will execute the check
141 if (!self::getWaitingJobForPID()) {
142 self::$state = self::STATE_LONG_LOOP;
144 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
145 // Count active workers and compare them with a maximum value that depends on the load
146 if (self::tooMuchWorkers()) {
147 Logger::info('Active worker limit reached, quitting.');
148 DI::lock()->release(self::LOCK_WORKER);
153 if (DI::process()->isMinMemoryReached()) {
154 Logger::info('Memory limit reached, quitting.');
155 DI::lock()->release(self::LOCK_WORKER);
158 DI::lock()->release(self::LOCK_WORKER);
162 // Quit the worker once every cron interval
163 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
164 Logger::info('Process lifetime reached, respawning.');
170 // Cleaning up. Possibly not needed, but it doesn't harm anything.
171 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
172 self::IPCSetJobState(false);
174 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
178 * Check if non executed tasks do exist in the worker queue
180 * @return boolean Returns "true" if tasks are existing
183 private static function entriesExists()
185 $stamp = (float)microtime(true);
186 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
187 self::$db_duration += (microtime(true) - $stamp);
192 * Returns the number of deferred entries in the worker queue
194 * @return integer Number of deferred entries in the worker queue
197 private static function deferredEntries()
199 $stamp = (float)microtime(true);
200 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
201 self::$db_duration += (microtime(true) - $stamp);
202 self::$db_duration_count += (microtime(true) - $stamp);
207 * Returns the number of non executed entries in the worker queue
209 * @return integer Number of non executed entries in the worker queue
212 private static function totalEntries()
214 $stamp = (float)microtime(true);
215 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
216 self::$db_duration += (microtime(true) - $stamp);
217 self::$db_duration_count += (microtime(true) - $stamp);
222 * Returns the highest priority in the worker queue that isn't executed
224 * @return integer Number of active worker processes
227 private static function highestPriority()
229 $stamp = (float)microtime(true);
230 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
231 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
232 self::$db_duration += (microtime(true) - $stamp);
233 if (DBA::isResult($workerqueue)) {
234 return $workerqueue["priority"];
241 * Returns if a process with the given priority is running
243 * @param integer $priority The priority that should be checked
245 * @return integer Is there a process running with that priority?
248 private static function processWithPriorityActive($priority)
250 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
251 return DBA::exists('workerqueue', $condition);
255 * Execute a worker entry
257 * @param array $queue Workerqueue entry
259 * @return boolean "true" if further processing should be stopped
260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
262 public static function execute($queue)
266 // Quit when in maintenance
267 if (DI::config()->get('system', 'maintenance', false, true)) {
268 Logger::info("Maintenance mode - quit process", ['pid' => $mypid]);
272 // Constantly check the number of parallel database processes
273 if (DI::process()->isMaxProcessesReached()) {
274 Logger::info("Max processes reached for process", ['pid' => $mypid]);
278 // Constantly check the number of available database connections to let the frontend be accessible at any time
279 if (self::maxConnectionsReached()) {
280 Logger::info("Max connection reached for process", ['pid' => $mypid]);
284 $argv = json_decode($queue["parameter"], true);
286 Logger::error('Parameter is empty', ['queue' => $queue]);
290 // Check for existance and validity of the include file
293 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
294 // We constantly update the "executed" date every minute to avoid being killed too soon
295 if (!isset(self::$last_update)) {
296 self::$last_update = strtotime($queue["executed"]);
299 $age = (time() - self::$last_update) / 60;
300 self::$last_update = time();
303 $stamp = (float)microtime(true);
304 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
305 self::$db_duration += (microtime(true) - $stamp);
306 self::$db_duration_write += (microtime(true) - $stamp);
311 self::execFunction($queue, $include, $argv, true);
313 $stamp = (float)microtime(true);
314 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
315 if (DBA::update('workerqueue', ['done' => true], $condition)) {
316 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
318 self::$db_duration = (microtime(true) - $stamp);
319 self::$db_duration_write += (microtime(true) - $stamp);
324 // The script could be provided as full path or only with the function name
325 if ($include == basename($include)) {
326 $include = "include/".$include.".php";
329 if (!validate_include($include)) {
330 Logger::log("Include file ".$argv[0]." is not valid!");
331 $stamp = (float)microtime(true);
332 DBA::delete('workerqueue', ['id' => $queue["id"]]);
333 self::$db_duration = (microtime(true) - $stamp);
334 self::$db_duration_write += (microtime(true) - $stamp);
338 require_once $include;
340 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
342 if (function_exists($funcname)) {
343 // We constantly update the "executed" date every minute to avoid being killed too soon
344 if (!isset(self::$last_update)) {
345 self::$last_update = strtotime($queue["executed"]);
348 $age = (time() - self::$last_update) / 60;
349 self::$last_update = time();
352 $stamp = (float)microtime(true);
353 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
354 self::$db_duration += (microtime(true) - $stamp);
355 self::$db_duration_write += (microtime(true) - $stamp);
358 self::execFunction($queue, $funcname, $argv, false);
360 $stamp = (float)microtime(true);
361 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
362 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
364 self::$db_duration = (microtime(true) - $stamp);
365 self::$db_duration_write += (microtime(true) - $stamp);
367 Logger::log("Function ".$funcname." does not exist");
368 $stamp = (float)microtime(true);
369 DBA::delete('workerqueue', ['id' => $queue["id"]]);
370 self::$db_duration = (microtime(true) - $stamp);
371 self::$db_duration_write += (microtime(true) - $stamp);
378 * Execute a function from the queue
380 * @param array $queue Workerqueue entry
381 * @param string $funcname name of the function
382 * @param array $argv Array of values to be passed to the function
383 * @param boolean $method_call boolean
385 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
387 private static function execFunction($queue, $funcname, $argv, $method_call)
391 Logger::enableWorker($funcname);
393 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
395 $stamp = (float)microtime(true);
397 // We use the callstack here to analyze the performance of executed worker entries.
398 // For this reason the variables have to be initialized.
399 DI::profiler()->reset();
403 $up_duration = microtime(true) - self::$up_start;
405 // Reset global data to avoid interferences
408 // Set the workerLogger as new default logger
410 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
412 $funcname($argv, count($argv));
415 Logger::disableWorker();
419 $duration = (microtime(true) - $stamp);
421 /* With these values we can analyze how effective the worker is.
422 * The database and rest time should be low since this is the unproductive time.
423 * The execution time is the productive time.
424 * By changing parameters like the maximum number of workers we can check the effectivness.
426 $dbtotal = round(self::$db_duration, 2);
427 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
428 $dbcount = round(self::$db_duration_count, 2);
429 $dbstat = round(self::$db_duration_stat, 2);
430 $dbwrite = round(self::$db_duration_write, 2);
431 $dblock = round(self::$lock_duration, 2);
432 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
433 $exec = round($duration, 2);
435 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
437 self::$up_start = microtime(true);
438 self::$db_duration = 0;
439 self::$db_duration_count = 0;
440 self::$db_duration_stat = 0;
441 self::$db_duration_write = 0;
442 self::$lock_duration = 0;
444 if ($duration > 3600) {
445 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
446 } elseif ($duration > 600) {
447 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
448 } elseif ($duration > 300) {
449 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
450 } elseif ($duration > 120) {
451 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
454 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
456 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
458 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
461 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
467 * Checks if the number of database connections has reached a critical limit.
469 * @return bool Are more than 3/4 of the maximum connections used?
470 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
472 private static function maxConnectionsReached()
474 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
475 $max = DI::config()->get("system", "max_connections");
477 // Fetch the percentage level where the worker will get active
478 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
481 // the maximum number of possible user connections can be a system variable
482 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
483 if (DBA::isResult($r)) {
486 // Or it can be granted. This overrides the system variable
487 $stamp = (float)microtime(true);
488 $r = DBA::p('SHOW GRANTS');
489 self::$db_duration += (microtime(true) - $stamp);
490 while ($grants = DBA::fetch($r)) {
491 $grant = array_pop($grants);
492 if (stristr($grant, "GRANT USAGE ON")) {
493 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
501 // If $max is set we will use the processlist to determine the current number of connections
502 // The processlist only shows entries of the current user
504 $stamp = (float)microtime(true);
505 $r = DBA::p('SHOW PROCESSLIST');
506 self::$db_duration += (microtime(true) - $stamp);
507 $used = DBA::numRows($r);
510 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
512 $level = ($used / $max) * 100;
514 if ($level >= $maxlevel) {
515 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
520 // We will now check for the system values.
521 // This limit could be reached although the user limits are fine.
522 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
523 if (!DBA::isResult($r)) {
526 $max = intval($r["Value"]);
530 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
531 if (!DBA::isResult($r)) {
534 $used = intval($r["Value"]);
538 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
540 $level = $used / $max * 100;
542 if ($level < $maxlevel) {
545 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
550 * fix the queue entry if the worker process died
555 private static function killStaleWorkers()
557 $stamp = (float)microtime(true);
558 $entries = DBA::select(
560 ['id', 'pid', 'executed', 'priority', 'parameter'],
561 ['NOT `done` AND `pid` != 0'],
562 ['order' => ['priority', 'created']]
564 self::$db_duration += (microtime(true) - $stamp);
566 while ($entry = DBA::fetch($entries)) {
567 if (!posix_kill($entry["pid"], 0)) {
568 $stamp = (float)microtime(true);
571 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
572 ['id' => $entry["id"]]
574 self::$db_duration += (microtime(true) - $stamp);
575 self::$db_duration_write += (microtime(true) - $stamp);
577 // Kill long running processes
578 // Check if the priority is in a valid range
579 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
580 $entry["priority"] = PRIORITY_MEDIUM;
583 // Define the maximum durations
584 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
585 $max_duration = $max_duration_defaults[$entry["priority"]];
587 $argv = json_decode($entry["parameter"], true);
592 $argv[0] = basename($argv[0]);
594 // How long is the process already running?
595 $duration = (time() - strtotime($entry["executed"])) / 60;
596 if ($duration > $max_duration) {
597 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
598 posix_kill($entry["pid"], SIGTERM);
600 // We killed the stale process.
601 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
602 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
603 $new_priority = $entry["priority"];
604 if ($entry["priority"] == PRIORITY_HIGH) {
605 $new_priority = PRIORITY_MEDIUM;
606 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
607 $new_priority = PRIORITY_LOW;
608 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
609 $new_priority = PRIORITY_NEGLIGIBLE;
611 $stamp = (float)microtime(true);
614 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
615 ['id' => $entry["id"]]
617 self::$db_duration += (microtime(true) - $stamp);
618 self::$db_duration_write += (microtime(true) - $stamp);
620 Logger::info('Process runtime is okay', ['pid' => $entry["pid"], 'duration' => $duration, 'max' => $max_duration, 'command' => substr(json_encode($argv), 0, 50)]);
624 DBA::close($entries);
628 * Checks if the number of active workers exceeds the given limits
630 * @return bool Are there too much workers running?
631 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
633 private static function tooMuchWorkers()
635 $queues = DI::config()->get("system", "worker_queues", 10);
637 $maxqueues = $queues;
639 $active = self::activeWorkers();
641 // Decrease the number of workers at higher load
642 $load = System::currentLoad();
644 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
646 /* Default exponent 3 causes queues to rapidly decrease as load increases.
647 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
648 * For some environments, this rapid decrease is not needed.
649 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
651 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
652 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
653 $queues = intval(ceil($slope * $maxqueues));
657 if (DI::config()->get('system', 'worker_jpm')) {
658 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
659 $jobs_per_minute = [];
660 foreach ($intervals as $interval) {
661 if ($interval == 0) {
664 $interval = (int)$interval;
667 $stamp = (float)microtime(true);
668 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
669 self::$db_duration += (microtime(true) - $stamp);
670 self::$db_duration_stat += (microtime(true) - $stamp);
671 if ($job = DBA::fetch($jobs)) {
672 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
676 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
679 // Create a list of queue entries grouped by their priority
680 $listitem = [0 => ''];
682 $idle_workers = $active;
684 $deferred = self::deferredEntries();
686 if (DI::config()->get('system', 'worker_debug')) {
687 $waiting_processes = 0;
688 // Now adding all processes with workerqueue entries
689 $stamp = (float)microtime(true);
690 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
691 self::$db_duration += (microtime(true) - $stamp);
692 self::$db_duration_stat += (microtime(true) - $stamp);
693 while ($entry = DBA::fetch($jobs)) {
694 $stamp = (float)microtime(true);
695 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
696 self::$db_duration += (microtime(true) - $stamp);
697 self::$db_duration_stat += (microtime(true) - $stamp);
698 if ($process = DBA::fetch($processes)) {
699 $idle_workers -= $process["running"];
700 $waiting_processes += $entry["entries"];
701 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
703 DBA::close($processes);
707 $waiting_processes = self::totalEntries();
708 $stamp = (float)microtime(true);
709 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
710 self::$db_duration += (microtime(true) - $stamp);
711 self::$db_duration_stat += (microtime(true) - $stamp);
713 while ($entry = DBA::fetch($jobs)) {
714 $idle_workers -= $entry["running"];
715 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
720 $waiting_processes -= $deferred;
722 $listitem[0] = "0:" . max(0, $idle_workers);
724 $processlist .= ' ('.implode(', ', $listitem).')';
726 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
727 $top_priority = self::highestPriority();
728 $high_running = self::processWithPriorityActive($top_priority);
730 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
731 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
732 $queues = $active + 1;
736 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
738 // Are there fewer workers running as possible? Then fork a new one.
739 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
740 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
741 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
742 self::IPCSetJobState(true);
749 // if there are too much worker, we don't spawn a new one.
750 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
751 self::IPCSetJobState(false);
754 return $active > $queues;
758 * Returns the number of active worker processes
760 * @return integer Number of active worker processes
763 private static function activeWorkers()
765 $stamp = (float)microtime(true);
766 $count = DBA::count('process', ['command' => 'Worker.php']);
767 self::$db_duration += (microtime(true) - $stamp);
772 * Returns waiting jobs for the current process id
774 * @return array waiting workerqueue jobs
777 private static function getWaitingJobForPID()
779 $stamp = (float)microtime(true);
780 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
781 self::$db_duration += (microtime(true) - $stamp);
782 if (DBA::isResult($r)) {
783 return DBA::toArray($r);
791 * Returns the next jobs that should be executed
793 * @return array array with next jobs
796 private static function nextProcess()
798 $priority = self::nextPriority();
799 if (empty($priority)) {
800 Logger::info('No tasks found');
804 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
807 $stamp = (float)microtime(true);
808 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
809 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
810 self::$db_duration += (microtime(true) - $stamp);
811 while ($task = DBA::fetch($tasks)) {
812 $ids[] = $task['id'];
813 // Only continue that loop while we are storing commands that can be processed quickly
814 $command = json_decode($task['parameter'])[0];
815 if (!in_array($command, self::FAST_COMMANDS)) {
821 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
826 * Returns the priority of the next workerqueue job
828 * @return string priority
831 private static function nextPriority()
834 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
835 foreach ($priorities as $priority) {
836 $stamp = (float)microtime(true);
837 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
838 $waiting[$priority] = true;
840 self::$db_duration += (microtime(true) - $stamp);
843 if (!empty($waiting[PRIORITY_CRITICAL])) {
844 return PRIORITY_CRITICAL;
849 $stamp = (float)microtime(true);
850 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
851 self::$db_duration += (microtime(true) - $stamp);
852 while ($process = DBA::fetch($processes)) {
853 $running[$process['priority']] = $process['running'];
854 $running_total += $process['running'];
856 DBA::close($processes);
858 foreach ($priorities as $priority) {
859 if (!empty($waiting[$priority]) && empty($running[$priority])) {
860 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
865 $active = max(self::activeWorkers(), $running_total);
866 $priorities = max(count($waiting), count($running));
870 for ($i = 1; $i <= $priorities; ++$i) {
871 $total += pow($i, $exponent);
875 for ($i = 1; $i <= $priorities; ++$i) {
876 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
880 foreach ($running as $priority => $workers) {
881 if ($workers < $limit[$i++]) {
882 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
887 if (!empty($waiting)) {
888 $priority = array_keys($waiting)[0];
889 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
897 * Find and claim the next worker process for us
899 * @return boolean Have we found something?
900 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
902 private static function findWorkerProcesses()
906 $ids = self::nextProcess();
908 // If there is no result we check without priority limit
910 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
912 $stamp = (float)microtime(true);
913 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
914 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
915 self::$db_duration += (microtime(true) - $stamp);
917 while ($task = DBA::fetch($tasks)) {
918 $ids[] = $task['id'];
919 // Only continue that loop while we are storing commands that can be processed quickly
920 $command = json_decode($task['parameter'])[0];
921 if (!in_array($command, self::FAST_COMMANDS)) {
929 $stamp = (float)microtime(true);
930 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
931 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
932 self::$db_duration += (microtime(true) - $stamp);
933 self::$db_duration_write += (microtime(true) - $stamp);
940 * Returns the next worker process
942 * @return array worker processes
943 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
945 public static function workerProcess()
947 // There can already be jobs for us in the queue.
948 $waiting = self::getWaitingJobForPID();
949 if (!empty($waiting)) {
953 $stamp = (float)microtime(true);
954 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
957 self::$lock_duration += (microtime(true) - $stamp);
959 $found = self::findWorkerProcesses();
961 DI::lock()->release(self::LOCK_PROCESS);
964 $stamp = (float)microtime(true);
965 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
966 self::$db_duration += (microtime(true) - $stamp);
967 return DBA::toArray($r);
973 * Removes a workerqueue entry from the current process
978 public static function unclaimProcess()
982 $stamp = (float)microtime(true);
983 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
984 self::$db_duration += (microtime(true) - $stamp);
985 self::$db_duration_write += (microtime(true) - $stamp);
989 * Call the front end worker
992 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
994 public static function callWorker()
996 if (!DI::config()->get("system", "frontend_worker")) {
1000 $url = DI::baseUrl() . '/worker';
1001 DI::httpRequest()->fetch($url, false, 1);
1005 * Call the front end worker if there aren't any active
1008 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1010 public static function executeIfIdle()
1012 if (!DI::config()->get("system", "frontend_worker")) {
1016 // Do we have "proc_open"? Then we can fork the worker
1017 if (function_exists("proc_open")) {
1018 // When was the last time that we called the worker?
1019 // Less than one minute? Then we quit
1020 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1024 DI::config()->set("system", "worker_started", time());
1026 // Do we have enough running workers? Then we quit here.
1027 if (self::tooMuchWorkers()) {
1028 // Cleaning dead processes
1029 self::killStaleWorkers();
1030 Process::deleteInactive();
1037 Logger::info('Call worker');
1038 self::spawnWorker();
1042 // We cannot execute background processes.
1043 // We now run the processes from the frontend.
1044 // This won't work with long running processes.
1047 self::clearProcesses();
1049 $workers = self::activeWorkers();
1051 if ($workers == 0) {
1057 * Removes long running worker processes
1060 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1062 public static function clearProcesses()
1064 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1066 /// @todo We should clean up the corresponding workerqueue entries as well
1067 $stamp = (float)microtime(true);
1068 $condition = ["`created` < ? AND `command` = 'worker.php'",
1069 DateTimeFormat::utc("now - ".$timeout." minutes")];
1070 DBA::delete('process', $condition);
1071 self::$db_duration = (microtime(true) - $stamp);
1072 self::$db_duration_write += (microtime(true) - $stamp);
1076 * Runs the cron processes
1079 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1081 private static function runCron()
1083 Logger::info('Add cron entries');
1085 // Check for spooled items
1086 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1088 // Run the cron job that calls all other jobs
1089 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1091 // Cleaning dead processes
1092 self::killStaleWorkers();
1096 * Spawns a new worker
1098 * @param bool $do_cron
1100 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1102 public static function spawnWorker($do_cron = false)
1104 $command = 'bin/worker.php';
1106 $args = ['no_cron' => !$do_cron];
1109 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), $a->getBasePath());
1110 $process->run($command, $args);
1112 // after spawning we have to remove the flag.
1113 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1114 self::IPCSetJobState(false);
1119 * Adds tasks to the worker queue
1121 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1123 * next args are passed as $cmd command line
1124 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1125 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1127 * @return boolean "false" if worker queue entry already existed or there had been an error
1128 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1129 * @note $cmd and string args are surrounded with ""
1135 public static function add($cmd)
1137 $args = func_get_args();
1139 if (!count($args)) {
1143 $arr = ['args' => $args, 'run_cmd' => true];
1145 Hook::callAll("proc_run", $arr);
1146 if (!$arr['run_cmd'] || !count($args)) {
1150 $priority = PRIORITY_MEDIUM;
1151 // Don't fork from frontend tasks by default
1152 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1153 $created = DateTimeFormat::utcNow();
1154 $force_priority = false;
1156 $run_parameter = array_shift($args);
1158 if (is_int($run_parameter)) {
1159 $priority = $run_parameter;
1160 } elseif (is_array($run_parameter)) {
1161 if (isset($run_parameter['priority'])) {
1162 $priority = $run_parameter['priority'];
1164 if (isset($run_parameter['created'])) {
1165 $created = $run_parameter['created'];
1167 if (isset($run_parameter['dont_fork'])) {
1168 $dont_fork = $run_parameter['dont_fork'];
1170 if (isset($run_parameter['force_priority'])) {
1171 $force_priority = $run_parameter['force_priority'];
1175 $parameters = json_encode($args);
1176 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1179 // Quit if there was a database error - a precaution for the update process to 3.5.3
1180 if (DBA::errorNo() != 0) {
1185 $added = DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1189 } elseif ($force_priority) {
1190 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1193 // Should we quit and wait for the worker to be called as a cronjob?
1198 // If there is a lock then we don't have to check for too much worker
1199 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1203 // If there are already enough workers running, don't fork another one
1204 $quit = self::tooMuchWorkers();
1205 DI::lock()->release(self::LOCK_WORKER);
1211 // We tell the daemon that a new job entry exists
1212 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1213 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1217 // Now call the worker to execute the jobs that we just added to the queue
1218 self::spawnWorker();
1224 * Returns the next retrial level for worker jobs.
1225 * This function will skip levels when jobs are older.
1227 * @param array $queue Worker queue entry
1228 * @param integer $max_level maximum retrial level
1229 * @return integer the next retrial level value
1231 private static function getNextRetrial($queue, $max_level)
1233 $created = strtotime($queue['created']);
1234 $retrial_time = time() - $created;
1236 $new_retrial = $queue['retrial'] + 1;
1238 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1239 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1241 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1242 $new_retrial = $retrial;
1245 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1246 return $new_retrial;
1250 * Defers the current worker entry
1252 * @return boolean had the entry been deferred?
1254 public static function defer()
1256 if (empty(DI::app()->queue)) {
1260 $queue = DI::app()->queue;
1262 $retrial = $queue['retrial'];
1264 $priority = $queue['priority'];
1266 $max_level = DI::config()->get('system', 'worker_defer_limit');
1268 $new_retrial = self::getNextRetrial($queue, $max_level);
1270 if ($new_retrial > $max_level) {
1271 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]);
1275 // Calculate the delay until the next trial
1276 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1277 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1279 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1280 $priority = PRIORITY_MEDIUM;
1281 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1282 $priority = PRIORITY_LOW;
1283 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1284 $priority = PRIORITY_NEGLIGIBLE;
1287 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1289 $stamp = (float)microtime(true);
1290 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1291 DBA::update('workerqueue', $fields, ['id' => $id]);
1292 self::$db_duration += (microtime(true) - $stamp);
1293 self::$db_duration_write += (microtime(true) - $stamp);
1299 * Log active processes into the "process" table
1301 public static function startProcess()
1303 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1305 $command = basename($trace[0]['file']);
1307 Process::deleteInactive();
1309 Process::insert($command);
1313 * Remove the active process from the "process" table
1316 * @throws \Exception
1318 public static function endProcess()
1320 return Process::deleteByPid();
1324 * Set the flag if some job is waiting
1326 * @param boolean $jobs Is there a waiting job?
1327 * @throws \Exception
1329 public static function IPCSetJobState($jobs)
1331 $stamp = (float)microtime(true);
1332 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1333 self::$db_duration += (microtime(true) - $stamp);
1334 self::$db_duration_write += (microtime(true) - $stamp);
1338 * Checks if some worker job waits to be executed
1341 * @throws \Exception
1343 public static function IPCJobsExists()
1345 $stamp = (float)microtime(true);
1346 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1347 self::$db_duration += (microtime(true) - $stamp);
1349 // When we don't have a row, no job is running
1350 if (!DBA::isResult($row)) {
1354 return (bool)$row['jobs'];