]> git.mxchange.org Git - friendica.git/blob - include/poller.php
Merge remote-tracking branch 'upstream/develop' into 1606-dbm
[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 != "")
32                 logger("Processlist: ".$processlist, LOGGER_DEBUG);
33
34         if (poller_max_connections_reached())
35                 return;
36
37         if (App::maxload_reached())
38                 return;
39
40         // Checking the number of workers
41         if (poller_too_much_workers(1)) {
42                 poller_kill_stale_workers();
43                 return;
44         }
45
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");
49
50                 // Run the cronhooks job separately from cron for being able to use a different timing
51                 proc_run("php","include/cronhooks.php");
52
53                 // Cleaning dead processes
54                 poller_kill_stale_workers();
55         } else
56                 // Sleep four seconds before checking for running processes again to avoid having too many workers
57                 sleep(4);
58
59         // Checking number of workers
60         if (poller_too_much_workers(2))
61                 return;
62
63         $starttime = time();
64
65         while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `created` LIMIT 1")) {
66
67                 // Log the type of database processes
68                 $processlist = dbm::processlist();
69                 if ($processlist != "")
70                         logger("Processlist: ".$processlist, LOGGER_DEBUG);
71
72                 // Constantly check the number of available database connections to let the frontend be accessible at any time
73                 if (poller_max_connections_reached())
74                         return;
75
76                 // Count active workers and compare them with a maximum value that depends on the load
77                 if (poller_too_much_workers(3))
78                         return;
79
80                 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
81                         dbesc(datetime_convert()),
82                         intval(getmypid()),
83                         intval($r[0]["id"]));
84
85                 // Assure that there are no tasks executed twice
86                 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
87                         intval($r[0]["id"]),
88                         intval(getmypid()));
89                 if (!$id) {
90                         logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
91                         continue;
92                 }
93
94                 $argv = json_decode($r[0]["parameter"]);
95
96                 $argc = count($argv);
97
98                 // Check for existance and validity of the include file
99                 $include = $argv[0];
100
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"]));
104                         continue;
105                 }
106
107                 require_once($include);
108
109                 $funcname=str_replace(".php", "", basename($argv[0]))."_run";
110
111                 if (function_exists($funcname)) {
112                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
113                         $funcname($argv, $argc);
114
115                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." - done");
116
117                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
118                 } else
119                         logger("Function ".$funcname." does not exist");
120
121                 // Quit the poller once every hour
122                 if (time() > ($starttime + 3600))
123                         return;
124         }
125
126 }
127
128 /**
129  * @brief Checks if the number of database connections has reached a critical limit.
130  *
131  * @return bool Are more than 3/4 of the maximum connections used?
132  */
133 function poller_max_connections_reached() {
134
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");
137
138         // Fetch the percentage level where the poller will get active
139         $maxlevel = get_config("system", "max_connections_level");
140         if ($maxlevel == 0)
141                 $maxlevel = 75;
142
143         if ($max == 0) {
144                 // the maximum number of possible user connections can be a system variable
145                 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
146                 if ($r)
147                         $max = $r[0]["Value"];
148
149                 // Or it can be granted. This overrides the system variable
150                 $r = q("SHOW GRANTS");
151                 if ($r)
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))
156                                                 $max = $match[1];
157                         }
158         }
159
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
162         if ($max != 0) {
163                 $r = q("SHOW PROCESSLIST");
164                 if (!$r)
165                         return false;
166
167                 $used = count($r);
168
169                 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
170
171                 $level = ($used / $max) * 100;
172
173                 if ($level >= $maxlevel) {
174                         logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
175                         return true;
176                 }
177         }
178
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'");
182         if (!$r)
183                 return false;
184
185         $max = intval($r[0]["Value"]);
186         if ($max == 0)
187                 return false;
188
189         $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
190         if (!$r)
191                 return false;
192
193         $used = intval($r[0]["Value"]);
194         if ($used == 0)
195                 return false;
196
197         logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
198
199         $level = $used / $max * 100;
200
201         if ($level < $maxlevel)
202                 return false;
203
204         logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
205         return true;
206 }
207
208 /**
209  * @brief fix the queue entry if the worker process died
210  *
211  */
212 function poller_kill_stale_workers() {
213         $r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
214
215         if (!is_array($r) || count($r) == 0) {
216                 // No processing here needed
217                 return;
218         }
219
220         foreach($r AS $pid)
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"]));
224                 else {
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);
230
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"]));
235                         } else
236                                 logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
237                 }
238 }
239
240 function poller_too_much_workers($stage) {
241
242         $queues = get_config("system", "worker_queues");
243
244         if ($queues == 0)
245                 $queues = 4;
246
247         $active = poller_active_workers();
248
249         // Decrease the number of workers at higher load
250         $load = current_load();
251         if($load) {
252                 $maxsysload = intval(get_config('system','maxloadavg'));
253                 if($maxsysload < 1)
254                         $maxsysload = 50;
255
256                 $maxworkers = $queues;
257
258                 // Some magical mathemathics to reduce the workers
259                 $exponent = 3;
260                 $slope = $maxworkers / pow($maxsysload, $exponent);
261                 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
262
263                 logger("Current load stage ".$stage.": ".$load." - maximum: ".$maxsysload." - current queues: ".$active." - maximum: ".$queues, LOGGER_DEBUG);
264
265         }
266
267         return($active >= $queues);
268 }
269
270 function poller_active_workers() {
271         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
272
273         return($workers[0]["workers"]);
274 }
275
276 if (array_search(__file__,get_included_files())===0){
277   poller_run($_SERVER["argv"],$_SERVER["argc"]);
278   killme();
279 }
280 ?>