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 // At first we check the number of workers and quit if there are too much of them
51 // This is done at the top to avoid that too much code is executed without a need to do so,
52 // since the poller mostly quits here.
53 if (poller_too_much_workers()) {
54 poller_kill_stale_workers();
55 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
59 // Do we have too few memory?
60 if ($a->min_memory_reached()) {
61 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
65 // Possibly there are too much database connections
66 if (poller_max_connections_reached()) {
67 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
71 // Possibly there are too much database processes that block the system
72 if ($a->max_processes_reached()) {
73 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
77 // Now we start additional cron processes if we should do so
78 if (($argc <= 1) || ($argv[1] != "no_cron")) {
84 // We fetch the next queue entry that is about to be executed
85 while ($r = poller_worker_process()) {
87 // If we got that queue entry we claim it for us
88 if (!poller_claim_process($r[0])) {
92 // Fetch all workerqueue data while the table is still locked
93 // This is redundant, but this speeds up the processing
94 $entries = poller_total_entries();
95 $top_priority = poller_highest_priority();
96 $high_running = poller_process_with_priority_active($top_priority);
100 // To avoid the quitting of multiple pollers only one poller at a time will execute the check
101 if (Lock::set('poller_worker', 0)) {
102 // Count active workers and compare them with a maximum value that depends on the load
103 if (poller_too_much_workers($entries, $top_priority, $high_running)) {
104 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
109 if ($a->min_memory_reached()) {
110 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
113 Lock::remove('poller_worker');
116 // finally the work will be done
117 if (!poller_execute($r[0])) {
118 logger('Process execution failed, quitting.', LOGGER_DEBUG);
122 // Quit the poller once every hour
123 if (time() > ($starttime + 3600)) {
124 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
128 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
132 * @brief Returns the number of non executed entries in the worker queue
134 * @return integer Number of non executed entries in the worker queue
136 function poller_total_entries() {
137 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s'", dbesc(NULL_DATE));
138 return $s[0]["total"];
142 * @brief Returns the highest priority in the worker queue that isn't executed
144 * @return integer Number of active poller processes
146 function poller_highest_priority() {
147 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
148 return $s[0]["priority"];
152 * @brief Returns if a process with the given priority is running
154 * @param integer $priority The priority that should be checked
156 * @return integer Is there a process running with that priority?
158 function poller_process_with_priority_active($priority) {
159 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' LIMIT 1",
160 intval($priority), dbesc(NULL_DATE));
161 return dbm::is_result($s);
165 * @brief Execute a worker entry
167 * @param array $queue Workerqueue entry
169 * @return boolean "true" if further processing should be stopped
171 function poller_execute($queue) {
177 // Quit when in maintenance
178 if (Config::get('system', 'maintenance', true)) {
179 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
183 // Constantly check the number of parallel database processes
184 if ($a->max_processes_reached()) {
185 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
189 // Constantly check the number of available database connections to let the frontend be accessible at any time
190 if (poller_max_connections_reached()) {
191 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
195 $argv = json_decode($queue["parameter"]);
197 // Check for existance and validity of the include file
200 if (!validate_include($include)) {
201 logger("Include file ".$argv[0]." is not valid!");
202 dba::delete('workerqueue', array('id' => $queue["id"]));
206 require_once($include);
208 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
210 if (function_exists($funcname)) {
211 poller_exec_function($queue, $funcname, $argv);
212 dba::delete('workerqueue', array('id' => $queue["id"]));
214 logger("Function ".$funcname." does not exist");
221 * @brief Execute a function from the queue
223 * @param array $queue Workerqueue entry
224 * @param string $funcname name of the function
225 * @param array $argv Array of values to be passed to the function
227 function poller_exec_function($queue, $funcname, $argv) {
233 $argc = count($argv);
235 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
237 $stamp = (float)microtime(true);
239 // We use the callstack here to analyze the performance of executed worker entries.
240 // For this reason the variables have to be initialized.
241 if (Config::get("system", "profiler")) {
242 $a->performance["start"] = microtime(true);
243 $a->performance["database"] = 0;
244 $a->performance["database_write"] = 0;
245 $a->performance["network"] = 0;
246 $a->performance["file"] = 0;
247 $a->performance["rendering"] = 0;
248 $a->performance["parser"] = 0;
249 $a->performance["marktime"] = 0;
250 $a->performance["markstart"] = microtime(true);
251 $a->callstack = array();
254 // For better logging create a new process id for every worker call
255 // But preserve the old one for the worker
256 $old_process_id = $a->process_id;
257 $a->process_id = uniqid("wrk", true);
259 $funcname($argv, $argc);
261 $a->process_id = $old_process_id;
263 $duration = number_format(microtime(true) - $stamp, 3);
265 if ($duration > 3600) {
266 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
267 } elseif ($duration > 600) {
268 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
269 } elseif ($duration > 300) {
270 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
271 } elseif ($duration > 120) {
272 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
275 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
277 // Write down the performance values into the log
278 if (Config::get("system", "profiler")) {
279 $duration = microtime(true)-$a->performance["start"];
281 if (Config::get("rendertime", "callstack")) {
282 if (isset($a->callstack["database"])) {
283 $o = "\nDatabase Read:\n";
284 foreach ($a->callstack["database"] AS $func => $time) {
285 $time = round($time, 3);
287 $o .= $func.": ".$time."\n";
291 if (isset($a->callstack["database_write"])) {
292 $o .= "\nDatabase Write:\n";
293 foreach ($a->callstack["database_write"] AS $func => $time) {
294 $time = round($time, 3);
296 $o .= $func.": ".$time."\n";
300 if (isset($a->callstack["network"])) {
301 $o .= "\nNetwork:\n";
302 foreach ($a->callstack["network"] AS $func => $time) {
303 $time = round($time, 3);
305 $o .= $func.": ".$time."\n";
313 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
314 number_format($a->performance["database"] - $a->performance["database_write"], 2),
315 number_format($a->performance["database_write"], 2),
316 number_format($a->performance["network"], 2),
317 number_format($a->performance["file"], 2),
318 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
319 number_format($duration, 2)),
323 $cooldown = Config::get("system", "worker_cooldown", 0);
326 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
332 * @brief Checks if the number of database connections has reached a critical limit.
334 * @return bool Are more than 3/4 of the maximum connections used?
336 function poller_max_connections_reached() {
338 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
339 $max = Config::get("system", "max_connections");
341 // Fetch the percentage level where the poller will get active
342 $maxlevel = Config::get("system", "max_connections_level", 75);
345 // the maximum number of possible user connections can be a system variable
346 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
347 if (dbm::is_result($r)) {
348 $max = $r[0]["Value"];
350 // Or it can be granted. This overrides the system variable
351 $r = q("SHOW GRANTS");
352 if (dbm::is_result($r)) {
353 foreach ($r AS $grants) {
354 $grant = array_pop($grants);
355 if (stristr($grant, "GRANT USAGE ON")) {
356 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
364 // If $max is set we will use the processlist to determine the current number of connections
365 // The processlist only shows entries of the current user
367 $r = q("SHOW PROCESSLIST");
368 if (!dbm::is_result($r)) {
373 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
375 $level = ($used / $max) * 100;
377 if ($level >= $maxlevel) {
378 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
383 // We will now check for the system values.
384 // This limit could be reached although the user limits are fine.
385 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
386 if (!dbm::is_result($r)) {
389 $max = intval($r[0]["Value"]);
393 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
394 if (!dbm::is_result($r)) {
397 $used = intval($r[0]["Value"]);
401 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
403 $level = $used / $max * 100;
405 if ($level < $maxlevel) {
408 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
413 * @brief fix the queue entry if the worker process died
416 function poller_kill_stale_workers() {
417 $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` > '%s'", dbesc(NULL_DATE));
419 if (!dbm::is_result($r)) {
420 // No processing here needed
424 foreach ($r AS $pid) {
425 if (!posix_kill($pid["pid"], 0)) {
426 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
427 array('pid' => $pid["pid"]));
429 // Kill long running processes
431 // Check if the priority is in a valid range
432 if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
433 $pid["priority"] = PRIORITY_MEDIUM;
436 // Define the maximum durations
437 $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
438 $max_duration = $max_duration_defaults[$pid["priority"]];
440 $argv = json_decode($pid["parameter"]);
441 $argv[0] = basename($argv[0]);
443 // How long is the process already running?
444 $duration = (time() - strtotime($pid["executed"])) / 60;
445 if ($duration > $max_duration) {
446 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
447 posix_kill($pid["pid"], SIGTERM);
449 // We killed the stale process.
450 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
451 // Additionally we are lowering the priority.
452 dba::update('workerqueue',
453 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => PRIORITY_NEGLIGIBLE, 'pid' => 0),
454 array('pid' => $pid["pid"]));
456 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
463 * @brief Checks if the number of active workers exceeds the given limits
465 * @param integer $entries The number of not executed entries in the worker queue
466 * @param integer $top_priority The highest not executed priority in the worker queue
467 * @param boolean $high_running Is a process with priority "$top_priority" running?
469 * @return bool Are there too much workers running?
471 function poller_too_much_workers($entries = NULL, $top_priority = NULL, $high_running = NULL) {
472 $queues = Config::get("system", "worker_queues", 4);
474 $maxqueues = $queues;
476 $active = poller_active_workers();
478 // Decrease the number of workers at higher load
479 $load = current_load();
481 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
483 $maxworkers = $queues;
485 // Some magical mathemathics to reduce the workers
487 $slope = $maxworkers / pow($maxsysload, $exponent);
488 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
490 if (Config::get('system', 'worker_debug')) {
491 // Create a list of queue entries grouped by their priority
494 // Adding all processes with no workerqueue entry
495 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS (SELECT id FROM `workerqueue` WHERE `workerqueue`.`pid` = `process`.`pid`)");
496 if ($process = dba::fetch($processes)) {
497 $listitem[0] = "0:".$process["running"];
499 dba::close($processes);
501 // Now adding all processes with workerqueue entries
502 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
503 while ($entry = dba::fetch($entries)) {
504 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE `priority` = ?", $entry["priority"]);
505 if ($process = dba::fetch($processes)) {
506 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
508 dba::close($processes);
510 dba::close($entries);
511 $processlist = ' ('.implode(', ', $listitem).')';
514 if (is_null($entries)) {
515 $entries = poller_total_entries();
517 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
518 if (is_null($top_priority)) {
519 $top_priority = poller_highest_priority();
521 if (is_null($high_running)) {
522 $high_running = poller_process_with_priority_active($top_priority);
524 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
525 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
526 $queues = $active + 1;
530 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
532 // Are there fewer workers running as possible? Then fork a new one.
533 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
534 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
535 $args = array("include/poller.php", "no_cron");
541 return $active >= $queues;
545 * @brief Returns the number of active poller processes
547 * @return integer Number of active poller processes
549 function poller_active_workers() {
550 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
552 return $workers[0]["processes"];
556 * @brief Check if we should pass some slow processes
558 * When the active processes of the highest priority are using more than 2/3
559 * of all processes, we let pass slower processes.
561 * @param string $highest_priority Returns the currently highest priority
562 * @return bool We let pass a slower process than $highest_priority
564 function poller_passing_slow(&$highest_priority) {
566 $highest_priority = 0;
568 $r = q("SELECT `priority`
570 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
572 // No active processes at all? Fine
573 if (!dbm::is_result($r)) {
576 $priorities = array();
577 foreach ($r AS $line) {
578 $priorities[] = $line["priority"];
581 if (count($priorities) == 0) {
584 $highest_priority = min($priorities);
586 // The highest process is already the slowest one?
588 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
592 foreach ($priorities AS $priority) {
593 if ($priority == $highest_priority) {
597 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
598 $passing_slow = (($high/count($priorities)) > (2/3));
601 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
603 return $passing_slow;
607 * @brief Returns the next worker process
609 * @return string SQL statement
611 function poller_worker_process() {
613 // Check if we should pass some low priority process
614 $highest_priority = 0;
616 if (poller_passing_slow($highest_priority)) {
617 dba::lock('workerqueue');
619 // Are there waiting processes with a higher priority than the currently highest?
620 $r = q("SELECT * FROM `workerqueue`
621 WHERE `executed` <= '%s' AND `priority` < %d
622 ORDER BY `priority`, `created` LIMIT 1",
624 intval($highest_priority));
625 if (dbm::is_result($r)) {
628 // Give slower processes some processing time
629 $r = q("SELECT * FROM `workerqueue`
630 WHERE `executed` <= '%s' AND `priority` > %d
631 ORDER BY `priority`, `created` LIMIT 1",
633 intval($highest_priority));
635 if (dbm::is_result($r)) {
639 dba::lock('workerqueue');
642 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
643 if (!dbm::is_result($r)) {
644 $r = q("SELECT * FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority`, `created` LIMIT 1", dbesc(NULL_DATE));
647 // We only unlock the tables here, when we got no data
648 if (!dbm::is_result($r)) {
656 * @brief Assigns a workerqueue entry to the current process
658 * When we are sure that the table locks are working correctly, we can remove the checks from here
660 * @param array $queue Workerqueue entry
662 * @return boolean "true" if the claiming was successful
664 function poller_claim_process($queue) {
667 $success = dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid),
668 array('id' => $queue["id"], 'pid' => 0));
671 logger("Couldn't update queue entry ".$queue["id"]." - skip this execution", LOGGER_DEBUG);
675 // Assure that there are no tasks executed twice
676 $id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
678 logger("Queue item ".$queue["id"]." vanished - skip this execution", LOGGER_DEBUG);
680 } elseif ((strtotime($id[0]["executed"]) <= 0) || ($id[0]["pid"] == 0)) {
681 logger("Entry for queue item ".$queue["id"]." wasn't stored - skip this execution", LOGGER_DEBUG);
683 } elseif ($id[0]["pid"] != $mypid) {
684 logger("Queue item ".$queue["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
691 * @brief Removes a workerqueue entry from the current process
693 function poller_unclaim_process() {
696 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid));
700 * @brief Call the front end worker
702 function call_worker() {
703 if (!Config::get("system", "frontend_worker")) {
707 $url = App::get_baseurl()."/worker";
708 fetch_url($url, false, $redirects, 1);
712 * @brief Call the front end worker if there aren't any active
714 function call_worker_if_idle() {
715 if (!Config::get("system", "frontend_worker")) {
719 // Do we have "proc_open"? Then we can fork the poller
720 if (function_exists("proc_open")) {
721 // When was the last time that we called the worker?
722 // Less than one minute? Then we quit
723 if ((time() - Config::get("system", "worker_started")) < 60) {
727 set_config("system", "worker_started", time());
729 // Do we have enough running workers? Then we quit here.
730 if (poller_too_much_workers()) {
731 // Cleaning dead processes
732 poller_kill_stale_workers();
733 get_app()->remove_inactive_processes();
740 logger('Call poller', LOGGER_DEBUG);
742 $args = array("include/poller.php", "no_cron");
748 // We cannot execute background processes.
749 // We now run the processes from the frontend.
750 // This won't work with long running processes.
753 clear_worker_processes();
755 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
757 if ($workers[0]["processes"] == 0) {
763 * @brief Removes long running worker processes
765 function clear_worker_processes() {
766 $timeout = Config::get("system", "frontend_worker_timeout", 10);
768 /// @todo We should clean up the corresponding workerqueue entries as well
769 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
770 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
774 * @brief Runs the cron processes
776 function poller_run_cron() {
777 logger('Add cron entries', LOGGER_DEBUG);
779 // Check for spooled items
780 proc_run(PRIORITY_HIGH, "include/spool_post.php");
782 // Run the cron job that calls all other jobs
783 proc_run(PRIORITY_MEDIUM, "include/cron.php");
785 // Run the cronhooks job separately from cron for being able to use a different timing
786 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
788 // Cleaning dead processes
789 poller_kill_stale_workers();
792 if (array_search(__file__,get_included_files())===0){
793 poller_run($_SERVER["argv"],$_SERVER["argc"]);
795 poller_unclaim_process();
797 get_app()->end_process();
799 Lock::remove('poller_worker');