4 use Friendica\Core\Config;
5 use Friendica\Util\Lock;
7 if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
8 $directory = dirname($_SERVER["argv"][0]);
10 if (substr($directory, 0, 1) != "/") {
11 $directory = $_SERVER["PWD"]."/".$directory;
13 $directory = realpath($directory."/..");
18 require_once("boot.php");
20 function poller_run($argv, $argc){
21 global $a, $db, $poller_up_start, $poller_db_duration;
23 $poller_up_start = microtime(true);
25 $a = new App(dirname(__DIR__));
27 @include(".htconfig.php");
28 require_once("include/dba.php");
29 $db = new dba($db_host, $db_user, $db_pass, $db_data);
30 unset($db_host, $db_user, $db_pass, $db_data);
34 // Quit when in maintenance
35 if (Config::get('system', 'maintenance', true)) {
39 $a->set_baseurl(Config::get('system', 'url'));
43 // At first check the maximum load. We shouldn't continue with a high load
44 if ($a->maxload_reached()) {
45 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
49 // We now start the process. This is done after the load check since this could increase the load.
52 // Kill stale processes every 5 minutes
53 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
54 if (time() > ($last_cleanup + 300)) {
55 Config::set('system', 'poller_last_cleaned', time());
56 poller_kill_stale_workers();
59 // Count active workers and compare them with a maximum value that depends on the load
60 if (poller_too_much_workers()) {
61 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
65 // Do we have too few memory?
66 if ($a->min_memory_reached()) {
67 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
71 // Possibly there are too much database connections
72 if (poller_max_connections_reached()) {
73 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
77 // Possibly there are too much database processes that block the system
78 if ($a->max_processes_reached()) {
79 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
83 // Now we start additional cron processes if we should do so
84 if (($argc <= 1) || ($argv[1] != "no_cron")) {
90 // We fetch the next queue entry that is about to be executed
91 while ($r = poller_worker_process()) {
95 foreach ($r AS $entry) {
96 // Assure that the priority is an integer value
97 $entry['priority'] = (int)$entry['priority'];
99 // The work will be done
100 if (!poller_execute($entry)) {
101 logger('Process execution failed, quitting.', LOGGER_DEBUG);
105 // If possible we will fetch new jobs for this worker
106 if (!$refetched && Lock::set('poller_worker_process', 0)) {
107 $stamp = (float)microtime(true);
108 $refetched = find_worker_processes();
109 $poller_db_duration += (microtime(true) - $stamp);
110 Lock::remove('poller_worker_process');
114 // To avoid the quitting of multiple pollers only one poller at a time will execute the check
115 if (Lock::set('poller_worker', 0)) {
116 $stamp = (float)microtime(true);
117 // Count active workers and compare them with a maximum value that depends on the load
118 if (poller_too_much_workers()) {
119 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
124 if ($a->min_memory_reached()) {
125 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
128 Lock::remove('poller_worker');
129 $poller_db_duration += (microtime(true) - $stamp);
132 // Quit the poller once every 5 minutes
133 if (time() > ($starttime + 300)) {
134 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
138 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
142 * @brief Returns the number of non executed entries in the worker queue
144 * @return integer Number of non executed entries in the worker queue
146 function poller_total_entries() {
147 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done`", dbesc(NULL_DATE));
148 if (dbm::is_result($s)) {
149 return $s[0]["total"];
156 * @brief Returns the highest priority in the worker queue that isn't executed
158 * @return integer Number of active poller processes
160 function poller_highest_priority() {
161 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done` ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
162 if (dbm::is_result($s)) {
163 return $s[0]["priority"];
170 * @brief Returns if a process with the given priority is running
172 * @param integer $priority The priority that should be checked
174 * @return integer Is there a process running with that priority?
176 function poller_process_with_priority_active($priority) {
177 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' AND NOT `done` LIMIT 1",
178 intval($priority), dbesc(NULL_DATE));
179 return dbm::is_result($s);
183 * @brief Execute a worker entry
185 * @param array $queue Workerqueue entry
187 * @return boolean "true" if further processing should be stopped
189 function poller_execute($queue) {
190 global $poller_db_duration, $poller_last_update;
196 // Quit when in maintenance
197 if (Config::get('system', 'maintenance', true)) {
198 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
202 // Constantly check the number of parallel database processes
203 if ($a->max_processes_reached()) {
204 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
208 // Constantly check the number of available database connections to let the frontend be accessible at any time
209 if (poller_max_connections_reached()) {
210 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
214 $argv = json_decode($queue["parameter"]);
216 // Check for existance and validity of the include file
219 if (!validate_include($include)) {
220 logger("Include file ".$argv[0]." is not valid!");
221 dba::delete('workerqueue', array('id' => $queue["id"]));
225 require_once($include);
227 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
229 if (function_exists($funcname)) {
231 // We constantly update the "executed" date every minute to avoid being killed to soon
232 if (!isset($poller_last_update)) {
233 $poller_last_update = strtotime($queue["executed"]);
236 $age = (time() - $poller_last_update) / 60;
237 $poller_last_update = time();
240 $stamp = (float)microtime(true);
241 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
242 $poller_db_duration += (microtime(true) - $stamp);
245 poller_exec_function($queue, $funcname, $argv);
247 $stamp = (float)microtime(true);
248 dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]));
249 $poller_db_duration = (microtime(true) - $stamp);
251 logger("Function ".$funcname." does not exist");
252 dba::delete('workerqueue', array('id' => $queue["id"]));
259 * @brief Execute a function from the queue
261 * @param array $queue Workerqueue entry
262 * @param string $funcname name of the function
263 * @param array $argv Array of values to be passed to the function
265 function poller_exec_function($queue, $funcname, $argv) {
266 global $poller_up_start, $poller_db_duration, $poller_lock_duration;
272 $argc = count($argv);
274 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
276 $stamp = (float)microtime(true);
278 // We use the callstack here to analyze the performance of executed worker entries.
279 // For this reason the variables have to be initialized.
280 if (Config::get("system", "profiler")) {
281 $a->performance["start"] = microtime(true);
282 $a->performance["database"] = 0;
283 $a->performance["database_write"] = 0;
284 $a->performance["network"] = 0;
285 $a->performance["file"] = 0;
286 $a->performance["rendering"] = 0;
287 $a->performance["parser"] = 0;
288 $a->performance["marktime"] = 0;
289 $a->performance["markstart"] = microtime(true);
290 $a->callstack = array();
293 // For better logging create a new process id for every worker call
294 // But preserve the old one for the worker
295 $old_process_id = $a->process_id;
296 $a->process_id = uniqid("wrk", true);
299 $up_duration = number_format(microtime(true) - $poller_up_start, 3);
301 $funcname($argv, $argc);
303 $a->process_id = $old_process_id;
306 $duration = number_format(microtime(true) - $stamp, 3);
308 $poller_up_start = microtime(true);
310 /* With these values we can analyze how effective the worker is.
311 * The database and rest time should be low since this is the unproductive time.
312 * The execution time is the productive time.
313 * By changing parameters like the maximum number of workers we can check the effectivness.
315 logger('DB: '.number_format($poller_db_duration, 2).
316 ' - Lock: '.number_format($poller_lock_duration, 2).
317 ' - Rest: '.number_format($up_duration - $poller_db_duration - $poller_lock_duration, 2).
318 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
319 $poller_lock_duration = 0;
321 if ($duration > 3600) {
322 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
323 } elseif ($duration > 600) {
324 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
325 } elseif ($duration > 300) {
326 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
327 } elseif ($duration > 120) {
328 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
331 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
333 // Write down the performance values into the log
334 if (Config::get("system", "profiler")) {
335 $duration = microtime(true)-$a->performance["start"];
337 if (Config::get("rendertime", "callstack")) {
338 if (isset($a->callstack["database"])) {
339 $o = "\nDatabase Read:\n";
340 foreach ($a->callstack["database"] AS $func => $time) {
341 $time = round($time, 3);
343 $o .= $func.": ".$time."\n";
347 if (isset($a->callstack["database_write"])) {
348 $o .= "\nDatabase Write:\n";
349 foreach ($a->callstack["database_write"] AS $func => $time) {
350 $time = round($time, 3);
352 $o .= $func.": ".$time."\n";
356 if (isset($a->callstack["network"])) {
357 $o .= "\nNetwork:\n";
358 foreach ($a->callstack["network"] AS $func => $time) {
359 $time = round($time, 3);
361 $o .= $func.": ".$time."\n";
369 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
370 number_format($a->performance["database"] - $a->performance["database_write"], 2),
371 number_format($a->performance["database_write"], 2),
372 number_format($a->performance["network"], 2),
373 number_format($a->performance["file"], 2),
374 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
375 number_format($duration, 2)),
379 $cooldown = Config::get("system", "worker_cooldown", 0);
382 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
388 * @brief Checks if the number of database connections has reached a critical limit.
390 * @return bool Are more than 3/4 of the maximum connections used?
392 function poller_max_connections_reached() {
394 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
395 $max = Config::get("system", "max_connections");
397 // Fetch the percentage level where the poller will get active
398 $maxlevel = Config::get("system", "max_connections_level", 75);
401 // the maximum number of possible user connections can be a system variable
402 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
403 if (dbm::is_result($r)) {
404 $max = $r[0]["Value"];
406 // Or it can be granted. This overrides the system variable
407 $r = q("SHOW GRANTS");
408 if (dbm::is_result($r)) {
409 foreach ($r AS $grants) {
410 $grant = array_pop($grants);
411 if (stristr($grant, "GRANT USAGE ON")) {
412 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
420 // If $max is set we will use the processlist to determine the current number of connections
421 // The processlist only shows entries of the current user
423 $r = q("SHOW PROCESSLIST");
424 if (!dbm::is_result($r)) {
429 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
431 $level = ($used / $max) * 100;
433 if ($level >= $maxlevel) {
434 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
439 // We will now check for the system values.
440 // This limit could be reached although the user limits are fine.
441 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
442 if (!dbm::is_result($r)) {
445 $max = intval($r[0]["Value"]);
449 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
450 if (!dbm::is_result($r)) {
453 $used = intval($r[0]["Value"]);
457 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
459 $level = $used / $max * 100;
461 if ($level < $maxlevel) {
464 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
469 * @brief fix the queue entry if the worker process died
472 function poller_kill_stale_workers() {
473 $entries = dba::p("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` > ? AND NOT `done` AND `pid` != 0", NULL_DATE);
475 while ($entry = dba::fetch($entries)) {
476 if (!posix_kill($entry["pid"], 0)) {
477 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
478 array('pid' => $entry["pid"], 'done' => false));
480 // Kill long running processes
481 // Check if the priority is in a valid range
482 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
483 $entry["priority"] = PRIORITY_MEDIUM;
486 // Define the maximum durations
487 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
488 $max_duration = $max_duration_defaults[$entry["priority"]];
490 $argv = json_decode($entry["parameter"]);
491 $argv[0] = basename($argv[0]);
493 // How long is the process already running?
494 $duration = (time() - strtotime($entry["executed"])) / 60;
495 if ($duration > $max_duration) {
496 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
497 posix_kill($entry["pid"], SIGTERM);
499 // We killed the stale process.
500 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
501 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
502 if ($entry["priority"] == PRIORITY_HIGH) {
503 $new_priority = PRIORITY_MEDIUM;
504 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
505 $new_priority = PRIORITY_LOW;
506 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
507 $new_priority = PRIORITY_NEGLIGIBLE;
509 dba::update('workerqueue',
510 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
511 array('pid' => $entry["pid"], 'done' => false));
513 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
520 * @brief Checks if the number of active workers exceeds the given limits
522 * @return bool Are there too much workers running?
524 function poller_too_much_workers() {
525 $queues = Config::get("system", "worker_queues", 4);
527 $maxqueues = $queues;
529 $active = poller_active_workers();
531 // Decrease the number of workers at higher load
532 $load = current_load();
534 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
536 $maxworkers = $queues;
538 // Some magical mathemathics to reduce the workers
540 $slope = $maxworkers / pow($maxsysload, $exponent);
541 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
543 if (Config::get('system', 'worker_debug')) {
544 // Create a list of queue entries grouped by their priority
547 // Adding all processes with no workerqueue entry
548 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
549 (SELECT id FROM `workerqueue`
550 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
551 if ($process = dba::fetch($processes)) {
552 $listitem[0] = "0:".$process["running"];
554 dba::close($processes);
556 // Now adding all processes with workerqueue entries
557 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
558 while ($entry = dba::fetch($entries)) {
559 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
560 if ($process = dba::fetch($processes)) {
561 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
563 dba::close($processes);
565 dba::close($entries);
567 $intervals = array(1, 10, 60);
568 $jobs_per_minute = array();
569 foreach ($intervals AS $interval) {
570 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
571 if ($job = dba::fetch($jobs)) {
572 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
576 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
579 $entries = poller_total_entries();
581 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
582 $top_priority = poller_highest_priority();
583 $high_running = poller_process_with_priority_active($top_priority);
585 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
586 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
587 $queues = $active + 1;
591 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
593 // Are there fewer workers running as possible? Then fork a new one.
594 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
595 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
596 $args = array("include/poller.php", "no_cron");
597 get_app()->proc_run($args);
601 return $active >= $queues;
605 * @brief Returns the number of active poller processes
607 * @return integer Number of active poller processes
609 function poller_active_workers() {
610 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
612 return $workers[0]["processes"];
616 * @brief Check if we should pass some slow processes
618 * When the active processes of the highest priority are using more than 2/3
619 * of all processes, we let pass slower processes.
621 * @param string $highest_priority Returns the currently highest priority
622 * @return bool We let pass a slower process than $highest_priority
624 function poller_passing_slow(&$highest_priority) {
626 $highest_priority = 0;
628 $r = q("SELECT `priority`
630 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
632 // No active processes at all? Fine
633 if (!dbm::is_result($r)) {
636 $priorities = array();
637 foreach ($r AS $line) {
638 $priorities[] = $line["priority"];
641 if (count($priorities) == 0) {
644 $highest_priority = min($priorities);
646 // The highest process is already the slowest one?
648 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
652 foreach ($priorities AS $priority) {
653 if ($priority == $highest_priority) {
657 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
658 $passing_slow = (($high/count($priorities)) > (2/3));
661 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
663 return $passing_slow;
667 * @brief Find and claim the next worker process for us
669 * @return boolean Have we found something?
671 function find_worker_processes() {
675 // Check if we should pass some low priority process
676 $highest_priority = 0;
679 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
680 $limit = Config::get("system", "worker_queues", 4);
681 $limit = Config::get('system', 'worker_fetch_limit', $limit);
683 if (poller_passing_slow($highest_priority)) {
684 // Are there waiting processes with a higher priority than the currently highest?
685 $result = dba::p("SELECT `id` FROM `workerqueue`
686 WHERE `executed` <= ? AND `priority` < ? AND NOT `done`
687 ORDER BY `priority`, `created` LIMIT ".intval($limit),
688 NULL_DATE, $highest_priority);
690 while ($id = dba::fetch($result)) {
695 $found = (count($ids) > 0);
698 // Give slower processes some processing time
699 $result = dba::p("SELECT `id` FROM `workerqueue`
700 WHERE `executed` <= ? AND `priority` > ? AND NOT `done`
701 ORDER BY `priority`, `created` LIMIT ".intval($limit),
702 NULL_DATE, $highest_priority);
704 while ($id = dba::fetch($result)) {
709 $found = (count($ids) > 0);
713 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
715 $result = dba::p("SELECT `id` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done` ORDER BY `priority`, `created` LIMIT ".intval($limit), NULL_DATE);
717 while ($id = dba::fetch($result)) {
722 $found = (count($ids) > 0);
726 $sql = "UPDATE `workerqueue` SET `executed` = ?, `pid` = ? WHERE `id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`;";
727 array_unshift($ids, datetime_convert(), $mypid);
735 * @brief Returns the next worker process
737 * @return string SQL statement
739 function poller_worker_process() {
740 global $poller_db_duration, $poller_lock_duration;
742 $stamp = (float)microtime(true);
744 // There can already be jobs for us in the queue.
745 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
746 if (dbm::is_result($r)) {
747 $poller_db_duration += (microtime(true) - $stamp);
751 $stamp = (float)microtime(true);
752 if (!Lock::set('poller_worker_process')) {
755 $poller_lock_duration = (microtime(true) - $stamp);
757 $stamp = (float)microtime(true);
758 $found = find_worker_processes();
759 $poller_db_duration += (microtime(true) - $stamp);
761 Lock::remove('poller_worker_process');
764 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
770 * @brief Removes a workerqueue entry from the current process
772 function poller_unclaim_process() {
775 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
779 * @brief Call the front end worker
781 function call_worker() {
782 if (!Config::get("system", "frontend_worker")) {
786 $url = App::get_baseurl()."/worker";
787 fetch_url($url, false, $redirects, 1);
791 * @brief Call the front end worker if there aren't any active
793 function call_worker_if_idle() {
794 if (!Config::get("system", "frontend_worker")) {
798 // Do we have "proc_open"? Then we can fork the poller
799 if (function_exists("proc_open")) {
800 // When was the last time that we called the worker?
801 // Less than one minute? Then we quit
802 if ((time() - Config::get("system", "worker_started")) < 60) {
806 set_config("system", "worker_started", time());
808 // Do we have enough running workers? Then we quit here.
809 if (poller_too_much_workers()) {
810 // Cleaning dead processes
811 poller_kill_stale_workers();
812 get_app()->remove_inactive_processes();
819 logger('Call poller', LOGGER_DEBUG);
821 $args = array("include/poller.php", "no_cron");
822 get_app()->proc_run($args);
826 // We cannot execute background processes.
827 // We now run the processes from the frontend.
828 // This won't work with long running processes.
831 clear_worker_processes();
833 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
835 if ($workers[0]["processes"] == 0) {
841 * @brief Removes long running worker processes
843 function clear_worker_processes() {
844 $timeout = Config::get("system", "frontend_worker_timeout", 10);
846 /// @todo We should clean up the corresponding workerqueue entries as well
847 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
848 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
852 * @brief Runs the cron processes
854 function poller_run_cron() {
855 logger('Add cron entries', LOGGER_DEBUG);
857 // Check for spooled items
858 proc_run(PRIORITY_HIGH, "include/spool_post.php");
860 // Run the cron job that calls all other jobs
861 proc_run(PRIORITY_MEDIUM, "include/cron.php");
863 // Run the cronhooks job separately from cron for being able to use a different timing
864 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
866 // Cleaning dead processes
867 poller_kill_stale_workers();
870 if (array_search(__file__,get_included_files())===0){
871 poller_run($_SERVER["argv"],$_SERVER["argc"]);
873 poller_unclaim_process();
875 get_app()->end_process();