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;
15 require_once("boot.php");
17 function poller_run($argv, $argc){
25 @include(".htconfig.php");
26 require_once("include/dba.php");
27 $db = new dba($db_host, $db_user, $db_pass, $db_data);
28 unset($db_host, $db_user, $db_pass, $db_data);
33 // Quit when in maintenance
34 if (Config::get('system', 'maintenance', true)) {
38 $a->set_baseurl(Config::get('system', 'url'));
44 if ($a->min_memory_reached()) {
48 if (poller_max_connections_reached()) {
52 if ($a->maxload_reached()) {
56 if(($argc <= 1) OR ($argv[1] != "no_cron")) {
60 if ($a->max_processes_reached()) {
64 // Checking the number of workers
65 if (poller_too_much_workers()) {
66 poller_kill_stale_workers();
72 while ($r = poller_worker_process()) {
74 // Count active workers and compare them with a maximum value that depends on the load
75 if (poller_too_much_workers()) {
79 if (!poller_execute($r[0])) {
83 // Quit the poller once every hour
84 if (time() > ($starttime + 3600))
91 * @brief Execute a worker entry
93 * @param array $queue Workerqueue entry
95 * @return boolean "true" if further processing should be stopped
97 function poller_execute($queue) {
103 // Quit when in maintenance
104 if (Config::get('system', 'maintenance', true)) {
108 // Constantly check the number of parallel database processes
109 if ($a->max_processes_reached()) {
113 // Constantly check the number of available database connections to let the frontend be accessible at any time
114 if (poller_max_connections_reached()) {
118 $upd = q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `pid` = 0",
119 dbesc(datetime_convert()),
121 intval($queue["id"]));
124 logger("Couldn't update queue entry ".$queue["id"]." - skip this execution", LOGGER_DEBUG);
129 // Assure that there are no tasks executed twice
130 $id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
132 logger("Queue item ".$queue["id"]." vanished - skip this execution", LOGGER_DEBUG);
135 } elseif ((strtotime($id[0]["executed"]) <= 0) OR ($id[0]["pid"] == 0)) {
136 logger("Entry for queue item ".$queue["id"]." wasn't stored - skip this execution", LOGGER_DEBUG);
139 } elseif ($id[0]["pid"] != $mypid) {
140 logger("Queue item ".$queue["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
146 $argv = json_decode($queue["parameter"]);
148 // Check for existance and validity of the include file
151 if (!validate_include($include)) {
152 logger("Include file ".$argv[0]." is not valid!");
153 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
157 require_once($include);
159 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
161 if (function_exists($funcname)) {
163 poller_exec_function($queue, $funcname, $argv);
165 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
167 logger("Function ".$funcname." does not exist");
174 * @brief Execute a function from the queue
176 * @param array $queue Workerqueue entry
177 * @param string $funcname name of the function
178 * @param array $argv Array of values to be passed to the function
180 function poller_exec_function($queue, $funcname, $argv) {
186 $argc = count($argv);
188 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
190 $stamp = (float)microtime(true);
192 // We use the callstack here to analyze the performance of executed worker entries.
193 // For this reason the variables have to be initialized.
194 if (Config::get("system", "profiler")) {
195 $a->performance["start"] = microtime(true);
196 $a->performance["database"] = 0;
197 $a->performance["database_write"] = 0;
198 $a->performance["network"] = 0;
199 $a->performance["file"] = 0;
200 $a->performance["rendering"] = 0;
201 $a->performance["parser"] = 0;
202 $a->performance["marktime"] = 0;
203 $a->performance["markstart"] = microtime(true);
204 $a->callstack = array();
207 // For better logging create a new process id for every worker call
208 // But preserve the old one for the worker
209 $old_process_id = $a->process_id;
210 $a->process_id = uniqid("wrk", true);
212 $funcname($argv, $argc);
214 $a->process_id = $old_process_id;
216 $duration = number_format(microtime(true) - $stamp, 3);
218 if ($duration > 3600) {
219 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
220 } elseif ($duration > 600) {
221 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
222 } elseif ($duration > 300) {
223 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
224 } elseif ($duration > 120) {
225 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
228 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
230 // Write down the performance values into the log
231 if (Config::get("system", "profiler")) {
232 $duration = microtime(true)-$a->performance["start"];
234 if (Config::get("rendertime", "callstack")) {
235 if (isset($a->callstack["database"])) {
236 $o = "\nDatabase Read:\n";
237 foreach ($a->callstack["database"] AS $func => $time) {
238 $time = round($time, 3);
240 $o .= $func.": ".$time."\n";
243 if (isset($a->callstack["database_write"])) {
244 $o .= "\nDatabase Write:\n";
245 foreach ($a->callstack["database_write"] AS $func => $time) {
246 $time = round($time, 3);
248 $o .= $func.": ".$time."\n";
251 if (isset($a->callstack["network"])) {
252 $o .= "\nNetwork:\n";
253 foreach ($a->callstack["network"] AS $func => $time) {
254 $time = round($time, 3);
256 $o .= $func.": ".$time."\n";
263 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
264 number_format($a->performance["database"] - $a->performance["database_write"], 2),
265 number_format($a->performance["database_write"], 2),
266 number_format($a->performance["network"], 2),
267 number_format($a->performance["file"], 2),
268 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
269 number_format($duration, 2)),
273 $cooldown = Config::get("system", "worker_cooldown", 0);
276 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
282 * @brief Checks if the number of database connections has reached a critical limit.
284 * @return bool Are more than 3/4 of the maximum connections used?
286 function poller_max_connections_reached() {
288 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
289 $max = Config::get("system", "max_connections");
291 // Fetch the percentage level where the poller will get active
292 $maxlevel = Config::get("system", "max_connections_level", 75);
295 // the maximum number of possible user connections can be a system variable
296 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
298 $max = $r[0]["Value"];
300 // Or it can be granted. This overrides the system variable
301 $r = q("SHOW GRANTS");
303 foreach ($r AS $grants) {
304 $grant = array_pop($grants);
305 if (stristr($grant, "GRANT USAGE ON"))
306 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
311 // If $max is set we will use the processlist to determine the current number of connections
312 // The processlist only shows entries of the current user
314 $r = q("SHOW PROCESSLIST");
315 if (!dbm::is_result($r))
320 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
322 $level = ($used / $max) * 100;
324 if ($level >= $maxlevel) {
325 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
330 // We will now check for the system values.
331 // This limit could be reached although the user limits are fine.
332 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
336 $max = intval($r[0]["Value"]);
340 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
344 $used = intval($r[0]["Value"]);
348 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
350 $level = $used / $max * 100;
352 if ($level < $maxlevel)
355 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
360 * @brief fix the queue entry if the worker process died
363 function poller_kill_stale_workers() {
364 $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` > '%s'", dbesc(NULL_DATE));
366 if (!dbm::is_result($r)) {
367 // No processing here needed
371 foreach ($r AS $pid) {
372 if (!posix_kill($pid["pid"], 0)) {
373 q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = 0 WHERE `pid` = %d",
374 dbesc(NULL_DATE), intval($pid["pid"]));
376 // Kill long running processes
378 // Check if the priority is in a valid range
379 if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE)))
380 $pid["priority"] = PRIORITY_MEDIUM;
382 // Define the maximum durations
383 $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
384 $max_duration = $max_duration_defaults[$pid["priority"]];
386 $argv = json_decode($pid["parameter"]);
387 $argv[0] = basename($argv[0]);
389 // How long is the process already running?
390 $duration = (time() - strtotime($pid["executed"])) / 60;
391 if ($duration > $max_duration) {
392 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
393 posix_kill($pid["pid"], SIGTERM);
395 // We killed the stale process.
396 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
397 // Additionally we are lowering the priority.
398 q("UPDATE `workerqueue` SET `executed` = '%s', `created` = '%s',
399 `priority` = %d, `pid` = 0 WHERE `pid` = %d",
401 dbesc(datetime_convert()),
402 intval(PRIORITY_NEGLIGIBLE),
403 intval($pid["pid"]));
405 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
412 * @brief Checks if the number of active workers exceeds the given limits
414 * @return bool Are there too much workers running?
416 function poller_too_much_workers() {
417 $queues = Config::get("system", "worker_queues", 4);
419 $maxqueues = $queues;
421 $active = poller_active_workers();
423 // Decrease the number of workers at higher load
424 $load = current_load();
426 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
428 $maxworkers = $queues;
430 // Some magical mathemathics to reduce the workers
432 $slope = $maxworkers / pow($maxsysload, $exponent);
433 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
435 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s'", dbesc(NULL_DATE));
436 $entries = $s[0]["total"];
438 if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
439 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
440 $top_priority = $s[0]["priority"];
442 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' LIMIT 1",
443 intval($top_priority), dbesc(NULL_DATE));
444 $high_running = dbm::is_result($s);
446 if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
447 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
448 $queues = $active + 1;
452 // Create a list of queue entries grouped by their priority
453 $running = array(PRIORITY_CRITICAL => 0,
455 PRIORITY_MEDIUM => 0,
457 PRIORITY_NEGLIGIBLE => 0);
459 $r = q("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` GROUP BY `priority`");
460 if (dbm::is_result($r))
461 foreach ($r AS $process)
462 $running[$process["priority"]] = $process["running"];
465 $r = q("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
466 if (dbm::is_result($r))
467 foreach ($r as $entry) {
468 if ($processlist != "")
469 $processlist .= ", ";
470 $processlist .= $entry["priority"].":".$running[$entry["priority"]]."/".$entry["entries"];
473 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries." (".$processlist.") - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
475 // Are there fewer workers running as possible? Then fork a new one.
476 if (!Config::get("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
477 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
478 $args = array("include/poller.php", "no_cron");
484 return($active >= $queues);
488 * @brief Returns the number of active poller processes
490 * @return integer Number of active poller processes
492 function poller_active_workers() {
493 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
495 return($workers[0]["processes"]);
499 * @brief Check if we should pass some slow processes
501 * When the active processes of the highest priority are using more than 2/3
502 * of all processes, we let pass slower processes.
504 * @param string $highest_priority Returns the currently highest priority
505 * @return bool We let pass a slower process than $highest_priority
507 function poller_passing_slow(&$highest_priority) {
509 $highest_priority = 0;
511 $r = q("SELECT `priority`
513 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
515 // No active processes at all? Fine
516 if (!dbm::is_result($r))
519 $priorities = array();
520 foreach ($r AS $line)
521 $priorities[] = $line["priority"];
524 if (count($priorities) == 0)
527 $highest_priority = min($priorities);
529 // The highest process is already the slowest one?
531 if ($highest_priority == PRIORITY_NEGLIGIBLE)
535 foreach ($priorities AS $priority)
536 if ($priority == $highest_priority)
539 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
540 $passing_slow = (($high/count($priorities)) > (2/3));
543 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
545 return($passing_slow);
549 * @brief Returns the next worker process
551 * @return string SQL statement
553 function poller_worker_process() {
555 q("START TRANSACTION;");
557 // Check if we should pass some low priority process
558 $highest_priority = 0;
560 if (poller_passing_slow($highest_priority)) {
561 // Are there waiting processes with a higher priority than the currently highest?
562 $r = q("SELECT * FROM `workerqueue`
563 WHERE `executed` <= '%s' AND `priority` < %d
564 ORDER BY `priority`, `created` LIMIT 1",
566 intval($highest_priority));
567 if (dbm::is_result($r)) {
570 // Give slower processes some processing time
571 $r = q("SELECT * FROM `workerqueue`
572 WHERE `executed` <= '%s' AND `priority` > %d
573 ORDER BY `priority`, `created` LIMIT 1",
575 intval($highest_priority));
578 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
579 if (($highest_priority == 0) OR !dbm::is_result($r)) {
580 $r = q("SELECT * FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority`, `created` LIMIT 1", dbesc(NULL_DATE));
586 * @brief Call the front end worker
588 function call_worker() {
589 if (!Config::get("system", "frontend_worker")) {
593 $url = App::get_baseurl()."/worker";
594 fetch_url($url, false, $redirects, 1);
598 * @brief Call the front end worker if there aren't any active
600 function call_worker_if_idle() {
601 if (!Config::get("system", "frontend_worker")) {
605 // Do we have "proc_open"? Then we can fork the poller
606 if (function_exists("proc_open")) {
607 // When was the last time that we called the worker?
608 // Less than one minute? Then we quit
609 if ((time() - Config::get("system", "worker_started")) < 60) {
613 set_config("system", "worker_started", time());
615 // Do we have enough running workers? Then we quit here.
616 if (poller_too_much_workers()) {
617 // Cleaning dead processes
618 poller_kill_stale_workers();
619 get_app()->remove_inactive_processes();
626 logger('Call poller', LOGGER_DEBUG);
628 $args = array("include/poller.php", "no_cron");
634 // We cannot execute background processes.
635 // We now run the processes from the frontend.
636 // This won't work with long running processes.
639 clear_worker_processes();
641 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
643 if ($workers[0]["processes"] == 0) {
649 * @brief Removes long running worker processes
651 function clear_worker_processes() {
652 $timeout = Config::get("system", "frontend_worker_timeout", 10);
654 /// @todo We should clean up the corresponding workerqueue entries as well
655 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
656 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
660 * @brief Runs the cron processes
662 function poller_run_cron() {
663 logger('Add cron entries', LOGGER_DEBUG);
665 // Check for spooled items
666 proc_run(PRIORITY_HIGH, "include/spool_post.php");
668 // Run the cron job that calls all other jobs
669 proc_run(PRIORITY_MEDIUM, "include/cron.php");
671 // Run the cronhooks job separately from cron for being able to use a different timing
672 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
674 // Cleaning dead processes
675 poller_kill_stale_workers();
678 if (array_search(__file__,get_included_files())===0){
679 poller_run($_SERVER["argv"],$_SERVER["argc"]);
681 get_app()->end_process();