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["list"] != "") {
32 logger("Processcheck: Processes: ".$processlist["amount"]." - Processlist: ".$processlist["list"], LOGGER_DEBUG);
34 $max_processes = get_config('system', 'max_processes_backend');
35 if (intval($max_processes) == 0)
38 if ($processlist["amount"] > $max_processes) {
39 logger("Processcheck: Maximum number of processes for backend tasks (".$max_processes.") reached.", LOGGER_DEBUG);
44 if (poller_max_connections_reached())
47 if (App::maxload_reached())
50 // Checking the number of workers
51 if (poller_too_much_workers(1)) {
52 poller_kill_stale_workers();
56 if(($argc <= 1) OR ($argv[1] != "no_cron")) {
57 // Run the cron job that calls all other jobs
58 proc_run("php","include/cron.php");
60 // Run the cronhooks job separately from cron for being able to use a different timing
61 proc_run("php","include/cronhooks.php");
63 // Cleaning dead processes
64 poller_kill_stale_workers();
66 // Sleep four seconds before checking for running processes again to avoid having too many workers
69 // Checking number of workers
70 if (poller_too_much_workers(2))
75 while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `created` LIMIT 1")) {
77 // Log the type of database processes
78 $processlist = dbm::processlist();
79 if ($processlist["amount"] != "") {
80 logger("Processcheck: Processes: ".$processlist["amount"]." - Processlist: ".$processlist["list"], LOGGER_DEBUG);
82 $max_processes = get_config('system', 'max_processes_backend');
83 if (intval($max_processes) == 0)
86 if ($processlist["amount"] > $max_processes) {
87 logger("Processcheck: Maximum number of processes for backend tasks (".$max_processes.") reached.", LOGGER_DEBUG);
92 // Constantly check the number of available database connections to let the frontend be accessible at any time
93 if (poller_max_connections_reached())
96 // Count active workers and compare them with a maximum value that depends on the load
97 if (poller_too_much_workers(3))
100 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
101 dbesc(datetime_convert()),
103 intval($r[0]["id"]));
105 // Assure that there are no tasks executed twice
106 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
110 logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
114 $argv = json_decode($r[0]["parameter"]);
116 $argc = count($argv);
118 // Check for existance and validity of the include file
121 if (!validate_include($include)) {
122 logger("Include file ".$argv[0]." is not valid!");
123 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
127 require_once($include);
129 $funcname=str_replace(".php", "", basename($argv[0]))."_run";
131 if (function_exists($funcname)) {
132 logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
133 $funcname($argv, $argc);
135 logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." - done");
137 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
139 logger("Function ".$funcname." does not exist");
141 // Quit the poller once every hour
142 if (time() > ($starttime + 3600))
149 * @brief Checks if the number of database connections has reached a critical limit.
151 * @return bool Are more than 3/4 of the maximum connections used?
153 function poller_max_connections_reached() {
155 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
156 $max = get_config("system", "max_connections");
158 // Fetch the percentage level where the poller will get active
159 $maxlevel = get_config("system", "max_connections_level");
164 // the maximum number of possible user connections can be a system variable
165 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
167 $max = $r[0]["Value"];
169 // Or it can be granted. This overrides the system variable
170 $r = q("SHOW GRANTS");
172 foreach ($r AS $grants) {
173 $grant = array_pop($grants);
174 if (stristr($grant, "GRANT USAGE ON"))
175 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
180 // If $max is set we will use the processlist to determine the current number of connections
181 // The processlist only shows entries of the current user
183 $r = q("SHOW PROCESSLIST");
189 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
191 $level = ($used / $max) * 100;
193 if ($level >= $maxlevel) {
194 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
199 // We will now check for the system values.
200 // This limit could be reached although the user limits are fine.
201 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
205 $max = intval($r[0]["Value"]);
209 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
213 $used = intval($r[0]["Value"]);
217 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
219 $level = $used / $max * 100;
221 if ($level < $maxlevel)
224 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
229 * @brief fix the queue entry if the worker process died
232 function poller_kill_stale_workers() {
233 $r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
235 if (!is_array($r) || count($r) == 0) {
236 // No processing here needed
241 if (!posix_kill($pid["pid"], 0))
242 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
243 intval($pid["pid"]));
245 // Kill long running processes
246 $duration = (time() - strtotime($pid["executed"])) / 60;
247 if ($duration > 180) {
248 logger("Worker process ".$pid["pid"]." took more than 3 hours. It will be killed now.");
249 posix_kill($pid["pid"], SIGTERM);
251 // Question: If a process is stale: Should we remove it or should we reschedule it?
252 // By now we rescheduling it. It's maybe not the wisest decision?
253 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
254 intval($pid["pid"]));
256 logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
260 function poller_too_much_workers($stage) {
262 $queues = get_config("system", "worker_queues");
267 $active = poller_active_workers();
269 // Decrease the number of workers at higher load
270 $load = current_load();
272 $maxsysload = intval(get_config('system','maxloadavg'));
276 $maxworkers = $queues;
278 // Some magical mathemathics to reduce the workers
280 $slope = $maxworkers / pow($maxsysload, $exponent);
281 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
283 logger("Current load stage ".$stage.": ".$load." - maximum: ".$maxsysload." - current queues: ".$active." - maximum: ".$queues, LOGGER_DEBUG);
287 return($active >= $queues);
290 function poller_active_workers() {
291 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
293 return($workers[0]["workers"]);
296 if (array_search(__file__,get_included_files())===0){
297 poller_run($_SERVER["argv"],$_SERVER["argc"]);