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'];
43 private static $up_start;
44 private static $db_duration = 0;
45 private static $db_duration_count = 0;
46 private static $db_duration_write = 0;
47 private static $db_duration_stat = 0;
48 private static $lock_duration = 0;
49 private static $last_update;
50 private static $state;
53 * Processes the tasks that are in the workerqueue table
55 * @param boolean $run_cron Should the cron processes be executed?
57 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
59 public static function processQueue($run_cron = true)
61 // Ensure that all "strtotime" operations do run timezone independent
62 date_default_timezone_set('UTC');
64 self::$up_start = microtime(true);
66 // At first check the maximum load. We shouldn't continue with a high load
67 if (DI::process()->isMaxLoadReached()) {
68 Logger::info('Pre check: maximum load reached, quitting.');
72 // We now start the process. This is done after the load check since this could increase the load.
75 // Kill stale processes every 5 minutes
76 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
77 if (time() > ($last_cleanup + 300)) {
78 DI::config()->set('system', 'worker_last_cleaned', time());
79 self::killStaleWorkers();
82 // Count active workers and compare them with a maximum value that depends on the load
83 if (self::tooMuchWorkers()) {
84 Logger::info('Pre check: Active worker limit reached, quitting.');
88 // Do we have too few memory?
89 if (DI::process()->isMinMemoryReached()) {
90 Logger::info('Pre check: Memory limit reached, quitting.');
94 // Possibly there are too much database connections
95 if (self::maxConnectionsReached()) {
96 Logger::info('Pre check: maximum connections reached, quitting.');
100 // Possibly there are too much database processes that block the system
101 if (DI::process()->isMaxProcessesReached()) {
102 Logger::info('Pre check: maximum processes reached, quitting.');
106 // Now we start additional cron processes if we should do so
112 self::$state = self::STATE_STARTUP;
114 // We fetch the next queue entry that is about to be executed
115 while ($r = self::workerProcess()) {
117 foreach ($r as $entry) {
118 // Assure that the priority is an integer value
119 $entry['priority'] = (int)$entry['priority'];
121 // The work will be done
122 if (!self::execute($entry)) {
123 Logger::info('Process execution failed, quitting.');
127 // Trying to fetch new processes - but only once when successful
128 if (!$refetched && DI::lock()->acquire('worker_process', 0)) {
129 self::findWorkerProcesses();
130 DI::lock()->release('worker_process');
131 self::$state = self::STATE_REFETCH;
134 self::$state = self::STATE_SHORT_LOOP;
138 // To avoid the quitting of multiple workers only one worker at a time will execute the check
139 if (!self::getWaitingJobForPID()) {
140 self::$state = self::STATE_LONG_LOOP;
142 if (DI::lock()->acquire('worker', 0)) {
143 // Count active workers and compare them with a maximum value that depends on the load
144 if (self::tooMuchWorkers()) {
145 Logger::info('Active worker limit reached, quitting.');
146 DI::lock()->release('worker');
151 if (DI::process()->isMinMemoryReached()) {
152 Logger::info('Memory limit reached, quitting.');
153 DI::lock()->release('worker');
156 DI::lock()->release('worker');
160 // Quit the worker once every cron interval
161 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
162 Logger::info('Process lifetime reached, respawning.');
168 // Cleaning up. Possibly not needed, but it doesn't harm anything.
169 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
170 self::IPCSetJobState(false);
172 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
176 * Check if non executed tasks do exist in the worker queue
178 * @return boolean Returns "true" if tasks are existing
181 private static function entriesExists()
183 $stamp = (float)microtime(true);
184 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
185 self::$db_duration += (microtime(true) - $stamp);
190 * Returns the number of deferred entries in the worker queue
192 * @return integer Number of deferred entries in the worker queue
195 private static function deferredEntries()
197 $stamp = (float)microtime(true);
198 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
199 self::$db_duration += (microtime(true) - $stamp);
200 self::$db_duration_count += (microtime(true) - $stamp);
205 * Returns the number of non executed entries in the worker queue
207 * @return integer Number of non executed entries in the worker queue
210 private static function totalEntries()
212 $stamp = (float)microtime(true);
213 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
214 self::$db_duration += (microtime(true) - $stamp);
215 self::$db_duration_count += (microtime(true) - $stamp);
220 * Returns the highest priority in the worker queue that isn't executed
222 * @return integer Number of active worker processes
225 private static function highestPriority()
227 $stamp = (float)microtime(true);
228 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
229 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
230 self::$db_duration += (microtime(true) - $stamp);
231 if (DBA::isResult($workerqueue)) {
232 return $workerqueue["priority"];
239 * Returns if a process with the given priority is running
241 * @param integer $priority The priority that should be checked
243 * @return integer Is there a process running with that priority?
246 private static function processWithPriorityActive($priority)
248 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
249 return DBA::exists('workerqueue', $condition);
253 * Execute a worker entry
255 * @param array $queue Workerqueue entry
257 * @return boolean "true" if further processing should be stopped
258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260 public static function execute($queue)
264 // Quit when in maintenance
265 if (DI::config()->get('system', 'maintenance', false, true)) {
266 Logger::info("Maintenance mode - quit process", ['pid' => $mypid]);
270 // Constantly check the number of parallel database processes
271 if (DI::process()->isMaxProcessesReached()) {
272 Logger::info("Max processes reached for process", ['pid' => $mypid]);
276 // Constantly check the number of available database connections to let the frontend be accessible at any time
277 if (self::maxConnectionsReached()) {
278 Logger::info("Max connection reached for process", ['pid' => $mypid]);
282 $argv = json_decode($queue["parameter"], true);
284 Logger::error('Parameter is empty', ['queue' => $queue]);
288 // Check for existance and validity of the include file
291 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
292 // We constantly update the "executed" date every minute to avoid being killed too soon
293 if (!isset(self::$last_update)) {
294 self::$last_update = strtotime($queue["executed"]);
297 $age = (time() - self::$last_update) / 60;
298 self::$last_update = time();
301 $stamp = (float)microtime(true);
302 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
303 self::$db_duration += (microtime(true) - $stamp);
304 self::$db_duration_write += (microtime(true) - $stamp);
309 self::execFunction($queue, $include, $argv, true);
311 $stamp = (float)microtime(true);
312 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
313 if (DBA::update('workerqueue', ['done' => true], $condition)) {
314 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
316 self::$db_duration = (microtime(true) - $stamp);
317 self::$db_duration_write += (microtime(true) - $stamp);
322 // The script could be provided as full path or only with the function name
323 if ($include == basename($include)) {
324 $include = "include/".$include.".php";
327 if (!validate_include($include)) {
328 Logger::log("Include file ".$argv[0]." is not valid!");
329 $stamp = (float)microtime(true);
330 DBA::delete('workerqueue', ['id' => $queue["id"]]);
331 self::$db_duration = (microtime(true) - $stamp);
332 self::$db_duration_write += (microtime(true) - $stamp);
336 require_once $include;
338 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
340 if (function_exists($funcname)) {
341 // We constantly update the "executed" date every minute to avoid being killed too soon
342 if (!isset(self::$last_update)) {
343 self::$last_update = strtotime($queue["executed"]);
346 $age = (time() - self::$last_update) / 60;
347 self::$last_update = time();
350 $stamp = (float)microtime(true);
351 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
352 self::$db_duration += (microtime(true) - $stamp);
353 self::$db_duration_write += (microtime(true) - $stamp);
356 self::execFunction($queue, $funcname, $argv, false);
358 $stamp = (float)microtime(true);
359 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
360 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
362 self::$db_duration = (microtime(true) - $stamp);
363 self::$db_duration_write += (microtime(true) - $stamp);
365 Logger::log("Function ".$funcname." does not exist");
366 $stamp = (float)microtime(true);
367 DBA::delete('workerqueue', ['id' => $queue["id"]]);
368 self::$db_duration = (microtime(true) - $stamp);
369 self::$db_duration_write += (microtime(true) - $stamp);
376 * Execute a function from the queue
378 * @param array $queue Workerqueue entry
379 * @param string $funcname name of the function
380 * @param array $argv Array of values to be passed to the function
381 * @param boolean $method_call boolean
383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
385 private static function execFunction($queue, $funcname, $argv, $method_call)
389 Logger::enableWorker($funcname);
391 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
393 $stamp = (float)microtime(true);
395 // We use the callstack here to analyze the performance of executed worker entries.
396 // For this reason the variables have to be initialized.
397 DI::profiler()->reset();
401 $up_duration = microtime(true) - self::$up_start;
403 // Reset global data to avoid interferences
406 // Set the workerLogger as new default logger
408 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
410 $funcname($argv, count($argv));
413 Logger::disableWorker();
417 $duration = (microtime(true) - $stamp);
419 /* With these values we can analyze how effective the worker is.
420 * The database and rest time should be low since this is the unproductive time.
421 * The execution time is the productive time.
422 * By changing parameters like the maximum number of workers we can check the effectivness.
424 $dbtotal = round(self::$db_duration, 2);
425 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
426 $dbcount = round(self::$db_duration_count, 2);
427 $dbstat = round(self::$db_duration_stat, 2);
428 $dbwrite = round(self::$db_duration_write, 2);
429 $dblock = round(self::$lock_duration, 2);
430 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
431 $exec = round($duration, 2);
433 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
435 self::$up_start = microtime(true);
436 self::$db_duration = 0;
437 self::$db_duration_count = 0;
438 self::$db_duration_stat = 0;
439 self::$db_duration_write = 0;
440 self::$lock_duration = 0;
442 if ($duration > 3600) {
443 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
444 } elseif ($duration > 600) {
445 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
446 } elseif ($duration > 300) {
447 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
448 } elseif ($duration > 120) {
449 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
452 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
454 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
456 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
459 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
465 * Checks if the number of database connections has reached a critical limit.
467 * @return bool Are more than 3/4 of the maximum connections used?
468 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
470 private static function maxConnectionsReached()
472 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
473 $max = DI::config()->get("system", "max_connections");
475 // Fetch the percentage level where the worker will get active
476 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
479 // the maximum number of possible user connections can be a system variable
480 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
481 if (DBA::isResult($r)) {
484 // Or it can be granted. This overrides the system variable
485 $stamp = (float)microtime(true);
486 $r = DBA::p('SHOW GRANTS');
487 self::$db_duration += (microtime(true) - $stamp);
488 while ($grants = DBA::fetch($r)) {
489 $grant = array_pop($grants);
490 if (stristr($grant, "GRANT USAGE ON")) {
491 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
499 // If $max is set we will use the processlist to determine the current number of connections
500 // The processlist only shows entries of the current user
502 $stamp = (float)microtime(true);
503 $r = DBA::p('SHOW PROCESSLIST');
504 self::$db_duration += (microtime(true) - $stamp);
505 $used = DBA::numRows($r);
508 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
510 $level = ($used / $max) * 100;
512 if ($level >= $maxlevel) {
513 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
518 // We will now check for the system values.
519 // This limit could be reached although the user limits are fine.
520 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
521 if (!DBA::isResult($r)) {
524 $max = intval($r["Value"]);
528 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
529 if (!DBA::isResult($r)) {
532 $used = intval($r["Value"]);
536 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
538 $level = $used / $max * 100;
540 if ($level < $maxlevel) {
543 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
548 * fix the queue entry if the worker process died
553 private static function killStaleWorkers()
555 $stamp = (float)microtime(true);
556 $entries = DBA::select(
558 ['id', 'pid', 'executed', 'priority', 'parameter'],
559 ['NOT `done` AND `pid` != 0'],
560 ['order' => ['priority', 'created']]
562 self::$db_duration += (microtime(true) - $stamp);
564 while ($entry = DBA::fetch($entries)) {
565 if (!posix_kill($entry["pid"], 0)) {
566 $stamp = (float)microtime(true);
569 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
570 ['id' => $entry["id"]]
572 self::$db_duration += (microtime(true) - $stamp);
573 self::$db_duration_write += (microtime(true) - $stamp);
575 // Kill long running processes
576 // Check if the priority is in a valid range
577 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
578 $entry["priority"] = PRIORITY_MEDIUM;
581 // Define the maximum durations
582 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
583 $max_duration = $max_duration_defaults[$entry["priority"]];
585 $argv = json_decode($entry["parameter"], true);
590 $argv[0] = basename($argv[0]);
592 // How long is the process already running?
593 $duration = (time() - strtotime($entry["executed"])) / 60;
594 if ($duration > $max_duration) {
595 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
596 posix_kill($entry["pid"], SIGTERM);
598 // We killed the stale process.
599 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
600 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
601 $new_priority = $entry["priority"];
602 if ($entry["priority"] == PRIORITY_HIGH) {
603 $new_priority = PRIORITY_MEDIUM;
604 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
605 $new_priority = PRIORITY_LOW;
606 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
607 $new_priority = PRIORITY_NEGLIGIBLE;
609 $stamp = (float)microtime(true);
612 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
613 ['id' => $entry["id"]]
615 self::$db_duration += (microtime(true) - $stamp);
616 self::$db_duration_write += (microtime(true) - $stamp);
618 Logger::info('Process runtime is okay', ['pid' => $entry["pid"], 'duration' => $duration, 'max' => $max_duration, 'command' => substr(json_encode($argv), 0, 50)]);
622 DBA::close($entries);
626 * Checks if the number of active workers exceeds the given limits
628 * @return bool Are there too much workers running?
629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
631 private static function tooMuchWorkers()
633 $queues = DI::config()->get("system", "worker_queues", 10);
635 $maxqueues = $queues;
637 $active = self::activeWorkers();
639 // Decrease the number of workers at higher load
640 $load = System::currentLoad();
642 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
644 /* Default exponent 3 causes queues to rapidly decrease as load increases.
645 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
646 * For some environments, this rapid decrease is not needed.
647 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
649 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
650 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
651 $queues = intval(ceil($slope * $maxqueues));
655 if (DI::config()->get('system', 'worker_jpm')) {
656 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
657 $jobs_per_minute = [];
658 foreach ($intervals as $interval) {
659 if ($interval == 0) {
662 $interval = (int)$interval;
665 $stamp = (float)microtime(true);
666 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
667 self::$db_duration += (microtime(true) - $stamp);
668 self::$db_duration_stat += (microtime(true) - $stamp);
669 if ($job = DBA::fetch($jobs)) {
670 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
674 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
677 // Create a list of queue entries grouped by their priority
678 $listitem = [0 => ''];
680 $idle_workers = $active;
682 $deferred = self::deferredEntries();
684 if (DI::config()->get('system', 'worker_debug')) {
685 $waiting_processes = 0;
686 // Now adding all processes with workerqueue entries
687 $stamp = (float)microtime(true);
688 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
689 self::$db_duration += (microtime(true) - $stamp);
690 self::$db_duration_stat += (microtime(true) - $stamp);
691 while ($entry = DBA::fetch($jobs)) {
692 $stamp = (float)microtime(true);
693 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
694 self::$db_duration += (microtime(true) - $stamp);
695 self::$db_duration_stat += (microtime(true) - $stamp);
696 if ($process = DBA::fetch($processes)) {
697 $idle_workers -= $process["running"];
698 $waiting_processes += $entry["entries"];
699 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
701 DBA::close($processes);
705 $waiting_processes = self::totalEntries();
706 $stamp = (float)microtime(true);
707 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
708 self::$db_duration += (microtime(true) - $stamp);
709 self::$db_duration_stat += (microtime(true) - $stamp);
711 while ($entry = DBA::fetch($jobs)) {
712 $idle_workers -= $entry["running"];
713 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
718 $waiting_processes -= $deferred;
720 $listitem[0] = "0:" . max(0, $idle_workers);
722 $processlist .= ' ('.implode(', ', $listitem).')';
724 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
725 $top_priority = self::highestPriority();
726 $high_running = self::processWithPriorityActive($top_priority);
728 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
729 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
730 $queues = $active + 1;
734 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
736 // Are there fewer workers running as possible? Then fork a new one.
737 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
738 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
739 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
740 self::IPCSetJobState(true);
747 // if there are too much worker, we don't spawn a new one.
748 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
749 self::IPCSetJobState(false);
752 return $active > $queues;
756 * Returns the number of active worker processes
758 * @return integer Number of active worker processes
761 private static function activeWorkers()
763 $stamp = (float)microtime(true);
764 $count = DBA::count('process', ['command' => 'Worker.php']);
765 self::$db_duration += (microtime(true) - $stamp);
770 * Returns waiting jobs for the current process id
772 * @return array waiting workerqueue jobs
775 private static function getWaitingJobForPID()
777 $stamp = (float)microtime(true);
778 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
779 self::$db_duration += (microtime(true) - $stamp);
780 if (DBA::isResult($r)) {
781 return DBA::toArray($r);
789 * Returns the next jobs that should be executed
791 * @return array array with next jobs
794 private static function nextProcess()
796 $priority = self::nextPriority();
797 if (empty($priority)) {
798 Logger::info('No tasks found');
802 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
805 $stamp = (float)microtime(true);
806 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
807 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
808 self::$db_duration += (microtime(true) - $stamp);
809 while ($task = DBA::fetch($tasks)) {
810 $ids[] = $task['id'];
811 // Only continue that loop while we are storing commands that can be processed quickly
812 $command = json_decode($task['parameter'])[0];
813 if (!in_array($command, self::FAST_COMMANDS)) {
819 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
824 * Returns the priority of the next workerqueue job
826 * @return string priority
829 private static function nextPriority()
832 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
833 foreach ($priorities as $priority) {
834 $stamp = (float)microtime(true);
835 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
836 $waiting[$priority] = true;
838 self::$db_duration += (microtime(true) - $stamp);
841 if (!empty($waiting[PRIORITY_CRITICAL])) {
842 return PRIORITY_CRITICAL;
847 $stamp = (float)microtime(true);
848 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
849 self::$db_duration += (microtime(true) - $stamp);
850 while ($process = DBA::fetch($processes)) {
851 $running[$process['priority']] = $process['running'];
852 $running_total += $process['running'];
854 DBA::close($processes);
856 foreach ($priorities as $priority) {
857 if (!empty($waiting[$priority]) && empty($running[$priority])) {
858 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
863 $active = max(self::activeWorkers(), $running_total);
864 $priorities = max(count($waiting), count($running));
868 for ($i = 1; $i <= $priorities; ++$i) {
869 $total += pow($i, $exponent);
873 for ($i = 1; $i <= $priorities; ++$i) {
874 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
878 foreach ($running as $priority => $workers) {
879 if ($workers < $limit[$i++]) {
880 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
885 if (!empty($waiting)) {
886 $priority = array_keys($waiting)[0];
887 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
895 * Find and claim the next worker process for us
897 * @return boolean Have we found something?
898 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
900 private static function findWorkerProcesses()
904 $ids = self::nextProcess();
906 // If there is no result we check without priority limit
908 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
910 $stamp = (float)microtime(true);
911 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
912 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
913 self::$db_duration += (microtime(true) - $stamp);
915 while ($task = DBA::fetch($tasks)) {
916 $ids[] = $task['id'];
917 // Only continue that loop while we are storing commands that can be processed quickly
918 $command = json_decode($task['parameter'])[0];
919 if (!in_array($command, self::FAST_COMMANDS)) {
927 $stamp = (float)microtime(true);
928 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
929 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
930 self::$db_duration += (microtime(true) - $stamp);
931 self::$db_duration_write += (microtime(true) - $stamp);
938 * Returns the next worker process
940 * @return array worker processes
941 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
943 public static function workerProcess()
945 // There can already be jobs for us in the queue.
946 $waiting = self::getWaitingJobForPID();
947 if (!empty($waiting)) {
951 $stamp = (float)microtime(true);
952 if (!DI::lock()->acquire('worker_process')) {
955 self::$lock_duration += (microtime(true) - $stamp);
957 $found = self::findWorkerProcesses();
959 DI::lock()->release('worker_process');
962 $stamp = (float)microtime(true);
963 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
964 self::$db_duration += (microtime(true) - $stamp);
965 return DBA::toArray($r);
971 * Removes a workerqueue entry from the current process
976 public static function unclaimProcess()
980 $stamp = (float)microtime(true);
981 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
982 self::$db_duration += (microtime(true) - $stamp);
983 self::$db_duration_write += (microtime(true) - $stamp);
987 * Call the front end worker
990 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
992 public static function callWorker()
994 if (!DI::config()->get("system", "frontend_worker")) {
998 $url = DI::baseUrl() . '/worker';
999 DI::httpRequest()->fetch($url, false, 1);
1003 * Call the front end worker if there aren't any active
1006 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1008 public static function executeIfIdle()
1010 if (!DI::config()->get("system", "frontend_worker")) {
1014 // Do we have "proc_open"? Then we can fork the worker
1015 if (function_exists("proc_open")) {
1016 // When was the last time that we called the worker?
1017 // Less than one minute? Then we quit
1018 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1022 DI::config()->set("system", "worker_started", time());
1024 // Do we have enough running workers? Then we quit here.
1025 if (self::tooMuchWorkers()) {
1026 // Cleaning dead processes
1027 self::killStaleWorkers();
1028 Process::deleteInactive();
1035 Logger::info('Call worker');
1036 self::spawnWorker();
1040 // We cannot execute background processes.
1041 // We now run the processes from the frontend.
1042 // This won't work with long running processes.
1045 self::clearProcesses();
1047 $workers = self::activeWorkers();
1049 if ($workers == 0) {
1055 * Removes long running worker processes
1058 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1060 public static function clearProcesses()
1062 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1064 /// @todo We should clean up the corresponding workerqueue entries as well
1065 $stamp = (float)microtime(true);
1066 $condition = ["`created` < ? AND `command` = 'worker.php'",
1067 DateTimeFormat::utc("now - ".$timeout." minutes")];
1068 DBA::delete('process', $condition);
1069 self::$db_duration = (microtime(true) - $stamp);
1070 self::$db_duration_write += (microtime(true) - $stamp);
1074 * Runs the cron processes
1077 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1079 private static function runCron()
1081 Logger::info('Add cron entries');
1083 // Check for spooled items
1084 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1086 // Run the cron job that calls all other jobs
1087 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1089 // Cleaning dead processes
1090 self::killStaleWorkers();
1094 * Spawns a new worker
1096 * @param bool $do_cron
1098 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1100 public static function spawnWorker($do_cron = false)
1102 $command = 'bin/worker.php';
1104 $args = ['no_cron' => !$do_cron];
1107 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), $a->getBasePath());
1108 $process->run($command, $args);
1110 // after spawning we have to remove the flag.
1111 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1112 self::IPCSetJobState(false);
1117 * Adds tasks to the worker queue
1119 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1121 * next args are passed as $cmd command line
1122 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1123 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1125 * @return boolean "false" if worker queue entry already existed or there had been an error
1126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1127 * @note $cmd and string args are surrounded with ""
1133 public static function add($cmd)
1135 $args = func_get_args();
1137 if (!count($args)) {
1141 $arr = ['args' => $args, 'run_cmd' => true];
1143 Hook::callAll("proc_run", $arr);
1144 if (!$arr['run_cmd'] || !count($args)) {
1148 $priority = PRIORITY_MEDIUM;
1149 // Don't fork from frontend tasks by default
1150 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1151 $created = DateTimeFormat::utcNow();
1152 $force_priority = false;
1154 $run_parameter = array_shift($args);
1156 if (is_int($run_parameter)) {
1157 $priority = $run_parameter;
1158 } elseif (is_array($run_parameter)) {
1159 if (isset($run_parameter['priority'])) {
1160 $priority = $run_parameter['priority'];
1162 if (isset($run_parameter['created'])) {
1163 $created = $run_parameter['created'];
1165 if (isset($run_parameter['dont_fork'])) {
1166 $dont_fork = $run_parameter['dont_fork'];
1168 if (isset($run_parameter['force_priority'])) {
1169 $force_priority = $run_parameter['force_priority'];
1173 $parameters = json_encode($args);
1174 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1177 // Quit if there was a database error - a precaution for the update process to 3.5.3
1178 if (DBA::errorNo() != 0) {
1183 $added = DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1187 } elseif ($force_priority) {
1188 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1191 // Should we quit and wait for the worker to be called as a cronjob?
1196 // If there is a lock then we don't have to check for too much worker
1197 if (!DI::lock()->acquire('worker', 0)) {
1201 // If there are already enough workers running, don't fork another one
1202 $quit = self::tooMuchWorkers();
1203 DI::lock()->release('worker');
1209 // We tell the daemon that a new job entry exists
1210 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1211 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1215 // Now call the worker to execute the jobs that we just added to the queue
1216 self::spawnWorker();
1222 * Returns the next retrial level for worker jobs.
1223 * This function will skip levels when jobs are older.
1225 * @param array $queue Worker queue entry
1226 * @param integer $max_level maximum retrial level
1227 * @return integer the next retrial level value
1229 private static function getNextRetrial($queue, $max_level)
1231 $created = strtotime($queue['created']);
1232 $retrial_time = time() - $created;
1234 $new_retrial = $queue['retrial'] + 1;
1236 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1237 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1239 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1240 $new_retrial = $retrial;
1243 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1244 return $new_retrial;
1248 * Defers the current worker entry
1250 * @return boolean had the entry been deferred?
1252 public static function defer()
1254 if (empty(DI::app()->queue)) {
1258 $queue = DI::app()->queue;
1260 $retrial = $queue['retrial'];
1262 $priority = $queue['priority'];
1264 $max_level = DI::config()->get('system', 'worker_defer_limit');
1266 $new_retrial = self::getNextRetrial($queue, $max_level);
1268 if ($new_retrial > $max_level) {
1269 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]);
1273 // Calculate the delay until the next trial
1274 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1275 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1277 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1278 $priority = PRIORITY_MEDIUM;
1279 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1280 $priority = PRIORITY_LOW;
1281 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1282 $priority = PRIORITY_NEGLIGIBLE;
1285 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1287 $stamp = (float)microtime(true);
1288 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1289 DBA::update('workerqueue', $fields, ['id' => $id]);
1290 self::$db_duration += (microtime(true) - $stamp);
1291 self::$db_duration_write += (microtime(true) - $stamp);
1297 * Log active processes into the "process" table
1299 public static function startProcess()
1301 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1303 $command = basename($trace[0]['file']);
1305 Process::deleteInactive();
1307 Process::insert($command);
1311 * Remove the active process from the "process" table
1314 * @throws \Exception
1316 public static function endProcess()
1318 return Process::deleteByPid();
1322 * Set the flag if some job is waiting
1324 * @param boolean $jobs Is there a waiting job?
1325 * @throws \Exception
1327 public static function IPCSetJobState($jobs)
1329 $stamp = (float)microtime(true);
1330 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1331 self::$db_duration += (microtime(true) - $stamp);
1332 self::$db_duration_write += (microtime(true) - $stamp);
1336 * Checks if some worker job waits to be executed
1339 * @throws \Exception
1341 public static function IPCJobsExists()
1343 $stamp = (float)microtime(true);
1344 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1345 self::$db_duration += (microtime(true) - $stamp);
1347 // When we don't have a row, no job is running
1348 if (!DBA::isResult($row)) {
1352 return (bool)$row['jobs'];