2 if (!file_exists("boot.php") AND (sizeof($_SERVER["argv"]) != 0)) {
3 $directory = dirname($_SERVER["argv"][0]);
5 if (substr($directory, 0, 1) != "/")
6 $directory = $_SERVER["PWD"]."/".$directory;
8 $directory = realpath($directory."/..");
13 use \Friendica\Core\Config;
14 use \Friendica\Core\PConfig;
16 require_once("boot.php");
18 function poller_run(&$argv, &$argc){
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);
32 if ($a->max_processes_reached())
35 if (poller_max_connections_reached())
38 if (App::maxload_reached())
41 // Checking the number of workers
42 if (poller_too_much_workers()) {
43 poller_kill_stale_workers();
47 if(($argc <= 1) OR ($argv[1] != "no_cron")) {
48 // Run the cron job that calls all other jobs
49 proc_run(PRIORITY_MEDIUM, "include/cron.php");
51 // Run the cronhooks job separately from cron for being able to use a different timing
52 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
54 // Cleaning dead processes
55 poller_kill_stale_workers();
57 // Sleep four seconds before checking for running processes again to avoid having too many workers
60 // Checking number of workers
61 if (poller_too_much_workers())
64 $cooldown = Config::get("system", "worker_cooldown", 0);
68 while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority`, `created` LIMIT 1")) {
70 // Constantly check the number of parallel database processes
71 if ($a->max_processes_reached())
74 // Constantly check the number of available database connections to let the frontend be accessible at any time
75 if (poller_max_connections_reached())
78 // Count active workers and compare them with a maximum value that depends on the load
79 if (poller_too_much_workers())
82 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
83 dbesc(datetime_convert()),
87 // Assure that there are no tasks executed twice
88 $id = q("SELECT `id` FROM `workerqueue` WHERE `id` = %d AND `pid` = %d",
92 logger("Queue item ".$r[0]["id"]." was executed multiple times - skip this execution", LOGGER_DEBUG);
96 $argv = json_decode($r[0]["parameter"]);
100 // Check for existance and validity of the include file
103 if (!validate_include($include)) {
104 logger("Include file ".$argv[0]." is not valid!");
105 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
109 require_once($include);
111 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
113 if (function_exists($funcname)) {
114 logger("Process ".getmypid()." - Prio ".$r[0]["priority"]." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
115 $funcname($argv, $argc);
118 logger("Process ".getmypid()." - Prio ".$r[0]["priority"]." - ID ".$r[0]["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
122 logger("Process ".getmypid()." - Prio ".$r[0]["priority"]." - ID ".$r[0]["id"].": ".$funcname." - done");
124 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
126 logger("Function ".$funcname." does not exist");
128 // Quit the poller once every hour
129 if (time() > ($starttime + 3600))
136 * @brief Checks if the number of database connections has reached a critical limit.
138 * @return bool Are more than 3/4 of the maximum connections used?
140 function poller_max_connections_reached() {
142 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
143 $max = get_config("system", "max_connections");
145 // Fetch the percentage level where the poller will get active
146 $maxlevel = get_config("system", "max_connections_level");
151 // the maximum number of possible user connections can be a system variable
152 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
154 $max = $r[0]["Value"];
156 // Or it can be granted. This overrides the system variable
157 $r = q("SHOW GRANTS");
159 foreach ($r AS $grants) {
160 $grant = array_pop($grants);
161 if (stristr($grant, "GRANT USAGE ON"))
162 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
167 // If $max is set we will use the processlist to determine the current number of connections
168 // The processlist only shows entries of the current user
170 $r = q("SHOW PROCESSLIST");
176 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
178 $level = ($used / $max) * 100;
180 if ($level >= $maxlevel) {
181 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
186 // We will now check for the system values.
187 // This limit could be reached although the user limits are fine.
188 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
192 $max = intval($r[0]["Value"]);
196 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
200 $used = intval($r[0]["Value"]);
204 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
206 $level = $used / $max * 100;
208 if ($level < $maxlevel)
211 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
216 * @brief fix the queue entry if the worker process died
219 function poller_kill_stale_workers() {
220 $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
222 if (!dbm::is_result($r)) {
223 // No processing here needed
228 if (!posix_kill($pid["pid"], 0))
229 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
230 intval($pid["pid"]));
232 // Kill long running processes
234 // Check if the priority is in a valid range
235 if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE)))
236 $pid["priority"] = PRIORITY_MEDIUM;
238 // Define the maximum durations
239 $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
240 $max_duration = $max_duration_defaults[$pid["priority"]];
242 $argv = json_decode($pid["parameter"]);
243 $argv[0] = basename($argv[0]);
245 // How long is the process already running?
246 $duration = (time() - strtotime($pid["executed"])) / 60;
247 if ($duration > $max_duration) {
248 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
249 posix_kill($pid["pid"], SIGTERM);
251 // We killed the stale process.
252 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
253 // Additionally we are lowering the priority.
254 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `created` = '%s',
255 `priority` = %d, `pid` = 0 WHERE `pid` = %d",
256 dbesc(datetime_convert()),
257 intval(PRIORITY_NEGLIGIBLE),
258 intval($pid["pid"]));
260 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
264 function poller_too_much_workers() {
267 $queues = get_config("system", "worker_queues");
272 $maxqueues = $queues;
274 $active = poller_active_workers();
276 // Decrease the number of workers at higher load
277 $load = current_load();
279 $maxsysload = intval(get_config('system','maxloadavg'));
283 $maxworkers = $queues;
285 // Some magical mathemathics to reduce the workers
287 $slope = $maxworkers / pow($maxsysload, $exponent);
288 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
290 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00'");
291 $entries = $s[0]["total"];
293 if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
294 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority` LIMIT 1");
295 $top_priority = $s[0]["priority"];
297 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` != '0000-00-00 00:00:00' LIMIT 1",
298 intval($top_priority));
299 $high_running = dbm::is_result($s);
301 if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
302 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
303 $queues = $active + 1;
307 logger("Current load: ".$load." - maximum: ".$maxsysload." - current queues: ".$active."/".$entries." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
309 // Are there fewer workers running as possible? Then fork a new one.
310 if (!get_config("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
311 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
312 $args = array("php", "include/poller.php", "no_cron");
318 return($active >= $queues);
321 function poller_active_workers() {
322 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
324 return($workers[0]["workers"]);
327 if (array_search(__file__,get_included_files())===0){
328 poller_run($_SERVER["argv"],$_SERVER["argc"]);