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\Network\HTTPRequest;
29 use Friendica\Util\DateTimeFormat;
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::info('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.
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::info('Pre check: Active worker limit reached, quitting.');
89 // Do we have too few memory?
90 if (DI::process()->isMinMemoryReached()) {
91 Logger::info('Pre check: Memory limit reached, quitting.');
95 // Possibly there are too much database connections
96 if (self::maxConnectionsReached()) {
97 Logger::info('Pre check: maximum connections reached, quitting.');
101 // Possibly there are too much database processes that block the system
102 if (DI::process()->isMaxProcessesReached()) {
103 Logger::info('Pre check: maximum processes reached, quitting.');
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::info('Process execution failed, quitting.');
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::info('Active worker limit reached, quitting.');
147 DI::lock()->release('worker');
152 if (DI::process()->isMinMemoryReached()) {
153 Logger::info('Memory limit reached, quitting.');
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::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
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::info("Maintenance mode - quit process", ['pid' => $mypid]);
271 // Constantly check the number of parallel database processes
272 if (DI::process()->isMaxProcessesReached()) {
273 Logger::info("Max processes reached for process", ['pid' => $mypid]);
277 // Constantly check the number of available database connections to let the frontend be accessible at any time
278 if (self::maxConnectionsReached()) {
279 Logger::info("Max connection reached for process", ['pid' => $mypid]);
283 $argv = json_decode($queue["parameter"], true);
285 Logger::error('Parameter is empty', ['queue' => $queue]);
289 // Check for existance and validity of the include file
292 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
293 // We constantly update the "executed" date every minute to avoid being killed too soon
294 if (!isset(self::$last_update)) {
295 self::$last_update = strtotime($queue["executed"]);
298 $age = (time() - self::$last_update) / 60;
299 self::$last_update = time();
302 $stamp = (float)microtime(true);
303 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
304 self::$db_duration += (microtime(true) - $stamp);
305 self::$db_duration_write += (microtime(true) - $stamp);
310 self::execFunction($queue, $include, $argv, true);
312 $stamp = (float)microtime(true);
313 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
314 if (DBA::update('workerqueue', ['done' => true], $condition)) {
315 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
317 self::$db_duration = (microtime(true) - $stamp);
318 self::$db_duration_write += (microtime(true) - $stamp);
323 // The script could be provided as full path or only with the function name
324 if ($include == basename($include)) {
325 $include = "include/".$include.".php";
328 if (!validate_include($include)) {
329 Logger::log("Include file ".$argv[0]." is not valid!");
330 $stamp = (float)microtime(true);
331 DBA::delete('workerqueue', ['id' => $queue["id"]]);
332 self::$db_duration = (microtime(true) - $stamp);
333 self::$db_duration_write += (microtime(true) - $stamp);
337 require_once $include;
339 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
341 if (function_exists($funcname)) {
342 // We constantly update the "executed" date every minute to avoid being killed too soon
343 if (!isset(self::$last_update)) {
344 self::$last_update = strtotime($queue["executed"]);
347 $age = (time() - self::$last_update) / 60;
348 self::$last_update = time();
351 $stamp = (float)microtime(true);
352 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
353 self::$db_duration += (microtime(true) - $stamp);
354 self::$db_duration_write += (microtime(true) - $stamp);
357 self::execFunction($queue, $funcname, $argv, false);
359 $stamp = (float)microtime(true);
360 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
361 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
363 self::$db_duration = (microtime(true) - $stamp);
364 self::$db_duration_write += (microtime(true) - $stamp);
366 Logger::log("Function ".$funcname." does not exist");
367 $stamp = (float)microtime(true);
368 DBA::delete('workerqueue', ['id' => $queue["id"]]);
369 self::$db_duration = (microtime(true) - $stamp);
370 self::$db_duration_write += (microtime(true) - $stamp);
377 * Execute a function from the queue
379 * @param array $queue Workerqueue entry
380 * @param string $funcname name of the function
381 * @param array $argv Array of values to be passed to the function
382 * @param boolean $method_call boolean
384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
386 private static function execFunction($queue, $funcname, $argv, $method_call)
390 Logger::enableWorker($funcname);
392 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
394 $stamp = (float)microtime(true);
396 // We use the callstack here to analyze the performance of executed worker entries.
397 // For this reason the variables have to be initialized.
398 DI::profiler()->reset();
402 $up_duration = microtime(true) - self::$up_start;
404 // Reset global data to avoid interferences
407 // Set the workerLogger as new default logger
409 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
411 $funcname($argv, count($argv));
414 Logger::disableWorker();
418 $duration = (microtime(true) - $stamp);
420 /* With these values we can analyze how effective the worker is.
421 * The database and rest time should be low since this is the unproductive time.
422 * The execution time is the productive time.
423 * By changing parameters like the maximum number of workers we can check the effectivness.
425 $dbtotal = round(self::$db_duration, 2);
426 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
427 $dbcount = round(self::$db_duration_count, 2);
428 $dbstat = round(self::$db_duration_stat, 2);
429 $dbwrite = round(self::$db_duration_write, 2);
430 $dblock = round(self::$lock_duration, 2);
431 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
432 $exec = round($duration, 2);
434 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
436 self::$up_start = microtime(true);
437 self::$db_duration = 0;
438 self::$db_duration_count = 0;
439 self::$db_duration_stat = 0;
440 self::$db_duration_write = 0;
441 self::$lock_duration = 0;
443 if ($duration > 3600) {
444 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
445 } elseif ($duration > 600) {
446 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
447 } elseif ($duration > 300) {
448 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
449 } elseif ($duration > 120) {
450 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
453 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
455 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
457 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
460 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
466 * Checks if the number of database connections has reached a critical limit.
468 * @return bool Are more than 3/4 of the maximum connections used?
469 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
471 private static function maxConnectionsReached()
473 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
474 $max = DI::config()->get("system", "max_connections");
476 // Fetch the percentage level where the worker will get active
477 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
480 // the maximum number of possible user connections can be a system variable
481 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
482 if (DBA::isResult($r)) {
485 // Or it can be granted. This overrides the system variable
486 $stamp = (float)microtime(true);
487 $r = DBA::p('SHOW GRANTS');
488 self::$db_duration += (microtime(true) - $stamp);
489 while ($grants = DBA::fetch($r)) {
490 $grant = array_pop($grants);
491 if (stristr($grant, "GRANT USAGE ON")) {
492 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
500 // If $max is set we will use the processlist to determine the current number of connections
501 // The processlist only shows entries of the current user
503 $stamp = (float)microtime(true);
504 $r = DBA::p('SHOW PROCESSLIST');
505 self::$db_duration += (microtime(true) - $stamp);
506 $used = DBA::numRows($r);
509 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
511 $level = ($used / $max) * 100;
513 if ($level >= $maxlevel) {
514 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
519 // We will now check for the system values.
520 // This limit could be reached although the user limits are fine.
521 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
522 if (!DBA::isResult($r)) {
525 $max = intval($r["Value"]);
529 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
530 if (!DBA::isResult($r)) {
533 $used = intval($r["Value"]);
537 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
539 $level = $used / $max * 100;
541 if ($level < $maxlevel) {
544 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
549 * fix the queue entry if the worker process died
554 private static function killStaleWorkers()
556 $stamp = (float)microtime(true);
557 $entries = DBA::select(
559 ['id', 'pid', 'executed', 'priority', 'parameter'],
560 ['NOT `done` AND `pid` != 0'],
561 ['order' => ['priority', 'created']]
563 self::$db_duration += (microtime(true) - $stamp);
565 while ($entry = DBA::fetch($entries)) {
566 if (!posix_kill($entry["pid"], 0)) {
567 $stamp = (float)microtime(true);
570 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
571 ['id' => $entry["id"]]
573 self::$db_duration += (microtime(true) - $stamp);
574 self::$db_duration_write += (microtime(true) - $stamp);
576 // Kill long running processes
577 // Check if the priority is in a valid range
578 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
579 $entry["priority"] = PRIORITY_MEDIUM;
582 // Define the maximum durations
583 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
584 $max_duration = $max_duration_defaults[$entry["priority"]];
586 $argv = json_decode($entry["parameter"], true);
591 $argv[0] = basename($argv[0]);
593 // How long is the process already running?
594 $duration = (time() - strtotime($entry["executed"])) / 60;
595 if ($duration > $max_duration) {
596 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
597 posix_kill($entry["pid"], SIGTERM);
599 // We killed the stale process.
600 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
601 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
602 $new_priority = $entry["priority"];
603 if ($entry["priority"] == PRIORITY_HIGH) {
604 $new_priority = PRIORITY_MEDIUM;
605 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
606 $new_priority = PRIORITY_LOW;
607 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
608 $new_priority = PRIORITY_NEGLIGIBLE;
610 $stamp = (float)microtime(true);
613 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
614 ['id' => $entry["id"]]
616 self::$db_duration += (microtime(true) - $stamp);
617 self::$db_duration_write += (microtime(true) - $stamp);
619 Logger::info('Process runtime is okay', ['pid' => $entry["pid"], 'duration' => $duration, 'max' => $max_duration, 'command' => substr(json_encode($argv), 0, 50)]);
623 DBA::close($entries);
627 * Checks if the number of active workers exceeds the given limits
629 * @return bool Are there too much workers running?
630 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
632 private static function tooMuchWorkers()
634 $queues = DI::config()->get("system", "worker_queues", 10);
636 $maxqueues = $queues;
638 $active = self::activeWorkers();
640 // Decrease the number of workers at higher load
641 $load = System::currentLoad();
643 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
645 /* Default exponent 3 causes queues to rapidly decrease as load increases.
646 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
647 * For some environments, this rapid decrease is not needed.
648 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
650 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
651 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
652 $queues = intval(ceil($slope * $maxqueues));
656 if (DI::config()->get('system', 'worker_jpm')) {
657 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
658 $jobs_per_minute = [];
659 foreach ($intervals as $interval) {
660 if ($interval == 0) {
663 $interval = (int)$interval;
666 $stamp = (float)microtime(true);
667 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
668 self::$db_duration += (microtime(true) - $stamp);
669 self::$db_duration_stat += (microtime(true) - $stamp);
670 if ($job = DBA::fetch($jobs)) {
671 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
675 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
678 // Create a list of queue entries grouped by their priority
679 $listitem = [0 => ''];
681 $idle_workers = $active;
683 $deferred = self::deferredEntries();
685 if (DI::config()->get('system', 'worker_debug')) {
686 $waiting_processes = 0;
687 // Now adding all processes with workerqueue entries
688 $stamp = (float)microtime(true);
689 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
690 self::$db_duration += (microtime(true) - $stamp);
691 self::$db_duration_stat += (microtime(true) - $stamp);
692 while ($entry = DBA::fetch($jobs)) {
693 $stamp = (float)microtime(true);
694 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
695 self::$db_duration += (microtime(true) - $stamp);
696 self::$db_duration_stat += (microtime(true) - $stamp);
697 if ($process = DBA::fetch($processes)) {
698 $idle_workers -= $process["running"];
699 $waiting_processes += $entry["entries"];
700 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
702 DBA::close($processes);
706 $waiting_processes = self::totalEntries();
707 $stamp = (float)microtime(true);
708 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
709 self::$db_duration += (microtime(true) - $stamp);
710 self::$db_duration_stat += (microtime(true) - $stamp);
712 while ($entry = DBA::fetch($jobs)) {
713 $idle_workers -= $entry["running"];
714 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
719 $waiting_processes -= $deferred;
721 $listitem[0] = "0:" . max(0, $idle_workers);
723 $processlist .= ' ('.implode(', ', $listitem).')';
725 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
726 $top_priority = self::highestPriority();
727 $high_running = self::processWithPriorityActive($top_priority);
729 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
730 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
731 $queues = $active + 1;
735 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
737 // Are there fewer workers running as possible? Then fork a new one.
738 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
739 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
740 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
741 self::IPCSetJobState(true);
748 // if there are too much worker, we don't spawn a new one.
749 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
750 self::IPCSetJobState(false);
753 return $active > $queues;
757 * Returns the number of active worker processes
759 * @return integer Number of active worker processes
762 private static function activeWorkers()
764 $stamp = (float)microtime(true);
765 $count = DBA::count('process', ['command' => 'Worker.php']);
766 self::$db_duration += (microtime(true) - $stamp);
771 * Returns waiting jobs for the current process id
773 * @return array waiting workerqueue jobs
776 private static function getWaitingJobForPID()
778 $stamp = (float)microtime(true);
779 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
780 self::$db_duration += (microtime(true) - $stamp);
781 if (DBA::isResult($r)) {
782 return DBA::toArray($r);
790 * Returns the next jobs that should be executed
792 * @return array array with next jobs
795 private static function nextProcess()
797 $priority = self::nextPriority();
798 if (empty($priority)) {
799 Logger::info('No tasks found');
803 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
806 $stamp = (float)microtime(true);
807 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
808 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
809 self::$db_duration += (microtime(true) - $stamp);
810 while ($task = DBA::fetch($tasks)) {
811 $ids[] = $task['id'];
812 // Only continue that loop while we are storing commands that can be processed quickly
813 $command = json_decode($task['parameter'])[0];
814 if (!in_array($command, self::FAST_COMMANDS)) {
820 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
825 * Returns the priority of the next workerqueue job
827 * @return string priority
830 private static function nextPriority()
833 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
834 foreach ($priorities as $priority) {
835 $stamp = (float)microtime(true);
836 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
837 $waiting[$priority] = true;
839 self::$db_duration += (microtime(true) - $stamp);
842 if (!empty($waiting[PRIORITY_CRITICAL])) {
843 return PRIORITY_CRITICAL;
848 $stamp = (float)microtime(true);
849 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
850 self::$db_duration += (microtime(true) - $stamp);
851 while ($process = DBA::fetch($processes)) {
852 $running[$process['priority']] = $process['running'];
853 $running_total += $process['running'];
855 DBA::close($processes);
857 foreach ($priorities as $priority) {
858 if (!empty($waiting[$priority]) && empty($running[$priority])) {
859 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
864 $active = max(self::activeWorkers(), $running_total);
865 $priorities = max(count($waiting), count($running));
869 for ($i = 1; $i <= $priorities; ++$i) {
870 $total += pow($i, $exponent);
874 for ($i = 1; $i <= $priorities; ++$i) {
875 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
879 foreach ($running as $priority => $workers) {
880 if ($workers < $limit[$i++]) {
881 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
886 if (!empty($waiting)) {
887 $priority = array_keys($waiting)[0];
888 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
896 * Find and claim the next worker process for us
898 * @return boolean Have we found something?
899 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
901 private static function findWorkerProcesses()
905 $ids = self::nextProcess();
907 // If there is no result we check without priority limit
909 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
911 $stamp = (float)microtime(true);
912 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
913 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
914 self::$db_duration += (microtime(true) - $stamp);
916 while ($task = DBA::fetch($tasks)) {
917 $ids[] = $task['id'];
918 // Only continue that loop while we are storing commands that can be processed quickly
919 $command = json_decode($task['parameter'])[0];
920 if (!in_array($command, self::FAST_COMMANDS)) {
928 $stamp = (float)microtime(true);
929 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
930 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
931 self::$db_duration += (microtime(true) - $stamp);
932 self::$db_duration_write += (microtime(true) - $stamp);
939 * Returns the next worker process
941 * @return array worker processes
942 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
944 public static function workerProcess()
946 // There can already be jobs for us in the queue.
947 $waiting = self::getWaitingJobForPID();
948 if (!empty($waiting)) {
952 $stamp = (float)microtime(true);
953 if (!DI::lock()->acquire('worker_process')) {
956 self::$lock_duration += (microtime(true) - $stamp);
958 $found = self::findWorkerProcesses();
960 DI::lock()->release('worker_process');
963 $stamp = (float)microtime(true);
964 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
965 self::$db_duration += (microtime(true) - $stamp);
966 return DBA::toArray($r);
972 * Removes a workerqueue entry from the current process
977 public static function unclaimProcess()
981 $stamp = (float)microtime(true);
982 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
983 self::$db_duration += (microtime(true) - $stamp);
984 self::$db_duration_write += (microtime(true) - $stamp);
988 * Call the front end worker
991 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
993 public static function callWorker()
995 if (!DI::config()->get("system", "frontend_worker")) {
999 $url = DI::baseUrl() . '/worker';
1000 HTTPRequest::fetchUrl($url, false, 1);
1004 * Call the front end worker if there aren't any active
1007 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1009 public static function executeIfIdle()
1011 if (!DI::config()->get("system", "frontend_worker")) {
1015 // Do we have "proc_open"? Then we can fork the worker
1016 if (function_exists("proc_open")) {
1017 // When was the last time that we called the worker?
1018 // Less than one minute? Then we quit
1019 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1023 DI::config()->set("system", "worker_started", time());
1025 // Do we have enough running workers? Then we quit here.
1026 if (self::tooMuchWorkers()) {
1027 // Cleaning dead processes
1028 self::killStaleWorkers();
1029 Process::deleteInactive();
1036 Logger::info('Call worker');
1037 self::spawnWorker();
1041 // We cannot execute background processes.
1042 // We now run the processes from the frontend.
1043 // This won't work with long running processes.
1046 self::clearProcesses();
1048 $workers = self::activeWorkers();
1050 if ($workers == 0) {
1056 * Removes long running worker processes
1059 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1061 public static function clearProcesses()
1063 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1065 /// @todo We should clean up the corresponding workerqueue entries as well
1066 $stamp = (float)microtime(true);
1067 $condition = ["`created` < ? AND `command` = 'worker.php'",
1068 DateTimeFormat::utc("now - ".$timeout." minutes")];
1069 DBA::delete('process', $condition);
1070 self::$db_duration = (microtime(true) - $stamp);
1071 self::$db_duration_write += (microtime(true) - $stamp);
1075 * Runs the cron processes
1078 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1080 private static function runCron()
1082 Logger::info('Add cron entries');
1084 // Check for spooled items
1085 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1087 // Run the cron job that calls all other jobs
1088 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1090 // Cleaning dead processes
1091 self::killStaleWorkers();
1095 * Spawns a new worker
1097 * @param bool $do_cron
1099 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1101 public static function spawnWorker($do_cron = false)
1103 $command = 'bin/worker.php';
1105 $args = ['no_cron' => !$do_cron];
1108 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), $a->getBasePath());
1109 $process->run($command, $args);
1111 // after spawning we have to remove the flag.
1112 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1113 self::IPCSetJobState(false);
1118 * Adds tasks to the worker queue
1120 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1122 * next args are passed as $cmd command line
1123 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1124 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1126 * @return boolean "false" if worker queue entry already existed or there had been an error
1127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1128 * @note $cmd and string args are surrounded with ""
1134 public static function add($cmd)
1136 $args = func_get_args();
1138 if (!count($args)) {
1142 $arr = ['args' => $args, 'run_cmd' => true];
1144 Hook::callAll("proc_run", $arr);
1145 if (!$arr['run_cmd'] || !count($args)) {
1149 $priority = PRIORITY_MEDIUM;
1150 // Don't fork from frontend tasks by default
1151 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1152 $created = DateTimeFormat::utcNow();
1153 $force_priority = false;
1155 $run_parameter = array_shift($args);
1157 if (is_int($run_parameter)) {
1158 $priority = $run_parameter;
1159 } elseif (is_array($run_parameter)) {
1160 if (isset($run_parameter['priority'])) {
1161 $priority = $run_parameter['priority'];
1163 if (isset($run_parameter['created'])) {
1164 $created = $run_parameter['created'];
1166 if (isset($run_parameter['dont_fork'])) {
1167 $dont_fork = $run_parameter['dont_fork'];
1169 if (isset($run_parameter['force_priority'])) {
1170 $force_priority = $run_parameter['force_priority'];
1174 $parameters = json_encode($args);
1175 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1178 // Quit if there was a database error - a precaution for the update process to 3.5.3
1179 if (DBA::errorNo() != 0) {
1184 $added = DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1188 } elseif ($force_priority) {
1189 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1192 // Should we quit and wait for the worker to be called as a cronjob?
1197 // If there is a lock then we don't have to check for too much worker
1198 if (!DI::lock()->acquire('worker', 0)) {
1202 // If there are already enough workers running, don't fork another one
1203 $quit = self::tooMuchWorkers();
1204 DI::lock()->release('worker');
1210 // We tell the daemon that a new job entry exists
1211 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1212 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1216 // Now call the worker to execute the jobs that we just added to the queue
1217 self::spawnWorker();
1223 * Returns the next retrial level for worker jobs.
1224 * This function will skip levels when jobs are older.
1226 * @param array $queue Worker queue entry
1227 * @param integer $max_level maximum retrial level
1228 * @return integer the next retrial level value
1230 private static function getNextRetrial($queue, $max_level)
1232 $created = strtotime($queue['created']);
1233 $retrial_time = time() - $created;
1235 $new_retrial = $queue['retrial'] + 1;
1237 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1238 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1240 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1241 $new_retrial = $retrial;
1244 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1245 return $new_retrial;
1249 * Defers the current worker entry
1251 * @return boolean had the entry been deferred?
1253 public static function defer()
1255 if (empty(DI::app()->queue)) {
1259 $queue = DI::app()->queue;
1261 $retrial = $queue['retrial'];
1263 $priority = $queue['priority'];
1265 $max_level = DI::config()->get('system', 'worker_defer_limit');
1267 $new_retrial = self::getNextRetrial($queue, $max_level);
1269 if ($new_retrial > $max_level) {
1270 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]);
1274 // Calculate the delay until the next trial
1275 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1276 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1278 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1279 $priority = PRIORITY_MEDIUM;
1280 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1281 $priority = PRIORITY_LOW;
1282 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1283 $priority = PRIORITY_NEGLIGIBLE;
1286 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1288 $stamp = (float)microtime(true);
1289 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1290 DBA::update('workerqueue', $fields, ['id' => $id]);
1291 self::$db_duration += (microtime(true) - $stamp);
1292 self::$db_duration_write += (microtime(true) - $stamp);
1298 * Log active processes into the "process" table
1300 public static function startProcess()
1302 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1304 $command = basename($trace[0]['file']);
1306 Process::deleteInactive();
1308 Process::insert($command);
1312 * Remove the active process from the "process" table
1315 * @throws \Exception
1317 public static function endProcess()
1319 return Process::deleteByPid();
1323 * Set the flag if some job is waiting
1325 * @param boolean $jobs Is there a waiting job?
1326 * @throws \Exception
1328 public static function IPCSetJobState($jobs)
1330 $stamp = (float)microtime(true);
1331 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1332 self::$db_duration += (microtime(true) - $stamp);
1333 self::$db_duration_write += (microtime(true) - $stamp);
1337 * Checks if some worker job waits to be executed
1340 * @throws \Exception
1342 public static function IPCJobsExists()
1344 $stamp = (float)microtime(true);
1345 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1346 self::$db_duration += (microtime(true) - $stamp);
1348 // When we don't have a row, no job is running
1349 if (!DBA::isResult($row)) {
1353 return (bool)$row['jobs'];