]> git.mxchange.org Git - friendica.git/blob - include/poller.php
Merge pull request #2314 from rabuzarus/0302_datetime_cleanup
[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         $load = current_load();
30         if($load) {
31                 $maxsysload = intval(get_config('system','maxloadavg'));
32                 if($maxsysload < 1)
33                         $maxsysload = 50;
34
35                 if(intval($load) > $maxsysload) {
36                         logger('system: load ' . $load . ' too high. poller deferred to next scheduled run.');
37                         return;
38                 }
39         }
40
41         // Checking the number of workers
42         if (poller_too_much_workers(1)) {
43                 poller_kill_stale_workers();
44                 return;
45         }
46
47         if(($argc <= 1) OR ($argv[1] != "no_cron")) {
48                 // Run the cron job that calls all other jobs
49                 proc_run("php","include/cron.php");
50
51                 // Run the cronhooks job separately from cron for being able to use a different timing
52                 proc_run("php","include/cronhooks.php");
53
54                 // Cleaning dead processes
55                 poller_kill_stale_workers();
56         } else
57                 // Sleep four seconds before checking for running processes again to avoid having too many workers
58                 sleep(4);
59
60         // Checking number of workers
61         if (poller_too_much_workers(2))
62                 return;
63
64         $starttime = time();
65
66         while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `created` LIMIT 1")) {
67
68                 // Count active workers and compare them with a maximum value that depends on the load
69                 if (poller_too_much_workers(3))
70                         return;
71
72                 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
73                         dbesc(datetime_convert()),
74                         intval(getmypid()),
75                         intval($r[0]["id"]));
76
77                 // Assure that there are no tasks executed twice
78                 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
79                         intval($r[0]["id"]),
80                         intval(getmypid()));
81                 if (!$id) {
82                         logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
83                         continue;
84                 }
85
86                 $argv = json_decode($r[0]["parameter"]);
87
88                 $argc = count($argv);
89
90                 // Check for existance and validity of the include file
91                 $include = $argv[0];
92
93                 if (!validate_include($include)) {
94                         logger("Include file ".$argv[0]." is not valid!");
95                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
96                         continue;
97                 }
98
99                 require_once($include);
100
101                 $funcname=str_replace(".php", "", basename($argv[0]))."_run";
102
103                 if (function_exists($funcname)) {
104                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
105                         $funcname($argv, $argc);
106
107                         logger("Process ".getmypid()." - ID ".$r[0]["id"].": ".$funcname." - done");
108
109                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
110                 } else
111                         logger("Function ".$funcname." does not exist");
112
113                 // Quit the poller once every hour
114                 if (time() > ($starttime + 3600))
115                         return;
116         }
117
118 }
119
120 /**
121  * @brief fix the queue entry if the worker process died
122  *
123  */
124 function poller_kill_stale_workers() {
125         $r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
126         foreach($r AS $pid)
127                 if (!posix_kill($pid["pid"], 0))
128                         q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
129                                 intval($pid["pid"]));
130                 else {
131                         // Kill long running processes
132                         $duration = (time() - strtotime($pid["executed"])) / 60;
133                         if ($duration > 180) {
134                                 logger("Worker process ".$pid["pid"]." took more than 3 hours. It will be killed now.");
135                                 posix_kill($pid["pid"], SIGTERM);
136
137                                 // Question: If a process is stale: Should we remove it or should we reschedule it?
138                                 // By now we rescheduling it. It's maybe not the wisest decision?
139                                 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
140                                         intval($pid["pid"]));
141                         } else
142                                 logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
143                 }
144 }
145
146 function poller_too_much_workers($stage) {
147
148         $queues = get_config("system", "worker_queues");
149
150         if ($queues == 0)
151                 $queues = 4;
152
153         $active = poller_active_workers();
154
155         // Decrease the number of workers at higher load
156         $load = current_load();
157         if($load) {
158                 $maxsysload = intval(get_config('system','maxloadavg'));
159                 if($maxsysload < 1)
160                         $maxsysload = 50;
161
162                 $maxworkers = $queues;
163
164                 // Some magical mathemathics to reduce the workers
165                 $exponent = 3;
166                 $slope = $maxworkers / pow($maxsysload, $exponent);
167                 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
168
169                 logger("Current load stage ".$stage.": ".$load." - maximum: ".$maxsysload." - current queues: ".$active." - maximum: ".$queues, LOGGER_DEBUG);
170
171         }
172
173         return($active >= $queues);
174 }
175
176 function poller_active_workers() {
177         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
178
179         return($workers[0]["workers"]);
180 }
181
182 if (array_search(__file__,get_included_files())===0){
183   poller_run($_SERVER["argv"],$_SERVER["argc"]);
184   killme();
185 }
186 ?>