]> git.mxchange.org Git - friendica.git/blob - include/poller.php
45dc332e1774d084d953c251a9f36a454e2629fe
[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 require_once("dbm.php");
15
16 function poller_run(&$argv, &$argc){
17         global $a, $db;
18
19         if(is_null($a)) {
20                 $a = new App;
21         }
22
23         if(is_null($db)) {
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);
28         };
29
30         $processlist = dbm::processlist();
31         if ($processlist["list"] != "") {
32                 logger("Processes: ".$processlist["amount"]." - Processlist: ".$processlist["list"], LOGGER_DEBUG);
33                 if ($processlist["amount"] > 5)
34                         return;
35         }
36
37         if (poller_max_connections_reached())
38                 return;
39
40         if (App::maxload_reached())
41                 return;
42
43         // Checking the number of workers
44         if (poller_too_much_workers(1)) {
45                 poller_kill_stale_workers();
46                 return;
47         }
48
49         if(($argc <= 1) OR ($argv[1] != "no_cron")) {
50                 // Run the cron job that calls all other jobs
51                 proc_run("php","include/cron.php");
52
53                 // Run the cronhooks job separately from cron for being able to use a different timing
54                 proc_run("php","include/cronhooks.php");
55
56                 // Cleaning dead processes
57                 poller_kill_stale_workers();
58         } else
59                 // Sleep four seconds before checking for running processes again to avoid having too many workers
60                 sleep(4);
61
62         // Checking number of workers
63         if (poller_too_much_workers(2))
64                 return;
65
66         $starttime = time();
67
68         while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `created` LIMIT 1")) {
69
70                 // Log the type of database processes
71                 $processlist = dbm::processlist();
72                 if ($processlist["amount"] != "") {
73                         logger("Processes: ".$processlist["amount"]." - Processlist: ".$processlist["list"], LOGGER_DEBUG);
74                         if ($processlist["amount"] > 5)
75                                 return;
76                 }
77
78                 // Constantly check the number of available database connections to let the frontend be accessible at any time
79                 if (poller_max_connections_reached())
80                         return;
81
82                 // Count active workers and compare them with a maximum value that depends on the load
83                 if (poller_too_much_workers(3))
84                         return;
85
86                 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
87                         dbesc(datetime_convert()),
88                         intval(getmypid()),
89                         intval($r[0]["id"]));
90
91                 // Assure that there are no tasks executed twice
92                 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
93                         intval($r[0]["id"]),
94                         intval(getmypid()));
95                 if (!$id) {
96                         logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
97                         continue;
98                 }
99
100                 $argv = json_decode($r[0]["parameter"]);
101
102                 $argc = count($argv);
103
104                 // Check for existance and validity of the include file
105                 $include = $argv[0];
106
107                 if (!validate_include($include)) {
108                         logger("Include file ".$argv[0]." is not valid!");
109                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
110                         continue;
111                 }
112
113                 require_once($include);
114
115                 $funcname=str_replace(".php", "", basename($argv[0]))."_run";
116
117                 if (function_exists($funcname)) {
118                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
119                         $funcname($argv, $argc);
120
121                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." - done");
122
123                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
124                 } else
125                         logger("Function ".$funcname." does not exist");
126
127                 // Quit the poller once every hour
128                 if (time() > ($starttime + 3600))
129                         return;
130         }
131
132 }
133
134 /**
135  * @brief Checks if the number of database connections has reached a critical limit.
136  *
137  * @return bool Are more than 3/4 of the maximum connections used?
138  */
139 function poller_max_connections_reached() {
140
141         // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
142         $max = get_config("system", "max_connections");
143
144         // Fetch the percentage level where the poller will get active
145         $maxlevel = get_config("system", "max_connections_level");
146         if ($maxlevel == 0)
147                 $maxlevel = 75;
148
149         if ($max == 0) {
150                 // the maximum number of possible user connections can be a system variable
151                 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
152                 if ($r)
153                         $max = $r[0]["Value"];
154
155                 // Or it can be granted. This overrides the system variable
156                 $r = q("SHOW GRANTS");
157                 if ($r)
158                         foreach ($r AS $grants) {
159                                 $grant = array_pop($grants);
160                                 if (stristr($grant, "GRANT USAGE ON"))
161                                         if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
162                                                 $max = $match[1];
163                         }
164         }
165
166         // If $max is set we will use the processlist to determine the current number of connections
167         // The processlist only shows entries of the current user
168         if ($max != 0) {
169                 $r = q("SHOW PROCESSLIST");
170                 if (!$r)
171                         return false;
172
173                 $used = count($r);
174
175                 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
176
177                 $level = ($used / $max) * 100;
178
179                 if ($level >= $maxlevel) {
180                         logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
181                         return true;
182                 }
183         }
184
185         // We will now check for the system values.
186         // This limit could be reached although the user limits are fine.
187         $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
188         if (!$r)
189                 return false;
190
191         $max = intval($r[0]["Value"]);
192         if ($max == 0)
193                 return false;
194
195         $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
196         if (!$r)
197                 return false;
198
199         $used = intval($r[0]["Value"]);
200         if ($used == 0)
201                 return false;
202
203         logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
204
205         $level = $used / $max * 100;
206
207         if ($level < $maxlevel)
208                 return false;
209
210         logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
211         return true;
212 }
213
214 /**
215  * @brief fix the queue entry if the worker process died
216  *
217  */
218 function poller_kill_stale_workers() {
219         $r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
220
221         if (!is_array($r) || count($r) == 0) {
222                 // No processing here needed
223                 return;
224         }
225
226         foreach($r AS $pid)
227                 if (!posix_kill($pid["pid"], 0))
228                         q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
229                                 intval($pid["pid"]));
230                 else {
231                         // Kill long running processes
232                         $duration = (time() - strtotime($pid["executed"])) / 60;
233                         if ($duration > 180) {
234                                 logger("Worker process ".$pid["pid"]." took more than 3 hours. It will be killed now.");
235                                 posix_kill($pid["pid"], SIGTERM);
236
237                                 // Question: If a process is stale: Should we remove it or should we reschedule it?
238                                 // By now we rescheduling it. It's maybe not the wisest decision?
239                                 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
240                                         intval($pid["pid"]));
241                         } else
242                                 logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
243                 }
244 }
245
246 function poller_too_much_workers($stage) {
247
248         $queues = get_config("system", "worker_queues");
249
250         if ($queues == 0)
251                 $queues = 4;
252
253         $active = poller_active_workers();
254
255         // Decrease the number of workers at higher load
256         $load = current_load();
257         if($load) {
258                 $maxsysload = intval(get_config('system','maxloadavg'));
259                 if($maxsysload < 1)
260                         $maxsysload = 50;
261
262                 $maxworkers = $queues;
263
264                 // Some magical mathemathics to reduce the workers
265                 $exponent = 3;
266                 $slope = $maxworkers / pow($maxsysload, $exponent);
267                 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
268
269                 logger("Current load stage ".$stage.": ".$load." - maximum: ".$maxsysload." - current queues: ".$active." - maximum: ".$queues, LOGGER_DEBUG);
270
271         }
272
273         return($active >= $queues);
274 }
275
276 function poller_active_workers() {
277         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
278
279         return($workers[0]["workers"]);
280 }
281
282 if (array_search(__file__,get_included_files())===0){
283   poller_run($_SERVER["argv"],$_SERVER["argc"]);
284   killme();
285 }
286 ?>