]> git.mxchange.org Git - friendica.git/blob - include/poller.php
Double check for maximum number of workers
[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(function_exists('sys_getloadavg')) {
30                 $maxsysload = intval(get_config('system','maxloadavg'));
31                 if($maxsysload < 1)
32                         $maxsysload = 50;
33
34                 $load = sys_getloadavg();
35                 if(intval($load[0]) > $maxsysload) {
36                         logger('system: load ' . $load[0] . ' too high. poller deferred to next scheduled run.');
37                         return;
38                 }
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                 $r = q("SELECT DISTINCT(`pid`) FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
50                 foreach($r AS $pid)
51                         if (!posix_kill($pid["pid"], 0))
52                                 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
53                                         intval($pid["pid"]));
54                         else {
55                                 // To-Do: Kill long running processes
56                                 // But: Update processes (like the database update) mustn't be killed
57                         }
58
59         } else {
60                 // Checking the number of workers
61                 if (poller_too_much_workers(1))
62                         return;
63
64                 // Sleep four seconds before checking for running processes again to avoid having too many workers
65                 sleep(4);
66         }
67
68         // Checking number of workers
69         if (poller_too_much_workers(2))
70                 return;
71
72         $starttime = time();
73
74         while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `created` LIMIT 1")) {
75
76                 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
77                         dbesc(datetime_convert()),
78                         intval(getmypid()),
79                         intval($r[0]["id"]));
80
81                 // Assure that there are no tasks executed twice
82                 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
83                         intval($r[0]["id"]),
84                         intval(getmypid()));
85                 if (!$id) {
86                         logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
87                         continue;
88                 }
89
90                 $argv = json_decode($r[0]["parameter"]);
91
92                 $argc = count($argv);
93
94                 // Check for existance and validity of the include file
95                 $include = $argv[0];
96
97                 if (!validate_include($include)) {
98                         logger("Include file ".$argv[0]." is not valid!");
99                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
100                         continue;
101                 }
102
103                 require_once($include);
104
105                 $funcname=str_replace(".php", "", basename($argv[0]))."_run";
106
107                 if (function_exists($funcname)) {
108                         logger("Process ".getmypid().": ".$funcname." ".$r[0]["parameter"]);
109                         $funcname($argv, $argc);
110
111                         logger("Process ".getmypid().": ".$funcname." - done");
112
113                         q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
114                 } else
115                         logger("Function ".$funcname." does not exist");
116
117                 // Quit the poller once every hour
118                 if (time() > ($starttime + 3600))
119                         return;
120
121                 // Count active workers and compare them with a maximum value that depends on the load
122                 if (poller_too_much_workers(3))
123                         return;
124         }
125
126 }
127
128 function poller_too_much_workers($stage) {
129
130         $queues = get_config("system", "worker_queues");
131
132         if ($queues == 0)
133                 $queues = 4;
134
135         $active = poller_active_workers();
136
137         // Decrease the number of workers at higher load
138         if(function_exists('sys_getloadavg')) {
139                 $load = max(sys_getloadavg());
140
141                 $maxsysload = intval(get_config('system','maxloadavg'));
142                 if($maxsysload < 1)
143                         $maxsysload = 50;
144
145                 $maxworkers = $queues;
146
147                 // Some magical mathemathics to reduce the workers
148                 $exponent = 3;
149                 $slope = $maxworkers / pow($maxsysload, $exponent);
150                 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
151
152                 logger("Current load stage ".$stage.": ".$load." - maximum: ".$maxsysload." - current queues: ".$active." - maximum: ".$queues, LOGGER_DEBUG);
153
154         }
155
156         return($active >= $queues);
157 }
158
159 function poller_active_workers() {
160         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
161
162         return($workers[0]["workers"]);
163 }
164
165 if (array_search(__file__,get_included_files())===0){
166   poller_run($_SERVER["argv"],$_SERVER["argc"]);
167   killme();
168 }
169 ?>