3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Model\Process;
10 use Friendica\Util\DateTimeFormat;
11 use Friendica\Util\Logger\WorkerLogger;
12 use Friendica\Util\Network;
15 * @file src/Core/Worker.php
17 * @brief Contains the class for the worker background job processing
21 * @brief Worker methods
25 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
26 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
27 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
28 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
30 const FAST_COMMANDS = ['APDelivery', 'Delivery', 'CreateShadowEntry'];
33 private static $up_start;
34 private static $db_duration = 0;
35 private static $db_duration_count = 0;
36 private static $db_duration_write = 0;
37 private static $db_duration_stat = 0;
38 private static $lock_duration = 0;
39 private static $last_update;
40 private static $state;
43 * @brief Processes the tasks that are in the workerqueue table
45 * @param boolean $run_cron Should the cron processes be executed?
47 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
49 public static function processQueue($run_cron = true)
53 // Ensure that all "strtotime" operations do run timezone independent
54 date_default_timezone_set('UTC');
56 self::$up_start = microtime(true);
58 // At first check the maximum load. We shouldn't continue with a high load
59 if ($a->isMaxLoadReached()) {
60 Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
64 // We now start the process. This is done after the load check since this could increase the load.
67 // Kill stale processes every 5 minutes
68 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
69 if (time() > ($last_cleanup + 300)) {
70 Config::set('system', 'worker_last_cleaned', time());
71 self::killStaleWorkers();
74 // Count active workers and compare them with a maximum value that depends on the load
75 if (self::tooMuchWorkers()) {
76 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
80 // Do we have too few memory?
81 if ($a->isMinMemoryReached()) {
82 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
86 // Possibly there are too much database connections
87 if (self::maxConnectionsReached()) {
88 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
92 // Possibly there are too much database processes that block the system
93 if ($a->isMaxProcessesReached()) {
94 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
98 // Now we start additional cron processes if we should do so
104 self::$state = self::STATE_STARTUP;
106 // We fetch the next queue entry that is about to be executed
107 while ($r = self::workerProcess()) {
109 foreach ($r as $entry) {
110 // Assure that the priority is an integer value
111 $entry['priority'] = (int)$entry['priority'];
113 // The work will be done
114 if (!self::execute($entry)) {
115 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
119 // Trying to fetch new processes - but only once when successful
120 if (!$refetched && Lock::acquire('worker_process', 0)) {
121 self::findWorkerProcesses();
122 Lock::release('worker_process');
123 self::$state = self::STATE_REFETCH;
126 self::$state = self::STATE_SHORT_LOOP;
130 // To avoid the quitting of multiple workers only one worker at a time will execute the check
131 if (!self::getWaitingJobForPID()) {
132 self::$state = self::STATE_LONG_LOOP;
134 if (Lock::acquire('worker', 0)) {
135 // Count active workers and compare them with a maximum value that depends on the load
136 if (self::tooMuchWorkers()) {
137 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
138 Lock::release('worker');
143 if ($a->isMinMemoryReached()) {
144 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
145 Lock::release('worker');
148 Lock::release('worker');
152 // Quit the worker once every cron interval
153 if (time() > ($starttime + (Config::get('system', 'cron_interval') * 60))) {
154 Logger::info('Process lifetime reached, respawning.');
160 // Cleaning up. Possibly not needed, but it doesn't harm anything.
161 if (Config::get('system', 'worker_daemon_mode', false)) {
162 self::IPCSetJobState(false);
164 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
168 * @brief Check if non executed tasks do exist in the worker queue
170 * @return boolean Returns "true" if tasks are existing
173 private static function entriesExists()
175 $stamp = (float)microtime(true);
176 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
177 self::$db_duration += (microtime(true) - $stamp);
182 * @brief Returns the number of deferred entries in the worker queue
184 * @return integer Number of deferred entries in the worker queue
187 private static function deferredEntries()
189 $stamp = (float)microtime(true);
190 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` > ?", DateTimeFormat::utcNow()]);
191 self::$db_duration += (microtime(true) - $stamp);
192 self::$db_duration_count += (microtime(true) - $stamp);
197 * @brief Returns the number of non executed entries in the worker queue
199 * @return integer Number of non executed entries in the worker queue
202 private static function totalEntries()
204 $stamp = (float)microtime(true);
205 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
206 self::$db_duration += (microtime(true) - $stamp);
207 self::$db_duration_count += (microtime(true) - $stamp);
212 * @brief Returns the highest priority in the worker queue that isn't executed
214 * @return integer Number of active worker processes
217 private static function highestPriority()
219 $stamp = (float)microtime(true);
220 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
221 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
222 self::$db_duration += (microtime(true) - $stamp);
223 if (DBA::isResult($workerqueue)) {
224 return $workerqueue["priority"];
231 * @brief Returns if a process with the given priority is running
233 * @param integer $priority The priority that should be checked
235 * @return integer Is there a process running with that priority?
238 private static function processWithPriorityActive($priority)
240 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
241 return DBA::exists('workerqueue', $condition);
245 * @brief Execute a worker entry
247 * @param array $queue Workerqueue entry
249 * @return boolean "true" if further processing should be stopped
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 public static function execute($queue)
258 // Quit when in maintenance
259 if (Config::get('system', 'maintenance', false, true)) {
260 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
264 // Constantly check the number of parallel database processes
265 if ($a->isMaxProcessesReached()) {
266 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
270 // Constantly check the number of available database connections to let the frontend be accessible at any time
271 if (self::maxConnectionsReached()) {
272 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
276 $argv = json_decode($queue["parameter"], true);
278 // Check for existance and validity of the include file
281 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
282 // We constantly update the "executed" date every minute to avoid being killed too soon
283 if (!isset(self::$last_update)) {
284 self::$last_update = strtotime($queue["executed"]);
287 $age = (time() - self::$last_update) / 60;
288 self::$last_update = time();
291 $stamp = (float)microtime(true);
292 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
293 self::$db_duration += (microtime(true) - $stamp);
294 self::$db_duration_write += (microtime(true) - $stamp);
299 self::execFunction($queue, $include, $argv, true);
301 $stamp = (float)microtime(true);
302 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
303 if (DBA::update('workerqueue', ['done' => true], $condition)) {
304 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
306 self::$db_duration = (microtime(true) - $stamp);
307 self::$db_duration_write += (microtime(true) - $stamp);
312 // The script could be provided as full path or only with the function name
313 if ($include == basename($include)) {
314 $include = "include/".$include.".php";
317 if (!validate_include($include)) {
318 Logger::log("Include file ".$argv[0]." is not valid!");
319 $stamp = (float)microtime(true);
320 DBA::delete('workerqueue', ['id' => $queue["id"]]);
321 self::$db_duration = (microtime(true) - $stamp);
322 self::$db_duration_write += (microtime(true) - $stamp);
326 require_once $include;
328 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
330 if (function_exists($funcname)) {
331 // We constantly update the "executed" date every minute to avoid being killed too soon
332 if (!isset(self::$last_update)) {
333 self::$last_update = strtotime($queue["executed"]);
336 $age = (time() - self::$last_update) / 60;
337 self::$last_update = time();
340 $stamp = (float)microtime(true);
341 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
342 self::$db_duration += (microtime(true) - $stamp);
343 self::$db_duration_write += (microtime(true) - $stamp);
346 self::execFunction($queue, $funcname, $argv, false);
348 $stamp = (float)microtime(true);
349 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
350 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
352 self::$db_duration = (microtime(true) - $stamp);
353 self::$db_duration_write += (microtime(true) - $stamp);
355 Logger::log("Function ".$funcname." does not exist");
356 $stamp = (float)microtime(true);
357 DBA::delete('workerqueue', ['id' => $queue["id"]]);
358 self::$db_duration = (microtime(true) - $stamp);
359 self::$db_duration_write += (microtime(true) - $stamp);
366 * @brief Execute a function from the queue
368 * @param array $queue Workerqueue entry
369 * @param string $funcname name of the function
370 * @param array $argv Array of values to be passed to the function
371 * @param boolean $method_call boolean
373 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
375 private static function execFunction($queue, $funcname, $argv, $method_call)
379 $argc = count($argv);
381 $logger = $a->getLogger();
382 $workerLogger = new WorkerLogger($logger, $funcname);
384 $workerLogger ->info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
386 $stamp = (float)microtime(true);
388 // We use the callstack here to analyze the performance of executed worker entries.
389 // For this reason the variables have to be initialized.
390 $a->getProfiler()->reset();
394 $up_duration = microtime(true) - self::$up_start;
396 // Reset global data to avoid interferences
399 // Set the workerLogger as new default logger
400 Logger::init($workerLogger);
402 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
404 $funcname($argv, $argc);
406 Logger::init($logger);
410 $duration = (microtime(true) - $stamp);
412 /* With these values we can analyze how effective the worker is.
413 * The database and rest time should be low since this is the unproductive time.
414 * The execution time is the productive time.
415 * By changing parameters like the maximum number of workers we can check the effectivness.
417 $dbtotal = round(self::$db_duration, 2);
418 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
419 $dbcount = round(self::$db_duration_count, 2);
420 $dbstat = round(self::$db_duration_stat, 2);
421 $dbwrite = round(self::$db_duration_write, 2);
422 $dblock = round(self::$lock_duration, 2);
423 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
424 $exec = round($duration, 2);
426 $logger->info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
428 self::$up_start = microtime(true);
429 self::$db_duration = 0;
430 self::$db_duration_count = 0;
431 self::$db_duration_stat = 0;
432 self::$db_duration_write = 0;
433 self::$lock_duration = 0;
435 if ($duration > 3600) {
436 $logger->info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
437 } elseif ($duration > 600) {
438 $logger->info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
439 } elseif ($duration > 300) {
440 $logger->info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
441 } elseif ($duration > 120) {
442 $logger->info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
445 $workerLogger->info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
447 $a->getProfiler()->saveLog($a->getLogger(), "ID " . $queue["id"] . ": " . $funcname);
449 $cooldown = Config::get("system", "worker_cooldown", 0);
452 $logger->info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
458 * @brief Checks if the number of database connections has reached a critical limit.
460 * @return bool Are more than 3/4 of the maximum connections used?
461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
463 private static function maxConnectionsReached()
465 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
466 $max = Config::get("system", "max_connections");
468 // Fetch the percentage level where the worker will get active
469 $maxlevel = Config::get("system", "max_connections_level", 75);
472 // the maximum number of possible user connections can be a system variable
473 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
474 if (DBA::isResult($r)) {
477 // Or it can be granted. This overrides the system variable
478 $stamp = (float)microtime(true);
479 $r = DBA::p('SHOW GRANTS');
480 self::$db_duration += (microtime(true) - $stamp);
481 while ($grants = DBA::fetch($r)) {
482 $grant = array_pop($grants);
483 if (stristr($grant, "GRANT USAGE ON")) {
484 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
492 // If $max is set we will use the processlist to determine the current number of connections
493 // The processlist only shows entries of the current user
495 $stamp = (float)microtime(true);
496 $r = DBA::p('SHOW PROCESSLIST');
497 self::$db_duration += (microtime(true) - $stamp);
498 $used = DBA::numRows($r);
501 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
503 $level = ($used / $max) * 100;
505 if ($level >= $maxlevel) {
506 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
511 // We will now check for the system values.
512 // This limit could be reached although the user limits are fine.
513 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
514 if (!DBA::isResult($r)) {
517 $max = intval($r["Value"]);
521 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
522 if (!DBA::isResult($r)) {
525 $used = intval($r["Value"]);
529 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
531 $level = $used / $max * 100;
533 if ($level < $maxlevel) {
536 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
541 * @brief fix the queue entry if the worker process died
545 private static function killStaleWorkers()
547 $stamp = (float)microtime(true);
548 $entries = DBA::select(
550 ['id', 'pid', 'executed', 'priority', 'parameter'],
551 ['NOT `done` AND `pid` != 0'],
552 ['order' => ['priority', 'created']]
554 self::$db_duration += (microtime(true) - $stamp);
556 while ($entry = DBA::fetch($entries)) {
557 if (!posix_kill($entry["pid"], 0)) {
558 $stamp = (float)microtime(true);
561 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
562 ['id' => $entry["id"]]
564 self::$db_duration += (microtime(true) - $stamp);
565 self::$db_duration_write += (microtime(true) - $stamp);
567 // Kill long running processes
568 // Check if the priority is in a valid range
569 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
570 $entry["priority"] = PRIORITY_MEDIUM;
573 // Define the maximum durations
574 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
575 $max_duration = $max_duration_defaults[$entry["priority"]];
577 $argv = json_decode($entry["parameter"], true);
578 $argv[0] = basename($argv[0]);
580 // How long is the process already running?
581 $duration = (time() - strtotime($entry["executed"])) / 60;
582 if ($duration > $max_duration) {
583 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
584 posix_kill($entry["pid"], SIGTERM);
586 // We killed the stale process.
587 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
588 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
589 $new_priority = $entry["priority"];
590 if ($entry["priority"] == PRIORITY_HIGH) {
591 $new_priority = PRIORITY_MEDIUM;
592 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
593 $new_priority = PRIORITY_LOW;
594 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
595 $new_priority = PRIORITY_NEGLIGIBLE;
597 $stamp = (float)microtime(true);
600 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
601 ['id' => $entry["id"]]
603 self::$db_duration += (microtime(true) - $stamp);
604 self::$db_duration_write += (microtime(true) - $stamp);
606 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", Logger::DEBUG);
613 * @brief Checks if the number of active workers exceeds the given limits
615 * @return bool Are there too much workers running?
616 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
618 private static function tooMuchWorkers()
620 $queues = Config::get("system", "worker_queues", 10);
622 $maxqueues = $queues;
624 $active = self::activeWorkers();
626 // Decrease the number of workers at higher load
627 $load = System::currentLoad();
629 $maxsysload = intval(Config::get("system", "maxloadavg", 20));
631 /* Default exponent 3 causes queues to rapidly decrease as load increases.
632 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
633 * For some environments, this rapid decrease is not needed.
634 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
636 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
637 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
638 $queues = intval(ceil($slope * $maxqueues));
642 if (Config::get('system', 'worker_jpm')) {
643 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
644 $jobs_per_minute = [];
645 foreach ($intervals as $interval) {
646 if ($interval == 0) {
649 $interval = (int)$interval;
652 $stamp = (float)microtime(true);
653 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
654 self::$db_duration += (microtime(true) - $stamp);
655 self::$db_duration_stat += (microtime(true) - $stamp);
656 if ($job = DBA::fetch($jobs)) {
657 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
661 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
664 // Create a list of queue entries grouped by their priority
665 $listitem = [0 => ''];
667 $idle_workers = $active;
669 $deferred = self::deferredEntries();
671 if (Config::get('system', 'worker_debug')) {
672 $waiting_processes = 0;
673 // Now adding all processes with workerqueue entries
674 $stamp = (float)microtime(true);
675 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
676 self::$db_duration += (microtime(true) - $stamp);
677 self::$db_duration_stat += (microtime(true) - $stamp);
678 while ($entry = DBA::fetch($jobs)) {
679 $stamp = (float)microtime(true);
680 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
681 self::$db_duration += (microtime(true) - $stamp);
682 self::$db_duration_stat += (microtime(true) - $stamp);
683 if ($process = DBA::fetch($processes)) {
684 $idle_workers -= $process["running"];
685 $waiting_processes += $entry["entries"];
686 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
688 DBA::close($processes);
691 $entries = $deferred + $waiting_processes;
693 $entries = self::totalEntries();
694 $waiting_processes = max(0, $entries - $deferred);
695 $stamp = (float)microtime(true);
696 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` GROUP BY `priority` ORDER BY `priority`");
697 self::$db_duration += (microtime(true) - $stamp);
698 self::$db_duration_stat += (microtime(true) - $stamp);
700 while ($entry = DBA::fetch($jobs)) {
701 $idle_workers -= $entry["running"];
702 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
707 $listitem[0] = "0:" . max(0, $idle_workers);
709 $processlist .= ' ('.implode(', ', $listitem).')';
711 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
712 $top_priority = self::highestPriority();
713 $high_running = self::processWithPriorityActive($top_priority);
715 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
716 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
717 $queues = $active + 1;
721 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
723 // Are there fewer workers running as possible? Then fork a new one.
724 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
725 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
726 if (Config::get('system', 'worker_daemon_mode', false)) {
727 self::IPCSetJobState(true);
734 // if there are too much worker, we don't spawn a new one.
735 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
736 self::IPCSetJobState(false);
739 return $active > $queues;
743 * @brief Returns the number of active worker processes
745 * @return integer Number of active worker processes
748 private static function activeWorkers()
750 $stamp = (float)microtime(true);
751 $count = DBA::count('process', ['command' => 'Worker.php']);
752 self::$db_duration += (microtime(true) - $stamp);
757 * @brief Returns waiting jobs for the current process id
759 * @return array waiting workerqueue jobs
762 private static function getWaitingJobForPID()
764 $stamp = (float)microtime(true);
765 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
766 self::$db_duration += (microtime(true) - $stamp);
767 if (DBA::isResult($r)) {
768 return DBA::toArray($r);
776 * @brief Returns the next jobs that should be executed
778 * @return array array with next jobs
781 private static function nextProcess()
783 $priority = self::nextPriority();
784 if (empty($priority)) {
785 Logger::info('No tasks found');
789 $limit = Config::get('system', 'worker_fetch_limit', 1);
792 $stamp = (float)microtime(true);
793 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
794 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
795 self::$db_duration += (microtime(true) - $stamp);
796 while ($task = DBA::fetch($tasks)) {
797 $ids[] = $task['id'];
798 // Only continue that loop while we are storing commands that can be processed quickly
799 $command = json_decode($task['parameter'])[0];
800 if (!in_array($command, self::FAST_COMMANDS)) {
806 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
811 * @brief Returns the priority of the next workerqueue job
813 * @return string priority
816 private static function nextPriority()
819 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
820 foreach ($priorities as $priority) {
821 $stamp = (float)microtime(true);
822 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
823 $waiting[$priority] = true;
825 self::$db_duration += (microtime(true) - $stamp);
828 if (!empty($waiting[PRIORITY_CRITICAL])) {
829 return PRIORITY_CRITICAL;
834 $stamp = (float)microtime(true);
835 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
836 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
837 WHERE NOT `done` GROUP BY `priority`");
838 self::$db_duration += (microtime(true) - $stamp);
839 while ($process = DBA::fetch($processes)) {
840 $running[$process['priority']] = $process['running'];
841 $running_total += $process['running'];
843 DBA::close($processes);
845 foreach ($priorities as $priority) {
846 if (!empty($waiting[$priority]) && empty($running[$priority])) {
847 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
852 $active = max(self::activeWorkers(), $running_total);
853 $priorities = max(count($waiting), count($running));
857 for ($i = 1; $i <= $priorities; ++$i) {
858 $total += pow($i, $exponent);
862 for ($i = 1; $i <= $priorities; ++$i) {
863 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
867 foreach ($running as $priority => $workers) {
868 if ($workers < $limit[$i++]) {
869 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
874 if (!empty($waiting)) {
875 $priority = array_keys($waiting)[0];
876 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
884 * @brief Find and claim the next worker process for us
886 * @return boolean Have we found something?
887 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
889 private static function findWorkerProcesses()
893 $ids = self::nextProcess();
895 // If there is no result we check without priority limit
897 $limit = Config::get('system', 'worker_fetch_limit', 1);
899 $stamp = (float)microtime(true);
900 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
901 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
902 self::$db_duration += (microtime(true) - $stamp);
904 while ($task = DBA::fetch($tasks)) {
905 $ids[] = $task['id'];
906 // Only continue that loop while we are storing commands that can be processed quickly
907 $command = json_decode($task['parameter'])[0];
908 if (!in_array($command, self::FAST_COMMANDS)) {
916 $stamp = (float)microtime(true);
917 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
918 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
919 self::$db_duration += (microtime(true) - $stamp);
920 self::$db_duration_write += (microtime(true) - $stamp);
927 * @brief Returns the next worker process
929 * @return string SQL statement
930 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932 public static function workerProcess()
934 // There can already be jobs for us in the queue.
935 $waiting = self::getWaitingJobForPID();
936 if (!empty($waiting)) {
940 $stamp = (float)microtime(true);
941 if (!Lock::acquire('worker_process')) {
944 self::$lock_duration += (microtime(true) - $stamp);
946 $found = self::findWorkerProcesses();
948 Lock::release('worker_process');
951 $stamp = (float)microtime(true);
952 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
953 self::$db_duration += (microtime(true) - $stamp);
954 return DBA::toArray($r);
960 * @brief Removes a workerqueue entry from the current process
964 public static function unclaimProcess()
968 $stamp = (float)microtime(true);
969 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
970 self::$db_duration += (microtime(true) - $stamp);
971 self::$db_duration_write += (microtime(true) - $stamp);
975 * @brief Call the front end worker
977 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
979 public static function callWorker()
981 if (!Config::get("system", "frontend_worker")) {
985 $url = System::baseUrl()."/worker";
986 Network::fetchUrl($url, false, $redirects, 1);
990 * @brief Call the front end worker if there aren't any active
992 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
994 public static function executeIfIdle()
996 if (!Config::get("system", "frontend_worker")) {
1000 // Do we have "proc_open"? Then we can fork the worker
1001 if (function_exists("proc_open")) {
1002 // When was the last time that we called the worker?
1003 // Less than one minute? Then we quit
1004 if ((time() - Config::get("system", "worker_started")) < 60) {
1008 Config::set("system", "worker_started", time());
1010 // Do we have enough running workers? Then we quit here.
1011 if (self::tooMuchWorkers()) {
1012 // Cleaning dead processes
1013 self::killStaleWorkers();
1014 Process::deleteInactive();
1021 Logger::log('Call worker', Logger::DEBUG);
1022 self::spawnWorker();
1026 // We cannot execute background processes.
1027 // We now run the processes from the frontend.
1028 // This won't work with long running processes.
1031 self::clearProcesses();
1033 $workers = self::activeWorkers();
1035 if ($workers == 0) {
1041 * @brief Removes long running worker processes
1043 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1045 public static function clearProcesses()
1047 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1049 /// @todo We should clean up the corresponding workerqueue entries as well
1050 $stamp = (float)microtime(true);
1051 $condition = ["`created` < ? AND `command` = 'worker.php'",
1052 DateTimeFormat::utc("now - ".$timeout." minutes")];
1053 DBA::delete('process', $condition);
1054 self::$db_duration = (microtime(true) - $stamp);
1055 self::$db_duration_write += (microtime(true) - $stamp);
1059 * @brief Runs the cron processes
1061 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1063 private static function runCron()
1065 Logger::log('Add cron entries', Logger::DEBUG);
1067 // Check for spooled items
1068 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1070 // Run the cron job that calls all other jobs
1071 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1073 // Cleaning dead processes
1074 self::killStaleWorkers();
1078 * @brief Spawns a new worker
1079 * @param bool $do_cron
1081 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1083 public static function spawnWorker($do_cron = false)
1085 $command = 'bin/worker.php';
1087 $args = ['no_cron' => !$do_cron];
1089 get_app()->proc_run($command, $args);
1091 // after spawning we have to remove the flag.
1092 if (Config::get('system', 'worker_daemon_mode', false)) {
1093 self::IPCSetJobState(false);
1098 * @brief Adds tasks to the worker queue
1100 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1102 * next args are passed as $cmd command line
1103 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1104 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1106 * @return boolean "false" if proc_run couldn't be executed
1107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1108 * @note $cmd and string args are surrounded with ""
1114 public static function add($cmd)
1116 $args = func_get_args();
1118 if (!count($args)) {
1122 $arr = ['args' => $args, 'run_cmd' => true];
1124 Hook::callAll("proc_run", $arr);
1125 if (!$arr['run_cmd'] || !count($args)) {
1129 $priority = PRIORITY_MEDIUM;
1130 $dont_fork = Config::get("system", "worker_dont_fork", false);
1131 $created = DateTimeFormat::utcNow();
1132 $force_priority = false;
1134 $run_parameter = array_shift($args);
1136 if (is_int($run_parameter)) {
1137 $priority = $run_parameter;
1138 } elseif (is_array($run_parameter)) {
1139 if (isset($run_parameter['priority'])) {
1140 $priority = $run_parameter['priority'];
1142 if (isset($run_parameter['created'])) {
1143 $created = $run_parameter['created'];
1145 if (isset($run_parameter['dont_fork'])) {
1146 $dont_fork = $run_parameter['dont_fork'];
1148 if (isset($run_parameter['force_priority'])) {
1149 $force_priority = $run_parameter['force_priority'];
1153 $parameters = json_encode($args);
1154 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1156 // Quit if there was a database error - a precaution for the update process to 3.5.3
1157 if (DBA::errorNo() != 0) {
1162 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1163 } elseif ($force_priority) {
1164 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1167 // Should we quit and wait for the worker to be called as a cronjob?
1172 // If there is a lock then we don't have to check for too much worker
1173 if (!Lock::acquire('worker', 0)) {
1177 // If there are already enough workers running, don't fork another one
1178 $quit = self::tooMuchWorkers();
1179 Lock::release('worker');
1185 // We tell the daemon that a new job entry exists
1186 if (Config::get('system', 'worker_daemon_mode', false)) {
1187 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1191 // Now call the worker to execute the jobs that we just added to the queue
1192 self::spawnWorker();
1198 * Defers the current worker entry
1200 public static function defer()
1202 if (empty(BaseObject::getApp()->queue)) {
1206 $queue = BaseObject::getApp()->queue;
1208 $retrial = $queue['retrial'];
1210 $priority = $queue['priority'];
1212 if ($retrial > 14) {
1213 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1217 // Calculate the delay until the next trial
1218 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1219 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1221 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1222 $priority = PRIORITY_MEDIUM;
1223 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1224 $priority = PRIORITY_LOW;
1225 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1226 $priority = PRIORITY_NEGLIGIBLE;
1229 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1231 $stamp = (float)microtime(true);
1232 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1233 DBA::update('workerqueue', $fields, ['id' => $id]);
1234 self::$db_duration += (microtime(true) - $stamp);
1235 self::$db_duration_write += (microtime(true) - $stamp);
1239 * Log active processes into the "process" table
1241 * @brief Log active processes into the "process" table
1243 public static function startProcess()
1245 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1247 $command = basename($trace[0]['file']);
1249 Process::deleteInactive();
1251 Process::insert($command);
1255 * Remove the active process from the "process" table
1257 * @brief Remove the active process from the "process" table
1259 * @throws \Exception
1261 public static function endProcess()
1263 return Process::deleteByPid();
1267 * Set the flag if some job is waiting
1269 * @brief Set the flag if some job is waiting
1270 * @param boolean $jobs Is there a waiting job?
1271 * @throws \Exception
1273 public static function IPCSetJobState($jobs)
1275 $stamp = (float)microtime(true);
1276 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1277 self::$db_duration += (microtime(true) - $stamp);
1278 self::$db_duration_write += (microtime(true) - $stamp);
1282 * Checks if some worker job waits to be executed
1284 * @brief Checks if some worker job waits to be executed
1286 * @throws \Exception
1288 public static function IPCJobsExists()
1290 $stamp = (float)microtime(true);
1291 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1292 self::$db_duration += (microtime(true) - $stamp);
1294 // When we don't have a row, no job is running
1295 if (!DBA::isResult($row)) {
1299 return (bool)$row['jobs'];