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