]> git.mxchange.org Git - friendica.git/blob - include/poller.php
Merge pull request #2768 from tobiasd/20160906-changes
[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         $a->start_process();
33
34         $mypid = getmypid();
35
36         if ($a->max_processes_reached())
37                 return;
38
39         if (poller_max_connections_reached())
40                 return;
41
42         if (App::maxload_reached())
43                 return;
44
45         // Checking the number of workers
46         if (poller_too_much_workers()) {
47                 poller_kill_stale_workers();
48                 return;
49         }
50
51         if(($argc <= 1) OR ($argv[1] != "no_cron")) {
52                 // Run the cron job that calls all other jobs
53                 proc_run(PRIORITY_MEDIUM, "include/cron.php");
54
55                 // Run the cronhooks job separately from cron for being able to use a different timing
56                 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
57
58                 // Cleaning dead processes
59                 poller_kill_stale_workers();
60         } else
61                 // Sleep four seconds before checking for running processes again to avoid having too many workers
62                 sleep(4);
63
64         // Checking number of workers
65         if (poller_too_much_workers())
66                 return;
67
68         $cooldown = Config::get("system", "worker_cooldown", 0);
69
70         $starttime = time();
71
72         while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority`, `created` LIMIT 1")) {
73
74                 // Constantly check the number of parallel database processes
75                 if ($a->max_processes_reached())
76                         return;
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())
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($mypid),
89                         intval($r[0]["id"]));
90
91                 // Assure that there are no tasks executed twice
92                 $id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
93                 if (!$id) {
94                         logger("Queue item ".$r[0]["id"]." vanished - skip this execution", LOGGER_DEBUG);
95                         continue;
96                 } elseif ((strtotime($id[0]["executed"]) <= 0) OR ($id[0]["pid"] == 0)) {
97                         logger("Entry for queue item ".$r[0]["id"]." wasn't stored - we better stop here", LOGGER_DEBUG);
98                         return;
99                 } elseif ($id[0]["pid"] != $mypid) {
100                         logger("Queue item ".$r[0]["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
101                         continue;
102                 }
103
104                 $argv = json_decode($r[0]["parameter"]);
105
106                 $argc = count($argv);
107
108                 // Check for existance and validity of the include file
109                 $include = $argv[0];
110
111                 if (!validate_include($include)) {
112                         logger("Include file ".$argv[0]." is not valid!");
113                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
114                         continue;
115                 }
116
117                 require_once($include);
118
119                 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
120
121                 if (function_exists($funcname)) {
122                         logger("Process ".$mypid." - Prio ".$r[0]["priority"]." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
123                         $funcname($argv, $argc);
124
125                         if ($cooldown > 0) {
126                                 logger("Process ".$mypid." - Prio ".$r[0]["priority"]." - ID ".$r[0]["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
127                                 sleep($cooldown);
128                         }
129
130                         logger("Process ".$mypid." - Prio ".$r[0]["priority"]." - ID ".$r[0]["id"].": ".$funcname." - done");
131
132                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
133                 } else
134                         logger("Function ".$funcname." does not exist");
135
136                 // Quit the poller once every hour
137                 if (time() > ($starttime + 3600))
138                         return;
139         }
140
141 }
142
143 /**
144  * @brief Checks if the number of database connections has reached a critical limit.
145  *
146  * @return bool Are more than 3/4 of the maximum connections used?
147  */
148 function poller_max_connections_reached() {
149
150         // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
151         $max = get_config("system", "max_connections");
152
153         // Fetch the percentage level where the poller will get active
154         $maxlevel = get_config("system", "max_connections_level");
155         if ($maxlevel == 0)
156                 $maxlevel = 75;
157
158         if ($max == 0) {
159                 // the maximum number of possible user connections can be a system variable
160                 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
161                 if ($r)
162                         $max = $r[0]["Value"];
163
164                 // Or it can be granted. This overrides the system variable
165                 $r = q("SHOW GRANTS");
166                 if ($r)
167                         foreach ($r AS $grants) {
168                                 $grant = array_pop($grants);
169                                 if (stristr($grant, "GRANT USAGE ON"))
170                                         if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
171                                                 $max = $match[1];
172                         }
173         }
174
175         // If $max is set we will use the processlist to determine the current number of connections
176         // The processlist only shows entries of the current user
177         if ($max != 0) {
178                 $r = q("SHOW PROCESSLIST");
179                 if (!$r)
180                         return false;
181
182                 $used = count($r);
183
184                 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
185
186                 $level = ($used / $max) * 100;
187
188                 if ($level >= $maxlevel) {
189                         logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
190                         return true;
191                 }
192         }
193
194         // We will now check for the system values.
195         // This limit could be reached although the user limits are fine.
196         $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
197         if (!$r)
198                 return false;
199
200         $max = intval($r[0]["Value"]);
201         if ($max == 0)
202                 return false;
203
204         $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
205         if (!$r)
206                 return false;
207
208         $used = intval($r[0]["Value"]);
209         if ($used == 0)
210                 return false;
211
212         logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
213
214         $level = $used / $max * 100;
215
216         if ($level < $maxlevel)
217                 return false;
218
219         logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
220         return true;
221 }
222
223 /**
224  * @brief fix the queue entry if the worker process died
225  *
226  */
227 function poller_kill_stale_workers() {
228         $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
229
230         if (!dbm::is_result($r)) {
231                 // No processing here needed
232                 return;
233         }
234
235         foreach($r AS $pid)
236                 if (!posix_kill($pid["pid"], 0))
237                         q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
238                                 intval($pid["pid"]));
239                 else {
240                         // Kill long running processes
241
242                         // Check if the priority is in a valid range
243                         if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE)))
244                                 $pid["priority"] = PRIORITY_MEDIUM;
245
246                         // Define the maximum durations
247                         $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
248                         $max_duration = $max_duration_defaults[$pid["priority"]];
249
250                         $argv = json_decode($pid["parameter"]);
251                         $argv[0] = basename($argv[0]);
252
253                         // How long is the process already running?
254                         $duration = (time() - strtotime($pid["executed"])) / 60;
255                         if ($duration > $max_duration) {
256                                 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
257                                 posix_kill($pid["pid"], SIGTERM);
258
259                                 // We killed the stale process.
260                                 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
261                                 // Additionally we are lowering the priority.
262                                 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `created` = '%s',
263                                                         `priority` = %d, `pid` = 0 WHERE `pid` = %d",
264                                         dbesc(datetime_convert()),
265                                         intval(PRIORITY_NEGLIGIBLE),
266                                         intval($pid["pid"]));
267                         } else
268                                 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
269                 }
270 }
271
272 function poller_too_much_workers() {
273
274
275         $queues = get_config("system", "worker_queues");
276
277         if ($queues == 0)
278                 $queues = 4;
279
280         $maxqueues = $queues;
281
282         $active = poller_active_workers();
283
284         // Decrease the number of workers at higher load
285         $load = current_load();
286         if($load) {
287                 $maxsysload = intval(get_config('system','maxloadavg'));
288                 if($maxsysload < 1)
289                         $maxsysload = 50;
290
291                 $maxworkers = $queues;
292
293                 // Some magical mathemathics to reduce the workers
294                 $exponent = 3;
295                 $slope = $maxworkers / pow($maxsysload, $exponent);
296                 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
297
298                 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00'");
299                 $entries = $s[0]["total"];
300
301                 if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
302                         $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority` LIMIT 1");
303                         $top_priority = $s[0]["priority"];
304
305                         $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` != '0000-00-00 00:00:00' LIMIT 1",
306                                 intval($top_priority));
307                         $high_running = dbm::is_result($s);
308
309                         if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
310                                 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
311                                 $queues = $active + 1;
312                         }
313                 }
314
315                 logger("Current load: ".$load." - maximum: ".$maxsysload." - current queues: ".$active."/".$entries." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
316
317                 // Are there fewer workers running as possible? Then fork a new one.
318                 if (!get_config("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
319                         logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
320                         $args = array("php", "include/poller.php", "no_cron");
321                         $a = get_app();
322                         $a->proc_run($args);
323                 }
324         }
325
326         return($active >= $queues);
327 }
328
329 function poller_active_workers() {
330         $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
331
332         return($workers[0]["processes"]);
333 }
334
335 if (array_search(__file__,get_included_files())===0){
336         poller_run($_SERVER["argv"],$_SERVER["argc"]);
337
338         get_app()->end_process();
339
340         killme();
341 }
342 ?>