4 use Friendica\Core\Config;
5 use Friendica\Util\Lock;
7 if (!file_exists("boot.php") AND (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) OR ($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 // To avoid the quitting of multiple pollers we serialize the next check
93 if (!Lock::set('poller_worker')) {
94 logger('Cannot get a lock, retrying.', LOGGER_DEBUG);
95 poller_unclaim_process();
99 // Count active workers and compare them with a maximum value that depends on the load
100 if (poller_too_much_workers()) {
101 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
105 Lock::remove('poller_worker');
108 if ($a->min_memory_reached()) {
109 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
113 // finally the work will be done
114 if (!poller_execute($r[0])) {
115 logger('Process execution failed, quitting.', LOGGER_DEBUG);
119 // Quit the poller once every hour
120 if (time() > ($starttime + 3600)) {
121 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
125 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
129 * @brief Execute a worker entry
131 * @param array $queue Workerqueue entry
133 * @return boolean "true" if further processing should be stopped
135 function poller_execute($queue) {
141 // Quit when in maintenance
142 if (Config::get('system', 'maintenance', true)) {
143 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
147 // Constantly check the number of parallel database processes
148 if ($a->max_processes_reached()) {
149 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
153 // Constantly check the number of available database connections to let the frontend be accessible at any time
154 if (poller_max_connections_reached()) {
155 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
159 $argv = json_decode($queue["parameter"]);
161 // Check for existance and validity of the include file
164 if (!validate_include($include)) {
165 logger("Include file ".$argv[0]." is not valid!");
166 dba::delete('workerqueue', array('id' => $queue["id"]));
170 require_once($include);
172 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
174 if (function_exists($funcname)) {
175 poller_exec_function($queue, $funcname, $argv);
176 dba::delete('workerqueue', array('id' => $queue["id"]));
178 logger("Function ".$funcname." does not exist");
185 * @brief Execute a function from the queue
187 * @param array $queue Workerqueue entry
188 * @param string $funcname name of the function
189 * @param array $argv Array of values to be passed to the function
191 function poller_exec_function($queue, $funcname, $argv) {
197 $argc = count($argv);
199 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
201 $stamp = (float)microtime(true);
203 // We use the callstack here to analyze the performance of executed worker entries.
204 // For this reason the variables have to be initialized.
205 if (Config::get("system", "profiler")) {
206 $a->performance["start"] = microtime(true);
207 $a->performance["database"] = 0;
208 $a->performance["database_write"] = 0;
209 $a->performance["network"] = 0;
210 $a->performance["file"] = 0;
211 $a->performance["rendering"] = 0;
212 $a->performance["parser"] = 0;
213 $a->performance["marktime"] = 0;
214 $a->performance["markstart"] = microtime(true);
215 $a->callstack = array();
218 // For better logging create a new process id for every worker call
219 // But preserve the old one for the worker
220 $old_process_id = $a->process_id;
221 $a->process_id = uniqid("wrk", true);
223 $funcname($argv, $argc);
225 $a->process_id = $old_process_id;
227 $duration = number_format(microtime(true) - $stamp, 3);
229 if ($duration > 3600) {
230 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
231 } elseif ($duration > 600) {
232 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
233 } elseif ($duration > 300) {
234 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
235 } elseif ($duration > 120) {
236 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
239 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
241 // Write down the performance values into the log
242 if (Config::get("system", "profiler")) {
243 $duration = microtime(true)-$a->performance["start"];
245 if (Config::get("rendertime", "callstack")) {
246 if (isset($a->callstack["database"])) {
247 $o = "\nDatabase Read:\n";
248 foreach ($a->callstack["database"] AS $func => $time) {
249 $time = round($time, 3);
251 $o .= $func.": ".$time."\n";
255 if (isset($a->callstack["database_write"])) {
256 $o .= "\nDatabase Write:\n";
257 foreach ($a->callstack["database_write"] AS $func => $time) {
258 $time = round($time, 3);
260 $o .= $func.": ".$time."\n";
264 if (isset($a->callstack["network"])) {
265 $o .= "\nNetwork:\n";
266 foreach ($a->callstack["network"] AS $func => $time) {
267 $time = round($time, 3);
269 $o .= $func.": ".$time."\n";
277 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
278 number_format($a->performance["database"] - $a->performance["database_write"], 2),
279 number_format($a->performance["database_write"], 2),
280 number_format($a->performance["network"], 2),
281 number_format($a->performance["file"], 2),
282 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
283 number_format($duration, 2)),
287 $cooldown = Config::get("system", "worker_cooldown", 0);
290 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
296 * @brief Checks if the number of database connections has reached a critical limit.
298 * @return bool Are more than 3/4 of the maximum connections used?
300 function poller_max_connections_reached() {
302 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
303 $max = Config::get("system", "max_connections");
305 // Fetch the percentage level where the poller will get active
306 $maxlevel = Config::get("system", "max_connections_level", 75);
309 // the maximum number of possible user connections can be a system variable
310 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
311 if (dbm::is_result($r)) {
312 $max = $r[0]["Value"];
314 // Or it can be granted. This overrides the system variable
315 $r = q("SHOW GRANTS");
316 if (dbm::is_result($r)) {
317 foreach ($r AS $grants) {
318 $grant = array_pop($grants);
319 if (stristr($grant, "GRANT USAGE ON")) {
320 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
328 // If $max is set we will use the processlist to determine the current number of connections
329 // The processlist only shows entries of the current user
331 $r = q("SHOW PROCESSLIST");
332 if (!dbm::is_result($r)) {
337 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
339 $level = ($used / $max) * 100;
341 if ($level >= $maxlevel) {
342 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
347 // We will now check for the system values.
348 // This limit could be reached although the user limits are fine.
349 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
350 if (!dbm::is_result($r)) {
353 $max = intval($r[0]["Value"]);
357 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
358 if (!dbm::is_result($r)) {
361 $used = intval($r[0]["Value"]);
365 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
367 $level = $used / $max * 100;
369 if ($level < $maxlevel) {
372 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
377 * @brief fix the queue entry if the worker process died
380 function poller_kill_stale_workers() {
381 $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` > '%s'", dbesc(NULL_DATE));
383 if (!dbm::is_result($r)) {
384 // No processing here needed
388 foreach ($r AS $pid) {
389 if (!posix_kill($pid["pid"], 0)) {
390 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
391 array('pid' => $pid["pid"]));
393 // Kill long running processes
395 // Check if the priority is in a valid range
396 if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
397 $pid["priority"] = PRIORITY_MEDIUM;
399 // Define the maximum durations
400 $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
401 $max_duration = $max_duration_defaults[$pid["priority"]];
403 $argv = json_decode($pid["parameter"]);
404 $argv[0] = basename($argv[0]);
406 // How long is the process already running?
407 $duration = (time() - strtotime($pid["executed"])) / 60;
408 if ($duration > $max_duration) {
409 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
410 posix_kill($pid["pid"], SIGTERM);
412 // We killed the stale process.
413 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
414 // Additionally we are lowering the priority.
415 dba::update('workerqueue',
416 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => PRIORITY_NEGLIGIBLE, 'pid' => 0),
417 array('pid' => $pid["pid"]));
419 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
426 * @brief Checks if the number of active workers exceeds the given limits
428 * @return bool Are there too much workers running?
430 function poller_too_much_workers() {
431 $queues = Config::get("system", "worker_queues", 4);
433 $maxqueues = $queues;
435 $active = poller_active_workers();
437 // Decrease the number of workers at higher load
438 $load = current_load();
440 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
442 $maxworkers = $queues;
444 // Some magical mathemathics to reduce the workers
446 $slope = $maxworkers / pow($maxsysload, $exponent);
447 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
449 // Create a list of queue entries grouped by their priority
452 // Adding all processes with no workerqueue entry
453 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS (SELECT id FROM `workerqueue` WHERE `workerqueue`.`pid` = `process`.`pid`)");
454 if ($process = dba::fetch($processes)) {
455 $listitem[0] = "0:".$process["running"];
457 dba::close($processes);
459 // Now adding all processes with workerqueue entries
460 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
461 while ($entry = dba::fetch($entries)) {
462 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE `priority` = ?", $entry["priority"]);
463 if ($process = dba::fetch($processes)) {
464 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
466 dba::close($processes);
468 dba::close($entries);
470 $processlist = implode(', ', $listitem);
472 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s'", dbesc(NULL_DATE));
473 $entries = $s[0]["total"];
475 if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
476 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
477 $top_priority = $s[0]["priority"];
479 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' LIMIT 1",
480 intval($top_priority), dbesc(NULL_DATE));
481 $high_running = dbm::is_result($s);
483 if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
484 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
485 $queues = $active + 1;
489 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries." (".$processlist.") - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
491 // Are there fewer workers running as possible? Then fork a new one.
492 if (!Config::get("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
493 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
494 $args = array("include/poller.php", "no_cron");
500 return $active >= $queues;
504 * @brief Returns the number of active poller processes
506 * @return integer Number of active poller processes
508 function poller_active_workers() {
509 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
511 return $workers[0]["processes"];
515 * @brief Check if we should pass some slow processes
517 * When the active processes of the highest priority are using more than 2/3
518 * of all processes, we let pass slower processes.
520 * @param string $highest_priority Returns the currently highest priority
521 * @return bool We let pass a slower process than $highest_priority
523 function poller_passing_slow(&$highest_priority) {
525 $highest_priority = 0;
527 $r = q("SELECT `priority`
529 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
531 // No active processes at all? Fine
532 if (!dbm::is_result($r)) {
535 $priorities = array();
536 foreach ($r AS $line) {
537 $priorities[] = $line["priority"];
540 if (count($priorities) == 0) {
543 $highest_priority = min($priorities);
545 // The highest process is already the slowest one?
547 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
551 foreach ($priorities AS $priority) {
552 if ($priority == $highest_priority) {
556 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
557 $passing_slow = (($high/count($priorities)) > (2/3));
560 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
562 return $passing_slow;
566 * @brief Returns the next worker process
568 * @return string SQL statement
570 function poller_worker_process() {
572 // Check if we should pass some low priority process
573 $highest_priority = 0;
575 if (poller_passing_slow($highest_priority)) {
576 dba::lock('workerqueue');
578 // Are there waiting processes with a higher priority than the currently highest?
579 $r = q("SELECT * FROM `workerqueue`
580 WHERE `executed` <= '%s' AND `priority` < %d
581 ORDER BY `priority`, `created` LIMIT 1",
583 intval($highest_priority));
584 if (dbm::is_result($r)) {
587 // Give slower processes some processing time
588 $r = q("SELECT * FROM `workerqueue`
589 WHERE `executed` <= '%s' AND `priority` > %d
590 ORDER BY `priority`, `created` LIMIT 1",
592 intval($highest_priority));
594 if (dbm::is_result($r)) {
598 dba::lock('workerqueue');
601 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
602 if (!dbm::is_result($r)) {
603 $r = q("SELECT * FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority`, `created` LIMIT 1", dbesc(NULL_DATE));
606 // We only unlock the tables here, when we got no data
607 if (!dbm::is_result($r)) {
615 * @brief Assigns a workerqueue entry to the current process
617 * When we are sure that the table locks are working correctly, we can remove the checks from here
619 * @param array $queue Workerqueue entry
621 * @return boolean "true" if the claiming was successful
623 function poller_claim_process($queue) {
626 $success = dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid),
627 array('id' => $queue["id"], 'pid' => 0));
631 logger("Couldn't update queue entry ".$queue["id"]." - skip this execution", LOGGER_DEBUG);
635 // Assure that there are no tasks executed twice
636 $id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
638 logger("Queue item ".$queue["id"]." vanished - skip this execution", LOGGER_DEBUG);
640 } elseif ((strtotime($id[0]["executed"]) <= 0) OR ($id[0]["pid"] == 0)) {
641 logger("Entry for queue item ".$queue["id"]." wasn't stored - skip this execution", LOGGER_DEBUG);
643 } elseif ($id[0]["pid"] != $mypid) {
644 logger("Queue item ".$queue["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
651 * @brief Removes a workerqueue entry from the current process
653 function poller_unclaim_process() {
656 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid));
660 * @brief Call the front end worker
662 function call_worker() {
663 if (!Config::get("system", "frontend_worker")) {
667 $url = App::get_baseurl()."/worker";
668 fetch_url($url, false, $redirects, 1);
672 * @brief Call the front end worker if there aren't any active
674 function call_worker_if_idle() {
675 if (!Config::get("system", "frontend_worker")) {
679 // Do we have "proc_open"? Then we can fork the poller
680 if (function_exists("proc_open")) {
681 // When was the last time that we called the worker?
682 // Less than one minute? Then we quit
683 if ((time() - Config::get("system", "worker_started")) < 60) {
687 set_config("system", "worker_started", time());
689 // Do we have enough running workers? Then we quit here.
690 if (poller_too_much_workers()) {
691 // Cleaning dead processes
692 poller_kill_stale_workers();
693 get_app()->remove_inactive_processes();
700 logger('Call poller', LOGGER_DEBUG);
702 $args = array("include/poller.php", "no_cron");
708 // We cannot execute background processes.
709 // We now run the processes from the frontend.
710 // This won't work with long running processes.
713 clear_worker_processes();
715 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
717 if ($workers[0]["processes"] == 0) {
723 * @brief Removes long running worker processes
725 function clear_worker_processes() {
726 $timeout = Config::get("system", "frontend_worker_timeout", 10);
728 /// @todo We should clean up the corresponding workerqueue entries as well
729 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
730 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
734 * @brief Runs the cron processes
736 function poller_run_cron() {
737 logger('Add cron entries', LOGGER_DEBUG);
739 // Check for spooled items
740 proc_run(PRIORITY_HIGH, "include/spool_post.php");
742 // Run the cron job that calls all other jobs
743 proc_run(PRIORITY_MEDIUM, "include/cron.php");
745 // Run the cronhooks job separately from cron for being able to use a different timing
746 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
748 // Cleaning dead processes
749 poller_kill_stale_workers();
752 if (array_search(__file__,get_included_files())===0){
753 poller_run($_SERVER["argv"],$_SERVER["argc"]);
755 Lock::remove('poller_worker');
757 poller_unclaim_process();
759 get_app()->end_process();