4 use Friendica\Core\Config;
5 use Friendica\Util\Lock;
7 if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
8 $directory = dirname($_SERVER["argv"][0]);
10 if (substr($directory, 0, 1) != "/") {
11 $directory = $_SERVER["PWD"]."/".$directory;
13 $directory = realpath($directory."/..");
18 require_once("boot.php");
20 function poller_run($argv, $argc){
23 $a = new App(dirname(__DIR__));
25 @include(".htconfig.php");
26 require_once("include/dba.php");
27 $db = new dba($db_host, $db_user, $db_pass, $db_data);
28 unset($db_host, $db_user, $db_pass, $db_data);
32 // Quit when in maintenance
33 if (Config::get('system', 'maintenance', true)) {
37 $a->set_baseurl(Config::get('system', 'url'));
41 // At first check the maximum load. We shouldn't continue with a high load
42 if ($a->maxload_reached()) {
43 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
47 // We now start the process. This is done after the load check since this could increase the load.
50 // Kill stale processes every 5 minutes
51 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
52 if (time() > ($last_cleanup + 300)) {
53 Config::set('system', 'poller_last_cleaned', time());
54 poller_kill_stale_workers();
57 // Count active workers and compare them with a maximum value that depends on the load
58 if (poller_too_much_workers()) {
59 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
63 // Do we have too few memory?
64 if ($a->min_memory_reached()) {
65 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
69 // Possibly there are too much database connections
70 if (poller_max_connections_reached()) {
71 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
75 // Possibly there are too much database processes that block the system
76 if ($a->max_processes_reached()) {
77 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
81 // Now we start additional cron processes if we should do so
82 if (($argc <= 1) || ($argv[1] != "no_cron")) {
88 // We fetch the next queue entry that is about to be executed
89 while ($r = poller_worker_process()) {
90 foreach ($r AS $entry) {
91 // Assure that the priority is an integer value
92 $entry['priority'] = (int)$entry['priority'];
94 // The work will be done
95 if (!poller_execute($entry)) {
96 logger('Process execution failed, quitting.', LOGGER_DEBUG);
101 // To avoid the quitting of multiple pollers only one poller at a time will execute the check
102 if (Lock::set('poller_worker', 0)) {
103 // Count active workers and compare them with a maximum value that depends on the load
104 if (poller_too_much_workers()) {
105 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
110 if ($a->min_memory_reached()) {
111 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
114 Lock::remove('poller_worker');
117 // Quit the poller once every 5 minutes
118 if (time() > ($starttime + 300)) {
119 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
123 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
127 * @brief Returns the number of non executed entries in the worker queue
129 * @return integer Number of non executed entries in the worker queue
131 function poller_total_entries() {
132 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s'", dbesc(NULL_DATE));
133 return $s[0]["total"];
137 * @brief Returns the highest priority in the worker queue that isn't executed
139 * @return integer Number of active poller processes
141 function poller_highest_priority() {
142 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
143 return $s[0]["priority"];
147 * @brief Returns if a process with the given priority is running
149 * @param integer $priority The priority that should be checked
151 * @return integer Is there a process running with that priority?
153 function poller_process_with_priority_active($priority) {
154 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' LIMIT 1",
155 intval($priority), dbesc(NULL_DATE));
156 return dbm::is_result($s);
160 * @brief Execute a worker entry
162 * @param array $queue Workerqueue entry
164 * @return boolean "true" if further processing should be stopped
166 function poller_execute($queue) {
172 // Quit when in maintenance
173 if (Config::get('system', 'maintenance', true)) {
174 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
178 // Constantly check the number of parallel database processes
179 if ($a->max_processes_reached()) {
180 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
184 // Constantly check the number of available database connections to let the frontend be accessible at any time
185 if (poller_max_connections_reached()) {
186 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
190 $argv = json_decode($queue["parameter"]);
192 // Check for existance and validity of the include file
195 if (!validate_include($include)) {
196 logger("Include file ".$argv[0]." is not valid!");
197 dba::delete('workerqueue', array('id' => $queue["id"]));
201 require_once($include);
203 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
205 if (function_exists($funcname)) {
206 poller_exec_function($queue, $funcname, $argv);
207 dba::delete('workerqueue', array('id' => $queue["id"]));
209 logger("Function ".$funcname." does not exist");
216 * @brief Execute a function from the queue
218 * @param array $queue Workerqueue entry
219 * @param string $funcname name of the function
220 * @param array $argv Array of values to be passed to the function
222 function poller_exec_function($queue, $funcname, $argv) {
228 $argc = count($argv);
230 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
232 $stamp = (float)microtime(true);
234 // We use the callstack here to analyze the performance of executed worker entries.
235 // For this reason the variables have to be initialized.
236 if (Config::get("system", "profiler")) {
237 $a->performance["start"] = microtime(true);
238 $a->performance["database"] = 0;
239 $a->performance["database_write"] = 0;
240 $a->performance["network"] = 0;
241 $a->performance["file"] = 0;
242 $a->performance["rendering"] = 0;
243 $a->performance["parser"] = 0;
244 $a->performance["marktime"] = 0;
245 $a->performance["markstart"] = microtime(true);
246 $a->callstack = array();
249 // For better logging create a new process id for every worker call
250 // But preserve the old one for the worker
251 $old_process_id = $a->process_id;
252 $a->process_id = uniqid("wrk", true);
255 $funcname($argv, $argc);
257 $a->process_id = $old_process_id;
260 $duration = number_format(microtime(true) - $stamp, 3);
262 if ($duration > 3600) {
263 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
264 } elseif ($duration > 600) {
265 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
266 } elseif ($duration > 300) {
267 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
268 } elseif ($duration > 120) {
269 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
272 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
274 // Write down the performance values into the log
275 if (Config::get("system", "profiler")) {
276 $duration = microtime(true)-$a->performance["start"];
278 if (Config::get("rendertime", "callstack")) {
279 if (isset($a->callstack["database"])) {
280 $o = "\nDatabase Read:\n";
281 foreach ($a->callstack["database"] AS $func => $time) {
282 $time = round($time, 3);
284 $o .= $func.": ".$time."\n";
288 if (isset($a->callstack["database_write"])) {
289 $o .= "\nDatabase Write:\n";
290 foreach ($a->callstack["database_write"] AS $func => $time) {
291 $time = round($time, 3);
293 $o .= $func.": ".$time."\n";
297 if (isset($a->callstack["network"])) {
298 $o .= "\nNetwork:\n";
299 foreach ($a->callstack["network"] AS $func => $time) {
300 $time = round($time, 3);
302 $o .= $func.": ".$time."\n";
310 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
311 number_format($a->performance["database"] - $a->performance["database_write"], 2),
312 number_format($a->performance["database_write"], 2),
313 number_format($a->performance["network"], 2),
314 number_format($a->performance["file"], 2),
315 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
316 number_format($duration, 2)),
320 $cooldown = Config::get("system", "worker_cooldown", 0);
323 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
329 * @brief Checks if the number of database connections has reached a critical limit.
331 * @return bool Are more than 3/4 of the maximum connections used?
333 function poller_max_connections_reached() {
335 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
336 $max = Config::get("system", "max_connections");
338 // Fetch the percentage level where the poller will get active
339 $maxlevel = Config::get("system", "max_connections_level", 75);
342 // the maximum number of possible user connections can be a system variable
343 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
344 if (dbm::is_result($r)) {
345 $max = $r[0]["Value"];
347 // Or it can be granted. This overrides the system variable
348 $r = q("SHOW GRANTS");
349 if (dbm::is_result($r)) {
350 foreach ($r AS $grants) {
351 $grant = array_pop($grants);
352 if (stristr($grant, "GRANT USAGE ON")) {
353 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
361 // If $max is set we will use the processlist to determine the current number of connections
362 // The processlist only shows entries of the current user
364 $r = q("SHOW PROCESSLIST");
365 if (!dbm::is_result($r)) {
370 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
372 $level = ($used / $max) * 100;
374 if ($level >= $maxlevel) {
375 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
380 // We will now check for the system values.
381 // This limit could be reached although the user limits are fine.
382 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
383 if (!dbm::is_result($r)) {
386 $max = intval($r[0]["Value"]);
390 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
391 if (!dbm::is_result($r)) {
394 $used = intval($r[0]["Value"]);
398 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
400 $level = $used / $max * 100;
402 if ($level < $maxlevel) {
405 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
410 * @brief fix the queue entry if the worker process died
413 function poller_kill_stale_workers() {
414 $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` > '%s'", dbesc(NULL_DATE));
416 if (!dbm::is_result($r)) {
417 // No processing here needed
421 foreach ($r AS $pid) {
422 if (!posix_kill($pid["pid"], 0)) {
423 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
424 array('pid' => $pid["pid"]));
426 // Kill long running processes
428 // Check if the priority is in a valid range
429 if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
430 $pid["priority"] = PRIORITY_MEDIUM;
433 // Define the maximum durations
434 $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
435 $max_duration = $max_duration_defaults[$pid["priority"]];
437 $argv = json_decode($pid["parameter"]);
438 $argv[0] = basename($argv[0]);
440 // How long is the process already running?
441 $duration = (time() - strtotime($pid["executed"])) / 60;
442 if ($duration > $max_duration) {
443 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
444 posix_kill($pid["pid"], SIGTERM);
446 // We killed the stale process.
447 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
448 // Additionally we are lowering the priority.
449 dba::update('workerqueue',
450 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => PRIORITY_NEGLIGIBLE, 'pid' => 0),
451 array('pid' => $pid["pid"]));
453 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
460 * @brief Checks if the number of active workers exceeds the given limits
462 * @param integer $entries The number of not executed entries in the worker queue
463 * @param integer $top_priority The highest not executed priority in the worker queue
464 * @param boolean $high_running Is a process with priority "$top_priority" running?
466 * @return bool Are there too much workers running?
468 function poller_too_much_workers() {
469 $queues = Config::get("system", "worker_queues", 4);
471 $maxqueues = $queues;
473 $active = poller_active_workers();
475 // Decrease the number of workers at higher load
476 $load = current_load();
478 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
480 $maxworkers = $queues;
482 // Some magical mathemathics to reduce the workers
484 $slope = $maxworkers / pow($maxsysload, $exponent);
485 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
487 if (Config::get('system', 'worker_debug')) {
488 // Create a list of queue entries grouped by their priority
491 // Adding all processes with no workerqueue entry
492 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS (SELECT id FROM `workerqueue` WHERE `workerqueue`.`pid` = `process`.`pid`)");
493 if ($process = dba::fetch($processes)) {
494 $listitem[0] = "0:".$process["running"];
496 dba::close($processes);
498 // Now adding all processes with workerqueue entries
499 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
500 while ($entry = dba::fetch($entries)) {
501 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE `priority` = ?", $entry["priority"]);
502 if ($process = dba::fetch($processes)) {
503 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
505 dba::close($processes);
507 dba::close($entries);
508 $processlist = ' ('.implode(', ', $listitem).')';
511 $entries = poller_total_entries();
513 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
514 $top_priority = poller_highest_priority();
515 $high_running = poller_process_with_priority_active($top_priority);
517 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
518 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
519 $queues = $active + 1;
523 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
525 // Are there fewer workers running as possible? Then fork a new one.
526 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
527 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
528 $args = array("include/poller.php", "no_cron");
534 return $active >= $queues;
538 * @brief Returns the number of active poller processes
540 * @return integer Number of active poller processes
542 function poller_active_workers() {
543 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
545 return $workers[0]["processes"];
549 * @brief Check if we should pass some slow processes
551 * When the active processes of the highest priority are using more than 2/3
552 * of all processes, we let pass slower processes.
554 * @param string $highest_priority Returns the currently highest priority
555 * @return bool We let pass a slower process than $highest_priority
557 function poller_passing_slow(&$highest_priority) {
559 $highest_priority = 0;
561 $r = q("SELECT `priority`
563 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
565 // No active processes at all? Fine
566 if (!dbm::is_result($r)) {
569 $priorities = array();
570 foreach ($r AS $line) {
571 $priorities[] = $line["priority"];
574 if (count($priorities) == 0) {
577 $highest_priority = min($priorities);
579 // The highest process is already the slowest one?
581 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
585 foreach ($priorities AS $priority) {
586 if ($priority == $highest_priority) {
590 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
591 $passing_slow = (($high/count($priorities)) > (2/3));
594 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
596 return $passing_slow;
600 * @brief Find and claim the next worker process for us
602 * @return boolean Have we found something?
604 function find_worker_processes() {
605 // Check if we should pass some low priority process
606 $highest_priority = 0;
609 if (poller_passing_slow($highest_priority)) {
610 // Are there waiting processes with a higher priority than the currently highest?
611 $result = dba::p("UPDATE `workerqueue` SET `executed` = ?, `pid` = ?
612 WHERE `executed` <= ? AND `priority` < ?
613 ORDER BY `priority`, `created` LIMIT 5",
614 datetime_convert(), getmypid(), NULL_DATE, $highest_priority);
615 if (dbm::is_result($result)) {
616 $found = (dba::num_rows($result) > 0);
621 // Give slower processes some processing time
622 $result = dba::p("UPDATE `workerqueue` SET `executed` = ?, `pid` = ?
623 WHERE `executed` <= ? AND `priority` > ?
624 ORDER BY `priority`, `created` LIMIT 1",
625 datetime_convert(), getmypid(), NULL_DATE, $highest_priority);
626 if (dbm::is_result($result)) {
627 $found = (dba::num_rows($result) > 0);
633 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
635 $result = dba::p("UPDATE `workerqueue` SET `executed` = ?, `pid` = ? WHERE `executed` <= ? ORDER BY `priority`, `created` LIMIT 5",
636 datetime_convert(), getmypid(), NULL_DATE);
637 if (dbm::is_result($result)) {
638 $found = (dba::num_rows($result) > 0);
646 * @brief Returns the next worker process
648 * @return string SQL statement
650 function poller_worker_process() {
652 $stamp = (float)microtime(true);
656 $found = find_worker_processes();
657 } while (!$found && (poller_total_entries() > 0) && (--$timeout > 0));
659 logger('Duration: '.number_format(microtime(true) - $stamp, 3), LOGGER_DEBUG);
662 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d", intval(getmypid()));
668 * @brief Removes a workerqueue entry from the current process
670 function poller_unclaim_process() {
673 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid));
677 * @brief Call the front end worker
679 function call_worker() {
680 if (!Config::get("system", "frontend_worker")) {
684 $url = App::get_baseurl()."/worker";
685 fetch_url($url, false, $redirects, 1);
689 * @brief Call the front end worker if there aren't any active
691 function call_worker_if_idle() {
692 if (!Config::get("system", "frontend_worker")) {
696 // Do we have "proc_open"? Then we can fork the poller
697 if (function_exists("proc_open")) {
698 // When was the last time that we called the worker?
699 // Less than one minute? Then we quit
700 if ((time() - Config::get("system", "worker_started")) < 60) {
704 set_config("system", "worker_started", time());
706 // Do we have enough running workers? Then we quit here.
707 if (poller_too_much_workers()) {
708 // Cleaning dead processes
709 poller_kill_stale_workers();
710 get_app()->remove_inactive_processes();
717 logger('Call poller', LOGGER_DEBUG);
719 $args = array("include/poller.php", "no_cron");
725 // We cannot execute background processes.
726 // We now run the processes from the frontend.
727 // This won't work with long running processes.
730 clear_worker_processes();
732 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
734 if ($workers[0]["processes"] == 0) {
740 * @brief Removes long running worker processes
742 function clear_worker_processes() {
743 $timeout = Config::get("system", "frontend_worker_timeout", 10);
745 /// @todo We should clean up the corresponding workerqueue entries as well
746 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
747 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
751 * @brief Runs the cron processes
753 function poller_run_cron() {
754 logger('Add cron entries', LOGGER_DEBUG);
756 // Check for spooled items
757 proc_run(PRIORITY_HIGH, "include/spool_post.php");
759 // Run the cron job that calls all other jobs
760 proc_run(PRIORITY_MEDIUM, "include/cron.php");
762 // Run the cronhooks job separately from cron for being able to use a different timing
763 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
765 // Cleaning dead processes
766 poller_kill_stale_workers();
769 if (array_search(__file__,get_included_files())===0){
770 poller_run($_SERVER["argv"],$_SERVER["argc"]);
772 poller_unclaim_process();
774 get_app()->end_process();
776 Lock::remove('poller_worker');