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