]> git.mxchange.org Git - friendica.git/blob - include/poller.php
Merge pull request #2347 from annando/1602-dfrn-forum
[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                 // Count active workers and compare them with a maximum value that depends on the load
72                 if (poller_too_much_workers(3))
73                         return;
74
75                 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
76                         dbesc(datetime_convert()),
77                         intval(getmypid()),
78                         intval($r[0]["id"]));
79
80                 // Assure that there are no tasks executed twice
81                 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
82                         intval($r[0]["id"]),
83                         intval(getmypid()));
84                 if (!$id) {
85                         logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
86                         continue;
87                 }
88
89                 $argv = json_decode($r[0]["parameter"]);
90
91                 $argc = count($argv);
92
93                 // Check for existance and validity of the include file
94                 $include = $argv[0];
95
96                 if (!validate_include($include)) {
97                         logger("Include file ".$argv[0]." is not valid!");
98                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
99                         continue;
100                 }
101
102                 require_once($include);
103
104                 $funcname=str_replace(".php", "", basename($argv[0]))."_run";
105
106                 if (function_exists($funcname)) {
107                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
108                         $funcname($argv, $argc);
109
110                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." - done");
111
112                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
113                 } else
114                         logger("Function ".$funcname." does not exist");
115
116                 // Quit the poller once every hour
117                 if (time() > ($starttime + 3600))
118                         return;
119         }
120
121 }
122
123 /**
124  * @brief Checks if the number of database connections has reached a critical limit.
125  *
126  * @return bool Are more than 3/4 of the maximum connections used?
127  */
128 function poller_max_connections_reached() {
129         $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
130         if (!$r)
131                 return false;
132
133         // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
134         // In that case we use the processlist to determine the current number of connections
135         $max = get_config("system", "max_connections");
136
137         if ($max == 0) {
138                 $max = intval($r[0]["Value"]);
139                 if ($max == 0)
140                         return false;
141
142                 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
143                 if (!$r)
144                         return false;
145
146                 $connected = intval($r[0]["Value"]);
147                 if ($connected == 0)
148                         return false;
149         } else {
150                 $r = q("SHOW PROCESSLIST");
151                 if (!$r)
152                         return false;
153
154                 $connected = count($r);
155         }
156
157         $level = $connected / $max;
158
159         logger("Connection usage: ".$connected."/".$max, LOGGER_DEBUG);
160
161         if ($level < (3/4))
162                 return false;
163
164         logger("Maximum level (3/4) of connections reached: ".$connected."/".$max);
165         return true;
166
167 }
168
169 /**
170  * @brief fix the queue entry if the worker process died
171  *
172  */
173 function poller_kill_stale_workers() {
174         $r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
175         foreach($r AS $pid)
176                 if (!posix_kill($pid["pid"], 0))
177                         q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
178                                 intval($pid["pid"]));
179                 else {
180                         // Kill long running processes
181                         $duration = (time() - strtotime($pid["executed"])) / 60;
182                         if ($duration > 180) {
183                                 logger("Worker process ".$pid["pid"]." took more than 3 hours. It will be killed now.");
184                                 posix_kill($pid["pid"], SIGTERM);
185
186                                 // Question: If a process is stale: Should we remove it or should we reschedule it?
187                                 // By now we rescheduling it. It's maybe not the wisest decision?
188                                 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
189                                         intval($pid["pid"]));
190                         } else
191                                 logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
192                 }
193 }
194
195 function poller_too_much_workers($stage) {
196
197         $queues = get_config("system", "worker_queues");
198
199         if ($queues == 0)
200                 $queues = 4;
201
202         $active = poller_active_workers();
203
204         // Decrease the number of workers at higher load
205         $load = current_load();
206         if($load) {
207                 $maxsysload = intval(get_config('system','maxloadavg'));
208                 if($maxsysload < 1)
209                         $maxsysload = 50;
210
211                 $maxworkers = $queues;
212
213                 // Some magical mathemathics to reduce the workers
214                 $exponent = 3;
215                 $slope = $maxworkers / pow($maxsysload, $exponent);
216                 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
217
218                 logger("Current load stage ".$stage.": ".$load." - maximum: ".$maxsysload." - current queues: ".$active." - maximum: ".$queues, LOGGER_DEBUG);
219
220         }
221
222         return($active >= $queues);
223 }
224
225 function poller_active_workers() {
226         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
227
228         return($workers[0]["workers"]);
229 }
230
231 if (array_search(__file__,get_included_files())===0){
232   poller_run($_SERVER["argv"],$_SERVER["argc"]);
233   killme();
234 }
235 ?>