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