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 if (dbm::is_result($s)) {
134 return $s[0]["total"];
141 * @brief Returns the highest priority in the worker queue that isn't executed
143 * @return integer Number of active poller processes
145 function poller_highest_priority() {
146 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
147 if (dbm::is_result($s)) {
148 return $s[0]["priority"];
155 * @brief Returns if a process with the given priority is running
157 * @param integer $priority The priority that should be checked
159 * @return integer Is there a process running with that priority?
161 function poller_process_with_priority_active($priority) {
162 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' LIMIT 1",
163 intval($priority), dbesc(NULL_DATE));
164 return dbm::is_result($s);
168 * @brief Execute a worker entry
170 * @param array $queue Workerqueue entry
172 * @return boolean "true" if further processing should be stopped
174 function poller_execute($queue) {
180 // Quit when in maintenance
181 if (Config::get('system', 'maintenance', true)) {
182 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
186 // Constantly check the number of parallel database processes
187 if ($a->max_processes_reached()) {
188 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
192 // Constantly check the number of available database connections to let the frontend be accessible at any time
193 if (poller_max_connections_reached()) {
194 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
198 $argv = json_decode($queue["parameter"]);
200 // Check for existance and validity of the include file
203 if (!validate_include($include)) {
204 logger("Include file ".$argv[0]." is not valid!");
205 dba::delete('workerqueue', array('id' => $queue["id"]));
209 require_once($include);
211 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
213 if (function_exists($funcname)) {
214 poller_exec_function($queue, $funcname, $argv);
215 dba::delete('workerqueue', array('id' => $queue["id"]));
217 logger("Function ".$funcname." does not exist");
224 * @brief Execute a function from the queue
226 * @param array $queue Workerqueue entry
227 * @param string $funcname name of the function
228 * @param array $argv Array of values to be passed to the function
230 function poller_exec_function($queue, $funcname, $argv) {
236 $argc = count($argv);
238 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
240 $stamp = (float)microtime(true);
242 // We use the callstack here to analyze the performance of executed worker entries.
243 // For this reason the variables have to be initialized.
244 if (Config::get("system", "profiler")) {
245 $a->performance["start"] = microtime(true);
246 $a->performance["database"] = 0;
247 $a->performance["database_write"] = 0;
248 $a->performance["network"] = 0;
249 $a->performance["file"] = 0;
250 $a->performance["rendering"] = 0;
251 $a->performance["parser"] = 0;
252 $a->performance["marktime"] = 0;
253 $a->performance["markstart"] = microtime(true);
254 $a->callstack = array();
257 // For better logging create a new process id for every worker call
258 // But preserve the old one for the worker
259 $old_process_id = $a->process_id;
260 $a->process_id = uniqid("wrk", true);
263 $funcname($argv, $argc);
265 $a->process_id = $old_process_id;
268 $duration = number_format(microtime(true) - $stamp, 3);
270 if ($duration > 3600) {
271 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
272 } elseif ($duration > 600) {
273 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
274 } elseif ($duration > 300) {
275 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
276 } elseif ($duration > 120) {
277 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
280 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
282 // Write down the performance values into the log
283 if (Config::get("system", "profiler")) {
284 $duration = microtime(true)-$a->performance["start"];
286 if (Config::get("rendertime", "callstack")) {
287 if (isset($a->callstack["database"])) {
288 $o = "\nDatabase Read:\n";
289 foreach ($a->callstack["database"] AS $func => $time) {
290 $time = round($time, 3);
292 $o .= $func.": ".$time."\n";
296 if (isset($a->callstack["database_write"])) {
297 $o .= "\nDatabase Write:\n";
298 foreach ($a->callstack["database_write"] AS $func => $time) {
299 $time = round($time, 3);
301 $o .= $func.": ".$time."\n";
305 if (isset($a->callstack["network"])) {
306 $o .= "\nNetwork:\n";
307 foreach ($a->callstack["network"] AS $func => $time) {
308 $time = round($time, 3);
310 $o .= $func.": ".$time."\n";
318 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
319 number_format($a->performance["database"] - $a->performance["database_write"], 2),
320 number_format($a->performance["database_write"], 2),
321 number_format($a->performance["network"], 2),
322 number_format($a->performance["file"], 2),
323 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
324 number_format($duration, 2)),
328 $cooldown = Config::get("system", "worker_cooldown", 0);
331 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
337 * @brief Checks if the number of database connections has reached a critical limit.
339 * @return bool Are more than 3/4 of the maximum connections used?
341 function poller_max_connections_reached() {
343 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
344 $max = Config::get("system", "max_connections");
346 // Fetch the percentage level where the poller will get active
347 $maxlevel = Config::get("system", "max_connections_level", 75);
350 // the maximum number of possible user connections can be a system variable
351 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
352 if (dbm::is_result($r)) {
353 $max = $r[0]["Value"];
355 // Or it can be granted. This overrides the system variable
356 $r = q("SHOW GRANTS");
357 if (dbm::is_result($r)) {
358 foreach ($r AS $grants) {
359 $grant = array_pop($grants);
360 if (stristr($grant, "GRANT USAGE ON")) {
361 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
369 // If $max is set we will use the processlist to determine the current number of connections
370 // The processlist only shows entries of the current user
372 $r = q("SHOW PROCESSLIST");
373 if (!dbm::is_result($r)) {
378 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
380 $level = ($used / $max) * 100;
382 if ($level >= $maxlevel) {
383 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
388 // We will now check for the system values.
389 // This limit could be reached although the user limits are fine.
390 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
391 if (!dbm::is_result($r)) {
394 $max = intval($r[0]["Value"]);
398 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
399 if (!dbm::is_result($r)) {
402 $used = intval($r[0]["Value"]);
406 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
408 $level = $used / $max * 100;
410 if ($level < $maxlevel) {
413 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
418 * @brief fix the queue entry if the worker process died
421 function poller_kill_stale_workers() {
422 $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` > '%s'", dbesc(NULL_DATE));
424 if (!dbm::is_result($r)) {
425 // No processing here needed
429 foreach ($r AS $pid) {
430 if (!posix_kill($pid["pid"], 0)) {
431 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
432 array('pid' => $pid["pid"]));
434 // Kill long running processes
436 // Check if the priority is in a valid range
437 if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
438 $pid["priority"] = PRIORITY_MEDIUM;
441 // Define the maximum durations
442 $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
443 $max_duration = $max_duration_defaults[$pid["priority"]];
445 $argv = json_decode($pid["parameter"]);
446 $argv[0] = basename($argv[0]);
448 // How long is the process already running?
449 $duration = (time() - strtotime($pid["executed"])) / 60;
450 if ($duration > $max_duration) {
451 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
452 posix_kill($pid["pid"], SIGTERM);
454 // We killed the stale process.
455 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
456 // Additionally we are lowering the priority.
457 dba::update('workerqueue',
458 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => PRIORITY_NEGLIGIBLE, 'pid' => 0),
459 array('pid' => $pid["pid"]));
461 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
468 * @brief Checks if the number of active workers exceeds the given limits
470 * @return bool Are there too much workers running?
472 function poller_too_much_workers() {
473 $queues = Config::get("system", "worker_queues", 4);
475 $maxqueues = $queues;
477 $active = poller_active_workers();
479 // Decrease the number of workers at higher load
480 $load = current_load();
482 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
484 $maxworkers = $queues;
486 // Some magical mathemathics to reduce the workers
488 $slope = $maxworkers / pow($maxsysload, $exponent);
489 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
491 if (Config::get('system', 'worker_debug')) {
492 // Create a list of queue entries grouped by their priority
495 // Adding all processes with no workerqueue entry
496 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS (SELECT id FROM `workerqueue` WHERE `workerqueue`.`pid` = `process`.`pid`)");
497 if ($process = dba::fetch($processes)) {
498 $listitem[0] = "0:".$process["running"];
500 dba::close($processes);
502 // Now adding all processes with workerqueue entries
503 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
504 while ($entry = dba::fetch($entries)) {
505 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE `priority` = ?", $entry["priority"]);
506 if ($process = dba::fetch($processes)) {
507 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
509 dba::close($processes);
511 dba::close($entries);
512 $processlist = ' ('.implode(', ', $listitem).')';
515 $entries = poller_total_entries();
517 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
518 $top_priority = poller_highest_priority();
519 $high_running = poller_process_with_priority_active($top_priority);
521 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
522 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
523 $queues = $active + 1;
527 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
529 // Are there fewer workers running as possible? Then fork a new one.
530 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
531 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
532 $args = array("include/poller.php", "no_cron");
538 return $active >= $queues;
542 * @brief Returns the number of active poller processes
544 * @return integer Number of active poller processes
546 function poller_active_workers() {
547 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
549 return $workers[0]["processes"];
553 * @brief Check if we should pass some slow processes
555 * When the active processes of the highest priority are using more than 2/3
556 * of all processes, we let pass slower processes.
558 * @param string $highest_priority Returns the currently highest priority
559 * @return bool We let pass a slower process than $highest_priority
561 function poller_passing_slow(&$highest_priority) {
563 $highest_priority = 0;
565 $r = q("SELECT `priority`
567 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
569 // No active processes at all? Fine
570 if (!dbm::is_result($r)) {
573 $priorities = array();
574 foreach ($r AS $line) {
575 $priorities[] = $line["priority"];
578 if (count($priorities) == 0) {
581 $highest_priority = min($priorities);
583 // The highest process is already the slowest one?
585 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
589 foreach ($priorities AS $priority) {
590 if ($priority == $highest_priority) {
594 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
595 $passing_slow = (($high/count($priorities)) > (2/3));
598 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
600 return $passing_slow;
604 * @brief Find and claim the next worker process for us
606 * @return boolean Have we found something?
608 function find_worker_processes() {
609 // Check if we should pass some low priority process
610 $highest_priority = 0;
613 if (poller_passing_slow($highest_priority)) {
614 // Are there waiting processes with a higher priority than the currently highest?
615 $result = dba::e("UPDATE `workerqueue` SET `executed` = ?, `pid` = ?
616 WHERE `executed` <= ? AND `priority` < ?
617 ORDER BY `priority`, `created` LIMIT 5",
618 datetime_convert(), getmypid(), NULL_DATE, $highest_priority);
620 $found = (dba::affected_rows() > 0);
624 // Give slower processes some processing time
625 $result = dba::e("UPDATE `workerqueue` SET `executed` = ?, `pid` = ?
626 WHERE `executed` <= ? AND `priority` > ?
627 ORDER BY `priority`, `created` LIMIT 1",
628 datetime_convert(), getmypid(), NULL_DATE, $highest_priority);
630 $found = (dba::affected_rows() > 0);
635 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
637 $result = dba::e("UPDATE `workerqueue` SET `executed` = ?, `pid` = ? WHERE `executed` <= ? ORDER BY `priority`, `created` LIMIT 5",
638 datetime_convert(), getmypid(), NULL_DATE);
640 $found = (dba::affected_rows() > 0);
647 * @brief Returns the next worker process
649 * @return string SQL statement
651 function poller_worker_process() {
653 $stamp = (float)microtime(true);
657 $found = find_worker_processes();
658 } while (!$found && (poller_total_entries() > 0) && (--$timeout > 0));
660 logger('Duration: '.number_format(microtime(true) - $stamp, 3), LOGGER_DEBUG);
663 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d", intval(getmypid()));
669 * @brief Removes a workerqueue entry from the current process
671 function poller_unclaim_process() {
674 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid));
678 * @brief Call the front end worker
680 function call_worker() {
681 if (!Config::get("system", "frontend_worker")) {
685 $url = App::get_baseurl()."/worker";
686 fetch_url($url, false, $redirects, 1);
690 * @brief Call the front end worker if there aren't any active
692 function call_worker_if_idle() {
693 if (!Config::get("system", "frontend_worker")) {
697 // Do we have "proc_open"? Then we can fork the poller
698 if (function_exists("proc_open")) {
699 // When was the last time that we called the worker?
700 // Less than one minute? Then we quit
701 if ((time() - Config::get("system", "worker_started")) < 60) {
705 set_config("system", "worker_started", time());
707 // Do we have enough running workers? Then we quit here.
708 if (poller_too_much_workers()) {
709 // Cleaning dead processes
710 poller_kill_stale_workers();
711 get_app()->remove_inactive_processes();
718 logger('Call poller', LOGGER_DEBUG);
720 $args = array("include/poller.php", "no_cron");
726 // We cannot execute background processes.
727 // We now run the processes from the frontend.
728 // This won't work with long running processes.
731 clear_worker_processes();
733 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
735 if ($workers[0]["processes"] == 0) {
741 * @brief Removes long running worker processes
743 function clear_worker_processes() {
744 $timeout = Config::get("system", "frontend_worker_timeout", 10);
746 /// @todo We should clean up the corresponding workerqueue entries as well
747 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
748 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
752 * @brief Runs the cron processes
754 function poller_run_cron() {
755 logger('Add cron entries', LOGGER_DEBUG);
757 // Check for spooled items
758 proc_run(PRIORITY_HIGH, "include/spool_post.php");
760 // Run the cron job that calls all other jobs
761 proc_run(PRIORITY_MEDIUM, "include/cron.php");
763 // Run the cronhooks job separately from cron for being able to use a different timing
764 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
766 // Cleaning dead processes
767 poller_kill_stale_workers();
770 if (array_search(__file__,get_included_files())===0){
771 poller_run($_SERVER["argv"],$_SERVER["argc"]);
773 poller_unclaim_process();
775 get_app()->end_process();
777 Lock::remove('poller_worker');