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