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