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