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))
38 if ($a->max_processes_reached())
41 if (poller_max_connections_reached())
44 if (App::maxload_reached())
47 // Checking the number of workers
48 if (poller_too_much_workers()) {
49 poller_kill_stale_workers();
53 if(($argc <= 1) OR ($argv[1] != "no_cron")) {
56 // Sleep four seconds before checking for running processes again to avoid having too many workers
59 // Checking number of workers
60 if (poller_too_much_workers())
65 while ($r = poller_worker_process()) {
67 // Count active workers and compare them with a maximum value that depends on the load
68 if (poller_too_much_workers()) {
72 if (!poller_execute($r[0])) {
76 // Quit the poller once every hour
77 if (time() > ($starttime + 3600))
84 * @brief Execute a worker entry
86 * @param array $queue Workerqueue entry
88 * @return boolean "true" if further processing should be stopped
90 function poller_execute($queue) {
96 $cooldown = Config::get("system", "worker_cooldown", 0);
98 // Quit when in maintenance
99 if (get_config('system', 'maintenance', true)) {
103 // Constantly check the number of parallel database processes
104 if ($a->max_processes_reached()) {
108 // Constantly check the number of available database connections to let the frontend be accessible at any time
109 if (poller_max_connections_reached()) {
113 $upd = q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `pid` = 0",
114 dbesc(datetime_convert()),
116 intval($queue["id"]));
119 logger("Couldn't update queue entry ".$queue["id"]." - skip this execution", LOGGER_DEBUG);
124 // Assure that there are no tasks executed twice
125 $id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
127 logger("Queue item ".$queue["id"]." vanished - skip this execution", LOGGER_DEBUG);
130 } elseif ((strtotime($id[0]["executed"]) <= 0) OR ($id[0]["pid"] == 0)) {
131 logger("Entry for queue item ".$queue["id"]." wasn't stored - skip this execution", LOGGER_DEBUG);
134 } elseif ($id[0]["pid"] != $mypid) {
135 logger("Queue item ".$queue["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
141 $argv = json_decode($queue["parameter"]);
143 $argc = count($argv);
145 // Check for existance and validity of the include file
148 if (!validate_include($include)) {
149 logger("Include file ".$argv[0]." is not valid!");
150 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
154 require_once($include);
156 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
158 if (function_exists($funcname)) {
159 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
161 // For better logging create a new process id for every worker call
162 // But preserve the old one for the worker
163 $old_process_id = $a->process_id;
164 $a->process_id = uniqid("wrk", true);
166 $funcname($argv, $argc);
168 $a->process_id = $old_process_id;
171 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
175 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done");
177 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
179 logger("Function ".$funcname." does not exist");
186 * @brief Checks if the number of database connections has reached a critical limit.
188 * @return bool Are more than 3/4 of the maximum connections used?
190 function poller_max_connections_reached() {
192 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
193 $max = get_config("system", "max_connections");
195 // Fetch the percentage level where the poller will get active
196 $maxlevel = get_config("system", "max_connections_level");
201 // the maximum number of possible user connections can be a system variable
202 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
204 $max = $r[0]["Value"];
206 // Or it can be granted. This overrides the system variable
207 $r = q("SHOW GRANTS");
209 foreach ($r AS $grants) {
210 $grant = array_pop($grants);
211 if (stristr($grant, "GRANT USAGE ON"))
212 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
217 // If $max is set we will use the processlist to determine the current number of connections
218 // The processlist only shows entries of the current user
220 $r = q("SHOW PROCESSLIST");
226 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
228 $level = ($used / $max) * 100;
230 if ($level >= $maxlevel) {
231 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
236 // We will now check for the system values.
237 // This limit could be reached although the user limits are fine.
238 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
242 $max = intval($r[0]["Value"]);
246 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
250 $used = intval($r[0]["Value"]);
254 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
256 $level = $used / $max * 100;
258 if ($level < $maxlevel)
261 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
266 * @brief fix the queue entry if the worker process died
269 function poller_kill_stale_workers() {
270 $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
272 if (!dbm::is_result($r)) {
273 // No processing here needed
278 if (!posix_kill($pid["pid"], 0))
279 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
280 intval($pid["pid"]));
282 // Kill long running processes
284 // Check if the priority is in a valid range
285 if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE)))
286 $pid["priority"] = PRIORITY_MEDIUM;
288 // Define the maximum durations
289 $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
290 $max_duration = $max_duration_defaults[$pid["priority"]];
292 $argv = json_decode($pid["parameter"]);
293 $argv[0] = basename($argv[0]);
295 // How long is the process already running?
296 $duration = (time() - strtotime($pid["executed"])) / 60;
297 if ($duration > $max_duration) {
298 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
299 posix_kill($pid["pid"], SIGTERM);
301 // We killed the stale process.
302 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
303 // Additionally we are lowering the priority.
304 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `created` = '%s',
305 `priority` = %d, `pid` = 0 WHERE `pid` = %d",
306 dbesc(datetime_convert()),
307 intval(PRIORITY_NEGLIGIBLE),
308 intval($pid["pid"]));
310 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
314 function poller_too_much_workers() {
317 $queues = get_config("system", "worker_queues");
322 $maxqueues = $queues;
324 $active = poller_active_workers();
326 // Decrease the number of workers at higher load
327 $load = current_load();
329 $maxsysload = intval(get_config('system','maxloadavg'));
333 $maxworkers = $queues;
335 // Some magical mathemathics to reduce the workers
337 $slope = $maxworkers / pow($maxsysload, $exponent);
338 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
340 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00'");
341 $entries = $s[0]["total"];
343 if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
344 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority` LIMIT 1");
345 $top_priority = $s[0]["priority"];
347 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` != '0000-00-00 00:00:00' LIMIT 1",
348 intval($top_priority));
349 $high_running = dbm::is_result($s);
351 if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
352 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
353 $queues = $active + 1;
357 // Create a list of queue entries grouped by their priority
358 $running = array(PRIORITY_CRITICAL => 0,
360 PRIORITY_MEDIUM => 0,
362 PRIORITY_NEGLIGIBLE => 0);
364 $r = q("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` GROUP BY `priority`");
365 if (dbm::is_result($r))
366 foreach ($r AS $process)
367 $running[$process["priority"]] = $process["running"];
370 $r = q("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
371 if (dbm::is_result($r))
372 foreach ($r as $entry) {
373 if ($processlist != "")
374 $processlist .= ", ";
375 $processlist .= $entry["priority"].":".$running[$entry["priority"]]."/".$entry["entries"];
378 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries." (".$processlist.") - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
380 // Are there fewer workers running as possible? Then fork a new one.
381 if (!get_config("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
382 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
383 $args = array("php", "include/poller.php", "no_cron");
389 return($active >= $queues);
392 function poller_active_workers() {
393 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
395 return($workers[0]["processes"]);
399 * @brief Check if we should pass some slow processes
401 * When the active processes of the highest priority are using more than 2/3
402 * of all processes, we let pass slower processes.
404 * @param string $highest_priority Returns the currently highest priority
405 * @return bool We let pass a slower process than $highest_priority
407 function poller_passing_slow(&$highest_priority) {
409 $highest_priority = 0;
411 $r = q("SELECT `priority`
413 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
415 // No active processes at all? Fine
416 if (!dbm::is_result($r))
419 $priorities = array();
420 foreach ($r AS $line)
421 $priorities[] = $line["priority"];
424 if (count($priorities) == 0)
427 $highest_priority = min($priorities);
429 // The highest process is already the slowest one?
431 if ($highest_priority == PRIORITY_NEGLIGIBLE)
435 foreach ($priorities AS $priority)
436 if ($priority == $highest_priority)
439 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
440 $passing_slow = (($high/count($priorities)) > (2/3));
443 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
445 return($passing_slow);
449 * @brief Returns the next worker process
451 * @return string SQL statement
453 function poller_worker_process() {
455 q("START TRANSACTION;");
457 // Check if we should pass some low priority process
458 $highest_priority = 0;
460 if (poller_passing_slow($highest_priority)) {
461 // Are there waiting processes with a higher priority than the currently highest?
462 $r = q("SELECT * FROM `workerqueue`
463 WHERE `executed` = '0000-00-00 00:00:00' AND `priority` < %d
464 ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
465 if (dbm::is_result($r))
468 // Give slower processes some processing time
469 $r = q("SELECT * FROM `workerqueue`
470 WHERE `executed` = '0000-00-00 00:00:00' AND `priority` > %d
471 ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
474 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
475 if (($highest_priority == 0) OR !dbm::is_result($r))
476 $r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority`, `created` LIMIT 1");
481 function call_worker() {
482 if (!get_config("system", "frontend_worker")) {
486 $url = get_app()->get_baseurl()."/worker";
487 fetch_url($url, false, $redirects, 1);
490 function call_worker_if_idle() {
491 if (!get_config("system", "frontend_worker")) {
497 clear_worker_processes();
499 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
501 if ($workers[0]["processes"] == 0) {
506 function clear_worker_processes() {
507 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
508 dbesc(datetime_convert('UTC','UTC',"now - 10 minutes")));
511 function poller_run_cron() {
512 // Run the cron job that calls all other jobs
513 proc_run(PRIORITY_MEDIUM, "include/cron.php");
515 // Run the cronhooks job separately from cron for being able to use a different timing
516 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
518 // Cleaning dead processes
519 poller_kill_stale_workers();
522 if (array_search(__file__,get_included_files())===0){
523 poller_run($_SERVER["argv"],$_SERVER["argc"]);
525 get_app()->end_process();