3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core;
25 use Friendica\Database\DBA;
27 use Friendica\Model\Process;
28 use Friendica\Util\DateTimeFormat;
29 use Friendica\Util\Network;
32 * Contains the class for the worker background job processing
36 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
37 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
38 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
39 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
41 const FAST_COMMANDS = ['APDelivery', 'Delivery', 'CreateShadowEntry'];
44 private static $up_start;
45 private static $db_duration = 0;
46 private static $db_duration_count = 0;
47 private static $db_duration_write = 0;
48 private static $db_duration_stat = 0;
49 private static $lock_duration = 0;
50 private static $last_update;
51 private static $state;
54 * Processes the tasks that are in the workerqueue table
56 * @param boolean $run_cron Should the cron processes be executed?
58 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
60 public static function processQueue($run_cron = true)
62 // Ensure that all "strtotime" operations do run timezone independent
63 date_default_timezone_set('UTC');
65 self::$up_start = microtime(true);
67 // At first check the maximum load. We shouldn't continue with a high load
68 if (DI::process()->isMaxLoadReached()) {
69 Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
73 // We now start the process. This is done after the load check since this could increase the load.
76 // Kill stale processes every 5 minutes
77 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
78 if (time() > ($last_cleanup + 300)) {
79 DI::config()->set('system', 'worker_last_cleaned', time());
80 self::killStaleWorkers();
83 // Count active workers and compare them with a maximum value that depends on the load
84 if (self::tooMuchWorkers()) {
85 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
89 // Do we have too few memory?
90 if (DI::process()->isMinMemoryReached()) {
91 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
95 // Possibly there are too much database connections
96 if (self::maxConnectionsReached()) {
97 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
101 // Possibly there are too much database processes that block the system
102 if (DI::process()->isMaxProcessesReached()) {
103 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
107 // Now we start additional cron processes if we should do so
113 self::$state = self::STATE_STARTUP;
115 // We fetch the next queue entry that is about to be executed
116 while ($r = self::workerProcess()) {
118 foreach ($r as $entry) {
119 // Assure that the priority is an integer value
120 $entry['priority'] = (int)$entry['priority'];
122 // The work will be done
123 if (!self::execute($entry)) {
124 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
128 // Trying to fetch new processes - but only once when successful
129 if (!$refetched && DI::lock()->acquire('worker_process', 0)) {
130 self::findWorkerProcesses();
131 DI::lock()->release('worker_process');
132 self::$state = self::STATE_REFETCH;
135 self::$state = self::STATE_SHORT_LOOP;
139 // To avoid the quitting of multiple workers only one worker at a time will execute the check
140 if (!self::getWaitingJobForPID()) {
141 self::$state = self::STATE_LONG_LOOP;
143 if (DI::lock()->acquire('worker', 0)) {
144 // Count active workers and compare them with a maximum value that depends on the load
145 if (self::tooMuchWorkers()) {
146 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
147 DI::lock()->release('worker');
152 if (DI::process()->isMinMemoryReached()) {
153 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
154 DI::lock()->release('worker');
157 DI::lock()->release('worker');
161 // Quit the worker once every cron interval
162 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
163 Logger::info('Process lifetime reached, respawning.');
169 // Cleaning up. Possibly not needed, but it doesn't harm anything.
170 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
171 self::IPCSetJobState(false);
173 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
177 * Check if non executed tasks do exist in the worker queue
179 * @return boolean Returns "true" if tasks are existing
182 private static function entriesExists()
184 $stamp = (float)microtime(true);
185 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
186 self::$db_duration += (microtime(true) - $stamp);
191 * Returns the number of deferred entries in the worker queue
193 * @return integer Number of deferred entries in the worker queue
196 private static function deferredEntries()
198 $stamp = (float)microtime(true);
199 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
200 self::$db_duration += (microtime(true) - $stamp);
201 self::$db_duration_count += (microtime(true) - $stamp);
206 * Returns the number of non executed entries in the worker queue
208 * @return integer Number of non executed entries in the worker queue
211 private static function totalEntries()
213 $stamp = (float)microtime(true);
214 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
215 self::$db_duration += (microtime(true) - $stamp);
216 self::$db_duration_count += (microtime(true) - $stamp);
221 * Returns the highest priority in the worker queue that isn't executed
223 * @return integer Number of active worker processes
226 private static function highestPriority()
228 $stamp = (float)microtime(true);
229 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
230 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
231 self::$db_duration += (microtime(true) - $stamp);
232 if (DBA::isResult($workerqueue)) {
233 return $workerqueue["priority"];
240 * Returns if a process with the given priority is running
242 * @param integer $priority The priority that should be checked
244 * @return integer Is there a process running with that priority?
247 private static function processWithPriorityActive($priority)
249 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
250 return DBA::exists('workerqueue', $condition);
254 * Execute a worker entry
256 * @param array $queue Workerqueue entry
258 * @return boolean "true" if further processing should be stopped
259 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
261 public static function execute($queue)
265 // Quit when in maintenance
266 if (DI::config()->get('system', 'maintenance', false, true)) {
267 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
271 // Constantly check the number of parallel database processes
272 if (DI::process()->isMaxProcessesReached()) {
273 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
277 // Constantly check the number of available database connections to let the frontend be accessible at any time
278 if (self::maxConnectionsReached()) {
279 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
283 $argv = json_decode($queue["parameter"], true);
285 // Check for existance and validity of the include file
288 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
289 // We constantly update the "executed" date every minute to avoid being killed too soon
290 if (!isset(self::$last_update)) {
291 self::$last_update = strtotime($queue["executed"]);
294 $age = (time() - self::$last_update) / 60;
295 self::$last_update = time();
298 $stamp = (float)microtime(true);
299 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
300 self::$db_duration += (microtime(true) - $stamp);
301 self::$db_duration_write += (microtime(true) - $stamp);
306 self::execFunction($queue, $include, $argv, true);
308 $stamp = (float)microtime(true);
309 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
310 if (DBA::update('workerqueue', ['done' => true], $condition)) {
311 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
313 self::$db_duration = (microtime(true) - $stamp);
314 self::$db_duration_write += (microtime(true) - $stamp);
319 // The script could be provided as full path or only with the function name
320 if ($include == basename($include)) {
321 $include = "include/".$include.".php";
324 if (!validate_include($include)) {
325 Logger::log("Include file ".$argv[0]." is not valid!");
326 $stamp = (float)microtime(true);
327 DBA::delete('workerqueue', ['id' => $queue["id"]]);
328 self::$db_duration = (microtime(true) - $stamp);
329 self::$db_duration_write += (microtime(true) - $stamp);
333 require_once $include;
335 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
337 if (function_exists($funcname)) {
338 // We constantly update the "executed" date every minute to avoid being killed too soon
339 if (!isset(self::$last_update)) {
340 self::$last_update = strtotime($queue["executed"]);
343 $age = (time() - self::$last_update) / 60;
344 self::$last_update = time();
347 $stamp = (float)microtime(true);
348 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
349 self::$db_duration += (microtime(true) - $stamp);
350 self::$db_duration_write += (microtime(true) - $stamp);
353 self::execFunction($queue, $funcname, $argv, false);
355 $stamp = (float)microtime(true);
356 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
357 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
359 self::$db_duration = (microtime(true) - $stamp);
360 self::$db_duration_write += (microtime(true) - $stamp);
362 Logger::log("Function ".$funcname." does not exist");
363 $stamp = (float)microtime(true);
364 DBA::delete('workerqueue', ['id' => $queue["id"]]);
365 self::$db_duration = (microtime(true) - $stamp);
366 self::$db_duration_write += (microtime(true) - $stamp);
373 * Execute a function from the queue
375 * @param array $queue Workerqueue entry
376 * @param string $funcname name of the function
377 * @param array $argv Array of values to be passed to the function
378 * @param boolean $method_call boolean
380 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
382 private static function execFunction($queue, $funcname, $argv, $method_call)
386 $argc = count($argv);
388 Logger::enableWorker($funcname);
390 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
392 $stamp = (float)microtime(true);
394 // We use the callstack here to analyze the performance of executed worker entries.
395 // For this reason the variables have to be initialized.
396 DI::profiler()->reset();
400 $up_duration = microtime(true) - self::$up_start;
402 // Reset global data to avoid interferences
405 // Set the workerLogger as new default logger
407 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
409 $funcname($argv, $argc);
412 Logger::disableWorker();
416 $duration = (microtime(true) - $stamp);
418 /* With these values we can analyze how effective the worker is.
419 * The database and rest time should be low since this is the unproductive time.
420 * The execution time is the productive time.
421 * By changing parameters like the maximum number of workers we can check the effectivness.
423 $dbtotal = round(self::$db_duration, 2);
424 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
425 $dbcount = round(self::$db_duration_count, 2);
426 $dbstat = round(self::$db_duration_stat, 2);
427 $dbwrite = round(self::$db_duration_write, 2);
428 $dblock = round(self::$lock_duration, 2);
429 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
430 $exec = round($duration, 2);
432 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
434 self::$up_start = microtime(true);
435 self::$db_duration = 0;
436 self::$db_duration_count = 0;
437 self::$db_duration_stat = 0;
438 self::$db_duration_write = 0;
439 self::$lock_duration = 0;
441 if ($duration > 3600) {
442 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
443 } elseif ($duration > 600) {
444 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
445 } elseif ($duration > 300) {
446 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
447 } elseif ($duration > 120) {
448 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
451 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
453 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
455 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
458 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
464 * Checks if the number of database connections has reached a critical limit.
466 * @return bool Are more than 3/4 of the maximum connections used?
467 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
469 private static function maxConnectionsReached()
471 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
472 $max = DI::config()->get("system", "max_connections");
474 // Fetch the percentage level where the worker will get active
475 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
478 // the maximum number of possible user connections can be a system variable
479 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
480 if (DBA::isResult($r)) {
483 // Or it can be granted. This overrides the system variable
484 $stamp = (float)microtime(true);
485 $r = DBA::p('SHOW GRANTS');
486 self::$db_duration += (microtime(true) - $stamp);
487 while ($grants = DBA::fetch($r)) {
488 $grant = array_pop($grants);
489 if (stristr($grant, "GRANT USAGE ON")) {
490 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
498 // If $max is set we will use the processlist to determine the current number of connections
499 // The processlist only shows entries of the current user
501 $stamp = (float)microtime(true);
502 $r = DBA::p('SHOW PROCESSLIST');
503 self::$db_duration += (microtime(true) - $stamp);
504 $used = DBA::numRows($r);
507 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
509 $level = ($used / $max) * 100;
511 if ($level >= $maxlevel) {
512 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
517 // We will now check for the system values.
518 // This limit could be reached although the user limits are fine.
519 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
520 if (!DBA::isResult($r)) {
523 $max = intval($r["Value"]);
527 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
528 if (!DBA::isResult($r)) {
531 $used = intval($r["Value"]);
535 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
537 $level = $used / $max * 100;
539 if ($level < $maxlevel) {
542 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
547 * fix the queue entry if the worker process died
552 private static function killStaleWorkers()
554 $stamp = (float)microtime(true);
555 $entries = DBA::select(
557 ['id', 'pid', 'executed', 'priority', 'parameter'],
558 ['NOT `done` AND `pid` != 0'],
559 ['order' => ['priority', 'created']]
561 self::$db_duration += (microtime(true) - $stamp);
563 while ($entry = DBA::fetch($entries)) {
564 if (!posix_kill($entry["pid"], 0)) {
565 $stamp = (float)microtime(true);
568 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
569 ['id' => $entry["id"]]
571 self::$db_duration += (microtime(true) - $stamp);
572 self::$db_duration_write += (microtime(true) - $stamp);
574 // Kill long running processes
575 // Check if the priority is in a valid range
576 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
577 $entry["priority"] = PRIORITY_MEDIUM;
580 // Define the maximum durations
581 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
582 $max_duration = $max_duration_defaults[$entry["priority"]];
584 $argv = json_decode($entry["parameter"], true);
585 $argv[0] = basename($argv[0]);
587 // How long is the process already running?
588 $duration = (time() - strtotime($entry["executed"])) / 60;
589 if ($duration > $max_duration) {
590 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
591 posix_kill($entry["pid"], SIGTERM);
593 // We killed the stale process.
594 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
595 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
596 $new_priority = $entry["priority"];
597 if ($entry["priority"] == PRIORITY_HIGH) {
598 $new_priority = PRIORITY_MEDIUM;
599 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
600 $new_priority = PRIORITY_LOW;
601 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
602 $new_priority = PRIORITY_NEGLIGIBLE;
604 $stamp = (float)microtime(true);
607 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
608 ['id' => $entry["id"]]
610 self::$db_duration += (microtime(true) - $stamp);
611 self::$db_duration_write += (microtime(true) - $stamp);
613 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", Logger::DEBUG);
617 DBA::close($entries);
621 * Checks if the number of active workers exceeds the given limits
623 * @return bool Are there too much workers running?
624 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
626 private static function tooMuchWorkers()
628 $queues = DI::config()->get("system", "worker_queues", 10);
630 $maxqueues = $queues;
632 $active = self::activeWorkers();
634 // Decrease the number of workers at higher load
635 $load = System::currentLoad();
637 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
639 /* Default exponent 3 causes queues to rapidly decrease as load increases.
640 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
641 * For some environments, this rapid decrease is not needed.
642 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
644 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
645 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
646 $queues = intval(ceil($slope * $maxqueues));
650 if (DI::config()->get('system', 'worker_jpm')) {
651 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
652 $jobs_per_minute = [];
653 foreach ($intervals as $interval) {
654 if ($interval == 0) {
657 $interval = (int)$interval;
660 $stamp = (float)microtime(true);
661 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
662 self::$db_duration += (microtime(true) - $stamp);
663 self::$db_duration_stat += (microtime(true) - $stamp);
664 if ($job = DBA::fetch($jobs)) {
665 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
669 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
672 // Create a list of queue entries grouped by their priority
673 $listitem = [0 => ''];
675 $idle_workers = $active;
677 $deferred = self::deferredEntries();
679 if (DI::config()->get('system', 'worker_debug')) {
680 $waiting_processes = 0;
681 // Now adding all processes with workerqueue entries
682 $stamp = (float)microtime(true);
683 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
684 self::$db_duration += (microtime(true) - $stamp);
685 self::$db_duration_stat += (microtime(true) - $stamp);
686 while ($entry = DBA::fetch($jobs)) {
687 $stamp = (float)microtime(true);
688 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
689 self::$db_duration += (microtime(true) - $stamp);
690 self::$db_duration_stat += (microtime(true) - $stamp);
691 if ($process = DBA::fetch($processes)) {
692 $idle_workers -= $process["running"];
693 $waiting_processes += $entry["entries"];
694 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
696 DBA::close($processes);
700 $waiting_processes = self::totalEntries();
701 $stamp = (float)microtime(true);
702 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
703 self::$db_duration += (microtime(true) - $stamp);
704 self::$db_duration_stat += (microtime(true) - $stamp);
706 while ($entry = DBA::fetch($jobs)) {
707 $idle_workers -= $entry["running"];
708 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
713 $waiting_processes -= $deferred;
715 $listitem[0] = "0:" . max(0, $idle_workers);
717 $processlist .= ' ('.implode(', ', $listitem).')';
719 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
720 $top_priority = self::highestPriority();
721 $high_running = self::processWithPriorityActive($top_priority);
723 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
724 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
725 $queues = $active + 1;
729 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
731 // Are there fewer workers running as possible? Then fork a new one.
732 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
733 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
734 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
735 self::IPCSetJobState(true);
742 // if there are too much worker, we don't spawn a new one.
743 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
744 self::IPCSetJobState(false);
747 return $active > $queues;
751 * Returns the number of active worker processes
753 * @return integer Number of active worker processes
756 private static function activeWorkers()
758 $stamp = (float)microtime(true);
759 $count = DBA::count('process', ['command' => 'Worker.php']);
760 self::$db_duration += (microtime(true) - $stamp);
765 * Returns waiting jobs for the current process id
767 * @return array waiting workerqueue jobs
770 private static function getWaitingJobForPID()
772 $stamp = (float)microtime(true);
773 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
774 self::$db_duration += (microtime(true) - $stamp);
775 if (DBA::isResult($r)) {
776 return DBA::toArray($r);
784 * Returns the next jobs that should be executed
786 * @return array array with next jobs
789 private static function nextProcess()
791 $priority = self::nextPriority();
792 if (empty($priority)) {
793 Logger::info('No tasks found');
797 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
800 $stamp = (float)microtime(true);
801 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
802 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
803 self::$db_duration += (microtime(true) - $stamp);
804 while ($task = DBA::fetch($tasks)) {
805 $ids[] = $task['id'];
806 // Only continue that loop while we are storing commands that can be processed quickly
807 $command = json_decode($task['parameter'])[0];
808 if (!in_array($command, self::FAST_COMMANDS)) {
814 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
819 * Returns the priority of the next workerqueue job
821 * @return string priority
824 private static function nextPriority()
827 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
828 foreach ($priorities as $priority) {
829 $stamp = (float)microtime(true);
830 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
831 $waiting[$priority] = true;
833 self::$db_duration += (microtime(true) - $stamp);
836 if (!empty($waiting[PRIORITY_CRITICAL])) {
837 return PRIORITY_CRITICAL;
842 $stamp = (float)microtime(true);
843 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
844 self::$db_duration += (microtime(true) - $stamp);
845 while ($process = DBA::fetch($processes)) {
846 $running[$process['priority']] = $process['running'];
847 $running_total += $process['running'];
849 DBA::close($processes);
851 foreach ($priorities as $priority) {
852 if (!empty($waiting[$priority]) && empty($running[$priority])) {
853 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
858 $active = max(self::activeWorkers(), $running_total);
859 $priorities = max(count($waiting), count($running));
863 for ($i = 1; $i <= $priorities; ++$i) {
864 $total += pow($i, $exponent);
868 for ($i = 1; $i <= $priorities; ++$i) {
869 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
873 foreach ($running as $priority => $workers) {
874 if ($workers < $limit[$i++]) {
875 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
880 if (!empty($waiting)) {
881 $priority = array_keys($waiting)[0];
882 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
890 * Find and claim the next worker process for us
892 * @return boolean Have we found something?
893 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
895 private static function findWorkerProcesses()
899 $ids = self::nextProcess();
901 // If there is no result we check without priority limit
903 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
905 $stamp = (float)microtime(true);
906 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
907 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
908 self::$db_duration += (microtime(true) - $stamp);
910 while ($task = DBA::fetch($tasks)) {
911 $ids[] = $task['id'];
912 // Only continue that loop while we are storing commands that can be processed quickly
913 $command = json_decode($task['parameter'])[0];
914 if (!in_array($command, self::FAST_COMMANDS)) {
922 $stamp = (float)microtime(true);
923 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
924 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
925 self::$db_duration += (microtime(true) - $stamp);
926 self::$db_duration_write += (microtime(true) - $stamp);
933 * Returns the next worker process
935 * @return string SQL statement
936 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
938 public static function workerProcess()
940 // There can already be jobs for us in the queue.
941 $waiting = self::getWaitingJobForPID();
942 if (!empty($waiting)) {
946 $stamp = (float)microtime(true);
947 if (!DI::lock()->acquire('worker_process')) {
950 self::$lock_duration += (microtime(true) - $stamp);
952 $found = self::findWorkerProcesses();
954 DI::lock()->release('worker_process');
957 $stamp = (float)microtime(true);
958 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
959 self::$db_duration += (microtime(true) - $stamp);
960 return DBA::toArray($r);
966 * Removes a workerqueue entry from the current process
971 public static function unclaimProcess()
975 $stamp = (float)microtime(true);
976 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
977 self::$db_duration += (microtime(true) - $stamp);
978 self::$db_duration_write += (microtime(true) - $stamp);
982 * Call the front end worker
985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
987 public static function callWorker()
989 if (!DI::config()->get("system", "frontend_worker")) {
993 $url = DI::baseUrl() . '/worker';
994 Network::fetchUrl($url, false, 1);
998 * Call the front end worker if there aren't any active
1001 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1003 public static function executeIfIdle()
1005 if (!DI::config()->get("system", "frontend_worker")) {
1009 // Do we have "proc_open"? Then we can fork the worker
1010 if (function_exists("proc_open")) {
1011 // When was the last time that we called the worker?
1012 // Less than one minute? Then we quit
1013 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1017 DI::config()->set("system", "worker_started", time());
1019 // Do we have enough running workers? Then we quit here.
1020 if (self::tooMuchWorkers()) {
1021 // Cleaning dead processes
1022 self::killStaleWorkers();
1023 Process::deleteInactive();
1030 Logger::log('Call worker', Logger::DEBUG);
1031 self::spawnWorker();
1035 // We cannot execute background processes.
1036 // We now run the processes from the frontend.
1037 // This won't work with long running processes.
1040 self::clearProcesses();
1042 $workers = self::activeWorkers();
1044 if ($workers == 0) {
1050 * Removes long running worker processes
1053 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1055 public static function clearProcesses()
1057 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1059 /// @todo We should clean up the corresponding workerqueue entries as well
1060 $stamp = (float)microtime(true);
1061 $condition = ["`created` < ? AND `command` = 'worker.php'",
1062 DateTimeFormat::utc("now - ".$timeout." minutes")];
1063 DBA::delete('process', $condition);
1064 self::$db_duration = (microtime(true) - $stamp);
1065 self::$db_duration_write += (microtime(true) - $stamp);
1069 * Runs the cron processes
1072 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1074 private static function runCron()
1076 Logger::log('Add cron entries', Logger::DEBUG);
1078 // Check for spooled items
1079 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1081 // Run the cron job that calls all other jobs
1082 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1084 // Cleaning dead processes
1085 self::killStaleWorkers();
1089 * Spawns a new worker
1091 * @param bool $do_cron
1093 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1095 public static function spawnWorker($do_cron = false)
1097 $command = 'bin/worker.php';
1099 $args = ['no_cron' => !$do_cron];
1102 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), $a->getBasePath());
1103 $process->run($command, $args);
1105 // after spawning we have to remove the flag.
1106 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1107 self::IPCSetJobState(false);
1112 * Adds tasks to the worker queue
1114 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1116 * next args are passed as $cmd command line
1117 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1118 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1120 * @return boolean "false" if worker queue entry already existed or there had been an error
1121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1122 * @note $cmd and string args are surrounded with ""
1128 public static function add($cmd)
1130 $args = func_get_args();
1132 if (!count($args)) {
1136 $arr = ['args' => $args, 'run_cmd' => true];
1138 Hook::callAll("proc_run", $arr);
1139 if (!$arr['run_cmd'] || !count($args)) {
1143 $priority = PRIORITY_MEDIUM;
1144 // Don't fork from frontend tasks by default
1145 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1146 $created = DateTimeFormat::utcNow();
1147 $force_priority = false;
1149 $run_parameter = array_shift($args);
1151 if (is_int($run_parameter)) {
1152 $priority = $run_parameter;
1153 } elseif (is_array($run_parameter)) {
1154 if (isset($run_parameter['priority'])) {
1155 $priority = $run_parameter['priority'];
1157 if (isset($run_parameter['created'])) {
1158 $created = $run_parameter['created'];
1160 if (isset($run_parameter['dont_fork'])) {
1161 $dont_fork = $run_parameter['dont_fork'];
1163 if (isset($run_parameter['force_priority'])) {
1164 $force_priority = $run_parameter['force_priority'];
1168 $parameters = json_encode($args);
1169 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1172 // Quit if there was a database error - a precaution for the update process to 3.5.3
1173 if (DBA::errorNo() != 0) {
1178 $added = DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1182 } elseif ($force_priority) {
1183 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1186 // Should we quit and wait for the worker to be called as a cronjob?
1191 // If there is a lock then we don't have to check for too much worker
1192 if (!DI::lock()->acquire('worker', 0)) {
1196 // If there are already enough workers running, don't fork another one
1197 $quit = self::tooMuchWorkers();
1198 DI::lock()->release('worker');
1204 // We tell the daemon that a new job entry exists
1205 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1206 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1210 // Now call the worker to execute the jobs that we just added to the queue
1211 self::spawnWorker();
1217 * Returns the next retrial level for worker jobs.
1218 * This function will skip levels when jobs are older.
1220 * @param array $queue Worker queue entry
1221 * @param integer $max_level maximum retrial level
1222 * @return integer the next retrial level value
1224 private static function getNextRetrial($queue, $max_level)
1226 $created = strtotime($queue['created']);
1227 $retrial_time = time() - $created;
1229 $new_retrial = $queue['retrial'] + 1;
1231 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1232 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1234 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1235 $new_retrial = $retrial;
1238 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1239 return $new_retrial;
1243 * Defers the current worker entry
1245 * @return boolean had the entry been deferred?
1247 public static function defer()
1249 if (empty(DI::app()->queue)) {
1253 $queue = DI::app()->queue;
1255 $retrial = $queue['retrial'];
1257 $priority = $queue['priority'];
1259 $max_level = DI::config()->get('system', 'worker_defer_limit');
1261 $new_retrial = self::getNextRetrial($queue, $max_level);
1263 if ($new_retrial > $max_level) {
1264 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]);
1268 // Calculate the delay until the next trial
1269 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1270 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1272 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1273 $priority = PRIORITY_MEDIUM;
1274 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1275 $priority = PRIORITY_LOW;
1276 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1277 $priority = PRIORITY_NEGLIGIBLE;
1280 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1282 $stamp = (float)microtime(true);
1283 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1284 DBA::update('workerqueue', $fields, ['id' => $id]);
1285 self::$db_duration += (microtime(true) - $stamp);
1286 self::$db_duration_write += (microtime(true) - $stamp);
1292 * Log active processes into the "process" table
1294 public static function startProcess()
1296 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1298 $command = basename($trace[0]['file']);
1300 Process::deleteInactive();
1302 Process::insert($command);
1306 * Remove the active process from the "process" table
1309 * @throws \Exception
1311 public static function endProcess()
1313 return Process::deleteByPid();
1317 * Set the flag if some job is waiting
1319 * @param boolean $jobs Is there a waiting job?
1320 * @throws \Exception
1322 public static function IPCSetJobState($jobs)
1324 $stamp = (float)microtime(true);
1325 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1326 self::$db_duration += (microtime(true) - $stamp);
1327 self::$db_duration_write += (microtime(true) - $stamp);
1331 * Checks if some worker job waits to be executed
1334 * @throws \Exception
1336 public static function IPCJobsExists()
1338 $stamp = (float)microtime(true);
1339 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1340 self::$db_duration += (microtime(true) - $stamp);
1342 // When we don't have a row, no job is running
1343 if (!DBA::isResult($row)) {
1347 return (bool)$row['jobs'];