3 * @copyright Copyright (C) 2010-2021, the Friendica project
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;
53 private static $daemon_mode = null;
56 * Processes the tasks that are in the workerqueue table
58 * @param boolean $run_cron Should the cron processes be executed?
60 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
62 public static function processQueue($run_cron = true)
64 self::$up_start = microtime(true);
66 // At first check the maximum load. We shouldn't continue with a high load
67 if (DI::process()->isMaxLoadReached()) {
68 Logger::notice('Pre check: maximum load reached, quitting.');
72 // We now start the process. This is done after the load check since this could increase the load.
73 DI::process()->start();
75 // Kill stale processes every 5 minutes
76 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
77 if (time() > ($last_cleanup + 300)) {
78 DI::config()->set('system', 'worker_last_cleaned', time());
79 self::killStaleWorkers();
82 // Check if the system is ready
83 if (!self::isReady()) {
87 // Now we start additional cron processes if we should do so
92 $last_check = $starttime = time();
93 self::$state = self::STATE_STARTUP;
95 // We fetch the next queue entry that is about to be executed
96 while ($r = self::workerProcess()) {
97 if (self::IPCJobsExists(getmypid())) {
98 self::IPCDeleteJobState(getmypid());
101 // Don't refetch when a worker fetches tasks for multiple workers
102 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
103 foreach ($r as $entry) {
104 // Assure that the priority is an integer value
105 $entry['priority'] = (int)$entry['priority'];
107 // The work will be done
108 if (!self::execute($entry)) {
109 Logger::notice('Process execution failed, quitting.');
113 // Trying to fetch new processes - but only once when successful
114 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
115 self::findWorkerProcesses();
116 DI::lock()->release(self::LOCK_PROCESS);
117 self::$state = self::STATE_REFETCH;
120 self::$state = self::STATE_SHORT_LOOP;
124 // To avoid the quitting of multiple workers only one worker at a time will execute the check
125 if ((time() > $last_check + 5) && !self::getWaitingJobForPID()) {
126 self::$state = self::STATE_LONG_LOOP;
128 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
129 // Count active workers and compare them with a maximum value that depends on the load
130 if (self::tooMuchWorkers()) {
131 Logger::notice('Active worker limit reached, quitting.');
132 DI::lock()->release(self::LOCK_WORKER);
137 if (DI::process()->isMinMemoryReached()) {
138 Logger::warning('Memory limit reached, quitting.');
139 DI::lock()->release(self::LOCK_WORKER);
142 DI::lock()->release(self::LOCK_WORKER);
144 $last_check = time();
147 // Quit the worker once every cron interval
148 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
149 Logger::info('Process lifetime reached, respawning.');
150 self::unclaimProcess();
151 if (self::isDaemonMode()) {
152 self::IPCSetJobState(true);
160 // Cleaning up. Possibly not needed, but it doesn't harm anything.
161 if (self::isDaemonMode()) {
162 self::IPCSetJobState(false);
164 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
168 * Checks if the system is ready.
170 * Several system parameters like memory, connections and processes are checked.
174 public static function isReady()
176 // Count active workers and compare them with a maximum value that depends on the load
177 if (self::tooMuchWorkers()) {
178 Logger::notice('Active worker limit reached, quitting.');
182 // Do we have too few memory?
183 if (DI::process()->isMinMemoryReached()) {
184 Logger::warning('Memory limit reached, quitting.');
188 // Possibly there are too much database connections
189 if (self::maxConnectionsReached()) {
190 Logger::warning('Maximum connections reached, quitting.');
194 // Possibly there are too much database processes that block the system
195 if (DI::process()->isMaxProcessesReached()) {
196 Logger::warning('Maximum processes reached, quitting.');
204 * Check if non executed tasks do exist in the worker queue
206 * @return boolean Returns "true" if tasks are existing
209 public static function entriesExists()
211 $stamp = (float)microtime(true);
212 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
213 self::$db_duration += (microtime(true) - $stamp);
218 * Returns the number of deferred entries in the worker queue
220 * @return integer Number of deferred entries in the worker queue
223 private static function deferredEntries()
225 $stamp = (float)microtime(true);
226 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
227 self::$db_duration += (microtime(true) - $stamp);
228 self::$db_duration_count += (microtime(true) - $stamp);
233 * Returns the number of non executed entries in the worker queue
235 * @return integer Number of non executed entries in the worker queue
238 private static function totalEntries()
240 $stamp = (float)microtime(true);
241 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
242 self::$db_duration += (microtime(true) - $stamp);
243 self::$db_duration_count += (microtime(true) - $stamp);
248 * Returns the highest priority in the worker queue that isn't executed
250 * @return integer Number of active worker processes
253 private static function highestPriority()
255 $stamp = (float)microtime(true);
256 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
257 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
258 self::$db_duration += (microtime(true) - $stamp);
259 if (DBA::isResult($workerqueue)) {
260 return $workerqueue["priority"];
267 * Returns if a process with the given priority is running
269 * @param integer $priority The priority that should be checked
271 * @return integer Is there a process running with that priority?
274 private static function processWithPriorityActive($priority)
276 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
277 return DBA::exists('workerqueue', $condition);
281 * Execute a worker entry
283 * @param array $queue Workerqueue entry
285 * @return boolean "true" if further processing should be stopped
286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288 public static function execute($queue)
292 // Quit when in maintenance
293 if (DI::config()->get('system', 'maintenance', false, true)) {
294 Logger::notice("Maintenance mode - quit process", ['pid' => $mypid]);
298 // Constantly check the number of parallel database processes
299 if (DI::process()->isMaxProcessesReached()) {
300 Logger::warning("Max processes reached for process", ['pid' => $mypid]);
304 // Constantly check the number of available database connections to let the frontend be accessible at any time
305 if (self::maxConnectionsReached()) {
306 Logger::warning("Max connection reached for process", ['pid' => $mypid]);
310 $argv = json_decode($queue['parameter'], true);
311 if (!is_array($argv)) {
315 if (!empty($queue['command'])) {
316 array_unshift($argv, $queue['command']);
320 Logger::warning('Parameter is empty', ['queue' => $queue]);
324 // Check for existance and validity of the include file
327 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
328 // We constantly update the "executed" date every minute to avoid being killed too soon
329 if (!isset(self::$last_update)) {
330 self::$last_update = strtotime($queue["executed"]);
333 $age = (time() - self::$last_update) / 60;
334 self::$last_update = time();
337 $stamp = (float)microtime(true);
338 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
339 self::$db_duration += (microtime(true) - $stamp);
340 self::$db_duration_write += (microtime(true) - $stamp);
345 self::execFunction($queue, $include, $argv, true);
347 $stamp = (float)microtime(true);
348 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
349 if (DBA::update('workerqueue', ['done' => true], $condition)) {
350 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
352 self::$db_duration = (microtime(true) - $stamp);
353 self::$db_duration_write += (microtime(true) - $stamp);
358 // The script could be provided as full path or only with the function name
359 if ($include == basename($include)) {
360 $include = "include/".$include.".php";
363 if (!validate_include($include)) {
364 Logger::warning("Include file is not valid", ['file' => $argv[0]]);
365 $stamp = (float)microtime(true);
366 DBA::delete('workerqueue', ['id' => $queue["id"]]);
367 self::$db_duration = (microtime(true) - $stamp);
368 self::$db_duration_write += (microtime(true) - $stamp);
372 require_once $include;
374 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
376 if (function_exists($funcname)) {
377 // We constantly update the "executed" date every minute to avoid being killed too soon
378 if (!isset(self::$last_update)) {
379 self::$last_update = strtotime($queue["executed"]);
382 $age = (time() - self::$last_update) / 60;
383 self::$last_update = time();
386 $stamp = (float)microtime(true);
387 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
388 self::$db_duration += (microtime(true) - $stamp);
389 self::$db_duration_write += (microtime(true) - $stamp);
392 self::execFunction($queue, $funcname, $argv, false);
394 $stamp = (float)microtime(true);
395 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
396 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
398 self::$db_duration = (microtime(true) - $stamp);
399 self::$db_duration_write += (microtime(true) - $stamp);
401 Logger::warning("Function does not exist", ['function' => $funcname]);
402 $stamp = (float)microtime(true);
403 DBA::delete('workerqueue', ['id' => $queue["id"]]);
404 self::$db_duration = (microtime(true) - $stamp);
405 self::$db_duration_write += (microtime(true) - $stamp);
412 * Execute a function from the queue
414 * @param array $queue Workerqueue entry
415 * @param string $funcname name of the function
416 * @param array $argv Array of values to be passed to the function
417 * @param boolean $method_call boolean
419 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
421 private static function execFunction($queue, $funcname, $argv, $method_call)
425 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
427 Logger::info('Pre execution cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
431 Logger::enableWorker($funcname);
433 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
435 $stamp = (float)microtime(true);
437 // We use the callstack here to analyze the performance of executed worker entries.
438 // For this reason the variables have to be initialized.
439 DI::profiler()->reset();
441 if (!in_array($queue['priority'], PRIORITIES)) {
442 Logger::warning('Invalid priority', ['queue' => $queue, 'callstack' => System::callstack(20)]);
443 $queue['priority'] = PRIORITY_MEDIUM;
446 $a->setQueue($queue);
448 $up_duration = microtime(true) - self::$up_start;
450 // Reset global data to avoid interferences
453 // Set the workerLogger as new default logger
455 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
457 $funcname($argv, count($argv));
460 Logger::disableWorker();
464 $duration = (microtime(true) - $stamp);
466 /* With these values we can analyze how effective the worker is.
467 * The database and rest time should be low since this is the unproductive time.
468 * The execution time is the productive time.
469 * By changing parameters like the maximum number of workers we can check the effectivness.
471 $dbtotal = round(self::$db_duration, 2);
472 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
473 $dbcount = round(self::$db_duration_count, 2);
474 $dbstat = round(self::$db_duration_stat, 2);
475 $dbwrite = round(self::$db_duration_write, 2);
476 $dblock = round(self::$lock_duration, 2);
477 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
478 $exec = round($duration, 2);
480 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
482 self::$up_start = microtime(true);
483 self::$db_duration = 0;
484 self::$db_duration_count = 0;
485 self::$db_duration_stat = 0;
486 self::$db_duration_write = 0;
487 self::$lock_duration = 0;
489 if ($duration > 3600) {
490 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
491 } elseif ($duration > 600) {
492 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
493 } elseif ($duration > 300) {
494 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
495 } elseif ($duration > 120) {
496 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
499 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
501 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
504 Logger::info('Post execution cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
510 * Checks if the number of database connections has reached a critical limit.
512 * @return bool Are more than 3/4 of the maximum connections used?
513 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
515 private static function maxConnectionsReached()
517 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
518 $max = DI::config()->get("system", "max_connections");
520 // Fetch the percentage level where the worker will get active
521 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
524 // the maximum number of possible user connections can be a system variable
525 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
526 if (DBA::isResult($r)) {
529 // Or it can be granted. This overrides the system variable
530 $stamp = (float)microtime(true);
531 $r = DBA::p('SHOW GRANTS');
532 self::$db_duration += (microtime(true) - $stamp);
533 while ($grants = DBA::fetch($r)) {
534 $grant = array_pop($grants);
535 if (stristr($grant, "GRANT USAGE ON")) {
536 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
544 // If $max is set we will use the processlist to determine the current number of connections
545 // The processlist only shows entries of the current user
547 $stamp = (float)microtime(true);
548 $r = DBA::p('SHOW PROCESSLIST');
549 self::$db_duration += (microtime(true) - $stamp);
550 $used = DBA::numRows($r);
553 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
555 $level = ($used / $max) * 100;
557 if ($level >= $maxlevel) {
558 Logger::warning("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
563 // We will now check for the system values.
564 // This limit could be reached although the user limits are fine.
565 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
566 if (!DBA::isResult($r)) {
569 $max = intval($r["Value"]);
573 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
574 if (!DBA::isResult($r)) {
577 $used = intval($r["Value"]);
581 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
583 $level = $used / $max * 100;
585 if ($level < $maxlevel) {
588 Logger::warning("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
593 * fix the queue entry if the worker process died
598 private static function killStaleWorkers()
600 $stamp = (float)microtime(true);
601 $entries = DBA::select(
603 ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
604 ['NOT `done` AND `pid` != 0'],
605 ['order' => ['priority', 'retrial', 'created']]
607 self::$db_duration += (microtime(true) - $stamp);
609 while ($entry = DBA::fetch($entries)) {
610 if (!posix_kill($entry["pid"], 0)) {
611 $stamp = (float)microtime(true);
614 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
615 ['id' => $entry["id"]]
617 self::$db_duration += (microtime(true) - $stamp);
618 self::$db_duration_write += (microtime(true) - $stamp);
620 // Kill long running processes
621 // Check if the priority is in a valid range
622 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
623 $entry["priority"] = PRIORITY_MEDIUM;
626 // Define the maximum durations
627 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
628 $max_duration = $max_duration_defaults[$entry["priority"]];
630 $argv = json_decode($entry['parameter'], true);
631 if (!empty($entry['command'])) {
632 $command = $entry['command'];
633 } elseif (!empty($argv)) {
634 $command = array_shift($argv);
639 $command = basename($command);
641 // How long is the process already running?
642 $duration = (time() - strtotime($entry["executed"])) / 60;
643 if ($duration > $max_duration) {
644 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]);
645 posix_kill($entry["pid"], SIGTERM);
647 // We killed the stale process.
648 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
649 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
650 $new_priority = $entry["priority"];
651 if ($entry["priority"] == PRIORITY_HIGH) {
652 $new_priority = PRIORITY_MEDIUM;
653 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
654 $new_priority = PRIORITY_LOW;
655 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
656 $new_priority = PRIORITY_NEGLIGIBLE;
658 $stamp = (float)microtime(true);
661 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
662 ['id' => $entry["id"]]
664 self::$db_duration += (microtime(true) - $stamp);
665 self::$db_duration_write += (microtime(true) - $stamp);
667 Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
671 DBA::close($entries);
675 * Checks if the number of active workers exceeds the given limits
677 * @return bool Are there too much workers running?
678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
680 private static function tooMuchWorkers()
682 $queues = DI::config()->get("system", "worker_queues", 10);
684 $maxqueues = $queues;
686 $active = self::activeWorkers();
688 // Decrease the number of workers at higher load
689 $load = System::currentLoad();
691 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
693 /* Default exponent 3 causes queues to rapidly decrease as load increases.
694 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
695 * For some environments, this rapid decrease is not needed.
696 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
698 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
699 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
700 $queues = intval(ceil($slope * $maxqueues));
704 if (DI::config()->get('system', 'worker_jpm')) {
705 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
706 $jobs_per_minute = [];
707 foreach ($intervals as $interval) {
708 if ($interval == 0) {
711 $interval = (int)$interval;
714 $stamp = (float)microtime(true);
715 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
716 self::$db_duration += (microtime(true) - $stamp);
717 self::$db_duration_stat += (microtime(true) - $stamp);
718 if ($job = DBA::fetch($jobs)) {
719 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
723 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
726 // Create a list of queue entries grouped by their priority
727 $listitem = [0 => ''];
729 $idle_workers = $active;
731 $deferred = self::deferredEntries();
733 if (DI::config()->get('system', 'worker_debug')) {
734 $waiting_processes = 0;
735 // Now adding all processes with workerqueue entries
736 $stamp = (float)microtime(true);
737 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
738 self::$db_duration += (microtime(true) - $stamp);
739 self::$db_duration_stat += (microtime(true) - $stamp);
740 while ($entry = DBA::fetch($jobs)) {
741 $stamp = (float)microtime(true);
742 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
743 self::$db_duration += (microtime(true) - $stamp);
744 self::$db_duration_stat += (microtime(true) - $stamp);
745 if ($process = DBA::fetch($processes)) {
746 $idle_workers -= $process["running"];
747 $waiting_processes += $entry["entries"];
748 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
750 DBA::close($processes);
754 $waiting_processes = self::totalEntries();
755 $stamp = (float)microtime(true);
756 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
757 self::$db_duration += (microtime(true) - $stamp);
758 self::$db_duration_stat += (microtime(true) - $stamp);
760 while ($entry = DBA::fetch($jobs)) {
761 $idle_workers -= $entry["running"];
762 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
767 $waiting_processes -= $deferred;
769 $listitem[0] = "0:" . max(0, $idle_workers);
771 $processlist .= ' ('.implode(', ', $listitem).')';
773 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
774 $top_priority = self::highestPriority();
775 $high_running = self::processWithPriorityActive($top_priority);
777 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
778 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
779 $queues = $active + 1;
783 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
785 // Are there fewer workers running as possible? Then fork a new one.
786 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
787 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
788 if (self::isDaemonMode()) {
789 self::IPCSetJobState(true);
796 // if there are too much worker, we don't spawn a new one.
797 if (self::isDaemonMode() && ($active > $queues)) {
798 self::IPCSetJobState(false);
801 return $active > $queues;
805 * Returns the number of active worker processes
807 * @return integer Number of active worker processes
810 private static function activeWorkers()
812 $stamp = (float)microtime(true);
813 $count = DBA::count('process', ['command' => 'Worker.php']);
814 self::$db_duration += (microtime(true) - $stamp);
815 self::$db_duration_count += (microtime(true) - $stamp);
820 * Returns the number of active worker processes
822 * @return array List of worker process ids
825 private static function getWorkerPIDList()
828 $stamp = (float)microtime(true);
830 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
831 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
832 GROUP BY `process`.`pid`");
833 while ($queue = DBA::fetch($queues)) {
834 $ids[$queue['pid']] = $queue['entries'];
838 self::$db_duration += (microtime(true) - $stamp);
839 self::$db_duration_count += (microtime(true) - $stamp);
844 * Returns waiting jobs for the current process id
846 * @return array waiting workerqueue jobs
849 private static function getWaitingJobForPID()
851 $stamp = (float)microtime(true);
852 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
853 self::$db_duration += (microtime(true) - $stamp);
854 if (DBA::isResult($r)) {
855 return DBA::toArray($r);
863 * Returns the next jobs that should be executed
865 * @return array array with next jobs
868 private static function nextProcess(int $limit)
870 $priority = self::nextPriority();
871 if (empty($priority)) {
872 Logger::info('No tasks found');
877 $stamp = (float)microtime(true);
878 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
879 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
880 self::$db_duration += (microtime(true) - $stamp);
881 while ($task = DBA::fetch($tasks)) {
882 $ids[] = $task['id'];
883 // Only continue that loop while we are storing commands that can be processed quickly
884 if (!empty($task['command'])) {
885 $command = $task['command'];
887 $command = json_decode($task['parameter'])[0];
890 if (!in_array($command, self::FAST_COMMANDS)) {
896 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
901 * Returns the priority of the next workerqueue job
903 * @return string priority
906 private static function nextPriority()
909 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
910 foreach ($priorities as $priority) {
911 $stamp = (float)microtime(true);
912 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
913 $waiting[$priority] = true;
915 self::$db_duration += (microtime(true) - $stamp);
918 if (!empty($waiting[PRIORITY_CRITICAL])) {
919 return PRIORITY_CRITICAL;
924 $stamp = (float)microtime(true);
925 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
926 self::$db_duration += (microtime(true) - $stamp);
927 while ($process = DBA::fetch($processes)) {
928 $running[$process['priority']] = $process['running'];
929 $running_total += $process['running'];
931 DBA::close($processes);
933 foreach ($priorities as $priority) {
934 if (!empty($waiting[$priority]) && empty($running[$priority])) {
935 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
940 $active = max(self::activeWorkers(), $running_total);
941 $priorities = max(count($waiting), count($running));
945 for ($i = 1; $i <= $priorities; ++$i) {
946 $total += pow($i, $exponent);
950 for ($i = 1; $i <= $priorities; ++$i) {
951 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
955 foreach ($running as $priority => $workers) {
956 if ($workers < $limit[$i++]) {
957 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
962 if (!empty($waiting)) {
963 $priority = array_keys($waiting)[0];
964 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
972 * Find and claim the next worker process for us
974 * @return boolean Have we found something?
975 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
977 private static function findWorkerProcesses()
979 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
981 if (DI::config()->get('system', 'worker_multiple_fetch')) {
983 foreach (self::getWorkerPIDList() as $pid => $count) {
984 if ($count <= $fetch_limit) {
991 $limit = $fetch_limit * count($pids);
993 $pids = [getmypid()];
994 $limit = $fetch_limit;
997 $ids = self::nextProcess($limit);
998 $limit -= count($ids);
1000 // If there is not enough results we check without priority limit
1002 $stamp = (float)microtime(true);
1003 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
1004 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
1005 self::$db_duration += (microtime(true) - $stamp);
1007 while ($task = DBA::fetch($tasks)) {
1008 $ids[] = $task['id'];
1009 // Only continue that loop while we are storing commands that can be processed quickly
1010 if (!empty($task['command'])) {
1011 $command = $task['command'];
1013 $command = json_decode($task['parameter'])[0];
1015 if (!in_array($command, self::FAST_COMMANDS)) {
1026 // Assign the task ids to the workers
1028 foreach (array_unique($ids) as $id) {
1031 $pid = reset($pids);
1033 $worker[$pid][] = $id;
1036 $stamp = (float)microtime(true);
1037 foreach ($worker as $worker_pid => $worker_ids) {
1038 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1039 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1040 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1042 self::$db_duration += (microtime(true) - $stamp);
1043 self::$db_duration_write += (microtime(true) - $stamp);
1047 * Returns the next worker process
1049 * @return array worker processes
1050 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1052 public static function workerProcess()
1054 // There can already be jobs for us in the queue.
1055 $waiting = self::getWaitingJobForPID();
1056 if (!empty($waiting)) {
1060 $stamp = (float)microtime(true);
1061 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1064 self::$lock_duration += (microtime(true) - $stamp);
1066 self::findWorkerProcesses();
1068 DI::lock()->release(self::LOCK_PROCESS);
1070 return self::getWaitingJobForPID();
1074 * Removes a workerqueue entry from the current process
1077 * @throws \Exception
1079 public static function unclaimProcess()
1081 $mypid = getmypid();
1083 $stamp = (float)microtime(true);
1084 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1085 self::$db_duration += (microtime(true) - $stamp);
1086 self::$db_duration_write += (microtime(true) - $stamp);
1090 * Runs the cron processes
1093 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1095 private static function runCron()
1097 Logger::info('Add cron entries');
1099 // Check for spooled items
1100 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1102 // Run the cron job that calls all other jobs
1103 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1105 // Cleaning dead processes
1106 self::killStaleWorkers();
1110 * Fork a child process
1112 * @param boolean $do_cron
1115 private static function forkProcess(bool $do_cron)
1117 if (DI::process()->isMinMemoryReached()) {
1118 Logger::warning('Memory limit reached - quitting');
1122 // Children inherit their parent's database connection.
1123 // To avoid problems we disconnect and connect both parent and child
1125 $pid = pcntl_fork();
1128 Logger::warning('Could not spawn worker');
1131 // The parent process continues here
1134 self::IPCSetJobState(true, $pid);
1135 Logger::info('Spawned new worker', ['pid' => $pid]);
1138 while (self::IPCJobsExists($pid) && (++$cycles < 100)) {
1142 Logger::info('Spawned worker is ready', ['pid' => $pid, 'wait_cycles' => $cycles]);
1146 // We now are in the new worker
1150 /// @todo Reinitialize the logger to set a new process_id and uid
1151 DI::process()->setPid($pid);
1154 while (!self::IPCJobsExists($pid) && (++$cycles < 100)) {
1158 Logger::info('Worker spawned', ['pid' => $pid, 'wait_cycles' => $cycles]);
1160 self::processQueue($do_cron);
1162 self::unclaimProcess();
1164 self::IPCSetJobState(false, $pid);
1165 DI::process()->end();
1166 Logger::info('Worker ended', ['pid' => $pid]);
1171 * Spawns a new worker
1173 * @param bool $do_cron
1175 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1177 public static function spawnWorker($do_cron = false)
1179 if (self::isDaemonMode() && DI::config()->get('system', 'worker_fork')) {
1180 self::forkProcess($do_cron);
1182 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(),
1183 DI::modelProcess(), DI::app()->getBasePath(), getmypid());
1184 $process->run('bin/worker.php', ['no_cron' => !$do_cron]);
1186 if (self::isDaemonMode()) {
1187 self::IPCSetJobState(false);
1192 * Adds tasks to the worker queue
1194 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1196 * next args are passed as $cmd command line
1197 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1198 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1200 * @return int "0" if worker queue entry already existed or there had been an error, otherwise the ID of the worker task
1201 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1202 * @note $cmd and string args are surrounded with ""
1208 public static function add($cmd)
1210 $args = func_get_args();
1212 if (!count($args)) {
1216 $arr = ['args' => $args, 'run_cmd' => true];
1218 Hook::callAll("proc_run", $arr);
1219 if (!$arr['run_cmd'] || !count($args)) {
1223 $priority = PRIORITY_MEDIUM;
1224 // Don't fork from frontend tasks by default
1225 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1226 $created = DateTimeFormat::utcNow();
1227 $delayed = DBA::NULL_DATETIME;
1228 $force_priority = false;
1230 $run_parameter = array_shift($args);
1232 if (is_int($run_parameter)) {
1233 $priority = $run_parameter;
1234 } elseif (is_array($run_parameter)) {
1235 if (isset($run_parameter['delayed'])) {
1236 $delayed = $run_parameter['delayed'];
1238 if (isset($run_parameter['priority'])) {
1239 $priority = $run_parameter['priority'];
1241 if (isset($run_parameter['created'])) {
1242 $created = $run_parameter['created'];
1244 if (isset($run_parameter['dont_fork'])) {
1245 $dont_fork = $run_parameter['dont_fork'];
1247 if (isset($run_parameter['force_priority'])) {
1248 $force_priority = $run_parameter['force_priority'];
1252 $command = array_shift($args);
1253 $parameters = json_encode($args);
1254 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1257 if (!in_array($priority, PRIORITIES)) {
1258 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1259 $priority = PRIORITY_MEDIUM;
1262 // Quit if there was a database error - a precaution for the update process to 3.5.3
1263 if (DBA::errorNo() != 0) {
1268 if (!DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1269 'priority' => $priority, 'next_try' => $delayed])) {
1272 $added = DBA::lastInsertId();
1273 } elseif ($force_priority) {
1274 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1277 // Set the IPC flag to ensure an immediate process execution via daemon
1278 if (self::isDaemonMode()) {
1279 self::IPCSetJobState(true);
1282 self::checkDaemonState();
1284 // Should we quit and wait for the worker to be called as a cronjob?
1289 // If there is a lock then we don't have to check for too much worker
1290 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1294 // If there are already enough workers running, don't fork another one
1295 $quit = self::tooMuchWorkers();
1296 DI::lock()->release(self::LOCK_WORKER);
1302 // Quit on daemon mode
1303 if (self::isDaemonMode()) {
1307 // Now call the worker to execute the jobs that we just added to the queue
1308 self::spawnWorker();
1313 public static function countWorkersByCommand(string $command)
1315 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1319 * Returns the next retrial level for worker jobs.
1320 * This function will skip levels when jobs are older.
1322 * @param array $queue Worker queue entry
1323 * @param integer $max_level maximum retrial level
1324 * @return integer the next retrial level value
1326 private static function getNextRetrial($queue, $max_level)
1328 $created = strtotime($queue['created']);
1329 $retrial_time = time() - $created;
1331 $new_retrial = $queue['retrial'] + 1;
1333 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1334 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1336 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1337 $new_retrial = $retrial;
1340 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1341 return $new_retrial;
1345 * Defers the current worker entry
1347 * @return boolean had the entry been deferred?
1349 public static function defer()
1351 $queue = DI::app()->getQueue();
1353 if (empty($queue)) {
1357 $retrial = $queue['retrial'];
1359 $priority = $queue['priority'];
1361 $max_level = DI::config()->get('system', 'worker_defer_limit');
1363 $new_retrial = self::getNextRetrial($queue, $max_level);
1365 if ($new_retrial > $max_level) {
1366 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]);
1370 // Calculate the delay until the next trial
1371 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1372 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1374 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1375 $priority = PRIORITY_MEDIUM;
1376 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1377 $priority = PRIORITY_LOW;
1378 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1379 $priority = PRIORITY_NEGLIGIBLE;
1382 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1384 $stamp = (float)microtime(true);
1385 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1386 DBA::update('workerqueue', $fields, ['id' => $id]);
1387 self::$db_duration += (microtime(true) - $stamp);
1388 self::$db_duration_write += (microtime(true) - $stamp);
1394 * Set the flag if some job is waiting
1396 * @param boolean $jobs Is there a waiting job?
1397 * @param int $key Key number
1398 * @throws \Exception
1400 public static function IPCSetJobState(bool $jobs, int $key = 0)
1402 $stamp = (float)microtime(true);
1403 DBA::replace('worker-ipc', ['jobs' => $jobs, 'key' => $key]);
1404 self::$db_duration += (microtime(true) - $stamp);
1405 self::$db_duration_write += (microtime(true) - $stamp);
1409 * Delete a key entry
1411 * @param int $key Key number
1412 * @throws \Exception
1414 public static function IPCDeleteJobState(int $key)
1416 $stamp = (float)microtime(true);
1417 DBA::delete('worker-ipc', ['key' => $key]);
1418 self::$db_duration += (microtime(true) - $stamp);
1419 self::$db_duration_write += (microtime(true) - $stamp);
1423 * Checks if some worker job waits to be executed
1425 * @param int $key Key number
1427 * @throws \Exception
1429 public static function IPCJobsExists(int $key = 0)
1431 $stamp = (float)microtime(true);
1432 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => $key]);
1433 self::$db_duration += (microtime(true) - $stamp);
1435 // When we don't have a row, no job is running
1436 if (!DBA::isResult($row)) {
1440 return (bool)$row['jobs'];
1444 * Checks if the worker is running in the daemon mode.
1448 public static function isDaemonMode()
1450 if (!is_null(self::$daemon_mode)) {
1451 return self::$daemon_mode;
1454 if (DI::mode()->getExecutor() == Mode::DAEMON) {
1458 $daemon_mode = DI::config()->get('system', 'worker_daemon_mode', false, true);
1460 return $daemon_mode;
1463 if (!function_exists('pcntl_fork')) {
1464 self::$daemon_mode = false;
1468 $pidfile = DI::config()->get('system', 'pidfile');
1469 if (empty($pidfile)) {
1470 // No pid file, no daemon
1471 self::$daemon_mode = false;
1475 if (!is_readable($pidfile)) {
1476 // No pid file. We assume that the daemon had been intentionally stopped.
1477 self::$daemon_mode = false;
1481 $pid = intval(file_get_contents($pidfile));
1482 $running = posix_kill($pid, 0);
1484 self::$daemon_mode = $running;
1489 * Test if the daemon is running. If not, it will be started
1493 private static function checkDaemonState()
1495 if (!DI::config()->get('system', 'daemon_watchdog', false)) {
1499 if (!DI::mode()->isNormal()) {
1503 // Check every minute if the daemon is running
1504 if (DI::config()->get('system', 'last_daemon_check', 0) + 60 > time()) {
1508 DI::config()->set('system', 'last_daemon_check', time());
1510 $pidfile = DI::config()->get('system', 'pidfile');
1511 if (empty($pidfile)) {
1512 // No pid file, no daemon
1516 if (!is_readable($pidfile)) {
1517 // No pid file. We assume that the daemon had been intentionally stopped.
1521 $pid = intval(file_get_contents($pidfile));
1522 if (posix_kill($pid, 0)) {
1523 Logger::info('Daemon process is running', ['pid' => $pid]);
1527 Logger::warning('Daemon process is not running', ['pid' => $pid]);
1529 self::spawnDaemon();
1533 * Spawn a new daemon process
1537 private static function spawnDaemon()
1539 Logger::notice('Starting new daemon process');
1540 $command = 'bin/daemon.php';
1542 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), DI::modelProcess(), $a->getBasePath(), getmypid());
1543 $process->run($command, ['start']);
1544 Logger::notice('New daemon process started');
1548 * Check if the system is inside the defined maintenance window
1552 public static function isInMaintenanceWindow(bool $check_last_execution = false)
1554 // Calculate the seconds of the start end end of the maintenance window
1555 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1556 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1558 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1560 if ($check_last_execution) {
1561 // Calculate the window duration
1562 $duration = max($start, $end) - min($start, $end);
1564 // Quit when the last cron execution had been after the previous window
1565 $last_cron = DI::config()->get('system', 'last_cron_daily');
1566 if ($last_cron + $duration > time()) {
1567 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)]);
1572 $current = time() % 86400;
1574 if ($start < $end) {
1575 // Execute if we are inside the window
1576 $execute = ($current >= $start) && ($current <= $end);
1578 // Don't execute if we are outside the window
1579 $execute = !(($current > $end) && ($current < $start));
1583 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)]);
1585 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)]);