]> git.mxchange.org Git - friendica.git/blob - include/poller.php
b4f5df4bf5a9fcd2a1704fb145a988bd885bdf33
[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         // Quit when in maintenance
33         if (get_config('system', 'maintenance', true))
34                 return;
35
36         $a->start_process();
37
38         if ($a->max_processes_reached())
39                 return;
40
41         if (poller_max_connections_reached())
42                 return;
43
44         if (App::maxload_reached())
45                 return;
46
47         // Checking the number of workers
48         if (poller_too_much_workers()) {
49                 poller_kill_stale_workers();
50                 return;
51         }
52
53         if(($argc <= 1) OR ($argv[1] != "no_cron")) {
54                 poller_run_cron();
55         } else
56                 // Sleep four seconds before checking for running processes again to avoid having too many workers
57                 sleep(4);
58
59         // Checking number of workers
60         if (poller_too_much_workers())
61                 return;
62
63         $starttime = time();
64
65         while ($r = poller_worker_process()) {
66
67                 // Count active workers and compare them with a maximum value that depends on the load
68                 if (poller_too_much_workers()) {
69                         return;
70                 }
71
72                 if (!poller_execute($r[0])) {
73                         return;
74                 }
75
76                 // Quit the poller once every hour
77                 if (time() > ($starttime + 3600))
78                         return;
79         }
80
81 }
82
83 /**
84  * @brief Execute a worker entry
85  *
86  * @param array $queue Workerqueue entry
87  *
88  * @return boolean "true" if further processing should be stopped
89  */
90 function poller_execute($queue) {
91
92         $a = get_app();
93
94         $mypid = getmypid();
95
96         $cooldown = Config::get("system", "worker_cooldown", 0);
97
98         // Quit when in maintenance
99         if (get_config('system', 'maintenance', true)) {
100                 return false;
101         }
102
103         // Constantly check the number of parallel database processes
104         if ($a->max_processes_reached()) {
105                 return false;
106         }
107
108         // Constantly check the number of available database connections to let the frontend be accessible at any time
109         if (poller_max_connections_reached()) {
110                 return false;
111         }
112
113         $upd = q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `pid` = 0",
114                 dbesc(datetime_convert()),
115                 intval($mypid),
116                 intval($queue["id"]));
117
118         if (!$upd) {
119                 logger("Couldn't update queue entry ".$queue["id"]." - skip this execution", LOGGER_DEBUG);
120                 q("COMMIT");
121                 return true;
122         }
123
124         // Assure that there are no tasks executed twice
125         $id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
126         if (!$id) {
127                 logger("Queue item ".$queue["id"]." vanished - skip this execution", LOGGER_DEBUG);
128                 q("COMMIT");
129                 return true;
130         } elseif ((strtotime($id[0]["executed"]) <= 0) OR ($id[0]["pid"] == 0)) {
131                 logger("Entry for queue item ".$queue["id"]." wasn't stored - skip this execution", LOGGER_DEBUG);
132                 q("COMMIT");
133                 return true;
134         } elseif ($id[0]["pid"] != $mypid) {
135                 logger("Queue item ".$queue["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
136                 q("COMMIT");
137                 return true;
138         }
139         q("COMMIT");
140
141         $argv = json_decode($queue["parameter"]);
142
143         $argc = count($argv);
144
145         // Check for existance and validity of the include file
146         $include = $argv[0];
147
148         if (!validate_include($include)) {
149                 logger("Include file ".$argv[0]." is not valid!");
150                 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
151                 return true;
152         }
153
154         require_once($include);
155
156         $funcname = str_replace(".php", "", basename($argv[0]))."_run";
157
158         if (function_exists($funcname)) {
159                 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
160
161                 // For better logging create a new process id for every worker call
162                 // But preserve the old one for the worker
163                 $old_process_id = $a->process_id;
164                 $a->process_id = uniqid("wrk", true);
165
166                 $funcname($argv, $argc);
167
168                 $a->process_id = $old_process_id;
169
170                 if ($cooldown > 0) {
171                         logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
172                         sleep($cooldown);
173                 }
174
175                 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done");
176
177                 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
178         } else {
179                 logger("Function ".$funcname." does not exist");
180         }
181
182         return true;
183 }
184
185 /**
186  * @brief Checks if the number of database connections has reached a critical limit.
187  *
188  * @return bool Are more than 3/4 of the maximum connections used?
189  */
190 function poller_max_connections_reached() {
191
192         // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
193         $max = get_config("system", "max_connections");
194
195         // Fetch the percentage level where the poller will get active
196         $maxlevel = get_config("system", "max_connections_level");
197         if ($maxlevel == 0)
198                 $maxlevel = 75;
199
200         if ($max == 0) {
201                 // the maximum number of possible user connections can be a system variable
202                 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
203                 if ($r)
204                         $max = $r[0]["Value"];
205
206                 // Or it can be granted. This overrides the system variable
207                 $r = q("SHOW GRANTS");
208                 if ($r)
209                         foreach ($r AS $grants) {
210                                 $grant = array_pop($grants);
211                                 if (stristr($grant, "GRANT USAGE ON"))
212                                         if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
213                                                 $max = $match[1];
214                         }
215         }
216
217         // If $max is set we will use the processlist to determine the current number of connections
218         // The processlist only shows entries of the current user
219         if ($max != 0) {
220                 $r = q("SHOW PROCESSLIST");
221                 if (!$r)
222                         return false;
223
224                 $used = count($r);
225
226                 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
227
228                 $level = ($used / $max) * 100;
229
230                 if ($level >= $maxlevel) {
231                         logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
232                         return true;
233                 }
234         }
235
236         // We will now check for the system values.
237         // This limit could be reached although the user limits are fine.
238         $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
239         if (!$r)
240                 return false;
241
242         $max = intval($r[0]["Value"]);
243         if ($max == 0)
244                 return false;
245
246         $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
247         if (!$r)
248                 return false;
249
250         $used = intval($r[0]["Value"]);
251         if ($used == 0)
252                 return false;
253
254         logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
255
256         $level = $used / $max * 100;
257
258         if ($level < $maxlevel)
259                 return false;
260
261         logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
262         return true;
263 }
264
265 /**
266  * @brief fix the queue entry if the worker process died
267  *
268  */
269 function poller_kill_stale_workers() {
270         $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
271
272         if (!dbm::is_result($r)) {
273                 // No processing here needed
274                 return;
275         }
276
277         foreach($r AS $pid)
278                 if (!posix_kill($pid["pid"], 0))
279                         q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
280                                 intval($pid["pid"]));
281                 else {
282                         // Kill long running processes
283
284                         // Check if the priority is in a valid range
285                         if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE)))
286                                 $pid["priority"] = PRIORITY_MEDIUM;
287
288                         // Define the maximum durations
289                         $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
290                         $max_duration = $max_duration_defaults[$pid["priority"]];
291
292                         $argv = json_decode($pid["parameter"]);
293                         $argv[0] = basename($argv[0]);
294
295                         // How long is the process already running?
296                         $duration = (time() - strtotime($pid["executed"])) / 60;
297                         if ($duration > $max_duration) {
298                                 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
299                                 posix_kill($pid["pid"], SIGTERM);
300
301                                 // We killed the stale process.
302                                 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
303                                 // Additionally we are lowering the priority.
304                                 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `created` = '%s',
305                                                         `priority` = %d, `pid` = 0 WHERE `pid` = %d",
306                                         dbesc(datetime_convert()),
307                                         intval(PRIORITY_NEGLIGIBLE),
308                                         intval($pid["pid"]));
309                         } else
310                                 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
311                 }
312 }
313
314 function poller_too_much_workers() {
315
316
317         $queues = get_config("system", "worker_queues");
318
319         if ($queues == 0)
320                 $queues = 4;
321
322         $maxqueues = $queues;
323
324         $active = poller_active_workers();
325
326         // Decrease the number of workers at higher load
327         $load = current_load();
328         if($load) {
329                 $maxsysload = intval(get_config('system','maxloadavg'));
330                 if($maxsysload < 1)
331                         $maxsysload = 50;
332
333                 $maxworkers = $queues;
334
335                 // Some magical mathemathics to reduce the workers
336                 $exponent = 3;
337                 $slope = $maxworkers / pow($maxsysload, $exponent);
338                 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
339
340                 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00'");
341                 $entries = $s[0]["total"];
342
343                 if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
344                         $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority` LIMIT 1");
345                         $top_priority = $s[0]["priority"];
346
347                         $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` != '0000-00-00 00:00:00' LIMIT 1",
348                                 intval($top_priority));
349                         $high_running = dbm::is_result($s);
350
351                         if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
352                                 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
353                                 $queues = $active + 1;
354                         }
355                 }
356
357                 // Create a list of queue entries grouped by their priority
358                 $running = array(PRIORITY_CRITICAL => 0,
359                                 PRIORITY_HIGH => 0,
360                                 PRIORITY_MEDIUM => 0,
361                                 PRIORITY_LOW => 0,
362                                 PRIORITY_NEGLIGIBLE => 0);
363
364                 $r = q("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` GROUP BY `priority`");
365                 if (dbm::is_result($r))
366                         foreach ($r AS $process)
367                                 $running[$process["priority"]] = $process["running"];
368
369                 $processlist = "";
370                 $r = q("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
371                 if (dbm::is_result($r))
372                         foreach ($r as $entry) {
373                                 if ($processlist != "")
374                                         $processlist .= ", ";
375                                 $processlist .= $entry["priority"].":".$running[$entry["priority"]]."/".$entry["entries"];
376                         }
377
378                 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries." (".$processlist.") - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
379
380                 // Are there fewer workers running as possible? Then fork a new one.
381                 if (!get_config("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
382                         logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
383                         $args = array("php", "include/poller.php", "no_cron");
384                         $a = get_app();
385                         $a->proc_run($args);
386                 }
387         }
388
389         return($active >= $queues);
390 }
391
392 function poller_active_workers() {
393         $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
394
395         return($workers[0]["processes"]);
396 }
397
398 /**
399  * @brief Check if we should pass some slow processes
400  *
401  * When the active processes of the highest priority are using more than 2/3
402  * of all processes, we let pass slower processes.
403  *
404  * @param string $highest_priority Returns the currently highest priority
405  * @return bool We let pass a slower process than $highest_priority
406  */
407 function poller_passing_slow(&$highest_priority) {
408
409         $highest_priority = 0;
410
411         $r = q("SELECT `priority`
412                 FROM `process`
413                 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
414
415         // No active processes at all? Fine
416         if (!dbm::is_result($r))
417                 return(false);
418
419         $priorities = array();
420         foreach ($r AS $line)
421                 $priorities[] = $line["priority"];
422
423         // Should not happen
424         if (count($priorities) == 0)
425                 return(false);
426
427         $highest_priority = min($priorities);
428
429         // The highest process is already the slowest one?
430         // Then we quit
431         if ($highest_priority == PRIORITY_NEGLIGIBLE)
432                 return(false);
433
434         $high = 0;
435         foreach ($priorities AS $priority)
436                 if ($priority == $highest_priority)
437                         ++$high;
438
439         logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
440         $passing_slow = (($high/count($priorities)) > (2/3));
441
442         if ($passing_slow)
443                 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
444
445         return($passing_slow);
446 }
447
448 /**
449  * @brief Returns the next worker process
450  *
451  * @return string SQL statement
452  */
453 function poller_worker_process() {
454
455         q("START TRANSACTION;");
456
457         // Check if we should pass some low priority process
458         $highest_priority = 0;
459
460         if (poller_passing_slow($highest_priority)) {
461                 // Are there waiting processes with a higher priority than the currently highest?
462                 $r = q("SELECT * FROM `workerqueue`
463                                 WHERE `executed` = '0000-00-00 00:00:00' AND `priority` < %d
464                                 ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
465                 if (dbm::is_result($r))
466                         return $r;
467
468                 // Give slower processes some processing time
469                 $r = q("SELECT * FROM `workerqueue`
470                                 WHERE `executed` = '0000-00-00 00:00:00' AND `priority` > %d
471                                 ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
472         }
473
474         // If there is no result (or we shouldn't pass lower processes) we check without priority limit
475         if (($highest_priority == 0) OR !dbm::is_result($r))
476                 $r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority`, `created` LIMIT 1");
477
478         return $r;
479 }
480
481 function call_worker() {
482         if (!get_config("system", "frontend_worker")) {
483                 return;
484         }
485
486         $url = get_app()->get_baseurl()."/worker";
487         fetch_url($url, false, $redirects, 1);
488 }
489
490 function call_worker_if_idle() {
491         if (!get_config("system", "frontend_worker")) {
492                 return;
493         }
494
495         poller_run_cron();
496
497         clear_worker_processes();
498
499         $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
500
501         if ($workers[0]["processes"] == 0) {
502                 call_worker();
503         }
504 }
505
506 function clear_worker_processes() {
507         q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
508                 dbesc(datetime_convert('UTC','UTC',"now - 10 minutes")));
509 }
510
511 function poller_run_cron() {
512         // Run the cron job that calls all other jobs
513         proc_run(PRIORITY_MEDIUM, "include/cron.php");
514
515         // Run the cronhooks job separately from cron for being able to use a different timing
516         proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
517
518         // Cleaning dead processes
519         poller_kill_stale_workers();
520 }
521
522 if (array_search(__file__,get_included_files())===0){
523         poller_run($_SERVER["argv"],$_SERVER["argc"]);
524
525         get_app()->end_process();
526
527         killme();
528 }
529 ?>