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