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");
15 function poller_run(&$argv, &$argc){
23 @include(".htconfig.php");
24 require_once("include/dba.php");
25 $db = new dba($db_host, $db_user, $db_pass, $db_data);
26 unset($db_host, $db_user, $db_pass, $db_data);
29 if (poller_max_connections_reached())
32 if (App::maxload_reached())
35 // Checking the number of workers
36 if (poller_too_much_workers(1)) {
37 poller_kill_stale_workers();
41 if(($argc <= 1) OR ($argv[1] != "no_cron")) {
42 // Run the cron job that calls all other jobs
43 proc_run("php","include/cron.php");
45 // Run the cronhooks job separately from cron for being able to use a different timing
46 proc_run("php","include/cronhooks.php");
48 // Cleaning dead processes
49 poller_kill_stale_workers();
51 // Sleep four seconds before checking for running processes again to avoid having too many workers
54 // Checking number of workers
55 if (poller_too_much_workers(2))
60 while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `created` LIMIT 1")) {
62 // Constantly check the number of available database connections to let the frontend be accessible at any time
63 if (poller_max_connections_reached())
66 // Count active workers and compare them with a maximum value that depends on the load
67 if (poller_too_much_workers(3))
70 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
71 dbesc(datetime_convert()),
75 // Assure that there are no tasks executed twice
76 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
80 logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
84 $argv = json_decode($r[0]["parameter"]);
88 // Check for existance and validity of the include file
91 if (!validate_include($include)) {
92 logger("Include file ".$argv[0]." is not valid!");
93 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
97 require_once($include);
99 $funcname=str_replace(".php", "", basename($argv[0]))."_run";
101 if (function_exists($funcname)) {
102 logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
103 $funcname($argv, $argc);
105 logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." - done");
107 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
109 logger("Function ".$funcname." does not exist");
111 // Quit the poller once every hour
112 if (time() > ($starttime + 3600))
119 * @brief Checks if the number of database connections has reached a critical limit.
121 * @return bool Are more than 3/4 of the maximum connections used?
123 function poller_max_connections_reached() {
125 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
126 $max = get_config("system", "max_connections");
128 // Fetch the percentage level where the poller will get active
129 $maxlevel = get_config("system", "max_connections_level");
134 // the maximum number of possible user connections can be a system variable
135 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
137 $max = $r[0]["Value"];
139 // Or it can be granted. This overrides the system variable
140 $r = q("SHOW GRANTS");
142 foreach ($r AS $grants) {
143 $grant = array_pop($grants);
144 if (stristr($grant, "GRANT USAGE ON"))
145 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
150 // If $max is set we will use the processlist to determine the current number of connections
151 // The processlist only shows entries of the current user
153 $r = q("SHOW PROCESSLIST");
159 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
161 $level = ($used / $max) * 100;
163 if ($level >= $maxlevel) {
164 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
169 // We will now check for the system values.
170 // This limit could be reached although the user limits are fine.
171 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
175 $max = intval($r[0]["Value"]);
179 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
183 $used = intval($r[0]["Value"]);
187 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
189 $level = $used / $max * 100;
191 if ($level < $maxlevel)
194 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
199 * @brief fix the queue entry if the worker process died
202 function poller_kill_stale_workers() {
203 $r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
205 if (!is_array($r) || count($r) == 0) {
206 // No processing here needed
211 if (!posix_kill($pid["pid"], 0))
212 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
213 intval($pid["pid"]));
215 // Kill long running processes
216 $duration = (time() - strtotime($pid["executed"])) / 60;
217 if ($duration > 180) {
218 logger("Worker process ".$pid["pid"]." took more than 3 hours. It will be killed now.");
219 posix_kill($pid["pid"], SIGTERM);
221 // Question: If a process is stale: Should we remove it or should we reschedule it?
222 // By now we rescheduling it. It's maybe not the wisest decision?
223 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
224 intval($pid["pid"]));
226 logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
230 function poller_too_much_workers($stage) {
232 $queues = get_config("system", "worker_queues");
237 $active = poller_active_workers();
239 // Decrease the number of workers at higher load
240 $load = current_load();
242 $maxsysload = intval(get_config('system','maxloadavg'));
246 $maxworkers = $queues;
248 // Some magical mathemathics to reduce the workers
250 $slope = $maxworkers / pow($maxsysload, $exponent);
251 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
253 logger("Current load stage ".$stage.": ".$load." - maximum: ".$maxsysload." - current queues: ".$active." - maximum: ".$queues, LOGGER_DEBUG);
257 return($active >= $queues);
260 function poller_active_workers() {
261 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
263 return($workers[0]["workers"]);
266 if (array_search(__file__,get_included_files())===0){
267 poller_run($_SERVER["argv"],$_SERVER["argc"]);