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)) {
40 if (poller_max_connections_reached()) {
44 if ($a->maxload_reached()) {
48 if(($argc <= 1) OR ($argv[1] != "no_cron")) {
52 if ($a->max_processes_reached()) {
56 // Checking the number of workers
57 if (poller_too_much_workers()) {
58 poller_kill_stale_workers();
64 while ($r = poller_worker_process()) {
66 // Count active workers and compare them with a maximum value that depends on the load
67 if (poller_too_much_workers()) {
71 if (!poller_execute($r[0])) {
75 // Quit the poller once every hour
76 if (time() > ($starttime + 3600))
83 * @brief Execute a worker entry
85 * @param array $queue Workerqueue entry
87 * @return boolean "true" if further processing should be stopped
89 function poller_execute($queue) {
95 // Quit when in maintenance
96 if (Config::get('system', 'maintenance', true)) {
100 // Constantly check the number of parallel database processes
101 if ($a->max_processes_reached()) {
105 // Constantly check the number of available database connections to let the frontend be accessible at any time
106 if (poller_max_connections_reached()) {
110 $upd = q("UPDATE `workerqueue` SET `executed` = '%s', `pid` = %d WHERE `id` = %d AND `pid` = 0",
111 dbesc(datetime_convert()),
113 intval($queue["id"]));
116 logger("Couldn't update queue entry ".$queue["id"]." - skip this execution", LOGGER_DEBUG);
121 // Assure that there are no tasks executed twice
122 $id = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
124 logger("Queue item ".$queue["id"]." vanished - skip this execution", LOGGER_DEBUG);
127 } elseif ((strtotime($id[0]["executed"]) <= 0) OR ($id[0]["pid"] == 0)) {
128 logger("Entry for queue item ".$queue["id"]." wasn't stored - skip this execution", LOGGER_DEBUG);
131 } elseif ($id[0]["pid"] != $mypid) {
132 logger("Queue item ".$queue["id"]." is to be executed by process ".$id[0]["pid"]." and not by me (".$mypid.") - skip this execution", LOGGER_DEBUG);
138 $argv = json_decode($queue["parameter"]);
140 // Check for existance and validity of the include file
143 if (!validate_include($include)) {
144 logger("Include file ".$argv[0]." is not valid!");
145 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
149 require_once($include);
151 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
153 if (function_exists($funcname)) {
155 poller_exec_function($queue, $funcname, $argv);
157 q("DELETE FROM `workerqueue` WHERE `id` = %d", intval($queue["id"]));
159 logger("Function ".$funcname." does not exist");
166 * @brief Execute a function from the queue
168 * @param array $queue Workerqueue entry
169 * @param string $funcname name of the function
170 * @param array $argv Array of values to be passed to the function
172 function poller_exec_function($queue, $funcname, $argv) {
178 $argc = count($argv);
180 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
182 $stamp = (float)microtime(true);
184 // We use the callstack here to analyze the performance of executed worker entries.
185 // For this reason the variables have to be initialized.
186 if (Config::get("system", "profiler")) {
187 $a->performance["start"] = microtime(true);
188 $a->performance["database"] = 0;
189 $a->performance["database_write"] = 0;
190 $a->performance["network"] = 0;
191 $a->performance["file"] = 0;
192 $a->performance["rendering"] = 0;
193 $a->performance["parser"] = 0;
194 $a->performance["marktime"] = 0;
195 $a->performance["markstart"] = microtime(true);
196 $a->callstack = array();
199 // For better logging create a new process id for every worker call
200 // But preserve the old one for the worker
201 $old_process_id = $a->process_id;
202 $a->process_id = uniqid("wrk", true);
204 $funcname($argv, $argc);
206 $a->process_id = $old_process_id;
208 $duration = number_format(microtime(true) - $stamp, 3);
210 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
212 // Write down the performance values into the log
213 if (Config::get("system", "profiler")) {
214 $duration = microtime(true)-$a->performance["start"];
216 if (Config::get("rendertime", "callstack")) {
217 if (isset($a->callstack["database"])) {
218 $o = "\nDatabase Read:\n";
219 foreach ($a->callstack["database"] AS $func => $time) {
220 $time = round($time, 3);
222 $o .= $func.": ".$time."\n";
225 if (isset($a->callstack["database_write"])) {
226 $o .= "\nDatabase Write:\n";
227 foreach ($a->callstack["database_write"] AS $func => $time) {
228 $time = round($time, 3);
230 $o .= $func.": ".$time."\n";
233 if (isset($a->callstack["network"])) {
234 $o .= "\nNetwork:\n";
235 foreach ($a->callstack["network"] AS $func => $time) {
236 $time = round($time, 3);
238 $o .= $func.": ".$time."\n";
245 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
246 number_format($a->performance["database"] - $a->performance["database_write"], 2),
247 number_format($a->performance["database_write"], 2),
248 number_format($a->performance["network"], 2),
249 number_format($a->performance["file"], 2),
250 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
251 number_format($duration, 2)),
255 $cooldown = Config::get("system", "worker_cooldown", 0);
258 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
264 * @brief Checks if the number of database connections has reached a critical limit.
266 * @return bool Are more than 3/4 of the maximum connections used?
268 function poller_max_connections_reached() {
270 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
271 $max = Config::get("system", "max_connections");
273 // Fetch the percentage level where the poller will get active
274 $maxlevel = Config::get("system", "max_connections_level", 75);
277 // the maximum number of possible user connections can be a system variable
278 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
280 $max = $r[0]["Value"];
282 // Or it can be granted. This overrides the system variable
283 $r = q("SHOW GRANTS");
285 foreach ($r AS $grants) {
286 $grant = array_pop($grants);
287 if (stristr($grant, "GRANT USAGE ON"))
288 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
293 // If $max is set we will use the processlist to determine the current number of connections
294 // The processlist only shows entries of the current user
296 $r = q("SHOW PROCESSLIST");
297 if (!dbm::is_result($r))
302 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
304 $level = ($used / $max) * 100;
306 if ($level >= $maxlevel) {
307 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
312 // We will now check for the system values.
313 // This limit could be reached although the user limits are fine.
314 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
318 $max = intval($r[0]["Value"]);
322 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
326 $used = intval($r[0]["Value"]);
330 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
332 $level = $used / $max * 100;
334 if ($level < $maxlevel)
337 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
342 * @brief fix the queue entry if the worker process died
345 function poller_kill_stale_workers() {
346 $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
348 if (!dbm::is_result($r)) {
349 // No processing here needed
354 if (!posix_kill($pid["pid"], 0))
355 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
356 intval($pid["pid"]));
358 // Kill long running processes
360 // Check if the priority is in a valid range
361 if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE)))
362 $pid["priority"] = PRIORITY_MEDIUM;
364 // Define the maximum durations
365 $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
366 $max_duration = $max_duration_defaults[$pid["priority"]];
368 $argv = json_decode($pid["parameter"]);
369 $argv[0] = basename($argv[0]);
371 // How long is the process already running?
372 $duration = (time() - strtotime($pid["executed"])) / 60;
373 if ($duration > $max_duration) {
374 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
375 posix_kill($pid["pid"], SIGTERM);
377 // We killed the stale process.
378 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
379 // Additionally we are lowering the priority.
380 q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `created` = '%s',
381 `priority` = %d, `pid` = 0 WHERE `pid` = %d",
382 dbesc(datetime_convert()),
383 intval(PRIORITY_NEGLIGIBLE),
384 intval($pid["pid"]));
386 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
391 * @brief Checks if the number of active workers exceeds the given limits
393 * @return bool Are there too much workers running?
395 function poller_too_much_workers() {
396 $queues = Config::get("system", "worker_queues", 4);
398 $maxqueues = $queues;
400 $active = poller_active_workers();
402 // Decrease the number of workers at higher load
403 $load = current_load();
405 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
407 $maxworkers = $queues;
409 // Some magical mathemathics to reduce the workers
411 $slope = $maxworkers / pow($maxsysload, $exponent);
412 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
414 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00'");
415 $entries = $s[0]["total"];
417 if (Config::get("system", "worker_fastlane", false) AND ($queues > 0) AND ($entries > 0) AND ($active >= $queues)) {
418 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority` LIMIT 1");
419 $top_priority = $s[0]["priority"];
421 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` != '0000-00-00 00:00:00' LIMIT 1",
422 intval($top_priority));
423 $high_running = dbm::is_result($s);
425 if (!$high_running AND ($top_priority > PRIORITY_UNDEFINED) AND ($top_priority < PRIORITY_NEGLIGIBLE)) {
426 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
427 $queues = $active + 1;
431 // Create a list of queue entries grouped by their priority
432 $running = array(PRIORITY_CRITICAL => 0,
434 PRIORITY_MEDIUM => 0,
436 PRIORITY_NEGLIGIBLE => 0);
438 $r = q("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` GROUP BY `priority`");
439 if (dbm::is_result($r))
440 foreach ($r AS $process)
441 $running[$process["priority"]] = $process["running"];
444 $r = q("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
445 if (dbm::is_result($r))
446 foreach ($r as $entry) {
447 if ($processlist != "")
448 $processlist .= ", ";
449 $processlist .= $entry["priority"].":".$running[$entry["priority"]]."/".$entry["entries"];
452 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries." (".$processlist.") - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
454 // Are there fewer workers running as possible? Then fork a new one.
455 if (!Config::get("system", "worker_dont_fork") AND ($queues > ($active + 1)) AND ($entries > 1)) {
456 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
457 $args = array("php", "include/poller.php", "no_cron");
463 return($active >= $queues);
467 * @brief Returns the number of active poller processes
469 * @return integer Number of active poller processes
471 function poller_active_workers() {
472 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
474 return($workers[0]["processes"]);
478 * @brief Check if we should pass some slow processes
480 * When the active processes of the highest priority are using more than 2/3
481 * of all processes, we let pass slower processes.
483 * @param string $highest_priority Returns the currently highest priority
484 * @return bool We let pass a slower process than $highest_priority
486 function poller_passing_slow(&$highest_priority) {
488 $highest_priority = 0;
490 $r = q("SELECT `priority`
492 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
494 // No active processes at all? Fine
495 if (!dbm::is_result($r))
498 $priorities = array();
499 foreach ($r AS $line)
500 $priorities[] = $line["priority"];
503 if (count($priorities) == 0)
506 $highest_priority = min($priorities);
508 // The highest process is already the slowest one?
510 if ($highest_priority == PRIORITY_NEGLIGIBLE)
514 foreach ($priorities AS $priority)
515 if ($priority == $highest_priority)
518 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
519 $passing_slow = (($high/count($priorities)) > (2/3));
522 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
524 return($passing_slow);
528 * @brief Returns the next worker process
530 * @return string SQL statement
532 function poller_worker_process() {
534 q("START TRANSACTION;");
536 // Check if we should pass some low priority process
537 $highest_priority = 0;
539 if (poller_passing_slow($highest_priority)) {
540 // Are there waiting processes with a higher priority than the currently highest?
541 $r = q("SELECT * FROM `workerqueue`
542 WHERE `executed` = '0000-00-00 00:00:00' AND `priority` < %d
543 ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
544 if (dbm::is_result($r))
547 // Give slower processes some processing time
548 $r = q("SELECT * FROM `workerqueue`
549 WHERE `executed` = '0000-00-00 00:00:00' AND `priority` > %d
550 ORDER BY `priority`, `created` LIMIT 1", dbesc($highest_priority));
553 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
554 if (($highest_priority == 0) OR !dbm::is_result($r))
555 $r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `priority`, `created` LIMIT 1");
561 * @brief Call the front end worker
563 function call_worker() {
564 if (!Config::get("system", "frontend_worker") OR !Config::get("system", "worker")) {
568 $url = App::get_baseurl()."/worker";
569 fetch_url($url, false, $redirects, 1);
573 * @brief Call the front end worker if there aren't any active
575 function call_worker_if_idle() {
576 if (!Config::get("system", "frontend_worker") OR !Config::get("system", "worker")) {
580 // Do we have "proc_open"? Then we can fork the poller
581 if (function_exists("proc_open")) {
582 // When was the last time that we called the worker?
583 // Less than one minute? Then we quit
584 if ((time() - Config::get("system", "worker_started")) < 60) {
588 set_config("system", "worker_started", time());
590 // Do we have enough running workers? Then we quit here.
591 if (poller_too_much_workers()) {
592 // Cleaning dead processes
593 poller_kill_stale_workers();
594 get_app()->remove_inactive_processes();
601 logger('Call poller', LOGGER_DEBUG);
603 $args = array("php", "include/poller.php", "no_cron");
609 // We cannot execute background processes.
610 // We now run the processes from the frontend.
611 // This won't work with long running processes.
614 clear_worker_processes();
616 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
618 if ($workers[0]["processes"] == 0) {
624 * @brief Removes long running worker processes
626 function clear_worker_processes() {
627 $timeout = Config::get("system", "frontend_worker_timeout", 10);
629 /// @todo We should clean up the corresponding workerqueue entries as well
630 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
631 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
635 * @brief Runs the cron processes
637 function poller_run_cron() {
638 logger('Add cron entries', LOGGER_DEBUG);
640 // Check for spooled items
641 proc_run(PRIORITY_HIGH, "include/spool_post.php");
643 // Run the cron job that calls all other jobs
644 proc_run(PRIORITY_MEDIUM, "include/cron.php");
646 // Run the cronhooks job separately from cron for being able to use a different timing
647 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
649 // Cleaning dead processes
650 poller_kill_stale_workers();
653 if (array_search(__file__,get_included_files())===0){
654 poller_run($_SERVER["argv"],$_SERVER["argc"]);
656 get_app()->end_process();