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;
24 use Friendica\App\Mode;
26 use Friendica\Database\DBA;
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'];
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::notice('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.
75 DI::process()->start();
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
94 $last_check = $starttime = time();
95 self::$state = self::STATE_STARTUP;
97 // We fetch the next queue entry that is about to be executed
98 while ($r = self::workerProcess()) {
99 // Don't refetch when a worker fetches tasks for multiple workers
100 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
101 foreach ($r as $entry) {
102 // Assure that the priority is an integer value
103 $entry['priority'] = (int)$entry['priority'];
105 // The work will be done
106 if (!self::execute($entry)) {
107 Logger::notice('Process execution failed, quitting.');
111 // Trying to fetch new processes - but only once when successful
112 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
113 self::findWorkerProcesses();
114 DI::lock()->release(self::LOCK_PROCESS);
115 self::$state = self::STATE_REFETCH;
118 self::$state = self::STATE_SHORT_LOOP;
122 // To avoid the quitting of multiple workers only one worker at a time will execute the check
123 if ((time() > $last_check + 5) && !self::getWaitingJobForPID()) {
124 self::$state = self::STATE_LONG_LOOP;
126 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
127 // Count active workers and compare them with a maximum value that depends on the load
128 if (self::tooMuchWorkers()) {
129 Logger::notice('Active worker limit reached, quitting.');
130 DI::lock()->release(self::LOCK_WORKER);
135 if (DI::process()->isMinMemoryReached()) {
136 Logger::warning('Memory limit reached, quitting.');
137 DI::lock()->release(self::LOCK_WORKER);
140 DI::lock()->release(self::LOCK_WORKER);
142 $last_check = time();
145 // Quit the worker once every cron interval
146 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
147 Logger::info('Process lifetime reached, respawning.');
148 self::unclaimProcess();
154 // Cleaning up. Possibly not needed, but it doesn't harm anything.
155 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
156 self::IPCSetJobState(false);
158 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
162 * Checks if the system is ready.
164 * Several system parameters like memory, connections and processes are checked.
168 public static function isReady()
170 // Count active workers and compare them with a maximum value that depends on the load
171 if (self::tooMuchWorkers()) {
172 Logger::notice('Active worker limit reached, quitting.');
176 // Do we have too few memory?
177 if (DI::process()->isMinMemoryReached()) {
178 Logger::warning('Memory limit reached, quitting.');
182 // Possibly there are too much database connections
183 if (self::maxConnectionsReached()) {
184 Logger::warning('Maximum connections reached, quitting.');
188 // Possibly there are too much database processes that block the system
189 if (DI::process()->isMaxProcessesReached()) {
190 Logger::warning('Maximum processes reached, quitting.');
198 * Check if non executed tasks do exist in the worker queue
200 * @return boolean Returns "true" if tasks are existing
203 public static function entriesExists()
205 $stamp = (float)microtime(true);
206 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
207 self::$db_duration += (microtime(true) - $stamp);
212 * Returns the number of deferred entries in the worker queue
214 * @return integer Number of deferred entries in the worker queue
217 private static function deferredEntries()
219 $stamp = (float)microtime(true);
220 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
221 self::$db_duration += (microtime(true) - $stamp);
222 self::$db_duration_count += (microtime(true) - $stamp);
227 * Returns the number of non executed entries in the worker queue
229 * @return integer Number of non executed entries in the worker queue
232 private static function totalEntries()
234 $stamp = (float)microtime(true);
235 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
236 self::$db_duration += (microtime(true) - $stamp);
237 self::$db_duration_count += (microtime(true) - $stamp);
242 * Returns the highest priority in the worker queue that isn't executed
244 * @return integer Number of active worker processes
247 private static function highestPriority()
249 $stamp = (float)microtime(true);
250 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
251 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
252 self::$db_duration += (microtime(true) - $stamp);
253 if (DBA::isResult($workerqueue)) {
254 return $workerqueue["priority"];
261 * Returns if a process with the given priority is running
263 * @param integer $priority The priority that should be checked
265 * @return integer Is there a process running with that priority?
268 private static function processWithPriorityActive($priority)
270 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
271 return DBA::exists('workerqueue', $condition);
275 * Execute a worker entry
277 * @param array $queue Workerqueue entry
279 * @return boolean "true" if further processing should be stopped
280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
282 public static function execute($queue)
286 // Quit when in maintenance
287 if (DI::config()->get('system', 'maintenance', false, true)) {
288 Logger::notice("Maintenance mode - quit process", ['pid' => $mypid]);
292 // Constantly check the number of parallel database processes
293 if (DI::process()->isMaxProcessesReached()) {
294 Logger::warning("Max processes reached for process", ['pid' => $mypid]);
298 // Constantly check the number of available database connections to let the frontend be accessible at any time
299 if (self::maxConnectionsReached()) {
300 Logger::warning("Max connection reached for process", ['pid' => $mypid]);
304 $argv = json_decode($queue['parameter'], true);
305 if (!empty($queue['command'])) {
306 array_unshift($argv, $queue['command']);
310 Logger::warning('Parameter is empty', ['queue' => $queue]);
314 // Check for existance and validity of the include file
317 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
318 // We constantly update the "executed" date every minute to avoid being killed too soon
319 if (!isset(self::$last_update)) {
320 self::$last_update = strtotime($queue["executed"]);
323 $age = (time() - self::$last_update) / 60;
324 self::$last_update = time();
327 $stamp = (float)microtime(true);
328 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
329 self::$db_duration += (microtime(true) - $stamp);
330 self::$db_duration_write += (microtime(true) - $stamp);
335 self::execFunction($queue, $include, $argv, true);
337 $stamp = (float)microtime(true);
338 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
339 if (DBA::update('workerqueue', ['done' => true], $condition)) {
340 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
342 self::$db_duration = (microtime(true) - $stamp);
343 self::$db_duration_write += (microtime(true) - $stamp);
348 // The script could be provided as full path or only with the function name
349 if ($include == basename($include)) {
350 $include = "include/".$include.".php";
353 if (!validate_include($include)) {
354 Logger::warning("Include file is not valid", ['file' => $argv[0]]);
355 $stamp = (float)microtime(true);
356 DBA::delete('workerqueue', ['id' => $queue["id"]]);
357 self::$db_duration = (microtime(true) - $stamp);
358 self::$db_duration_write += (microtime(true) - $stamp);
362 require_once $include;
364 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
366 if (function_exists($funcname)) {
367 // We constantly update the "executed" date every minute to avoid being killed too soon
368 if (!isset(self::$last_update)) {
369 self::$last_update = strtotime($queue["executed"]);
372 $age = (time() - self::$last_update) / 60;
373 self::$last_update = time();
376 $stamp = (float)microtime(true);
377 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
378 self::$db_duration += (microtime(true) - $stamp);
379 self::$db_duration_write += (microtime(true) - $stamp);
382 self::execFunction($queue, $funcname, $argv, false);
384 $stamp = (float)microtime(true);
385 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
386 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
388 self::$db_duration = (microtime(true) - $stamp);
389 self::$db_duration_write += (microtime(true) - $stamp);
391 Logger::warning("Function does not exist", ['function' => $funcname]);
392 $stamp = (float)microtime(true);
393 DBA::delete('workerqueue', ['id' => $queue["id"]]);
394 self::$db_duration = (microtime(true) - $stamp);
395 self::$db_duration_write += (microtime(true) - $stamp);
402 * Execute a function from the queue
404 * @param array $queue Workerqueue entry
405 * @param string $funcname name of the function
406 * @param array $argv Array of values to be passed to the function
407 * @param boolean $method_call boolean
409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
411 private static function execFunction($queue, $funcname, $argv, $method_call)
415 Logger::enableWorker($funcname);
417 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
419 $stamp = (float)microtime(true);
421 // We use the callstack here to analyze the performance of executed worker entries.
422 // For this reason the variables have to be initialized.
423 DI::profiler()->reset();
425 if (!in_array($queue['priority'], PRIORITIES)) {
426 Logger::warning('Invalid priority', ['queue' => $queue, 'callstack' => System::callstack(20)]);
427 $queue['priority'] = PRIORITY_MEDIUM;
432 $up_duration = microtime(true) - self::$up_start;
434 // Reset global data to avoid interferences
437 // Set the workerLogger as new default logger
439 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
441 $funcname($argv, count($argv));
444 Logger::disableWorker();
448 $duration = (microtime(true) - $stamp);
450 /* With these values we can analyze how effective the worker is.
451 * The database and rest time should be low since this is the unproductive time.
452 * The execution time is the productive time.
453 * By changing parameters like the maximum number of workers we can check the effectivness.
455 $dbtotal = round(self::$db_duration, 2);
456 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
457 $dbcount = round(self::$db_duration_count, 2);
458 $dbstat = round(self::$db_duration_stat, 2);
459 $dbwrite = round(self::$db_duration_write, 2);
460 $dblock = round(self::$lock_duration, 2);
461 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
462 $exec = round($duration, 2);
464 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
466 self::$up_start = microtime(true);
467 self::$db_duration = 0;
468 self::$db_duration_count = 0;
469 self::$db_duration_stat = 0;
470 self::$db_duration_write = 0;
471 self::$lock_duration = 0;
473 if ($duration > 3600) {
474 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
475 } elseif ($duration > 600) {
476 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
477 } elseif ($duration > 300) {
478 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
479 } elseif ($duration > 120) {
480 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
483 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
485 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
487 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
490 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
496 * Checks if the number of database connections has reached a critical limit.
498 * @return bool Are more than 3/4 of the maximum connections used?
499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 private static function maxConnectionsReached()
503 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
504 $max = DI::config()->get("system", "max_connections");
506 // Fetch the percentage level where the worker will get active
507 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
510 // the maximum number of possible user connections can be a system variable
511 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
512 if (DBA::isResult($r)) {
515 // Or it can be granted. This overrides the system variable
516 $stamp = (float)microtime(true);
517 $r = DBA::p('SHOW GRANTS');
518 self::$db_duration += (microtime(true) - $stamp);
519 while ($grants = DBA::fetch($r)) {
520 $grant = array_pop($grants);
521 if (stristr($grant, "GRANT USAGE ON")) {
522 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
530 // If $max is set we will use the processlist to determine the current number of connections
531 // The processlist only shows entries of the current user
533 $stamp = (float)microtime(true);
534 $r = DBA::p('SHOW PROCESSLIST');
535 self::$db_duration += (microtime(true) - $stamp);
536 $used = DBA::numRows($r);
539 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
541 $level = ($used / $max) * 100;
543 if ($level >= $maxlevel) {
544 Logger::warning("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
549 // We will now check for the system values.
550 // This limit could be reached although the user limits are fine.
551 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
552 if (!DBA::isResult($r)) {
555 $max = intval($r["Value"]);
559 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
560 if (!DBA::isResult($r)) {
563 $used = intval($r["Value"]);
567 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
569 $level = $used / $max * 100;
571 if ($level < $maxlevel) {
574 Logger::warning("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
579 * fix the queue entry if the worker process died
584 private static function killStaleWorkers()
586 $stamp = (float)microtime(true);
587 $entries = DBA::select(
589 ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
590 ['NOT `done` AND `pid` != 0'],
591 ['order' => ['priority', 'retrial', 'created']]
593 self::$db_duration += (microtime(true) - $stamp);
595 while ($entry = DBA::fetch($entries)) {
596 if (!posix_kill($entry["pid"], 0)) {
597 $stamp = (float)microtime(true);
600 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
601 ['id' => $entry["id"]]
603 self::$db_duration += (microtime(true) - $stamp);
604 self::$db_duration_write += (microtime(true) - $stamp);
606 // Kill long running processes
607 // Check if the priority is in a valid range
608 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
609 $entry["priority"] = PRIORITY_MEDIUM;
612 // Define the maximum durations
613 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
614 $max_duration = $max_duration_defaults[$entry["priority"]];
616 $argv = json_decode($entry['parameter'], true);
617 if (!empty($entry['command'])) {
618 $command = $entry['command'];
619 } elseif (!empty($argv)) {
620 $command = array_shift($argv);
625 $command = basename($command);
627 // How long is the process already running?
628 $duration = (time() - strtotime($entry["executed"])) / 60;
629 if ($duration > $max_duration) {
630 Logger::notice('Worker process took too much time - killed', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
631 posix_kill($entry["pid"], SIGTERM);
633 // We killed the stale process.
634 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
635 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
636 $new_priority = $entry["priority"];
637 if ($entry["priority"] == PRIORITY_HIGH) {
638 $new_priority = PRIORITY_MEDIUM;
639 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
640 $new_priority = PRIORITY_LOW;
641 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
642 $new_priority = PRIORITY_NEGLIGIBLE;
644 $stamp = (float)microtime(true);
647 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
648 ['id' => $entry["id"]]
650 self::$db_duration += (microtime(true) - $stamp);
651 self::$db_duration_write += (microtime(true) - $stamp);
653 Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
657 DBA::close($entries);
661 * Checks if the number of active workers exceeds the given limits
663 * @return bool Are there too much workers running?
664 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
666 private static function tooMuchWorkers()
668 $queues = DI::config()->get("system", "worker_queues", 10);
670 $maxqueues = $queues;
672 $active = self::activeWorkers();
674 // Decrease the number of workers at higher load
675 $load = System::currentLoad();
677 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
679 /* Default exponent 3 causes queues to rapidly decrease as load increases.
680 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
681 * For some environments, this rapid decrease is not needed.
682 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
684 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
685 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
686 $queues = intval(ceil($slope * $maxqueues));
690 if (DI::config()->get('system', 'worker_jpm')) {
691 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
692 $jobs_per_minute = [];
693 foreach ($intervals as $interval) {
694 if ($interval == 0) {
697 $interval = (int)$interval;
700 $stamp = (float)microtime(true);
701 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
702 self::$db_duration += (microtime(true) - $stamp);
703 self::$db_duration_stat += (microtime(true) - $stamp);
704 if ($job = DBA::fetch($jobs)) {
705 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
709 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
712 // Create a list of queue entries grouped by their priority
713 $listitem = [0 => ''];
715 $idle_workers = $active;
717 $deferred = self::deferredEntries();
719 if (DI::config()->get('system', 'worker_debug')) {
720 $waiting_processes = 0;
721 // Now adding all processes with workerqueue entries
722 $stamp = (float)microtime(true);
723 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
724 self::$db_duration += (microtime(true) - $stamp);
725 self::$db_duration_stat += (microtime(true) - $stamp);
726 while ($entry = DBA::fetch($jobs)) {
727 $stamp = (float)microtime(true);
728 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
729 self::$db_duration += (microtime(true) - $stamp);
730 self::$db_duration_stat += (microtime(true) - $stamp);
731 if ($process = DBA::fetch($processes)) {
732 $idle_workers -= $process["running"];
733 $waiting_processes += $entry["entries"];
734 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
736 DBA::close($processes);
740 $waiting_processes = self::totalEntries();
741 $stamp = (float)microtime(true);
742 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
743 self::$db_duration += (microtime(true) - $stamp);
744 self::$db_duration_stat += (microtime(true) - $stamp);
746 while ($entry = DBA::fetch($jobs)) {
747 $idle_workers -= $entry["running"];
748 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
753 $waiting_processes -= $deferred;
755 $listitem[0] = "0:" . max(0, $idle_workers);
757 $processlist .= ' ('.implode(', ', $listitem).')';
759 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
760 $top_priority = self::highestPriority();
761 $high_running = self::processWithPriorityActive($top_priority);
763 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
764 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
765 $queues = $active + 1;
769 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
771 // Are there fewer workers running as possible? Then fork a new one.
772 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
773 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
774 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
775 self::IPCSetJobState(true);
782 // if there are too much worker, we don't spawn a new one.
783 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
784 self::IPCSetJobState(false);
787 return $active > $queues;
791 * Returns the number of active worker processes
793 * @return integer Number of active worker processes
796 private static function activeWorkers()
798 $stamp = (float)microtime(true);
799 $count = DBA::count('process', ['command' => 'Worker.php']);
800 self::$db_duration += (microtime(true) - $stamp);
801 self::$db_duration_count += (microtime(true) - $stamp);
806 * Returns the number of active worker processes
808 * @return array List of worker process ids
811 private static function getWorkerPIDList()
814 $stamp = (float)microtime(true);
816 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
817 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
818 GROUP BY `process`.`pid`");
819 while ($queue = DBA::fetch($queues)) {
820 $ids[$queue['pid']] = $queue['entries'];
824 self::$db_duration += (microtime(true) - $stamp);
825 self::$db_duration_count += (microtime(true) - $stamp);
830 * Returns waiting jobs for the current process id
832 * @return array waiting workerqueue jobs
835 private static function getWaitingJobForPID()
837 $stamp = (float)microtime(true);
838 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
839 self::$db_duration += (microtime(true) - $stamp);
840 if (DBA::isResult($r)) {
841 return DBA::toArray($r);
849 * Returns the next jobs that should be executed
851 * @return array array with next jobs
854 private static function nextProcess(int $limit)
856 $priority = self::nextPriority();
857 if (empty($priority)) {
858 Logger::info('No tasks found');
863 $stamp = (float)microtime(true);
864 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
865 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
866 self::$db_duration += (microtime(true) - $stamp);
867 while ($task = DBA::fetch($tasks)) {
868 $ids[] = $task['id'];
869 // Only continue that loop while we are storing commands that can be processed quickly
870 if (!empty($task['command'])) {
871 $command = $task['command'];
873 $command = json_decode($task['parameter'])[0];
876 if (!in_array($command, self::FAST_COMMANDS)) {
882 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
887 * Returns the priority of the next workerqueue job
889 * @return string priority
892 private static function nextPriority()
895 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
896 foreach ($priorities as $priority) {
897 $stamp = (float)microtime(true);
898 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
899 $waiting[$priority] = true;
901 self::$db_duration += (microtime(true) - $stamp);
904 if (!empty($waiting[PRIORITY_CRITICAL])) {
905 return PRIORITY_CRITICAL;
910 $stamp = (float)microtime(true);
911 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
912 self::$db_duration += (microtime(true) - $stamp);
913 while ($process = DBA::fetch($processes)) {
914 $running[$process['priority']] = $process['running'];
915 $running_total += $process['running'];
917 DBA::close($processes);
919 foreach ($priorities as $priority) {
920 if (!empty($waiting[$priority]) && empty($running[$priority])) {
921 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
926 $active = max(self::activeWorkers(), $running_total);
927 $priorities = max(count($waiting), count($running));
931 for ($i = 1; $i <= $priorities; ++$i) {
932 $total += pow($i, $exponent);
936 for ($i = 1; $i <= $priorities; ++$i) {
937 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
941 foreach ($running as $priority => $workers) {
942 if ($workers < $limit[$i++]) {
943 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
948 if (!empty($waiting)) {
949 $priority = array_keys($waiting)[0];
950 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
958 * Find and claim the next worker process for us
960 * @return boolean Have we found something?
961 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
963 private static function findWorkerProcesses()
965 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
967 if (DI::config()->get('system', 'worker_multiple_fetch')) {
969 foreach (self::getWorkerPIDList() as $pid => $count) {
970 if ($count <= $fetch_limit) {
977 $limit = $fetch_limit * count($pids);
979 $pids = [getmypid()];
980 $limit = $fetch_limit;
983 $ids = self::nextProcess($limit);
984 $limit -= count($ids);
986 // If there is not enough results we check without priority limit
988 $stamp = (float)microtime(true);
989 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
990 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
991 self::$db_duration += (microtime(true) - $stamp);
993 while ($task = DBA::fetch($tasks)) {
994 $ids[] = $task['id'];
995 // Only continue that loop while we are storing commands that can be processed quickly
996 if (!empty($task['command'])) {
997 $command = $task['command'];
999 $command = json_decode($task['parameter'])[0];
1001 if (!in_array($command, self::FAST_COMMANDS)) {
1012 // Assign the task ids to the workers
1014 foreach (array_unique($ids) as $id) {
1017 $pid = reset($pids);
1019 $worker[$pid][] = $id;
1022 $stamp = (float)microtime(true);
1023 foreach ($worker as $worker_pid => $worker_ids) {
1024 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1025 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1026 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1028 self::$db_duration += (microtime(true) - $stamp);
1029 self::$db_duration_write += (microtime(true) - $stamp);
1033 * Returns the next worker process
1035 * @return array worker processes
1036 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1038 public static function workerProcess()
1040 // There can already be jobs for us in the queue.
1041 $waiting = self::getWaitingJobForPID();
1042 if (!empty($waiting)) {
1046 $stamp = (float)microtime(true);
1047 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1050 self::$lock_duration += (microtime(true) - $stamp);
1052 self::findWorkerProcesses();
1054 DI::lock()->release(self::LOCK_PROCESS);
1056 return self::getWaitingJobForPID();
1060 * Removes a workerqueue entry from the current process
1063 * @throws \Exception
1065 public static function unclaimProcess()
1067 $mypid = getmypid();
1069 $stamp = (float)microtime(true);
1070 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1071 self::$db_duration += (microtime(true) - $stamp);
1072 self::$db_duration_write += (microtime(true) - $stamp);
1076 * Call the front end worker
1079 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1081 public static function callWorker()
1083 if (!DI::config()->get("system", "frontend_worker")) {
1087 $url = DI::baseUrl() . '/worker';
1088 DI::httpRequest()->fetch($url, 1);
1092 * Call the front end worker if there aren't any active
1095 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1097 public static function executeIfIdle()
1099 self::checkDaemonState();
1101 if (!DI::config()->get("system", "frontend_worker")) {
1105 // Do we have "proc_open"? Then we can fork the worker
1106 if (function_exists("proc_open")) {
1107 // When was the last time that we called the worker?
1108 // Less than one minute? Then we quit
1109 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1113 DI::config()->set("system", "worker_started", time());
1115 // Do we have enough running workers? Then we quit here.
1116 if (self::tooMuchWorkers()) {
1117 // Cleaning dead processes
1118 self::killStaleWorkers();
1119 DI::modelProcess()->deleteInactive();
1126 Logger::info('Call worker');
1127 self::spawnWorker();
1131 // We cannot execute background processes.
1132 // We now run the processes from the frontend.
1133 // This won't work with long running processes.
1136 self::clearProcesses();
1138 $workers = self::activeWorkers();
1140 if ($workers == 0) {
1146 * Removes long running worker processes
1149 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1151 public static function clearProcesses()
1153 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1155 /// @todo We should clean up the corresponding workerqueue entries as well
1156 $stamp = (float)microtime(true);
1157 $condition = ["`created` < ? AND `command` = 'worker.php'",
1158 DateTimeFormat::utc("now - ".$timeout." minutes")];
1159 DBA::delete('process', $condition);
1160 self::$db_duration = (microtime(true) - $stamp);
1161 self::$db_duration_write += (microtime(true) - $stamp);
1165 * Runs the cron processes
1168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1170 private static function runCron()
1172 Logger::info('Add cron entries');
1174 // Check for spooled items
1175 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1177 // Run the cron job that calls all other jobs
1178 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1180 // Cleaning dead processes
1181 self::killStaleWorkers();
1185 * Fork a child process
1187 * @param boolean $do_cron
1190 private static function forkProcess(bool $do_cron)
1192 // Children inherit their parent's database connection.
1193 // To avoid problems we disconnect and connect both parent and child
1195 $pid = pcntl_fork();
1198 Logger::warning('Could not spawn worker');
1201 // The parent process continues here
1203 Logger::info('Spawned new worker', ['cron' => $do_cron, 'pid' => $pid]);
1207 // We now are in the new worker
1209 Logger::info('Worker spawned', ['cron' => $do_cron, 'pid' => getmypid()]);
1211 DI::process()->start();
1213 self::processQueue($do_cron);
1215 self::unclaimProcess();
1217 DI::process()->end();
1218 Logger::info('Worker ended', ['cron' => $do_cron, 'pid' => getmypid()]);
1223 * Spawns a new worker
1225 * @param bool $do_cron
1227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1229 public static function spawnWorker($do_cron = false)
1231 // Worker and daemon are started from the command line.
1232 // This means that this is executed by a PHP interpreter without runtime limitations
1233 if (in_array(DI::mode()->getExecutor(), [Mode::DAEMON, Mode::WORKER])) {
1234 self::forkProcess($do_cron);
1236 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(),
1237 DI::modelProcess(), DI::app()->getBasePath(), getmypid());
1238 $process->run('bin/worker.php', ['no_cron' => !$do_cron]);
1241 // after spawning we have to remove the flag.
1242 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1243 self::IPCSetJobState(false);
1248 * Adds tasks to the worker queue
1250 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1252 * next args are passed as $cmd command line
1253 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1254 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1256 * @return boolean "false" if worker queue entry already existed or there had been an error
1257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1258 * @note $cmd and string args are surrounded with ""
1264 public static function add($cmd)
1266 $args = func_get_args();
1268 if (!count($args)) {
1272 $arr = ['args' => $args, 'run_cmd' => true];
1274 Hook::callAll("proc_run", $arr);
1275 if (!$arr['run_cmd'] || !count($args)) {
1279 $priority = PRIORITY_MEDIUM;
1280 // Don't fork from frontend tasks by default
1281 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1282 $created = DateTimeFormat::utcNow();
1283 $delayed = DBA::NULL_DATETIME;
1284 $force_priority = false;
1286 $run_parameter = array_shift($args);
1288 if (is_int($run_parameter)) {
1289 $priority = $run_parameter;
1290 } elseif (is_array($run_parameter)) {
1291 if (isset($run_parameter['delayed'])) {
1292 $delayed = $run_parameter['delayed'];
1294 if (isset($run_parameter['priority'])) {
1295 $priority = $run_parameter['priority'];
1297 if (isset($run_parameter['created'])) {
1298 $created = $run_parameter['created'];
1300 if (isset($run_parameter['dont_fork'])) {
1301 $dont_fork = $run_parameter['dont_fork'];
1303 if (isset($run_parameter['force_priority'])) {
1304 $force_priority = $run_parameter['force_priority'];
1308 $command = array_shift($args);
1309 $parameters = json_encode($args);
1310 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1313 if (!in_array($priority, PRIORITIES)) {
1314 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1315 $priority = PRIORITY_MEDIUM;
1318 // Quit if there was a database error - a precaution for the update process to 3.5.3
1319 if (DBA::errorNo() != 0) {
1324 $added = DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1325 'priority' => $priority, 'next_try' => $delayed]);
1329 } elseif ($force_priority) {
1330 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1333 // Set the IPC flag to ensure an immediate process execution via daemon
1334 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1335 self::IPCSetJobState(true);
1338 self::checkDaemonState();
1340 // Should we quit and wait for the worker to be called as a cronjob?
1345 // If there is a lock then we don't have to check for too much worker
1346 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1350 // If there are already enough workers running, don't fork another one
1351 $quit = self::tooMuchWorkers();
1352 DI::lock()->release(self::LOCK_WORKER);
1358 // Quit on daemon mode
1359 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1363 // Now call the worker to execute the jobs that we just added to the queue
1364 self::spawnWorker();
1369 public static function countWorkersByCommand(string $command)
1371 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1375 * Returns the next retrial level for worker jobs.
1376 * This function will skip levels when jobs are older.
1378 * @param array $queue Worker queue entry
1379 * @param integer $max_level maximum retrial level
1380 * @return integer the next retrial level value
1382 private static function getNextRetrial($queue, $max_level)
1384 $created = strtotime($queue['created']);
1385 $retrial_time = time() - $created;
1387 $new_retrial = $queue['retrial'] + 1;
1389 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1390 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1392 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1393 $new_retrial = $retrial;
1396 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1397 return $new_retrial;
1401 * Defers the current worker entry
1403 * @return boolean had the entry been deferred?
1405 public static function defer()
1407 if (empty(DI::app()->queue)) {
1411 $queue = DI::app()->queue;
1413 $retrial = $queue['retrial'];
1415 $priority = $queue['priority'];
1417 $max_level = DI::config()->get('system', 'worker_defer_limit');
1419 $new_retrial = self::getNextRetrial($queue, $max_level);
1421 if ($new_retrial > $max_level) {
1422 Logger::notice('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]);
1426 // Calculate the delay until the next trial
1427 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1428 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1430 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1431 $priority = PRIORITY_MEDIUM;
1432 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1433 $priority = PRIORITY_LOW;
1434 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1435 $priority = PRIORITY_NEGLIGIBLE;
1438 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1440 $stamp = (float)microtime(true);
1441 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1442 DBA::update('workerqueue', $fields, ['id' => $id]);
1443 self::$db_duration += (microtime(true) - $stamp);
1444 self::$db_duration_write += (microtime(true) - $stamp);
1450 * Set the flag if some job is waiting
1452 * @param boolean $jobs Is there a waiting job?
1453 * @throws \Exception
1455 public static function IPCSetJobState($jobs)
1457 $stamp = (float)microtime(true);
1458 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1459 self::$db_duration += (microtime(true) - $stamp);
1460 self::$db_duration_write += (microtime(true) - $stamp);
1464 * Checks if some worker job waits to be executed
1467 * @throws \Exception
1469 public static function IPCJobsExists()
1471 $stamp = (float)microtime(true);
1472 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1473 self::$db_duration += (microtime(true) - $stamp);
1475 // When we don't have a row, no job is running
1476 if (!DBA::isResult($row)) {
1480 return (bool)$row['jobs'];
1484 * Test if the daemon is running. If not, it will be started
1488 private static function checkDaemonState()
1490 if (!DI::config()->get('system', 'daemon_watchdog', false)) {
1494 if (!DI::mode()->isNormal()) {
1498 // Check every minute if the daemon is running
1499 if (DI::config()->get('system', 'last_daemon_check', 0) + 60 > time()) {
1503 DI::config()->set('system', 'last_daemon_check', time());
1505 $pidfile = DI::config()->get('system', 'pidfile');
1506 if (empty($pidfile)) {
1507 // No pid file, no daemon
1511 if (!is_readable($pidfile)) {
1512 // No pid file. We assume that the daemon had been intentionally stopped.
1516 $pid = intval(file_get_contents($pidfile));
1517 if (posix_kill($pid, 0)) {
1518 Logger::info('Daemon process is running', ['pid' => $pid]);
1522 Logger::warning('Daemon process is not running', ['pid' => $pid]);
1524 self::spawnDaemon();
1528 * Spawn a new daemon process
1532 private static function spawnDaemon()
1534 Logger::notice('Starting new daemon process');
1535 $command = 'bin/daemon.php';
1537 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), DI::modelProcess(), $a->getBasePath(), getmypid());
1538 $process->run($command, ['start']);
1539 Logger::notice('New daemon process started');
1543 * Check if the system is inside the defined maintenance window
1547 public static function isInMaintenanceWindow(bool $check_last_execution = false)
1549 // Calculate the seconds of the start end end of the maintenance window
1550 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1551 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1553 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1555 if ($check_last_execution) {
1556 // Calculate the window duration
1557 $duration = max($start, $end) - min($start, $end);
1559 // Quit when the last cron execution had been after the previous window
1560 $last_cron = DI::config()->get('system', 'last_cron_daily');
1561 if ($last_cron + $duration > time()) {
1562 Logger::info('The Daily cron had been executed recently', ['last' => date(DateTimeFormat::MYSQL, $last_cron), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1567 $current = time() % 86400;
1569 if ($start < $end) {
1570 // Execute if we are inside the window
1571 $execute = ($current >= $start) && ($current <= $end);
1573 // Don't execute if we are outside the window
1574 $execute = !(($current > $end) && ($current < $start));
1578 Logger::info('We are inside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1580 Logger::info('We are outside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);