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\Network;
14 * @file src/Core/Worker.php
16 * @brief Contains the class for the worker background job processing
20 * @brief Worker methods
24 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
25 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
26 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
27 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
29 const FAST_COMMANDS = ['APDelivery', 'Delivery', 'CreateShadowEntry'];
32 private static $up_start;
33 private static $db_duration = 0;
34 private static $db_duration_count = 0;
35 private static $db_duration_write = 0;
36 private static $db_duration_stat = 0;
37 private static $lock_duration = 0;
38 private static $last_update;
39 private static $state;
42 * @brief Processes the tasks that are in the workerqueue table
44 * @param boolean $run_cron Should the cron processes be executed?
46 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
48 public static function processQueue($run_cron = true)
52 // Ensure that all "strtotime" operations do run timezone independent
53 date_default_timezone_set('UTC');
55 self::$up_start = microtime(true);
57 // At first check the maximum load. We shouldn't continue with a high load
58 if ($a->isMaxLoadReached()) {
59 Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
63 // We now start the process. This is done after the load check since this could increase the load.
66 // Kill stale processes every 5 minutes
67 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
68 if (time() > ($last_cleanup + 300)) {
69 Config::set('system', 'worker_last_cleaned', time());
70 self::killStaleWorkers();
73 // Count active workers and compare them with a maximum value that depends on the load
74 if (self::tooMuchWorkers()) {
75 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
79 // Do we have too few memory?
80 if ($a->isMinMemoryReached()) {
81 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
85 // Possibly there are too much database connections
86 if (self::maxConnectionsReached()) {
87 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
91 // Possibly there are too much database processes that block the system
92 if ($a->isMaxProcessesReached()) {
93 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
97 // Now we start additional cron processes if we should do so
103 self::$state = self::STATE_STARTUP;
105 // We fetch the next queue entry that is about to be executed
106 while ($r = self::workerProcess()) {
108 foreach ($r as $entry) {
109 // Assure that the priority is an integer value
110 $entry['priority'] = (int)$entry['priority'];
112 // The work will be done
113 if (!self::execute($entry)) {
114 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
118 // Trying to fetch new processes - but only once when successful
119 if (!$refetched && Lock::acquire('worker_process', 0)) {
120 self::findWorkerProcesses();
121 Lock::release('worker_process');
122 self::$state = self::STATE_REFETCH;
125 self::$state = self::STATE_SHORT_LOOP;
129 // To avoid the quitting of multiple workers only one worker at a time will execute the check
130 if (!self::getWaitingJobForPID()) {
131 self::$state = self::STATE_LONG_LOOP;
133 if (Lock::acquire('worker', 0)) {
134 // Count active workers and compare them with a maximum value that depends on the load
135 if (self::tooMuchWorkers()) {
136 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
137 Lock::release('worker');
142 if ($a->isMinMemoryReached()) {
143 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
144 Lock::release('worker');
147 Lock::release('worker');
151 // Quit the worker once every cron interval
152 if (time() > ($starttime + (Config::get('system', 'cron_interval') * 60))) {
153 Logger::info('Process lifetime reached, respawning.');
159 // Cleaning up. Possibly not needed, but it doesn't harm anything.
160 if (Config::get('system', 'worker_daemon_mode', false)) {
161 self::IPCSetJobState(false);
163 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
167 * @brief Check if non executed tasks do exist in the worker queue
169 * @return boolean Returns "true" if tasks are existing
172 private static function entriesExists()
174 $stamp = (float)microtime(true);
175 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
176 self::$db_duration += (microtime(true) - $stamp);
181 * @brief Returns the number of deferred entries in the worker queue
183 * @return integer Number of deferred entries in the worker queue
186 private static function deferredEntries()
188 $stamp = (float)microtime(true);
189 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
190 self::$db_duration += (microtime(true) - $stamp);
191 self::$db_duration_count += (microtime(true) - $stamp);
196 * @brief Returns the number of non executed entries in the worker queue
198 * @return integer Number of non executed entries in the worker queue
201 private static function totalEntries()
203 $stamp = (float)microtime(true);
204 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
205 self::$db_duration += (microtime(true) - $stamp);
206 self::$db_duration_count += (microtime(true) - $stamp);
211 * @brief Returns the highest priority in the worker queue that isn't executed
213 * @return integer Number of active worker processes
216 private static function highestPriority()
218 $stamp = (float)microtime(true);
219 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
220 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
221 self::$db_duration += (microtime(true) - $stamp);
222 if (DBA::isResult($workerqueue)) {
223 return $workerqueue["priority"];
230 * @brief Returns if a process with the given priority is running
232 * @param integer $priority The priority that should be checked
234 * @return integer Is there a process running with that priority?
237 private static function processWithPriorityActive($priority)
239 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
240 return DBA::exists('workerqueue', $condition);
244 * @brief Execute a worker entry
246 * @param array $queue Workerqueue entry
248 * @return boolean "true" if further processing should be stopped
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 public static function execute($queue)
257 // Quit when in maintenance
258 if (Config::get('system', 'maintenance', false, true)) {
259 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
263 // Constantly check the number of parallel database processes
264 if ($a->isMaxProcessesReached()) {
265 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
269 // Constantly check the number of available database connections to let the frontend be accessible at any time
270 if (self::maxConnectionsReached()) {
271 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
275 $argv = json_decode($queue["parameter"], true);
277 // Check for existance and validity of the include file
280 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
281 // We constantly update the "executed" date every minute to avoid being killed too soon
282 if (!isset(self::$last_update)) {
283 self::$last_update = strtotime($queue["executed"]);
286 $age = (time() - self::$last_update) / 60;
287 self::$last_update = time();
290 $stamp = (float)microtime(true);
291 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
292 self::$db_duration += (microtime(true) - $stamp);
293 self::$db_duration_write += (microtime(true) - $stamp);
298 self::execFunction($queue, $include, $argv, true);
300 $stamp = (float)microtime(true);
301 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
302 if (DBA::update('workerqueue', ['done' => true], $condition)) {
303 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
305 self::$db_duration = (microtime(true) - $stamp);
306 self::$db_duration_write += (microtime(true) - $stamp);
311 // The script could be provided as full path or only with the function name
312 if ($include == basename($include)) {
313 $include = "include/".$include.".php";
316 if (!validate_include($include)) {
317 Logger::log("Include file ".$argv[0]." is not valid!");
318 $stamp = (float)microtime(true);
319 DBA::delete('workerqueue', ['id' => $queue["id"]]);
320 self::$db_duration = (microtime(true) - $stamp);
321 self::$db_duration_write += (microtime(true) - $stamp);
325 require_once $include;
327 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
329 if (function_exists($funcname)) {
330 // We constantly update the "executed" date every minute to avoid being killed too soon
331 if (!isset(self::$last_update)) {
332 self::$last_update = strtotime($queue["executed"]);
335 $age = (time() - self::$last_update) / 60;
336 self::$last_update = time();
339 $stamp = (float)microtime(true);
340 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
341 self::$db_duration += (microtime(true) - $stamp);
342 self::$db_duration_write += (microtime(true) - $stamp);
345 self::execFunction($queue, $funcname, $argv, false);
347 $stamp = (float)microtime(true);
348 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
349 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
351 self::$db_duration = (microtime(true) - $stamp);
352 self::$db_duration_write += (microtime(true) - $stamp);
354 Logger::log("Function ".$funcname." does not exist");
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);
365 * @brief Execute a function from the queue
367 * @param array $queue Workerqueue entry
368 * @param string $funcname name of the function
369 * @param array $argv Array of values to be passed to the function
370 * @param boolean $method_call boolean
372 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
374 private static function execFunction($queue, $funcname, $argv, $method_call)
378 $argc = count($argv);
380 Logger::enableWorker($funcname);
382 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
384 $stamp = (float)microtime(true);
386 // We use the callstack here to analyze the performance of executed worker entries.
387 // For this reason the variables have to be initialized.
388 $a->getProfiler()->reset();
392 $up_duration = microtime(true) - self::$up_start;
394 // Reset global data to avoid interferences
397 // Set the workerLogger as new default logger
399 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
401 $funcname($argv, $argc);
404 Logger::disableWorker();
408 $duration = (microtime(true) - $stamp);
410 /* With these values we can analyze how effective the worker is.
411 * The database and rest time should be low since this is the unproductive time.
412 * The execution time is the productive time.
413 * By changing parameters like the maximum number of workers we can check the effectivness.
415 $dbtotal = round(self::$db_duration, 2);
416 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
417 $dbcount = round(self::$db_duration_count, 2);
418 $dbstat = round(self::$db_duration_stat, 2);
419 $dbwrite = round(self::$db_duration_write, 2);
420 $dblock = round(self::$lock_duration, 2);
421 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
422 $exec = round($duration, 2);
424 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
426 self::$up_start = microtime(true);
427 self::$db_duration = 0;
428 self::$db_duration_count = 0;
429 self::$db_duration_stat = 0;
430 self::$db_duration_write = 0;
431 self::$lock_duration = 0;
433 if ($duration > 3600) {
434 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
435 } elseif ($duration > 600) {
436 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
437 } elseif ($duration > 300) {
438 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
439 } elseif ($duration > 120) {
440 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
443 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
445 $a->getProfiler()->saveLog($a->getLogger(), "ID " . $queue["id"] . ": " . $funcname);
447 $cooldown = Config::get("system", "worker_cooldown", 0);
450 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
456 * @brief Checks if the number of database connections has reached a critical limit.
458 * @return bool Are more than 3/4 of the maximum connections used?
459 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
461 private static function maxConnectionsReached()
463 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
464 $max = Config::get("system", "max_connections");
466 // Fetch the percentage level where the worker will get active
467 $maxlevel = Config::get("system", "max_connections_level", 75);
470 // the maximum number of possible user connections can be a system variable
471 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
472 if (DBA::isResult($r)) {
475 // Or it can be granted. This overrides the system variable
476 $stamp = (float)microtime(true);
477 $r = DBA::p('SHOW GRANTS');
478 self::$db_duration += (microtime(true) - $stamp);
479 while ($grants = DBA::fetch($r)) {
480 $grant = array_pop($grants);
481 if (stristr($grant, "GRANT USAGE ON")) {
482 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
490 // If $max is set we will use the processlist to determine the current number of connections
491 // The processlist only shows entries of the current user
493 $stamp = (float)microtime(true);
494 $r = DBA::p('SHOW PROCESSLIST');
495 self::$db_duration += (microtime(true) - $stamp);
496 $used = DBA::numRows($r);
499 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
501 $level = ($used / $max) * 100;
503 if ($level >= $maxlevel) {
504 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
509 // We will now check for the system values.
510 // This limit could be reached although the user limits are fine.
511 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
512 if (!DBA::isResult($r)) {
515 $max = intval($r["Value"]);
519 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
520 if (!DBA::isResult($r)) {
523 $used = intval($r["Value"]);
527 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
529 $level = $used / $max * 100;
531 if ($level < $maxlevel) {
534 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
539 * @brief fix the queue entry if the worker process died
543 private static function killStaleWorkers()
545 $stamp = (float)microtime(true);
546 $entries = DBA::select(
548 ['id', 'pid', 'executed', 'priority', 'parameter'],
549 ['NOT `done` AND `pid` != 0'],
550 ['order' => ['priority', 'created']]
552 self::$db_duration += (microtime(true) - $stamp);
554 while ($entry = DBA::fetch($entries)) {
555 if (!posix_kill($entry["pid"], 0)) {
556 $stamp = (float)microtime(true);
559 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
560 ['id' => $entry["id"]]
562 self::$db_duration += (microtime(true) - $stamp);
563 self::$db_duration_write += (microtime(true) - $stamp);
565 // Kill long running processes
566 // Check if the priority is in a valid range
567 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
568 $entry["priority"] = PRIORITY_MEDIUM;
571 // Define the maximum durations
572 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
573 $max_duration = $max_duration_defaults[$entry["priority"]];
575 $argv = json_decode($entry["parameter"], true);
576 $argv[0] = basename($argv[0]);
578 // How long is the process already running?
579 $duration = (time() - strtotime($entry["executed"])) / 60;
580 if ($duration > $max_duration) {
581 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
582 posix_kill($entry["pid"], SIGTERM);
584 // We killed the stale process.
585 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
586 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
587 $new_priority = $entry["priority"];
588 if ($entry["priority"] == PRIORITY_HIGH) {
589 $new_priority = PRIORITY_MEDIUM;
590 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
591 $new_priority = PRIORITY_LOW;
592 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
593 $new_priority = PRIORITY_NEGLIGIBLE;
595 $stamp = (float)microtime(true);
598 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
599 ['id' => $entry["id"]]
601 self::$db_duration += (microtime(true) - $stamp);
602 self::$db_duration_write += (microtime(true) - $stamp);
604 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);
611 * @brief Checks if the number of active workers exceeds the given limits
613 * @return bool Are there too much workers running?
614 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
616 private static function tooMuchWorkers()
618 $queues = Config::get("system", "worker_queues", 10);
620 $maxqueues = $queues;
622 $active = self::activeWorkers();
624 // Decrease the number of workers at higher load
625 $load = System::currentLoad();
627 $maxsysload = intval(Config::get("system", "maxloadavg", 20));
629 /* Default exponent 3 causes queues to rapidly decrease as load increases.
630 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
631 * For some environments, this rapid decrease is not needed.
632 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
634 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
635 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
636 $queues = intval(ceil($slope * $maxqueues));
640 if (Config::get('system', 'worker_jpm')) {
641 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
642 $jobs_per_minute = [];
643 foreach ($intervals as $interval) {
644 if ($interval == 0) {
647 $interval = (int)$interval;
650 $stamp = (float)microtime(true);
651 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
652 self::$db_duration += (microtime(true) - $stamp);
653 self::$db_duration_stat += (microtime(true) - $stamp);
654 if ($job = DBA::fetch($jobs)) {
655 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
659 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
662 // Create a list of queue entries grouped by their priority
663 $listitem = [0 => ''];
665 $idle_workers = $active;
667 $deferred = self::deferredEntries();
669 if (Config::get('system', 'worker_debug')) {
670 $waiting_processes = 0;
671 // Now adding all processes with workerqueue entries
672 $stamp = (float)microtime(true);
673 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
674 self::$db_duration += (microtime(true) - $stamp);
675 self::$db_duration_stat += (microtime(true) - $stamp);
676 while ($entry = DBA::fetch($jobs)) {
677 $stamp = (float)microtime(true);
678 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
679 self::$db_duration += (microtime(true) - $stamp);
680 self::$db_duration_stat += (microtime(true) - $stamp);
681 if ($process = DBA::fetch($processes)) {
682 $idle_workers -= $process["running"];
683 $waiting_processes += $entry["entries"];
684 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
686 DBA::close($processes);
690 $waiting_processes = self::totalEntries();
691 $stamp = (float)microtime(true);
692 $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`");
693 self::$db_duration += (microtime(true) - $stamp);
694 self::$db_duration_stat += (microtime(true) - $stamp);
696 while ($entry = DBA::fetch($jobs)) {
697 $idle_workers -= $entry["running"];
698 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
703 $listitem[0] = "0:" . max(0, $idle_workers);
705 $processlist .= ' ('.implode(', ', $listitem).')';
707 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
708 $top_priority = self::highestPriority();
709 $high_running = self::processWithPriorityActive($top_priority);
711 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
712 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
713 $queues = $active + 1;
717 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
719 // Are there fewer workers running as possible? Then fork a new one.
720 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
721 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
722 if (Config::get('system', 'worker_daemon_mode', false)) {
723 self::IPCSetJobState(true);
730 // if there are too much worker, we don't spawn a new one.
731 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
732 self::IPCSetJobState(false);
735 return $active > $queues;
739 * @brief Returns the number of active worker processes
741 * @return integer Number of active worker processes
744 private static function activeWorkers()
746 $stamp = (float)microtime(true);
747 $count = DBA::count('process', ['command' => 'Worker.php']);
748 self::$db_duration += (microtime(true) - $stamp);
753 * @brief Returns waiting jobs for the current process id
755 * @return array waiting workerqueue jobs
758 private static function getWaitingJobForPID()
760 $stamp = (float)microtime(true);
761 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
762 self::$db_duration += (microtime(true) - $stamp);
763 if (DBA::isResult($r)) {
764 return DBA::toArray($r);
772 * @brief Returns the next jobs that should be executed
774 * @return array array with next jobs
777 private static function nextProcess()
779 $priority = self::nextPriority();
780 if (empty($priority)) {
781 Logger::info('No tasks found');
785 $limit = Config::get('system', 'worker_fetch_limit', 1);
788 $stamp = (float)microtime(true);
789 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
790 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
791 self::$db_duration += (microtime(true) - $stamp);
792 while ($task = DBA::fetch($tasks)) {
793 $ids[] = $task['id'];
794 // Only continue that loop while we are storing commands that can be processed quickly
795 $command = json_decode($task['parameter'])[0];
796 if (!in_array($command, self::FAST_COMMANDS)) {
802 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
807 * @brief Returns the priority of the next workerqueue job
809 * @return string priority
812 private static function nextPriority()
815 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
816 foreach ($priorities as $priority) {
817 $stamp = (float)microtime(true);
818 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
819 $waiting[$priority] = true;
821 self::$db_duration += (microtime(true) - $stamp);
824 if (!empty($waiting[PRIORITY_CRITICAL])) {
825 return PRIORITY_CRITICAL;
830 $stamp = (float)microtime(true);
831 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
832 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
833 WHERE NOT `done` GROUP BY `priority`");
834 self::$db_duration += (microtime(true) - $stamp);
835 while ($process = DBA::fetch($processes)) {
836 $running[$process['priority']] = $process['running'];
837 $running_total += $process['running'];
839 DBA::close($processes);
841 foreach ($priorities as $priority) {
842 if (!empty($waiting[$priority]) && empty($running[$priority])) {
843 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
848 $active = max(self::activeWorkers(), $running_total);
849 $priorities = max(count($waiting), count($running));
853 for ($i = 1; $i <= $priorities; ++$i) {
854 $total += pow($i, $exponent);
858 for ($i = 1; $i <= $priorities; ++$i) {
859 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
863 foreach ($running as $priority => $workers) {
864 if ($workers < $limit[$i++]) {
865 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
870 if (!empty($waiting)) {
871 $priority = array_keys($waiting)[0];
872 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
880 * @brief Find and claim the next worker process for us
882 * @return boolean Have we found something?
883 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
885 private static function findWorkerProcesses()
889 $ids = self::nextProcess();
891 // If there is no result we check without priority limit
893 $limit = Config::get('system', 'worker_fetch_limit', 1);
895 $stamp = (float)microtime(true);
896 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
897 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
898 self::$db_duration += (microtime(true) - $stamp);
900 while ($task = DBA::fetch($tasks)) {
901 $ids[] = $task['id'];
902 // Only continue that loop while we are storing commands that can be processed quickly
903 $command = json_decode($task['parameter'])[0];
904 if (!in_array($command, self::FAST_COMMANDS)) {
912 $stamp = (float)microtime(true);
913 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
914 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
915 self::$db_duration += (microtime(true) - $stamp);
916 self::$db_duration_write += (microtime(true) - $stamp);
923 * @brief Returns the next worker process
925 * @return string SQL statement
926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
928 public static function workerProcess()
930 // There can already be jobs for us in the queue.
931 $waiting = self::getWaitingJobForPID();
932 if (!empty($waiting)) {
936 $stamp = (float)microtime(true);
937 if (!Lock::acquire('worker_process')) {
940 self::$lock_duration += (microtime(true) - $stamp);
942 $found = self::findWorkerProcesses();
944 Lock::release('worker_process');
947 $stamp = (float)microtime(true);
948 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
949 self::$db_duration += (microtime(true) - $stamp);
950 return DBA::toArray($r);
956 * @brief Removes a workerqueue entry from the current process
960 public static function unclaimProcess()
964 $stamp = (float)microtime(true);
965 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
966 self::$db_duration += (microtime(true) - $stamp);
967 self::$db_duration_write += (microtime(true) - $stamp);
971 * @brief Call the front end worker
973 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
975 public static function callWorker()
977 if (!Config::get("system", "frontend_worker")) {
981 $url = System::baseUrl()."/worker";
982 Network::fetchUrl($url, false, 1);
986 * @brief Call the front end worker if there aren't any active
988 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
990 public static function executeIfIdle()
992 if (!Config::get("system", "frontend_worker")) {
996 // Do we have "proc_open"? Then we can fork the worker
997 if (function_exists("proc_open")) {
998 // When was the last time that we called the worker?
999 // Less than one minute? Then we quit
1000 if ((time() - Config::get("system", "worker_started")) < 60) {
1004 Config::set("system", "worker_started", time());
1006 // Do we have enough running workers? Then we quit here.
1007 if (self::tooMuchWorkers()) {
1008 // Cleaning dead processes
1009 self::killStaleWorkers();
1010 Process::deleteInactive();
1017 Logger::log('Call worker', Logger::DEBUG);
1018 self::spawnWorker();
1022 // We cannot execute background processes.
1023 // We now run the processes from the frontend.
1024 // This won't work with long running processes.
1027 self::clearProcesses();
1029 $workers = self::activeWorkers();
1031 if ($workers == 0) {
1037 * @brief Removes long running worker processes
1039 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1041 public static function clearProcesses()
1043 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1045 /// @todo We should clean up the corresponding workerqueue entries as well
1046 $stamp = (float)microtime(true);
1047 $condition = ["`created` < ? AND `command` = 'worker.php'",
1048 DateTimeFormat::utc("now - ".$timeout." minutes")];
1049 DBA::delete('process', $condition);
1050 self::$db_duration = (microtime(true) - $stamp);
1051 self::$db_duration_write += (microtime(true) - $stamp);
1055 * @brief Runs the cron processes
1057 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1059 private static function runCron()
1061 Logger::log('Add cron entries', Logger::DEBUG);
1063 // Check for spooled items
1064 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1066 // Run the cron job that calls all other jobs
1067 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1069 // Cleaning dead processes
1070 self::killStaleWorkers();
1074 * @brief Spawns a new worker
1075 * @param bool $do_cron
1077 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1079 public static function spawnWorker($do_cron = false)
1081 $command = 'bin/worker.php';
1083 $args = ['no_cron' => !$do_cron];
1085 get_app()->proc_run($command, $args);
1087 // after spawning we have to remove the flag.
1088 if (Config::get('system', 'worker_daemon_mode', false)) {
1089 self::IPCSetJobState(false);
1094 * @brief Adds tasks to the worker queue
1096 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1098 * next args are passed as $cmd command line
1099 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1100 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1102 * @return boolean "false" if proc_run couldn't be executed
1103 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1104 * @note $cmd and string args are surrounded with ""
1110 public static function add($cmd)
1112 $args = func_get_args();
1114 if (!count($args)) {
1118 $arr = ['args' => $args, 'run_cmd' => true];
1120 Hook::callAll("proc_run", $arr);
1121 if (!$arr['run_cmd'] || !count($args)) {
1125 $priority = PRIORITY_MEDIUM;
1126 // Don't fork from frontend tasks by default
1127 $dont_fork = Config::get("system", "worker_dont_fork", false) || !\get_app()->isBackend();
1128 $created = DateTimeFormat::utcNow();
1129 $force_priority = false;
1131 $run_parameter = array_shift($args);
1133 if (is_int($run_parameter)) {
1134 $priority = $run_parameter;
1135 } elseif (is_array($run_parameter)) {
1136 if (isset($run_parameter['priority'])) {
1137 $priority = $run_parameter['priority'];
1139 if (isset($run_parameter['created'])) {
1140 $created = $run_parameter['created'];
1142 if (isset($run_parameter['dont_fork'])) {
1143 $dont_fork = $run_parameter['dont_fork'];
1145 if (isset($run_parameter['force_priority'])) {
1146 $force_priority = $run_parameter['force_priority'];
1150 $parameters = json_encode($args);
1151 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1153 // Quit if there was a database error - a precaution for the update process to 3.5.3
1154 if (DBA::errorNo() != 0) {
1159 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1160 } elseif ($force_priority) {
1161 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1164 // Should we quit and wait for the worker to be called as a cronjob?
1169 // If there is a lock then we don't have to check for too much worker
1170 if (!Lock::acquire('worker', 0)) {
1174 // If there are already enough workers running, don't fork another one
1175 $quit = self::tooMuchWorkers();
1176 Lock::release('worker');
1182 // We tell the daemon that a new job entry exists
1183 if (Config::get('system', 'worker_daemon_mode', false)) {
1184 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1188 // Now call the worker to execute the jobs that we just added to the queue
1189 self::spawnWorker();
1195 * Returns the next retrial level for worker jobs.
1196 * This function will skip levels when jobs are older.
1198 * @param array $queue Worker queue entry
1199 * @param integer $max_level maximum retrial level
1200 * @return integer the next retrial level value
1202 private static function getNextRetrial($queue, $max_level)
1204 $created = strtotime($queue['created']);
1205 $retrial_time = time() - $created;
1207 $new_retrial = $queue['retrial'] + 1;
1209 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1210 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1212 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1213 $new_retrial = $retrial;
1216 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1217 return $new_retrial;
1221 * Defers the current worker entry
1223 public static function defer()
1225 if (empty(BaseObject::getApp()->queue)) {
1229 $queue = BaseObject::getApp()->queue;
1231 $retrial = $queue['retrial'];
1233 $priority = $queue['priority'];
1235 $max_level = Config::get('system', 'worker_defer_limit');
1237 $new_retrial = self::getNextRetrial($queue, $max_level);
1239 if ($new_retrial > $max_level) {
1240 Logger::info('The task exceeded the maximum retry count', ['id' => $id, 'max_level' => $max_level, 'retrial' => $new_retrial]);
1244 // Calculate the delay until the next trial
1245 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1246 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1248 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1249 $priority = PRIORITY_MEDIUM;
1250 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1251 $priority = PRIORITY_LOW;
1252 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1253 $priority = PRIORITY_NEGLIGIBLE;
1256 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1258 $stamp = (float)microtime(true);
1259 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1260 DBA::update('workerqueue', $fields, ['id' => $id]);
1261 self::$db_duration += (microtime(true) - $stamp);
1262 self::$db_duration_write += (microtime(true) - $stamp);
1266 * Log active processes into the "process" table
1268 * @brief Log active processes into the "process" table
1270 public static function startProcess()
1272 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1274 $command = basename($trace[0]['file']);
1276 Process::deleteInactive();
1278 Process::insert($command);
1282 * Remove the active process from the "process" table
1284 * @brief Remove the active process from the "process" table
1286 * @throws \Exception
1288 public static function endProcess()
1290 return Process::deleteByPid();
1294 * Set the flag if some job is waiting
1296 * @brief Set the flag if some job is waiting
1297 * @param boolean $jobs Is there a waiting job?
1298 * @throws \Exception
1300 public static function IPCSetJobState($jobs)
1302 $stamp = (float)microtime(true);
1303 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1304 self::$db_duration += (microtime(true) - $stamp);
1305 self::$db_duration_write += (microtime(true) - $stamp);
1309 * Checks if some worker job waits to be executed
1311 * @brief Checks if some worker job waits to be executed
1313 * @throws \Exception
1315 public static function IPCJobsExists()
1317 $stamp = (float)microtime(true);
1318 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1319 self::$db_duration += (microtime(true) - $stamp);
1321 // When we don't have a row, no job is running
1322 if (!DBA::isResult($row)) {
1326 return (bool)$row['jobs'];