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;
29 use Friendica\Util\Network;
32 * Contains the class for the worker background job processing
36 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
37 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
38 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
39 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
41 const FAST_COMMANDS = ['APDelivery', 'Delivery', 'CreateShadowEntry'];
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::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
73 // We now start the process. This is done after the load check since this could increase the load.
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 // Count active workers and compare them with a maximum value that depends on the load
84 if (self::tooMuchWorkers()) {
85 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
89 // Do we have too few memory?
90 if (DI::process()->isMinMemoryReached()) {
91 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
95 // Possibly there are too much database connections
96 if (self::maxConnectionsReached()) {
97 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
101 // Possibly there are too much database processes that block the system
102 if (DI::process()->isMaxProcessesReached()) {
103 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
107 // Now we start additional cron processes if we should do so
113 self::$state = self::STATE_STARTUP;
115 // We fetch the next queue entry that is about to be executed
116 while ($r = self::workerProcess()) {
118 foreach ($r as $entry) {
119 // Assure that the priority is an integer value
120 $entry['priority'] = (int)$entry['priority'];
122 // The work will be done
123 if (!self::execute($entry)) {
124 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
128 // Trying to fetch new processes - but only once when successful
129 if (!$refetched && DI::lock()->acquire('worker_process', 0)) {
130 self::findWorkerProcesses();
131 DI::lock()->release('worker_process');
132 self::$state = self::STATE_REFETCH;
135 self::$state = self::STATE_SHORT_LOOP;
139 // To avoid the quitting of multiple workers only one worker at a time will execute the check
140 if (!self::getWaitingJobForPID()) {
141 self::$state = self::STATE_LONG_LOOP;
143 if (DI::lock()->acquire('worker', 0)) {
144 // Count active workers and compare them with a maximum value that depends on the load
145 if (self::tooMuchWorkers()) {
146 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
147 DI::lock()->release('worker');
152 if (DI::process()->isMinMemoryReached()) {
153 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
154 DI::lock()->release('worker');
157 DI::lock()->release('worker');
161 // Quit the worker once every cron interval
162 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
163 Logger::info('Process lifetime reached, respawning.');
169 // Cleaning up. Possibly not needed, but it doesn't harm anything.
170 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
171 self::IPCSetJobState(false);
173 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
177 * Check if non executed tasks do exist in the worker queue
179 * @return boolean Returns "true" if tasks are existing
182 private static function entriesExists()
184 $stamp = (float)microtime(true);
185 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
186 self::$db_duration += (microtime(true) - $stamp);
191 * Returns the number of deferred entries in the worker queue
193 * @return integer Number of deferred entries in the worker queue
196 private static function deferredEntries()
198 $stamp = (float)microtime(true);
199 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
200 self::$db_duration += (microtime(true) - $stamp);
201 self::$db_duration_count += (microtime(true) - $stamp);
206 * Returns the number of non executed entries in the worker queue
208 * @return integer Number of non executed entries in the worker queue
211 private static function totalEntries()
213 $stamp = (float)microtime(true);
214 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
215 self::$db_duration += (microtime(true) - $stamp);
216 self::$db_duration_count += (microtime(true) - $stamp);
221 * Returns the highest priority in the worker queue that isn't executed
223 * @return integer Number of active worker processes
226 private static function highestPriority()
228 $stamp = (float)microtime(true);
229 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
230 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
231 self::$db_duration += (microtime(true) - $stamp);
232 if (DBA::isResult($workerqueue)) {
233 return $workerqueue["priority"];
240 * Returns if a process with the given priority is running
242 * @param integer $priority The priority that should be checked
244 * @return integer Is there a process running with that priority?
247 private static function processWithPriorityActive($priority)
249 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
250 return DBA::exists('workerqueue', $condition);
254 * Execute a worker entry
256 * @param array $queue Workerqueue entry
258 * @return boolean "true" if further processing should be stopped
259 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
261 public static function execute($queue)
265 // Quit when in maintenance
266 if (DI::config()->get('system', 'maintenance', false, true)) {
267 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
271 // Constantly check the number of parallel database processes
272 if (DI::process()->isMaxProcessesReached()) {
273 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
277 // Constantly check the number of available database connections to let the frontend be accessible at any time
278 if (self::maxConnectionsReached()) {
279 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
283 $argv = json_decode($queue["parameter"], true);
285 // Check for existance and validity of the include file
288 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
289 // We constantly update the "executed" date every minute to avoid being killed too soon
290 if (!isset(self::$last_update)) {
291 self::$last_update = strtotime($queue["executed"]);
294 $age = (time() - self::$last_update) / 60;
295 self::$last_update = time();
298 $stamp = (float)microtime(true);
299 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
300 self::$db_duration += (microtime(true) - $stamp);
301 self::$db_duration_write += (microtime(true) - $stamp);
306 self::execFunction($queue, $include, $argv, true);
308 $stamp = (float)microtime(true);
309 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
310 if (DBA::update('workerqueue', ['done' => true], $condition)) {
311 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
313 self::$db_duration = (microtime(true) - $stamp);
314 self::$db_duration_write += (microtime(true) - $stamp);
319 // The script could be provided as full path or only with the function name
320 if ($include == basename($include)) {
321 $include = "include/".$include.".php";
324 if (!validate_include($include)) {
325 Logger::log("Include file ".$argv[0]." is not valid!");
326 $stamp = (float)microtime(true);
327 DBA::delete('workerqueue', ['id' => $queue["id"]]);
328 self::$db_duration = (microtime(true) - $stamp);
329 self::$db_duration_write += (microtime(true) - $stamp);
333 require_once $include;
335 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
337 if (function_exists($funcname)) {
338 // We constantly update the "executed" date every minute to avoid being killed too soon
339 if (!isset(self::$last_update)) {
340 self::$last_update = strtotime($queue["executed"]);
343 $age = (time() - self::$last_update) / 60;
344 self::$last_update = time();
347 $stamp = (float)microtime(true);
348 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
349 self::$db_duration += (microtime(true) - $stamp);
350 self::$db_duration_write += (microtime(true) - $stamp);
353 self::execFunction($queue, $funcname, $argv, false);
355 $stamp = (float)microtime(true);
356 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
357 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
359 self::$db_duration = (microtime(true) - $stamp);
360 self::$db_duration_write += (microtime(true) - $stamp);
362 Logger::log("Function ".$funcname." does not exist");
363 $stamp = (float)microtime(true);
364 DBA::delete('workerqueue', ['id' => $queue["id"]]);
365 self::$db_duration = (microtime(true) - $stamp);
366 self::$db_duration_write += (microtime(true) - $stamp);
373 * Execute a function from the queue
375 * @param array $queue Workerqueue entry
376 * @param string $funcname name of the function
377 * @param array $argv Array of values to be passed to the function
378 * @param boolean $method_call boolean
380 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
382 private static function execFunction($queue, $funcname, $argv, $method_call)
386 $argc = count($argv);
388 Logger::enableWorker($funcname);
390 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
392 $stamp = (float)microtime(true);
394 // We use the callstack here to analyze the performance of executed worker entries.
395 // For this reason the variables have to be initialized.
396 DI::profiler()->reset();
400 $up_duration = microtime(true) - self::$up_start;
402 // Reset global data to avoid interferences
405 // Set the workerLogger as new default logger
407 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
409 $funcname($argv, $argc);
412 Logger::disableWorker();
416 $duration = (microtime(true) - $stamp);
418 /* With these values we can analyze how effective the worker is.
419 * The database and rest time should be low since this is the unproductive time.
420 * The execution time is the productive time.
421 * By changing parameters like the maximum number of workers we can check the effectivness.
423 $dbtotal = round(self::$db_duration, 2);
424 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
425 $dbcount = round(self::$db_duration_count, 2);
426 $dbstat = round(self::$db_duration_stat, 2);
427 $dbwrite = round(self::$db_duration_write, 2);
428 $dblock = round(self::$lock_duration, 2);
429 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
430 $exec = round($duration, 2);
432 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
434 self::$up_start = microtime(true);
435 self::$db_duration = 0;
436 self::$db_duration_count = 0;
437 self::$db_duration_stat = 0;
438 self::$db_duration_write = 0;
439 self::$lock_duration = 0;
441 if ($duration > 3600) {
442 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
443 } elseif ($duration > 600) {
444 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
445 } elseif ($duration > 300) {
446 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
447 } elseif ($duration > 120) {
448 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
451 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
453 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
455 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
458 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
464 * Checks if the number of database connections has reached a critical limit.
466 * @return bool Are more than 3/4 of the maximum connections used?
467 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
469 private static function maxConnectionsReached()
471 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
472 $max = DI::config()->get("system", "max_connections");
474 // Fetch the percentage level where the worker will get active
475 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
478 // the maximum number of possible user connections can be a system variable
479 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
480 if (DBA::isResult($r)) {
483 // Or it can be granted. This overrides the system variable
484 $stamp = (float)microtime(true);
485 $r = DBA::p('SHOW GRANTS');
486 self::$db_duration += (microtime(true) - $stamp);
487 while ($grants = DBA::fetch($r)) {
488 $grant = array_pop($grants);
489 if (stristr($grant, "GRANT USAGE ON")) {
490 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
498 // If $max is set we will use the processlist to determine the current number of connections
499 // The processlist only shows entries of the current user
501 $stamp = (float)microtime(true);
502 $r = DBA::p('SHOW PROCESSLIST');
503 self::$db_duration += (microtime(true) - $stamp);
504 $used = DBA::numRows($r);
507 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
509 $level = ($used / $max) * 100;
511 if ($level >= $maxlevel) {
512 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
517 // We will now check for the system values.
518 // This limit could be reached although the user limits are fine.
519 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
520 if (!DBA::isResult($r)) {
523 $max = intval($r["Value"]);
527 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
528 if (!DBA::isResult($r)) {
531 $used = intval($r["Value"]);
535 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
537 $level = $used / $max * 100;
539 if ($level < $maxlevel) {
542 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
547 * fix the queue entry if the worker process died
552 private static function killStaleWorkers()
554 $stamp = (float)microtime(true);
555 $entries = DBA::select(
557 ['id', 'pid', 'executed', 'priority', 'parameter'],
558 ['NOT `done` AND `pid` != 0'],
559 ['order' => ['priority', 'created']]
561 self::$db_duration += (microtime(true) - $stamp);
563 while ($entry = DBA::fetch($entries)) {
564 if (!posix_kill($entry["pid"], 0)) {
565 $stamp = (float)microtime(true);
568 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
569 ['id' => $entry["id"]]
571 self::$db_duration += (microtime(true) - $stamp);
572 self::$db_duration_write += (microtime(true) - $stamp);
574 // Kill long running processes
575 // Check if the priority is in a valid range
576 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
577 $entry["priority"] = PRIORITY_MEDIUM;
580 // Define the maximum durations
581 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
582 $max_duration = $max_duration_defaults[$entry["priority"]];
584 $argv = json_decode($entry["parameter"], true);
585 $argv[0] = basename($argv[0]);
587 // How long is the process already running?
588 $duration = (time() - strtotime($entry["executed"])) / 60;
589 if ($duration > $max_duration) {
590 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
591 posix_kill($entry["pid"], SIGTERM);
593 // We killed the stale process.
594 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
595 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
596 $new_priority = $entry["priority"];
597 if ($entry["priority"] == PRIORITY_HIGH) {
598 $new_priority = PRIORITY_MEDIUM;
599 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
600 $new_priority = PRIORITY_LOW;
601 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
602 $new_priority = PRIORITY_NEGLIGIBLE;
604 $stamp = (float)microtime(true);
607 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
608 ['id' => $entry["id"]]
610 self::$db_duration += (microtime(true) - $stamp);
611 self::$db_duration_write += (microtime(true) - $stamp);
613 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", Logger::DEBUG);
620 * Checks if the number of active workers exceeds the given limits
622 * @return bool Are there too much workers running?
623 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
625 private static function tooMuchWorkers()
627 $queues = DI::config()->get("system", "worker_queues", 10);
629 $maxqueues = $queues;
631 $active = self::activeWorkers();
633 // Decrease the number of workers at higher load
634 $load = System::currentLoad();
636 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
638 /* Default exponent 3 causes queues to rapidly decrease as load increases.
639 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
640 * For some environments, this rapid decrease is not needed.
641 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
643 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
644 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
645 $queues = intval(ceil($slope * $maxqueues));
649 if (DI::config()->get('system', 'worker_jpm')) {
650 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
651 $jobs_per_minute = [];
652 foreach ($intervals as $interval) {
653 if ($interval == 0) {
656 $interval = (int)$interval;
659 $stamp = (float)microtime(true);
660 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
661 self::$db_duration += (microtime(true) - $stamp);
662 self::$db_duration_stat += (microtime(true) - $stamp);
663 if ($job = DBA::fetch($jobs)) {
664 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
668 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
671 // Create a list of queue entries grouped by their priority
672 $listitem = [0 => ''];
674 $idle_workers = $active;
676 $deferred = self::deferredEntries();
678 if (DI::config()->get('system', 'worker_debug')) {
679 $waiting_processes = 0;
680 // Now adding all processes with workerqueue entries
681 $stamp = (float)microtime(true);
682 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
683 self::$db_duration += (microtime(true) - $stamp);
684 self::$db_duration_stat += (microtime(true) - $stamp);
685 while ($entry = DBA::fetch($jobs)) {
686 $stamp = (float)microtime(true);
687 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
688 self::$db_duration += (microtime(true) - $stamp);
689 self::$db_duration_stat += (microtime(true) - $stamp);
690 if ($process = DBA::fetch($processes)) {
691 $idle_workers -= $process["running"];
692 $waiting_processes += $entry["entries"];
693 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
695 DBA::close($processes);
699 $waiting_processes = self::totalEntries();
700 $stamp = (float)microtime(true);
701 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` GROUP BY `priority` ORDER BY `priority`");
702 self::$db_duration += (microtime(true) - $stamp);
703 self::$db_duration_stat += (microtime(true) - $stamp);
705 while ($entry = DBA::fetch($jobs)) {
706 $idle_workers -= $entry["running"];
707 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
712 $waiting_processes -= $deferred;
714 $listitem[0] = "0:" . max(0, $idle_workers);
716 $processlist .= ' ('.implode(', ', $listitem).')';
718 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
719 $top_priority = self::highestPriority();
720 $high_running = self::processWithPriorityActive($top_priority);
722 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
723 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
724 $queues = $active + 1;
728 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
730 // Are there fewer workers running as possible? Then fork a new one.
731 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
732 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
733 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
734 self::IPCSetJobState(true);
741 // if there are too much worker, we don't spawn a new one.
742 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
743 self::IPCSetJobState(false);
746 return $active > $queues;
750 * Returns the number of active worker processes
752 * @return integer Number of active worker processes
755 private static function activeWorkers()
757 $stamp = (float)microtime(true);
758 $count = DBA::count('process', ['command' => 'Worker.php']);
759 self::$db_duration += (microtime(true) - $stamp);
764 * Returns waiting jobs for the current process id
766 * @return array waiting workerqueue jobs
769 private static function getWaitingJobForPID()
771 $stamp = (float)microtime(true);
772 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
773 self::$db_duration += (microtime(true) - $stamp);
774 if (DBA::isResult($r)) {
775 return DBA::toArray($r);
783 * Returns the next jobs that should be executed
785 * @return array array with next jobs
788 private static function nextProcess()
790 $priority = self::nextPriority();
791 if (empty($priority)) {
792 Logger::info('No tasks found');
796 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
799 $stamp = (float)microtime(true);
800 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
801 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
802 self::$db_duration += (microtime(true) - $stamp);
803 while ($task = DBA::fetch($tasks)) {
804 $ids[] = $task['id'];
805 // Only continue that loop while we are storing commands that can be processed quickly
806 $command = json_decode($task['parameter'])[0];
807 if (!in_array($command, self::FAST_COMMANDS)) {
813 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
818 * Returns the priority of the next workerqueue job
820 * @return string priority
823 private static function nextPriority()
826 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
827 foreach ($priorities as $priority) {
828 $stamp = (float)microtime(true);
829 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
830 $waiting[$priority] = true;
832 self::$db_duration += (microtime(true) - $stamp);
835 if (!empty($waiting[PRIORITY_CRITICAL])) {
836 return PRIORITY_CRITICAL;
841 $stamp = (float)microtime(true);
842 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
843 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
844 WHERE NOT `done` GROUP BY `priority`");
845 self::$db_duration += (microtime(true) - $stamp);
846 while ($process = DBA::fetch($processes)) {
847 $running[$process['priority']] = $process['running'];
848 $running_total += $process['running'];
850 DBA::close($processes);
852 foreach ($priorities as $priority) {
853 if (!empty($waiting[$priority]) && empty($running[$priority])) {
854 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
859 $active = max(self::activeWorkers(), $running_total);
860 $priorities = max(count($waiting), count($running));
864 for ($i = 1; $i <= $priorities; ++$i) {
865 $total += pow($i, $exponent);
869 for ($i = 1; $i <= $priorities; ++$i) {
870 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
874 foreach ($running as $priority => $workers) {
875 if ($workers < $limit[$i++]) {
876 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
881 if (!empty($waiting)) {
882 $priority = array_keys($waiting)[0];
883 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
891 * Find and claim the next worker process for us
893 * @return boolean Have we found something?
894 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
896 private static function findWorkerProcesses()
900 $ids = self::nextProcess();
902 // If there is no result we check without priority limit
904 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
906 $stamp = (float)microtime(true);
907 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
908 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
909 self::$db_duration += (microtime(true) - $stamp);
911 while ($task = DBA::fetch($tasks)) {
912 $ids[] = $task['id'];
913 // Only continue that loop while we are storing commands that can be processed quickly
914 $command = json_decode($task['parameter'])[0];
915 if (!in_array($command, self::FAST_COMMANDS)) {
923 $stamp = (float)microtime(true);
924 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
925 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
926 self::$db_duration += (microtime(true) - $stamp);
927 self::$db_duration_write += (microtime(true) - $stamp);
934 * Returns the next worker process
936 * @return string SQL statement
937 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
939 public static function workerProcess()
941 // There can already be jobs for us in the queue.
942 $waiting = self::getWaitingJobForPID();
943 if (!empty($waiting)) {
947 $stamp = (float)microtime(true);
948 if (!DI::lock()->acquire('worker_process')) {
951 self::$lock_duration += (microtime(true) - $stamp);
953 $found = self::findWorkerProcesses();
955 DI::lock()->release('worker_process');
958 $stamp = (float)microtime(true);
959 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
960 self::$db_duration += (microtime(true) - $stamp);
961 return DBA::toArray($r);
967 * Removes a workerqueue entry from the current process
972 public static function unclaimProcess()
976 $stamp = (float)microtime(true);
977 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
978 self::$db_duration += (microtime(true) - $stamp);
979 self::$db_duration_write += (microtime(true) - $stamp);
983 * Call the front end worker
986 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
988 public static function callWorker()
990 if (!DI::config()->get("system", "frontend_worker")) {
994 $url = DI::baseUrl() . '/worker';
995 Network::fetchUrl($url, false, 1);
999 * Call the front end worker if there aren't any active
1002 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1004 public static function executeIfIdle()
1006 if (!DI::config()->get("system", "frontend_worker")) {
1010 // Do we have "proc_open"? Then we can fork the worker
1011 if (function_exists("proc_open")) {
1012 // When was the last time that we called the worker?
1013 // Less than one minute? Then we quit
1014 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1018 DI::config()->set("system", "worker_started", time());
1020 // Do we have enough running workers? Then we quit here.
1021 if (self::tooMuchWorkers()) {
1022 // Cleaning dead processes
1023 self::killStaleWorkers();
1024 Process::deleteInactive();
1031 Logger::log('Call worker', Logger::DEBUG);
1032 self::spawnWorker();
1036 // We cannot execute background processes.
1037 // We now run the processes from the frontend.
1038 // This won't work with long running processes.
1041 self::clearProcesses();
1043 $workers = self::activeWorkers();
1045 if ($workers == 0) {
1051 * Removes long running worker processes
1054 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1056 public static function clearProcesses()
1058 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1060 /// @todo We should clean up the corresponding workerqueue entries as well
1061 $stamp = (float)microtime(true);
1062 $condition = ["`created` < ? AND `command` = 'worker.php'",
1063 DateTimeFormat::utc("now - ".$timeout." minutes")];
1064 DBA::delete('process', $condition);
1065 self::$db_duration = (microtime(true) - $stamp);
1066 self::$db_duration_write += (microtime(true) - $stamp);
1070 * Runs the cron processes
1073 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1075 private static function runCron()
1077 Logger::log('Add cron entries', Logger::DEBUG);
1079 // Check for spooled items
1080 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1082 // Run the cron job that calls all other jobs
1083 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1085 // Cleaning dead processes
1086 self::killStaleWorkers();
1090 * Spawns a new worker
1092 * @param bool $do_cron
1094 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1096 public static function spawnWorker($do_cron = false)
1098 $command = 'bin/worker.php';
1100 $args = ['no_cron' => !$do_cron];
1103 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), $a->getBasePath());
1104 $process->run($command, $args);
1106 // after spawning we have to remove the flag.
1107 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1108 self::IPCSetJobState(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), "CreateShadowEntry", $post_id);
1121 * @return boolean "false" if worker queue entry already existed or there had been an error
1122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1123 * @note $cmd and string args are surrounded with ""
1129 public static function add($cmd)
1131 $args = func_get_args();
1133 if (!count($args)) {
1137 $arr = ['args' => $args, 'run_cmd' => true];
1139 Hook::callAll("proc_run", $arr);
1140 if (!$arr['run_cmd'] || !count($args)) {
1144 $priority = PRIORITY_MEDIUM;
1145 // Don't fork from frontend tasks by default
1146 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1147 $created = DateTimeFormat::utcNow();
1148 $force_priority = false;
1150 $run_parameter = array_shift($args);
1152 if (is_int($run_parameter)) {
1153 $priority = $run_parameter;
1154 } elseif (is_array($run_parameter)) {
1155 if (isset($run_parameter['priority'])) {
1156 $priority = $run_parameter['priority'];
1158 if (isset($run_parameter['created'])) {
1159 $created = $run_parameter['created'];
1161 if (isset($run_parameter['dont_fork'])) {
1162 $dont_fork = $run_parameter['dont_fork'];
1164 if (isset($run_parameter['force_priority'])) {
1165 $force_priority = $run_parameter['force_priority'];
1169 $parameters = json_encode($args);
1170 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1173 // Quit if there was a database error - a precaution for the update process to 3.5.3
1174 if (DBA::errorNo() != 0) {
1179 $added = DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1183 } elseif ($force_priority) {
1184 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1187 // Should we quit and wait for the worker to be called as a cronjob?
1192 // If there is a lock then we don't have to check for too much worker
1193 if (!DI::lock()->acquire('worker', 0)) {
1197 // If there are already enough workers running, don't fork another one
1198 $quit = self::tooMuchWorkers();
1199 DI::lock()->release('worker');
1205 // We tell the daemon that a new job entry exists
1206 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1207 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1211 // Now call the worker to execute the jobs that we just added to the queue
1212 self::spawnWorker();
1218 * Returns the next retrial level for worker jobs.
1219 * This function will skip levels when jobs are older.
1221 * @param array $queue Worker queue entry
1222 * @param integer $max_level maximum retrial level
1223 * @return integer the next retrial level value
1225 private static function getNextRetrial($queue, $max_level)
1227 $created = strtotime($queue['created']);
1228 $retrial_time = time() - $created;
1230 $new_retrial = $queue['retrial'] + 1;
1232 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1233 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1235 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1236 $new_retrial = $retrial;
1239 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1240 return $new_retrial;
1244 * Defers the current worker entry
1246 * @return boolean had the entry been deferred?
1248 public static function defer()
1250 if (empty(DI::app()->queue)) {
1254 $queue = DI::app()->queue;
1256 $retrial = $queue['retrial'];
1258 $priority = $queue['priority'];
1260 $max_level = DI::config()->get('system', 'worker_defer_limit');
1262 $new_retrial = self::getNextRetrial($queue, $max_level);
1264 if ($new_retrial > $max_level) {
1265 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]);
1269 // Calculate the delay until the next trial
1270 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1271 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1273 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1274 $priority = PRIORITY_MEDIUM;
1275 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1276 $priority = PRIORITY_LOW;
1277 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1278 $priority = PRIORITY_NEGLIGIBLE;
1281 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1283 $stamp = (float)microtime(true);
1284 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1285 DBA::update('workerqueue', $fields, ['id' => $id]);
1286 self::$db_duration += (microtime(true) - $stamp);
1287 self::$db_duration_write += (microtime(true) - $stamp);
1293 * Log active processes into the "process" table
1295 public static function startProcess()
1297 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1299 $command = basename($trace[0]['file']);
1301 Process::deleteInactive();
1303 Process::insert($command);
1307 * Remove the active process from the "process" table
1310 * @throws \Exception
1312 public static function endProcess()
1314 return Process::deleteByPid();
1318 * Set the flag if some job is waiting
1320 * @param boolean $jobs Is there a waiting job?
1321 * @throws \Exception
1323 public static function IPCSetJobState($jobs)
1325 $stamp = (float)microtime(true);
1326 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1327 self::$db_duration += (microtime(true) - $stamp);
1328 self::$db_duration_write += (microtime(true) - $stamp);
1332 * Checks if some worker job waits to be executed
1335 * @throws \Exception
1337 public static function IPCJobsExists()
1339 $stamp = (float)microtime(true);
1340 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1341 self::$db_duration += (microtime(true) - $stamp);
1343 // When we don't have a row, no job is running
1344 if (!DBA::isResult($row)) {
1348 return (bool)$row['jobs'];