2 if (!file_exists("boot.php") AND (sizeof($_SERVER["argv"]) != 0)) {
3 $directory = dirname($_SERVER["argv"][0]);
5 if (substr($directory, 0, 1) != "/")
6 $directory = $_SERVER["PWD"]."/".$directory;
8 $directory = realpath($directory."/..");
13 require_once("boot.php");
14 require_once("dbm.php");
16 function poller_run(&$argv, &$argc){
24 @include(".htconfig.php");
25 require_once("include/dba.php");
26 $db = new dba($db_host, $db_user, $db_pass, $db_data);
27 unset($db_host, $db_user, $db_pass, $db_data);
30 $processlist = dbm::processlist();
31 if ($processlist != "")
32 logger("Processlist: ".$processlist, LOGGER_DEBUG);
34 if (poller_max_connections_reached())
37 if (App::maxload_reached())
40 // Checking the number of workers
41 if (poller_too_much_workers(1)) {
42 poller_kill_stale_workers();
46 if(($argc <= 1) OR ($argv[1] != "no_cron")) {
47 // Run the cron job that calls all other jobs
48 proc_run("php","include/cron.php");
50 // Run the cronhooks job separately from cron for being able to use a different timing
51 proc_run("php","include/cronhooks.php");
53 // Cleaning dead processes
54 poller_kill_stale_workers();
56 // Sleep four seconds before checking for running processes again to avoid having too many workers
59 // Checking number of workers
60 if (poller_too_much_workers(2))
65 while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `created` LIMIT 1")) {
67 // Log the type of database processes
68 $processlist = dbm::processlist();
69 if ($processlist != "")
70 logger("Processlist: ".$processlist, LOGGER_DEBUG);
72 // Constantly check the number of available database connections to let the frontend be accessible at any time
73 if (poller_max_connections_reached())
76 // Count active workers and compare them with a maximum value that depends on the load
77 if (poller_too_much_workers(3))
80 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
81 dbesc(datetime_convert()),
85 // Assure that there are no tasks executed twice
86 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
90 logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
94 $argv = json_decode($r[0]["parameter"]);
98 // Check for existance and validity of the include file
101 if (!validate_include($include)) {
102 logger("Include file ".$argv[0]." is not valid!");
103 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
107 require_once($include);
109 $funcname=str_replace(".php", "", basename($argv[0]))."_run";
111 if (function_exists($funcname)) {
112 logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
113 $funcname($argv, $argc);
115 logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." - done");
117 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
119 logger("Function ".$funcname." does not exist");
121 // Quit the poller once every hour
122 if (time() > ($starttime + 3600))
129 * @brief Checks if the number of database connections has reached a critical limit.
131 * @return bool Are more than 3/4 of the maximum connections used?
133 function poller_max_connections_reached() {
135 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
136 $max = get_config("system", "max_connections");
138 // Fetch the percentage level where the poller will get active
139 $maxlevel = get_config("system", "max_connections_level");
144 // the maximum number of possible user connections can be a system variable
145 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
147 $max = $r[0]["Value"];
149 // Or it can be granted. This overrides the system variable
150 $r = q("SHOW GRANTS");
152 foreach ($r AS $grants) {
153 $grant = array_pop($grants);
154 if (stristr($grant, "GRANT USAGE ON"))
155 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
160 // If $max is set we will use the processlist to determine the current number of connections
161 // The processlist only shows entries of the current user
163 $r = q("SHOW PROCESSLIST");
169 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
171 $level = ($used / $max) * 100;
173 if ($level >= $maxlevel) {
174 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
179 // We will now check for the system values.
180 // This limit could be reached although the user limits are fine.
181 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
185 $max = intval($r[0]["Value"]);
189 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
193 $used = intval($r[0]["Value"]);
197 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
199 $level = $used / $max * 100;
201 if ($level < $maxlevel)
204 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
209 * @brief fix the queue entry if the worker process died
212 function poller_kill_stale_workers() {
213 $r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
215 if (!is_array($r) || count($r) == 0) {
216 // No processing here needed
221 if (!posix_kill($pid["pid"], 0))
222 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
223 intval($pid["pid"]));
225 // Kill long running processes
226 $duration = (time() - strtotime($pid["executed"])) / 60;
227 if ($duration > 180) {
228 logger("Worker process ".$pid["pid"]." took more than 3 hours. It will be killed now.");
229 posix_kill($pid["pid"], SIGTERM);
231 // Question: If a process is stale: Should we remove it or should we reschedule it?
232 // By now we rescheduling it. It's maybe not the wisest decision?
233 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
234 intval($pid["pid"]));
236 logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
240 function poller_too_much_workers($stage) {
242 $queues = get_config("system", "worker_queues");
247 $active = poller_active_workers();
249 // Decrease the number of workers at higher load
250 $load = current_load();
252 $maxsysload = intval(get_config('system','maxloadavg'));
256 $maxworkers = $queues;
258 // Some magical mathemathics to reduce the workers
260 $slope = $maxworkers / pow($maxsysload, $exponent);
261 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
263 logger("Current load stage ".$stage.": ".$load." - maximum: ".$maxsysload." - current queues: ".$active." - maximum: ".$queues, LOGGER_DEBUG);
267 return($active >= $queues);
270 function poller_active_workers() {
271 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
273 return($workers[0]["workers"]);
276 if (array_search(__file__,get_included_files())===0){
277 poller_run($_SERVER["argv"],$_SERVER["argc"]);