]> git.mxchange.org Git - friendica.git/blob - include/poller.php
Merge pull request #2480 from rabuzarus/2504_vier_mobile_fix
[friendica.git] / include / poller.php
1 <?php
2 if (!file_exists("boot.php") AND (sizeof($_SERVER["argv"]) != 0)) {
3         $directory = dirname($_SERVER["argv"][0]);
4
5         if (substr($directory, 0, 1) != "/")
6                 $directory = $_SERVER["PWD"]."/".$directory;
7
8         $directory = realpath($directory."/..");
9
10         chdir($directory);
11 }
12
13 require_once("boot.php");
14
15 function poller_run(&$argv, &$argc){
16         global $a, $db;
17
18         if(is_null($a)) {
19                 $a = new App;
20         }
21
22         if(is_null($db)) {
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);
27         };
28
29         if (poller_max_connections_reached())
30                 return;
31
32         if (App::maxload_reached())
33                 return;
34
35         // Checking the number of workers
36         if (poller_too_much_workers(1)) {
37                 poller_kill_stale_workers();
38                 return;
39         }
40
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");
44
45                 // Run the cronhooks job separately from cron for being able to use a different timing
46                 proc_run("php","include/cronhooks.php");
47
48                 // Cleaning dead processes
49                 poller_kill_stale_workers();
50         } else
51                 // Sleep four seconds before checking for running processes again to avoid having too many workers
52                 sleep(4);
53
54         // Checking number of workers
55         if (poller_too_much_workers(2))
56                 return;
57
58         $starttime = time();
59
60         while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `created` LIMIT 1")) {
61
62                 // Constantly check the number of available database connections to let the frontend be accessible at any time
63                 if (poller_max_connections_reached())
64                         return;
65
66                 // Count active workers and compare them with a maximum value that depends on the load
67                 if (poller_too_much_workers(3))
68                         return;
69
70                 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
71                         dbesc(datetime_convert()),
72                         intval(getmypid()),
73                         intval($r[0]["id"]));
74
75                 // Assure that there are no tasks executed twice
76                 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
77                         intval($r[0]["id"]),
78                         intval(getmypid()));
79                 if (!$id) {
80                         logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
81                         continue;
82                 }
83
84                 $argv = json_decode($r[0]["parameter"]);
85
86                 $argc = count($argv);
87
88                 // Check for existance and validity of the include file
89                 $include = $argv[0];
90
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"]));
94                         continue;
95                 }
96
97                 require_once($include);
98
99                 $funcname=str_replace(".php", "", basename($argv[0]))."_run";
100
101                 if (function_exists($funcname)) {
102                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
103                         $funcname($argv, $argc);
104
105                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." - done");
106
107                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
108                 } else
109                         logger("Function ".$funcname." does not exist");
110
111                 // Quit the poller once every hour
112                 if (time() > ($starttime + 3600))
113                         return;
114         }
115
116 }
117
118 /**
119  * @brief Checks if the number of database connections has reached a critical limit.
120  *
121  * @return bool Are more than 3/4 of the maximum connections used?
122  */
123 function poller_max_connections_reached() {
124
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");
127
128         // Fetch the percentage level where the poller will get active
129         $maxlevel = get_config("system", "max_connections_level");
130         if ($maxlevel == 0)
131                 $maxlevel = 75;
132
133         if ($max == 0) {
134                 // the maximum number of possible user connections can be a system variable
135                 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
136                 if ($r)
137                         $max = $r[0]["Value"];
138
139                 // Or it can be granted. This overrides the system variable
140                 $r = q("SHOW GRANTS");
141                 if ($r)
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))
146                                                 $max = $match[1];
147                         }
148         }
149
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
152         if ($max != 0) {
153                 $r = q("SHOW PROCESSLIST");
154                 if (!$r)
155                         return false;
156
157                 $used = count($r);
158
159                 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
160
161                 $level = ($used / $max) * 100;
162
163                 if ($level >= $maxlevel) {
164                         logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
165                         return true;
166                 }
167         }
168
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'");
172         if (!$r)
173                 return false;
174
175         $max = intval($r[0]["Value"]);
176         if ($max == 0)
177                 return false;
178
179         $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
180         if (!$r)
181                 return false;
182
183         $used = intval($r[0]["Value"]);
184         if ($used == 0)
185                 return false;
186
187         logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
188
189         $level = $used / $max * 100;
190
191         if ($level < $maxlevel)
192                 return false;
193
194         logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
195         return true;
196 }
197
198 /**
199  * @brief fix the queue entry if the worker process died
200  *
201  */
202 function poller_kill_stale_workers() {
203         $r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
204
205         if (!is_array($r) || count($r) == 0) {
206                 // No processing here needed
207                 return;
208         }
209
210         foreach($r AS $pid)
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"]));
214                 else {
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);
220
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"]));
225                         } else
226                                 logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
227                 }
228 }
229
230 function poller_too_much_workers($stage) {
231
232         $queues = get_config("system", "worker_queues");
233
234         if ($queues == 0)
235                 $queues = 4;
236
237         $active = poller_active_workers();
238
239         // Decrease the number of workers at higher load
240         $load = current_load();
241         if($load) {
242                 $maxsysload = intval(get_config('system','maxloadavg'));
243                 if($maxsysload < 1)
244                         $maxsysload = 50;
245
246                 $maxworkers = $queues;
247
248                 // Some magical mathemathics to reduce the workers
249                 $exponent = 3;
250                 $slope = $maxworkers / pow($maxsysload, $exponent);
251                 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
252
253                 logger("Current load stage ".$stage.": ".$load." - maximum: ".$maxsysload." - current queues: ".$active." - maximum: ".$queues, LOGGER_DEBUG);
254
255         }
256
257         return($active >= $queues);
258 }
259
260 function poller_active_workers() {
261         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
262
263         return($workers[0]["workers"]);
264 }
265
266 if (array_search(__file__,get_included_files())===0){
267   poller_run($_SERVER["argv"],$_SERVER["argc"]);
268   killme();
269 }
270 ?>