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 // Quit when in maintenance
33 if (get_config('system', 'maintenance', true))
40 if ($a->max_processes_reached())
43 if (poller_max_connections_reached())
46 if (App::maxload_reached())
49 // Checking the number of workers
50 if (poller_too_much_workers()) {
51 poller_kill_stale_workers();
55 if(($argc <= 1) OR ($argv[1] != "no_cron")) {
56 // Run the cron job that calls all other jobs
57 proc_run(PRIORITY_MEDIUM, "include/cron.php");
59 // Run the cronhooks job separately from cron for being able to use a different timing
60 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
62 // Cleaning dead processes
63 poller_kill_stale_workers();
65 // Sleep four seconds before checking for running processes again to avoid having too many workers
68 // Checking number of workers
69 if (poller_too_much_workers())
72 $cooldown = Config::get("system", "worker_cooldown", 0);
76 while ($r = poller_worker_process()) {
78 // Quit when in maintenance
79 if (get_config('system', 'maintenance', true))
82 // Constantly check the number of parallel database processes
83 if ($a->max_processes_reached())
86 // Constantly check the number of available database connections to let the frontend be accessible at any time
87 if (poller_max_connections_reached())
90 // Count active workers and compare them with a maximum value that depends on the load
91 if (poller_too_much_workers())
94 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `executed` = '0000-00-00 00:00:00'",
95 dbesc(datetime_convert()),
99 // Assure that there are no tasks executed twice
100 $id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
102 logger("Queue item ".$r[0]["id"]." vanished - skip this execution", LOGGER_DEBUG);
104 } elseif ((strtotime($id[0]["executed"]) <= 0) OR ($id[0]["pid"] == 0)) {
105 logger("Entry for queue item ".$r[0]["id"]." wasn't stored - we better stop here", LOGGER_DEBUG);
107 } elseif ($id[0]["pid"] != $mypid) {
108 logger("Queue item ".$r[0]["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
112 $argv = json_decode($r[0]["parameter"]);
114 $argc = count($argv);
116 // Check for existance and validity of the include file
119 if (!validate_include($include)) {
120 logger("Include file ".$argv[0]." is not valid!");
121 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
125 require_once($include);
127 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
129 if (function_exists($funcname)) {
130 logger("Process ".$mypid." - Prio ".$r[0]["priority"]." - ID ".$r[0]["id"].": ".$funcname." ".$r[0]["parameter"]);
132 // For better logging create a new process id for every worker call
133 // But preserve the old one for the worker
134 $old_process_id = $a->process_id;
135 $a->process_id = uniqid("wrk", true);
137 $funcname($argv, $argc);
139 $a->process_id = $old_process_id;
142 logger("Process ".$mypid." - Prio ".$r[0]["priority"]." - ID ".$r[0]["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
146 logger("Process ".$mypid." - Prio ".$r[0]["priority"]." - ID ".$r[0]["id"].": ".$funcname." - done");
148 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($r[0]["id"]));
150 logger("Function ".$funcname." does not exist");
152 // Quit the poller once every hour
153 if (time() > ($starttime + 3600))
160 * @brief Checks if the number of database connections has reached a critical limit.
162 * @return bool Are more than 3/4 of the maximum connections used?
164 function poller_max_connections_reached() {
166 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
167 $max = get_config("system", "max_connections");
169 // Fetch the percentage level where the poller will get active
170 $maxlevel = get_config("system", "max_connections_level");
175 // the maximum number of possible user connections can be a system variable
176 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
178 $max = $r[0]["Value"];
180 // Or it can be granted. This overrides the system variable
181 $r = q("SHOW GRANTS");
183 foreach ($r AS $grants) {
184 $grant = array_pop($grants);
185 if (stristr($grant, "GRANT USAGE ON"))
186 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
191 // If $max is set we will use the processlist to determine the current number of connections
192 // The processlist only shows entries of the current user
194 $r = q("SHOW PROCESSLIST");
200 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
202 $level = ($used / $max) * 100;
204 if ($level >= $maxlevel) {
205 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
210 // We will now check for the system values.
211 // This limit could be reached although the user limits are fine.
212 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
216 $max = intval($r[0]["Value"]);
220 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
224 $used = intval($r[0]["Value"]);
228 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
230 $level = $used / $max * 100;
232 if ($level < $maxlevel)
235 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
240 * @brief fix the queue entry if the worker process died
243 function poller_kill_stale_workers() {
244 $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
246 if (!dbm::is_result($r)) {
247 // No processing here needed
252 if (!posix_kill($pid["pid"], 0))
253 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
254 intval($pid["pid"]));
256 // Kill long running processes
258 // Check if the priority is in a valid range
259 if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE)))
260 $pid["priority"] = PRIORITY_MEDIUM;
262 // Define the maximum durations
263 $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
264 $max_duration = $max_duration_defaults[$pid["priority"]];
266 $argv = json_decode($pid["parameter"]);
267 $argv[0] = basename($argv[0]);
269 // How long is the process already running?
270 $duration = (time() - strtotime($pid["executed"])) / 60;
271 if ($duration > $max_duration) {
272 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
273 posix_kill($pid["pid"], SIGTERM);
275 // We killed the stale process.
276 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
277 // Additionally we are lowering the priority.
278 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `created` = '%s',
279 `priority` = %d, `pid` = 0 WHERE `pid` = %d",
280 dbesc(datetime_convert()),
281 intval(PRIORITY_NEGLIGIBLE),
282 intval($pid["pid"]));
284 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
288 function poller_too_much_workers() {
291 $queues = get_config("system", "worker_queues");
296 $maxqueues = $queues;
298 $active = poller_active_workers();
300 // Decrease the number of workers at higher load
301 $load = current_load();
303 $maxsysload = intval(get_config('system','maxloadavg'));
307 $maxworkers = $queues;
309 // Some magical mathemathics to reduce the workers
311 $slope = $maxworkers / pow($maxsysload, $exponent);
312 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
314 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00'");
315 $entries = $s[0]["total"];
317 if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
318 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority` LIMIT 1");
319 $top_priority = $s[0]["priority"];
321 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` != '0000-00-00 00:00:00' LIMIT 1",
322 intval($top_priority));
323 $high_running = dbm::is_result($s);
325 if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
326 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
327 $queues = $active + 1;
331 // Create a list of queue entries grouped by their priority
332 $running = array(PRIORITY_CRITICAL => 0,
334 PRIORITY_MEDIUM => 0,
336 PRIORITY_NEGLIGIBLE => 0);
338 $r = q("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` GROUP BY `priority`");
339 if (dbm::is_result($r))
340 foreach ($r AS $process)
341 $running[$process["priority"]] = $process["running"];
344 $r = q("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
345 if (dbm::is_result($r))
346 foreach ($r as $entry) {
347 if ($processlist != "")
348 $processlist .= ", ";
349 $processlist .= $entry["priority"].":".$running[$entry["priority"]]."/".$entry["entries"];
352 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries." (".$processlist.") - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
354 // Are there fewer workers running as possible? Then fork a new one.
355 if (!get_config("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
356 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
357 $args = array("php", "include/poller.php", "no_cron");
363 return($active >= $queues);
366 function poller_active_workers() {
367 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
369 return($workers[0]["processes"]);
373 * @brief Check if we should pass some slow processes
375 * When the active processes of the highest priority are using more than 2/3
376 * of all processes, we let pass slower processes.
378 * @param string $highest_priority Returns the currently highest priority
379 * @return bool We let pass a slower process than $highest_priority
381 function poller_passing_slow(&$highest_priority) {
383 $highest_priority = 0;
385 $r = q("SELECT `priority`
387 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
388 WHERE `process`.`command` = 'poller.php'");
390 // No active processes at all? Fine
391 if (!dbm::is_result($r))
394 $priorities = array();
395 foreach ($r AS $line)
396 $priorities[] = $line["priority"];
399 if (count($priorities) == 0)
402 $highest_priority = min($priorities);
404 // The highest process is already the slowest one?
406 if ($highest_priority == PRIORITY_NEGLIGIBLE)
410 foreach ($priorities AS $priority)
411 if ($priority == $highest_priority)
414 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
415 $passing_slow = (($high/count($priorities)) > (2/3));
418 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
420 return($passing_slow);
424 * @brief Returns the next worker process
426 * @return string SQL statement
429 function poller_worker_process() {
431 // Check if we should pass some low priority process
432 $highest_priority = 0;
434 if (poller_passing_slow($highest_priority)) {
435 // Are there waiting processes with a higher priority than the currently highest?
436 $r = q("SELECT * FROM `workerqueue`
437 WHERE `executed` = '0000-00-00 00:00:00' AND `priority` < %d
438 ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
439 if (dbm::is_result($r))
442 // Give slower processes some processing time
443 $r = q("SELECT * FROM `workerqueue`
444 WHERE `executed` = '0000-00-00 00:00:00' AND `priority` > %d
445 ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
448 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
449 if (($highest_priority == 0) OR !dbm::is_result($r))
450 $r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority`, `created` LIMIT 1");
455 if (array_search(__file__,get_included_files())===0){
456 poller_run($_SERVER["argv"],$_SERVER["argc"]);
458 get_app()->end_process();