3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core;
25 use Friendica\Database\DBA;
27 use Friendica\Model\Process;
28 use Friendica\Util\DateTimeFormat;
31 * Contains the class for the worker background job processing
35 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
36 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
37 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
38 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
40 const FAST_COMMANDS = ['APDelivery', 'Delivery', 'CreateShadowEntry'];
42 const LOCK_PROCESS = 'worker_process';
43 const LOCK_WORKER = 'worker';
45 private static $up_start;
46 private static $db_duration = 0;
47 private static $db_duration_count = 0;
48 private static $db_duration_write = 0;
49 private static $db_duration_stat = 0;
50 private static $lock_duration = 0;
51 private static $last_update;
52 private static $state;
55 * Processes the tasks that are in the workerqueue table
57 * @param boolean $run_cron Should the cron processes be executed?
59 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
61 public static function processQueue($run_cron = true)
63 // Ensure that all "strtotime" operations do run timezone independent
64 date_default_timezone_set('UTC');
66 self::$up_start = microtime(true);
68 // At first check the maximum load. We shouldn't continue with a high load
69 if (DI::process()->isMaxLoadReached()) {
70 Logger::info('Pre check: maximum load reached, quitting.');
74 // We now start the process. This is done after the load check since this could increase the load.
77 // Kill stale processes every 5 minutes
78 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
79 if (time() > ($last_cleanup + 300)) {
80 DI::config()->set('system', 'worker_last_cleaned', time());
81 self::killStaleWorkers();
84 // Check if the system is ready
85 if (!self::isReady()) {
89 // Now we start additional cron processes if we should do so
95 self::$state = self::STATE_STARTUP;
97 // We fetch the next queue entry that is about to be executed
98 while ($r = self::workerProcess()) {
100 foreach ($r as $entry) {
101 // Assure that the priority is an integer value
102 $entry['priority'] = (int)$entry['priority'];
104 // The work will be done
105 if (!self::execute($entry)) {
106 Logger::info('Process execution failed, quitting.');
110 // Trying to fetch new processes - but only once when successful
111 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
112 self::findWorkerProcesses();
113 DI::lock()->release(self::LOCK_PROCESS);
114 self::$state = self::STATE_REFETCH;
117 self::$state = self::STATE_SHORT_LOOP;
121 // To avoid the quitting of multiple workers only one worker at a time will execute the check
122 if (!self::getWaitingJobForPID()) {
123 self::$state = self::STATE_LONG_LOOP;
125 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
126 // Count active workers and compare them with a maximum value that depends on the load
127 if (self::tooMuchWorkers()) {
128 Logger::info('Active worker limit reached, quitting.');
129 DI::lock()->release(self::LOCK_WORKER);
134 if (DI::process()->isMinMemoryReached()) {
135 Logger::info('Memory limit reached, quitting.');
136 DI::lock()->release(self::LOCK_WORKER);
139 DI::lock()->release(self::LOCK_WORKER);
143 // Quit the worker once every cron interval
144 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
145 Logger::info('Process lifetime reached, respawning.');
151 // Cleaning up. Possibly not needed, but it doesn't harm anything.
152 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
153 self::IPCSetJobState(false);
155 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
159 * Checks if the system is ready.
161 * Several system parameters like memory, connections and processes are checked.
165 public static function isReady()
167 // Count active workers and compare them with a maximum value that depends on the load
168 if (self::tooMuchWorkers()) {
169 Logger::info('Active worker limit reached, quitting.');
173 // Do we have too few memory?
174 if (DI::process()->isMinMemoryReached()) {
175 Logger::info('Memory limit reached, quitting.');
179 // Possibly there are too much database connections
180 if (self::maxConnectionsReached()) {
181 Logger::info('Maximum connections reached, quitting.');
185 // Possibly there are too much database processes that block the system
186 if (DI::process()->isMaxProcessesReached()) {
187 Logger::info('Maximum processes reached, quitting.');
195 * Check if non executed tasks do exist in the worker queue
197 * @return boolean Returns "true" if tasks are existing
200 public static function entriesExists()
202 $stamp = (float)microtime(true);
203 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
204 self::$db_duration += (microtime(true) - $stamp);
209 * Returns the number of deferred entries in the worker queue
211 * @return integer Number of deferred entries in the worker queue
214 private static function deferredEntries()
216 $stamp = (float)microtime(true);
217 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
218 self::$db_duration += (microtime(true) - $stamp);
219 self::$db_duration_count += (microtime(true) - $stamp);
224 * Returns the number of non executed entries in the worker queue
226 * @return integer Number of non executed entries in the worker queue
229 private static function totalEntries()
231 $stamp = (float)microtime(true);
232 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
233 self::$db_duration += (microtime(true) - $stamp);
234 self::$db_duration_count += (microtime(true) - $stamp);
239 * Returns the highest priority in the worker queue that isn't executed
241 * @return integer Number of active worker processes
244 private static function highestPriority()
246 $stamp = (float)microtime(true);
247 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
248 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
249 self::$db_duration += (microtime(true) - $stamp);
250 if (DBA::isResult($workerqueue)) {
251 return $workerqueue["priority"];
258 * Returns if a process with the given priority is running
260 * @param integer $priority The priority that should be checked
262 * @return integer Is there a process running with that priority?
265 private static function processWithPriorityActive($priority)
267 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
268 return DBA::exists('workerqueue', $condition);
272 * Execute a worker entry
274 * @param array $queue Workerqueue entry
276 * @return boolean "true" if further processing should be stopped
277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279 public static function execute($queue)
283 // Quit when in maintenance
284 if (DI::config()->get('system', 'maintenance', false, true)) {
285 Logger::info("Maintenance mode - quit process", ['pid' => $mypid]);
289 // Constantly check the number of parallel database processes
290 if (DI::process()->isMaxProcessesReached()) {
291 Logger::info("Max processes reached for process", ['pid' => $mypid]);
295 // Constantly check the number of available database connections to let the frontend be accessible at any time
296 if (self::maxConnectionsReached()) {
297 Logger::info("Max connection reached for process", ['pid' => $mypid]);
301 $argv = json_decode($queue["parameter"], true);
303 Logger::error('Parameter is empty', ['queue' => $queue]);
307 // Check for existance and validity of the include file
310 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
311 // We constantly update the "executed" date every minute to avoid being killed too soon
312 if (!isset(self::$last_update)) {
313 self::$last_update = strtotime($queue["executed"]);
316 $age = (time() - self::$last_update) / 60;
317 self::$last_update = time();
320 $stamp = (float)microtime(true);
321 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
322 self::$db_duration += (microtime(true) - $stamp);
323 self::$db_duration_write += (microtime(true) - $stamp);
328 self::execFunction($queue, $include, $argv, true);
330 $stamp = (float)microtime(true);
331 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
332 if (DBA::update('workerqueue', ['done' => true], $condition)) {
333 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
335 self::$db_duration = (microtime(true) - $stamp);
336 self::$db_duration_write += (microtime(true) - $stamp);
341 // The script could be provided as full path or only with the function name
342 if ($include == basename($include)) {
343 $include = "include/".$include.".php";
346 if (!validate_include($include)) {
347 Logger::log("Include file ".$argv[0]." is not valid!");
348 $stamp = (float)microtime(true);
349 DBA::delete('workerqueue', ['id' => $queue["id"]]);
350 self::$db_duration = (microtime(true) - $stamp);
351 self::$db_duration_write += (microtime(true) - $stamp);
355 require_once $include;
357 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
359 if (function_exists($funcname)) {
360 // We constantly update the "executed" date every minute to avoid being killed too soon
361 if (!isset(self::$last_update)) {
362 self::$last_update = strtotime($queue["executed"]);
365 $age = (time() - self::$last_update) / 60;
366 self::$last_update = time();
369 $stamp = (float)microtime(true);
370 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
371 self::$db_duration += (microtime(true) - $stamp);
372 self::$db_duration_write += (microtime(true) - $stamp);
375 self::execFunction($queue, $funcname, $argv, false);
377 $stamp = (float)microtime(true);
378 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
379 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
381 self::$db_duration = (microtime(true) - $stamp);
382 self::$db_duration_write += (microtime(true) - $stamp);
384 Logger::log("Function ".$funcname." does not exist");
385 $stamp = (float)microtime(true);
386 DBA::delete('workerqueue', ['id' => $queue["id"]]);
387 self::$db_duration = (microtime(true) - $stamp);
388 self::$db_duration_write += (microtime(true) - $stamp);
395 * Execute a function from the queue
397 * @param array $queue Workerqueue entry
398 * @param string $funcname name of the function
399 * @param array $argv Array of values to be passed to the function
400 * @param boolean $method_call boolean
402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
404 private static function execFunction($queue, $funcname, $argv, $method_call)
408 Logger::enableWorker($funcname);
410 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
412 $stamp = (float)microtime(true);
414 // We use the callstack here to analyze the performance of executed worker entries.
415 // For this reason the variables have to be initialized.
416 DI::profiler()->reset();
420 $up_duration = microtime(true) - self::$up_start;
422 // Reset global data to avoid interferences
425 // Set the workerLogger as new default logger
427 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
429 $funcname($argv, count($argv));
432 Logger::disableWorker();
436 $duration = (microtime(true) - $stamp);
438 /* With these values we can analyze how effective the worker is.
439 * The database and rest time should be low since this is the unproductive time.
440 * The execution time is the productive time.
441 * By changing parameters like the maximum number of workers we can check the effectivness.
443 $dbtotal = round(self::$db_duration, 2);
444 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
445 $dbcount = round(self::$db_duration_count, 2);
446 $dbstat = round(self::$db_duration_stat, 2);
447 $dbwrite = round(self::$db_duration_write, 2);
448 $dblock = round(self::$lock_duration, 2);
449 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
450 $exec = round($duration, 2);
452 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
454 self::$up_start = microtime(true);
455 self::$db_duration = 0;
456 self::$db_duration_count = 0;
457 self::$db_duration_stat = 0;
458 self::$db_duration_write = 0;
459 self::$lock_duration = 0;
461 if ($duration > 3600) {
462 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
463 } elseif ($duration > 600) {
464 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
465 } elseif ($duration > 300) {
466 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
467 } elseif ($duration > 120) {
468 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
471 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
473 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
475 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
478 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
484 * Checks if the number of database connections has reached a critical limit.
486 * @return bool Are more than 3/4 of the maximum connections used?
487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489 private static function maxConnectionsReached()
491 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
492 $max = DI::config()->get("system", "max_connections");
494 // Fetch the percentage level where the worker will get active
495 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
498 // the maximum number of possible user connections can be a system variable
499 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
500 if (DBA::isResult($r)) {
503 // Or it can be granted. This overrides the system variable
504 $stamp = (float)microtime(true);
505 $r = DBA::p('SHOW GRANTS');
506 self::$db_duration += (microtime(true) - $stamp);
507 while ($grants = DBA::fetch($r)) {
508 $grant = array_pop($grants);
509 if (stristr($grant, "GRANT USAGE ON")) {
510 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
518 // If $max is set we will use the processlist to determine the current number of connections
519 // The processlist only shows entries of the current user
521 $stamp = (float)microtime(true);
522 $r = DBA::p('SHOW PROCESSLIST');
523 self::$db_duration += (microtime(true) - $stamp);
524 $used = DBA::numRows($r);
527 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
529 $level = ($used / $max) * 100;
531 if ($level >= $maxlevel) {
532 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
537 // We will now check for the system values.
538 // This limit could be reached although the user limits are fine.
539 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
540 if (!DBA::isResult($r)) {
543 $max = intval($r["Value"]);
547 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
548 if (!DBA::isResult($r)) {
551 $used = intval($r["Value"]);
555 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
557 $level = $used / $max * 100;
559 if ($level < $maxlevel) {
562 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
567 * fix the queue entry if the worker process died
572 private static function killStaleWorkers()
574 $stamp = (float)microtime(true);
575 $entries = DBA::select(
577 ['id', 'pid', 'executed', 'priority', 'parameter'],
578 ['NOT `done` AND `pid` != 0'],
579 ['order' => ['priority', 'created']]
581 self::$db_duration += (microtime(true) - $stamp);
583 while ($entry = DBA::fetch($entries)) {
584 if (!posix_kill($entry["pid"], 0)) {
585 $stamp = (float)microtime(true);
588 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
589 ['id' => $entry["id"]]
591 self::$db_duration += (microtime(true) - $stamp);
592 self::$db_duration_write += (microtime(true) - $stamp);
594 // Kill long running processes
595 // Check if the priority is in a valid range
596 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
597 $entry["priority"] = PRIORITY_MEDIUM;
600 // Define the maximum durations
601 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
602 $max_duration = $max_duration_defaults[$entry["priority"]];
604 $argv = json_decode($entry["parameter"], true);
609 $argv[0] = basename($argv[0]);
611 // How long is the process already running?
612 $duration = (time() - strtotime($entry["executed"])) / 60;
613 if ($duration > $max_duration) {
614 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
615 posix_kill($entry["pid"], SIGTERM);
617 // We killed the stale process.
618 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
619 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
620 $new_priority = $entry["priority"];
621 if ($entry["priority"] == PRIORITY_HIGH) {
622 $new_priority = PRIORITY_MEDIUM;
623 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
624 $new_priority = PRIORITY_LOW;
625 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
626 $new_priority = PRIORITY_NEGLIGIBLE;
628 $stamp = (float)microtime(true);
631 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
632 ['id' => $entry["id"]]
634 self::$db_duration += (microtime(true) - $stamp);
635 self::$db_duration_write += (microtime(true) - $stamp);
637 Logger::info('Process runtime is okay', ['pid' => $entry["pid"], 'duration' => $duration, 'max' => $max_duration, 'command' => substr(json_encode($argv), 0, 50)]);
641 DBA::close($entries);
645 * Checks if the number of active workers exceeds the given limits
647 * @return bool Are there too much workers running?
648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
650 private static function tooMuchWorkers()
652 $queues = DI::config()->get("system", "worker_queues", 10);
654 $maxqueues = $queues;
656 $active = self::activeWorkers();
658 // Decrease the number of workers at higher load
659 $load = System::currentLoad();
661 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
663 /* Default exponent 3 causes queues to rapidly decrease as load increases.
664 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
665 * For some environments, this rapid decrease is not needed.
666 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
668 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
669 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
670 $queues = intval(ceil($slope * $maxqueues));
674 if (DI::config()->get('system', 'worker_jpm')) {
675 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
676 $jobs_per_minute = [];
677 foreach ($intervals as $interval) {
678 if ($interval == 0) {
681 $interval = (int)$interval;
684 $stamp = (float)microtime(true);
685 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
686 self::$db_duration += (microtime(true) - $stamp);
687 self::$db_duration_stat += (microtime(true) - $stamp);
688 if ($job = DBA::fetch($jobs)) {
689 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
693 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
696 // Create a list of queue entries grouped by their priority
697 $listitem = [0 => ''];
699 $idle_workers = $active;
701 $deferred = self::deferredEntries();
703 if (DI::config()->get('system', 'worker_debug')) {
704 $waiting_processes = 0;
705 // Now adding all processes with workerqueue entries
706 $stamp = (float)microtime(true);
707 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
708 self::$db_duration += (microtime(true) - $stamp);
709 self::$db_duration_stat += (microtime(true) - $stamp);
710 while ($entry = DBA::fetch($jobs)) {
711 $stamp = (float)microtime(true);
712 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
713 self::$db_duration += (microtime(true) - $stamp);
714 self::$db_duration_stat += (microtime(true) - $stamp);
715 if ($process = DBA::fetch($processes)) {
716 $idle_workers -= $process["running"];
717 $waiting_processes += $entry["entries"];
718 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
720 DBA::close($processes);
724 $waiting_processes = self::totalEntries();
725 $stamp = (float)microtime(true);
726 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
727 self::$db_duration += (microtime(true) - $stamp);
728 self::$db_duration_stat += (microtime(true) - $stamp);
730 while ($entry = DBA::fetch($jobs)) {
731 $idle_workers -= $entry["running"];
732 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
737 $waiting_processes -= $deferred;
739 $listitem[0] = "0:" . max(0, $idle_workers);
741 $processlist .= ' ('.implode(', ', $listitem).')';
743 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
744 $top_priority = self::highestPriority();
745 $high_running = self::processWithPriorityActive($top_priority);
747 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
748 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
749 $queues = $active + 1;
753 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
755 // Are there fewer workers running as possible? Then fork a new one.
756 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
757 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
758 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
759 self::IPCSetJobState(true);
766 // if there are too much worker, we don't spawn a new one.
767 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
768 self::IPCSetJobState(false);
771 return $active > $queues;
775 * Returns the number of active worker processes
777 * @return integer Number of active worker processes
780 private static function activeWorkers()
782 $stamp = (float)microtime(true);
783 $count = DBA::count('process', ['command' => 'Worker.php']);
784 self::$db_duration += (microtime(true) - $stamp);
789 * Returns waiting jobs for the current process id
791 * @return array waiting workerqueue jobs
794 private static function getWaitingJobForPID()
796 $stamp = (float)microtime(true);
797 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
798 self::$db_duration += (microtime(true) - $stamp);
799 if (DBA::isResult($r)) {
800 return DBA::toArray($r);
808 * Returns the next jobs that should be executed
810 * @return array array with next jobs
813 private static function nextProcess()
815 $priority = self::nextPriority();
816 if (empty($priority)) {
817 Logger::info('No tasks found');
821 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
824 $stamp = (float)microtime(true);
825 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
826 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
827 self::$db_duration += (microtime(true) - $stamp);
828 while ($task = DBA::fetch($tasks)) {
829 $ids[] = $task['id'];
830 // Only continue that loop while we are storing commands that can be processed quickly
831 $command = json_decode($task['parameter'])[0];
832 if (!in_array($command, self::FAST_COMMANDS)) {
838 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
843 * Returns the priority of the next workerqueue job
845 * @return string priority
848 private static function nextPriority()
851 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
852 foreach ($priorities as $priority) {
853 $stamp = (float)microtime(true);
854 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
855 $waiting[$priority] = true;
857 self::$db_duration += (microtime(true) - $stamp);
860 if (!empty($waiting[PRIORITY_CRITICAL])) {
861 return PRIORITY_CRITICAL;
866 $stamp = (float)microtime(true);
867 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
868 self::$db_duration += (microtime(true) - $stamp);
869 while ($process = DBA::fetch($processes)) {
870 $running[$process['priority']] = $process['running'];
871 $running_total += $process['running'];
873 DBA::close($processes);
875 foreach ($priorities as $priority) {
876 if (!empty($waiting[$priority]) && empty($running[$priority])) {
877 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
882 $active = max(self::activeWorkers(), $running_total);
883 $priorities = max(count($waiting), count($running));
887 for ($i = 1; $i <= $priorities; ++$i) {
888 $total += pow($i, $exponent);
892 for ($i = 1; $i <= $priorities; ++$i) {
893 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
897 foreach ($running as $priority => $workers) {
898 if ($workers < $limit[$i++]) {
899 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
904 if (!empty($waiting)) {
905 $priority = array_keys($waiting)[0];
906 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
914 * Find and claim the next worker process for us
916 * @return boolean Have we found something?
917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
919 private static function findWorkerProcesses()
923 $ids = self::nextProcess();
925 // If there is no result we check without priority limit
927 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
929 $stamp = (float)microtime(true);
930 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
931 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
932 self::$db_duration += (microtime(true) - $stamp);
934 while ($task = DBA::fetch($tasks)) {
935 $ids[] = $task['id'];
936 // Only continue that loop while we are storing commands that can be processed quickly
937 $command = json_decode($task['parameter'])[0];
938 if (!in_array($command, self::FAST_COMMANDS)) {
946 $stamp = (float)microtime(true);
947 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
948 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
949 self::$db_duration += (microtime(true) - $stamp);
950 self::$db_duration_write += (microtime(true) - $stamp);
957 * Returns the next worker process
959 * @return array worker processes
960 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
962 public static function workerProcess()
964 // There can already be jobs for us in the queue.
965 $waiting = self::getWaitingJobForPID();
966 if (!empty($waiting)) {
970 $stamp = (float)microtime(true);
971 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
974 self::$lock_duration += (microtime(true) - $stamp);
976 $found = self::findWorkerProcesses();
978 DI::lock()->release(self::LOCK_PROCESS);
981 $stamp = (float)microtime(true);
982 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
983 self::$db_duration += (microtime(true) - $stamp);
984 return DBA::toArray($r);
990 * Removes a workerqueue entry from the current process
995 public static function unclaimProcess()
999 $stamp = (float)microtime(true);
1000 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1001 self::$db_duration += (microtime(true) - $stamp);
1002 self::$db_duration_write += (microtime(true) - $stamp);
1006 * Call the front end worker
1009 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1011 public static function callWorker()
1013 if (!DI::config()->get("system", "frontend_worker")) {
1017 $url = DI::baseUrl() . '/worker';
1018 DI::httpRequest()->fetch($url, false, 1);
1022 * Call the front end worker if there aren't any active
1025 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 public static function executeIfIdle()
1029 if (!DI::config()->get("system", "frontend_worker")) {
1033 // Do we have "proc_open"? Then we can fork the worker
1034 if (function_exists("proc_open")) {
1035 // When was the last time that we called the worker?
1036 // Less than one minute? Then we quit
1037 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1041 DI::config()->set("system", "worker_started", time());
1043 // Do we have enough running workers? Then we quit here.
1044 if (self::tooMuchWorkers()) {
1045 // Cleaning dead processes
1046 self::killStaleWorkers();
1047 Process::deleteInactive();
1054 Logger::info('Call worker');
1055 self::spawnWorker();
1059 // We cannot execute background processes.
1060 // We now run the processes from the frontend.
1061 // This won't work with long running processes.
1064 self::clearProcesses();
1066 $workers = self::activeWorkers();
1068 if ($workers == 0) {
1074 * Removes long running worker processes
1077 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1079 public static function clearProcesses()
1081 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1083 /// @todo We should clean up the corresponding workerqueue entries as well
1084 $stamp = (float)microtime(true);
1085 $condition = ["`created` < ? AND `command` = 'worker.php'",
1086 DateTimeFormat::utc("now - ".$timeout." minutes")];
1087 DBA::delete('process', $condition);
1088 self::$db_duration = (microtime(true) - $stamp);
1089 self::$db_duration_write += (microtime(true) - $stamp);
1093 * Runs the cron processes
1096 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1098 private static function runCron()
1100 Logger::info('Add cron entries');
1102 // Check for spooled items
1103 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1105 // Run the cron job that calls all other jobs
1106 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1108 // Cleaning dead processes
1109 self::killStaleWorkers();
1113 * Spawns a new worker
1115 * @param bool $do_cron
1117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1119 public static function spawnWorker($do_cron = false)
1121 $command = 'bin/worker.php';
1123 $args = ['no_cron' => !$do_cron];
1126 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), $a->getBasePath());
1127 $process->run($command, $args);
1129 // after spawning we have to remove the flag.
1130 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1131 self::IPCSetJobState(false);
1136 * Adds tasks to the worker queue
1138 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1140 * next args are passed as $cmd command line
1141 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1142 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1144 * @return boolean "false" if worker queue entry already existed or there had been an error
1145 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1146 * @note $cmd and string args are surrounded with ""
1152 public static function add($cmd)
1154 $args = func_get_args();
1156 if (!count($args)) {
1160 $arr = ['args' => $args, 'run_cmd' => true];
1162 Hook::callAll("proc_run", $arr);
1163 if (!$arr['run_cmd'] || !count($args)) {
1167 $priority = PRIORITY_MEDIUM;
1168 // Don't fork from frontend tasks by default
1169 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1170 $created = DateTimeFormat::utcNow();
1171 $force_priority = false;
1173 $run_parameter = array_shift($args);
1175 if (is_int($run_parameter)) {
1176 $priority = $run_parameter;
1177 } elseif (is_array($run_parameter)) {
1178 if (isset($run_parameter['priority'])) {
1179 $priority = $run_parameter['priority'];
1181 if (isset($run_parameter['created'])) {
1182 $created = $run_parameter['created'];
1184 if (isset($run_parameter['dont_fork'])) {
1185 $dont_fork = $run_parameter['dont_fork'];
1187 if (isset($run_parameter['force_priority'])) {
1188 $force_priority = $run_parameter['force_priority'];
1192 $parameters = json_encode($args);
1193 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1196 // Quit if there was a database error - a precaution for the update process to 3.5.3
1197 if (DBA::errorNo() != 0) {
1202 $added = DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1206 } elseif ($force_priority) {
1207 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1210 // Should we quit and wait for the worker to be called as a cronjob?
1215 // If there is a lock then we don't have to check for too much worker
1216 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1220 // If there are already enough workers running, don't fork another one
1221 $quit = self::tooMuchWorkers();
1222 DI::lock()->release(self::LOCK_WORKER);
1228 // We tell the daemon that a new job entry exists
1229 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1230 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1234 // Now call the worker to execute the jobs that we just added to the queue
1235 self::spawnWorker();
1241 * Returns the next retrial level for worker jobs.
1242 * This function will skip levels when jobs are older.
1244 * @param array $queue Worker queue entry
1245 * @param integer $max_level maximum retrial level
1246 * @return integer the next retrial level value
1248 private static function getNextRetrial($queue, $max_level)
1250 $created = strtotime($queue['created']);
1251 $retrial_time = time() - $created;
1253 $new_retrial = $queue['retrial'] + 1;
1255 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1256 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1258 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1259 $new_retrial = $retrial;
1262 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1263 return $new_retrial;
1267 * Defers the current worker entry
1269 * @return boolean had the entry been deferred?
1271 public static function defer()
1273 if (empty(DI::app()->queue)) {
1277 $queue = DI::app()->queue;
1279 $retrial = $queue['retrial'];
1281 $priority = $queue['priority'];
1283 $max_level = DI::config()->get('system', 'worker_defer_limit');
1285 $new_retrial = self::getNextRetrial($queue, $max_level);
1287 if ($new_retrial > $max_level) {
1288 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]);
1292 // Calculate the delay until the next trial
1293 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1294 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1296 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1297 $priority = PRIORITY_MEDIUM;
1298 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1299 $priority = PRIORITY_LOW;
1300 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1301 $priority = PRIORITY_NEGLIGIBLE;
1304 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1306 $stamp = (float)microtime(true);
1307 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1308 DBA::update('workerqueue', $fields, ['id' => $id]);
1309 self::$db_duration += (microtime(true) - $stamp);
1310 self::$db_duration_write += (microtime(true) - $stamp);
1316 * Log active processes into the "process" table
1318 public static function startProcess()
1320 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1322 $command = basename($trace[0]['file']);
1324 Process::deleteInactive();
1326 Process::insert($command);
1330 * Remove the active process from the "process" table
1333 * @throws \Exception
1335 public static function endProcess()
1337 return Process::deleteByPid();
1341 * Set the flag if some job is waiting
1343 * @param boolean $jobs Is there a waiting job?
1344 * @throws \Exception
1346 public static function IPCSetJobState($jobs)
1348 $stamp = (float)microtime(true);
1349 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1350 self::$db_duration += (microtime(true) - $stamp);
1351 self::$db_duration_write += (microtime(true) - $stamp);
1355 * Checks if some worker job waits to be executed
1358 * @throws \Exception
1360 public static function IPCJobsExists()
1362 $stamp = (float)microtime(true);
1363 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1364 self::$db_duration += (microtime(true) - $stamp);
1366 // When we don't have a row, no job is running
1367 if (!DBA::isResult($row)) {
1371 return (bool)$row['jobs'];