4 use Friendica\Core\System;
5 use Friendica\Core\Config;
6 use Friendica\Util\Lock;
8 if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
9 $directory = dirname($_SERVER["argv"][0]);
11 if (substr($directory, 0, 1) != "/") {
12 $directory = $_SERVER["PWD"]."/".$directory;
14 $directory = realpath($directory."/..");
19 require_once("boot.php");
21 function poller_run($argv, $argc){
22 global $a, $db, $poller_up_start, $poller_db_duration;
24 $poller_up_start = microtime(true);
26 $a = new App(dirname(__DIR__));
28 @include(".htconfig.php");
29 require_once("include/dba.php");
30 $db = new dba($db_host, $db_user, $db_pass, $db_data);
31 unset($db_host, $db_user, $db_pass, $db_data);
35 // Check the database structure and possibly fixes it
38 // Quit when in maintenance
39 if (Config::get('system', 'maintenance', true)) {
43 $a->set_baseurl(Config::get('system', 'url'));
47 // At first check the maximum load. We shouldn't continue with a high load
48 if ($a->maxload_reached()) {
49 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
53 // We now start the process. This is done after the load check since this could increase the load.
56 // Kill stale processes every 5 minutes
57 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
58 if (time() > ($last_cleanup + 300)) {
59 Config::set('system', 'poller_last_cleaned', time());
60 poller_kill_stale_workers();
63 // Count active workers and compare them with a maximum value that depends on the load
64 if (poller_too_much_workers()) {
65 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
69 // Do we have too few memory?
70 if ($a->min_memory_reached()) {
71 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
75 // Possibly there are too much database connections
76 if (poller_max_connections_reached()) {
77 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
81 // Possibly there are too much database processes that block the system
82 if ($a->max_processes_reached()) {
83 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
87 // Now we start additional cron processes if we should do so
88 if (($argc <= 1) || ($argv[1] != "no_cron")) {
94 // We fetch the next queue entry that is about to be executed
95 while ($r = poller_worker_process($passing_slow)) {
97 // When we are processing jobs with a lower priority, we don't refetch new jobs
98 // Otherwise fast jobs could wait behind slow ones and could be blocked.
99 $refetched = $passing_slow;
101 foreach ($r AS $entry) {
102 // Assure that the priority is an integer value
103 $entry['priority'] = (int)$entry['priority'];
105 // The work will be done
106 if (!poller_execute($entry)) {
107 logger('Process execution failed, quitting.', LOGGER_DEBUG);
111 // If possible we will fetch new jobs for this worker
112 if (!$refetched && Lock::set('poller_worker_process', 0)) {
113 $stamp = (float)microtime(true);
114 $refetched = find_worker_processes($passing_slow);
115 $poller_db_duration += (microtime(true) - $stamp);
116 Lock::remove('poller_worker_process');
120 // To avoid the quitting of multiple pollers only one poller at a time will execute the check
121 if (Lock::set('poller_worker', 0)) {
122 $stamp = (float)microtime(true);
123 // Count active workers and compare them with a maximum value that depends on the load
124 if (poller_too_much_workers()) {
125 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
130 if ($a->min_memory_reached()) {
131 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
134 Lock::remove('poller_worker');
135 $poller_db_duration += (microtime(true) - $stamp);
138 // Quit the poller once every 5 minutes
139 if (time() > ($starttime + 300)) {
140 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
144 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
148 * @brief Returns the number of non executed entries in the worker queue
150 * @return integer Number of non executed entries in the worker queue
152 function poller_total_entries() {
153 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done`", dbesc(NULL_DATE));
154 if (dbm::is_result($s)) {
155 return $s[0]["total"];
162 * @brief Returns the highest priority in the worker queue that isn't executed
164 * @return integer Number of active poller processes
166 function poller_highest_priority() {
167 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done` ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
168 if (dbm::is_result($s)) {
169 return $s[0]["priority"];
176 * @brief Returns if a process with the given priority is running
178 * @param integer $priority The priority that should be checked
180 * @return integer Is there a process running with that priority?
182 function poller_process_with_priority_active($priority) {
183 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' AND NOT `done` LIMIT 1",
184 intval($priority), dbesc(NULL_DATE));
185 return dbm::is_result($s);
189 * @brief Execute a worker entry
191 * @param array $queue Workerqueue entry
193 * @return boolean "true" if further processing should be stopped
195 function poller_execute($queue) {
196 global $poller_db_duration, $poller_last_update;
202 // Quit when in maintenance
203 if (Config::get('system', 'maintenance', true)) {
204 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
208 // Constantly check the number of parallel database processes
209 if ($a->max_processes_reached()) {
210 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
214 // Constantly check the number of available database connections to let the frontend be accessible at any time
215 if (poller_max_connections_reached()) {
216 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
220 $argv = json_decode($queue["parameter"]);
222 // Check for existance and validity of the include file
225 if (!validate_include($include)) {
226 logger("Include file ".$argv[0]." is not valid!");
227 dba::delete('workerqueue', array('id' => $queue["id"]));
231 require_once($include);
233 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
235 if (function_exists($funcname)) {
237 // We constantly update the "executed" date every minute to avoid being killed too soon
238 if (!isset($poller_last_update)) {
239 $poller_last_update = strtotime($queue["executed"]);
242 $age = (time() - $poller_last_update) / 60;
243 $poller_last_update = time();
246 $stamp = (float)microtime(true);
247 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
248 $poller_db_duration += (microtime(true) - $stamp);
251 poller_exec_function($queue, $funcname, $argv);
253 $stamp = (float)microtime(true);
254 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
255 Config::set('system', 'last_poller_execution', datetime_convert());
257 $poller_db_duration = (microtime(true) - $stamp);
259 logger("Function ".$funcname." does not exist");
260 dba::delete('workerqueue', array('id' => $queue["id"]));
267 * @brief Execute a function from the queue
269 * @param array $queue Workerqueue entry
270 * @param string $funcname name of the function
271 * @param array $argv Array of values to be passed to the function
273 function poller_exec_function($queue, $funcname, $argv) {
274 global $poller_up_start, $poller_db_duration, $poller_lock_duration;
280 $argc = count($argv);
282 $new_process_id = uniqid("wrk", true);
284 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
286 $stamp = (float)microtime(true);
288 // We use the callstack here to analyze the performance of executed worker entries.
289 // For this reason the variables have to be initialized.
290 if (Config::get("system", "profiler")) {
291 $a->performance["start"] = microtime(true);
292 $a->performance["database"] = 0;
293 $a->performance["database_write"] = 0;
294 $a->performance["network"] = 0;
295 $a->performance["file"] = 0;
296 $a->performance["rendering"] = 0;
297 $a->performance["parser"] = 0;
298 $a->performance["marktime"] = 0;
299 $a->performance["markstart"] = microtime(true);
300 $a->callstack = array();
303 // For better logging create a new process id for every worker call
304 // But preserve the old one for the worker
305 $old_process_id = $a->process_id;
306 $a->process_id = $new_process_id;
309 $up_duration = number_format(microtime(true) - $poller_up_start, 3);
311 // Reset global data to avoid interferences
314 $funcname($argv, $argc);
316 $a->process_id = $old_process_id;
319 $duration = number_format(microtime(true) - $stamp, 3);
321 $poller_up_start = microtime(true);
323 /* With these values we can analyze how effective the worker is.
324 * The database and rest time should be low since this is the unproductive time.
325 * The execution time is the productive time.
326 * By changing parameters like the maximum number of workers we can check the effectivness.
328 logger('DB: '.number_format($poller_db_duration, 2).
329 ' - Lock: '.number_format($poller_lock_duration, 2).
330 ' - Rest: '.number_format($up_duration - $poller_db_duration - $poller_lock_duration, 2).
331 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
332 $poller_lock_duration = 0;
334 if ($duration > 3600) {
335 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
336 } elseif ($duration > 600) {
337 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
338 } elseif ($duration > 300) {
339 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
340 } elseif ($duration > 120) {
341 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
344 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
346 // Write down the performance values into the log
347 if (Config::get("system", "profiler")) {
348 $duration = microtime(true)-$a->performance["start"];
350 if (Config::get("rendertime", "callstack")) {
351 if (isset($a->callstack["database"])) {
352 $o = "\nDatabase Read:\n";
353 foreach ($a->callstack["database"] AS $func => $time) {
354 $time = round($time, 3);
356 $o .= $func.": ".$time."\n";
360 if (isset($a->callstack["database_write"])) {
361 $o .= "\nDatabase Write:\n";
362 foreach ($a->callstack["database_write"] AS $func => $time) {
363 $time = round($time, 3);
365 $o .= $func.": ".$time."\n";
369 if (isset($a->callstack["network"])) {
370 $o .= "\nNetwork:\n";
371 foreach ($a->callstack["network"] AS $func => $time) {
372 $time = round($time, 3);
374 $o .= $func.": ".$time."\n";
382 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
383 number_format($a->performance["database"] - $a->performance["database_write"], 2),
384 number_format($a->performance["database_write"], 2),
385 number_format($a->performance["network"], 2),
386 number_format($a->performance["file"], 2),
387 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
388 number_format($duration, 2)),
392 $cooldown = Config::get("system", "worker_cooldown", 0);
395 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
401 * @brief Checks if the number of database connections has reached a critical limit.
403 * @return bool Are more than 3/4 of the maximum connections used?
405 function poller_max_connections_reached() {
407 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
408 $max = Config::get("system", "max_connections");
410 // Fetch the percentage level where the poller will get active
411 $maxlevel = Config::get("system", "max_connections_level", 75);
414 // the maximum number of possible user connections can be a system variable
415 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
416 if (dbm::is_result($r)) {
417 $max = $r[0]["Value"];
419 // Or it can be granted. This overrides the system variable
420 $r = q("SHOW GRANTS");
421 if (dbm::is_result($r)) {
422 foreach ($r AS $grants) {
423 $grant = array_pop($grants);
424 if (stristr($grant, "GRANT USAGE ON")) {
425 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
433 // If $max is set we will use the processlist to determine the current number of connections
434 // The processlist only shows entries of the current user
436 $r = q("SHOW PROCESSLIST");
437 if (!dbm::is_result($r)) {
442 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
444 $level = ($used / $max) * 100;
446 if ($level >= $maxlevel) {
447 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
452 // We will now check for the system values.
453 // This limit could be reached although the user limits are fine.
454 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
455 if (!dbm::is_result($r)) {
458 $max = intval($r[0]["Value"]);
462 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
463 if (!dbm::is_result($r)) {
466 $used = intval($r[0]["Value"]);
470 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
472 $level = $used / $max * 100;
474 if ($level < $maxlevel) {
477 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
482 * @brief fix the queue entry if the worker process died
485 function poller_kill_stale_workers() {
486 $entries = dba::select('workerqueue', array('id', 'pid', 'executed', 'priority', 'parameter'),
487 array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
488 array('order' => array('priority', 'created')));
489 while ($entry = dba::fetch($entries)) {
490 if (!posix_kill($entry["pid"], 0)) {
491 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
492 array('id' => $entry["id"]));
494 // Kill long running processes
495 // Check if the priority is in a valid range
496 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
497 $entry["priority"] = PRIORITY_MEDIUM;
500 // Define the maximum durations
501 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
502 $max_duration = $max_duration_defaults[$entry["priority"]];
504 $argv = json_decode($entry["parameter"]);
505 $argv[0] = basename($argv[0]);
507 // How long is the process already running?
508 $duration = (time() - strtotime($entry["executed"])) / 60;
509 if ($duration > $max_duration) {
510 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
511 posix_kill($entry["pid"], SIGTERM);
513 // We killed the stale process.
514 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
515 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
516 if ($entry["priority"] == PRIORITY_HIGH) {
517 $new_priority = PRIORITY_MEDIUM;
518 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
519 $new_priority = PRIORITY_LOW;
520 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
521 $new_priority = PRIORITY_NEGLIGIBLE;
523 dba::update('workerqueue',
524 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
525 array('id' => $entry["id"]));
527 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
534 * @brief Checks if the number of active workers exceeds the given limits
536 * @return bool Are there too much workers running?
538 function poller_too_much_workers() {
539 $queues = Config::get("system", "worker_queues", 4);
541 $maxqueues = $queues;
543 $active = poller_active_workers();
545 // Decrease the number of workers at higher load
546 $load = current_load();
548 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
550 $maxworkers = $queues;
552 // Some magical mathemathics to reduce the workers
554 $slope = $maxworkers / pow($maxsysload, $exponent);
555 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
557 if (Config::get('system', 'worker_debug')) {
558 // Create a list of queue entries grouped by their priority
561 // Adding all processes with no workerqueue entry
562 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
563 (SELECT id FROM `workerqueue`
564 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
565 if ($process = dba::fetch($processes)) {
566 $listitem[0] = "0:".$process["running"];
568 dba::close($processes);
570 // Now adding all processes with workerqueue entries
571 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
572 while ($entry = dba::fetch($entries)) {
573 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
574 if ($process = dba::fetch($processes)) {
575 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
577 dba::close($processes);
579 dba::close($entries);
581 $intervals = array(1, 10, 60);
582 $jobs_per_minute = array();
583 foreach ($intervals AS $interval) {
584 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
585 if ($job = dba::fetch($jobs)) {
586 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
590 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
593 $entries = poller_total_entries();
595 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
596 $top_priority = poller_highest_priority();
597 $high_running = poller_process_with_priority_active($top_priority);
599 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
600 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
601 $queues = $active + 1;
605 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
607 // Are there fewer workers running as possible? Then fork a new one.
608 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
609 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
610 $args = array("include/poller.php", "no_cron");
611 get_app()->proc_run($args);
615 return $active >= $queues;
619 * @brief Returns the number of active poller processes
621 * @return integer Number of active poller processes
623 function poller_active_workers() {
624 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
626 return $workers[0]["processes"];
630 * @brief Check if we should pass some slow processes
632 * When the active processes of the highest priority are using more than 2/3
633 * of all processes, we let pass slower processes.
635 * @param string $highest_priority Returns the currently highest priority
636 * @return bool We let pass a slower process than $highest_priority
638 function poller_passing_slow(&$highest_priority) {
640 $highest_priority = 0;
642 $r = q("SELECT `priority`
644 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
646 // No active processes at all? Fine
647 if (!dbm::is_result($r)) {
650 $priorities = array();
651 foreach ($r AS $line) {
652 $priorities[] = $line["priority"];
655 if (count($priorities) == 0) {
658 $highest_priority = min($priorities);
660 // The highest process is already the slowest one?
662 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
666 foreach ($priorities AS $priority) {
667 if ($priority == $highest_priority) {
671 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
672 $passing_slow = (($high/count($priorities)) > (2/3));
675 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
677 return $passing_slow;
681 * @brief Find and claim the next worker process for us
683 * @param boolean $passing_slow Returns if we had passed low priority processes
684 * @return boolean Have we found something?
686 function find_worker_processes(&$passing_slow) {
690 // Check if we should pass some low priority process
691 $highest_priority = 0;
693 $passing_slow = false;
695 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
696 // We decrease the limit with the number of entries left in the queue
697 $worker_queues = Config::get("system", "worker_queues", 4);
698 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
699 $lower_job_limit = $worker_queues * $queue_length * 2;
700 $jobs = poller_total_entries();
704 $slope = $queue_length / pow($lower_job_limit, $exponent);
705 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
707 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
709 if (poller_passing_slow($highest_priority)) {
710 // Are there waiting processes with a higher priority than the currently highest?
711 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority),
712 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
714 while ($id = dba::fetch($result)) {
719 $found = (count($ids) > 0);
722 // Give slower processes some processing time
723 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority),
724 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
726 while ($id = dba::fetch($result)) {
731 $found = (count($ids) > 0);
732 $passing_slow = $found;
736 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
738 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND NOT `done`", NULL_DATE),
739 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
741 while ($id = dba::fetch($result)) {
746 $found = (count($ids) > 0);
750 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
751 array_unshift($ids, $condition);
752 dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
759 * @brief Returns the next worker process
761 * @param boolean $passing_slow Returns if we had passed low priority processes
762 * @return string SQL statement
764 function poller_worker_process(&$passing_slow) {
765 global $poller_db_duration, $poller_lock_duration;
767 $stamp = (float)microtime(true);
769 // There can already be jobs for us in the queue.
770 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
771 if (dbm::is_result($r)) {
772 $poller_db_duration += (microtime(true) - $stamp);
776 $stamp = (float)microtime(true);
777 if (!Lock::set('poller_worker_process')) {
780 $poller_lock_duration = (microtime(true) - $stamp);
782 $stamp = (float)microtime(true);
783 $found = find_worker_processes($passing_slow);
784 $poller_db_duration += (microtime(true) - $stamp);
786 Lock::remove('poller_worker_process');
789 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
795 * @brief Removes a workerqueue entry from the current process
797 function poller_unclaim_process() {
800 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
804 * @brief Call the front end worker
806 function call_worker() {
807 if (!Config::get("system", "frontend_worker")) {
811 $url = System::baseUrl()."/worker";
812 fetch_url($url, false, $redirects, 1);
816 * @brief Call the front end worker if there aren't any active
818 function call_worker_if_idle() {
819 if (!Config::get("system", "frontend_worker")) {
823 // Do we have "proc_open"? Then we can fork the poller
824 if (function_exists("proc_open")) {
825 // When was the last time that we called the worker?
826 // Less than one minute? Then we quit
827 if ((time() - Config::get("system", "worker_started")) < 60) {
831 set_config("system", "worker_started", time());
833 // Do we have enough running workers? Then we quit here.
834 if (poller_too_much_workers()) {
835 // Cleaning dead processes
836 poller_kill_stale_workers();
837 get_app()->remove_inactive_processes();
844 logger('Call poller', LOGGER_DEBUG);
846 $args = array("include/poller.php", "no_cron");
847 get_app()->proc_run($args);
851 // We cannot execute background processes.
852 // We now run the processes from the frontend.
853 // This won't work with long running processes.
856 clear_worker_processes();
858 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
860 if ($workers[0]["processes"] == 0) {
866 * @brief Removes long running worker processes
868 function clear_worker_processes() {
869 $timeout = Config::get("system", "frontend_worker_timeout", 10);
871 /// @todo We should clean up the corresponding workerqueue entries as well
872 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
873 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
877 * @brief Runs the cron processes
879 function poller_run_cron() {
880 logger('Add cron entries', LOGGER_DEBUG);
882 // Check for spooled items
883 proc_run(PRIORITY_HIGH, "include/spool_post.php");
885 // Run the cron job that calls all other jobs
886 proc_run(PRIORITY_MEDIUM, "include/cron.php");
888 // Run the cronhooks job separately from cron for being able to use a different timing
889 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
891 // Cleaning dead processes
892 poller_kill_stale_workers();
895 if (array_search(__file__,get_included_files())===0) {
896 poller_run($_SERVER["argv"],$_SERVER["argc"]);
898 poller_unclaim_process();
900 get_app()->end_process();