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