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($passing_slow)) {
93 // When we are processing jobs with a lower priority, we don't refetch new jobs
94 // Otherwise fast jobs could wait behind slow ones and could be blocked.
95 $refetched = $passing_slow;
97 foreach ($r AS $entry) {
98 // Assure that the priority is an integer value
99 $entry['priority'] = (int)$entry['priority'];
101 // The work will be done
102 if (!poller_execute($entry)) {
103 logger('Process execution failed, quitting.', LOGGER_DEBUG);
107 // If possible we will fetch new jobs for this worker
108 if (!$refetched && Lock::set('poller_worker_process', 0)) {
109 $stamp = (float)microtime(true);
110 $refetched = find_worker_processes($passing_slow);
111 $poller_db_duration += (microtime(true) - $stamp);
112 Lock::remove('poller_worker_process');
116 // To avoid the quitting of multiple pollers only one poller at a time will execute the check
117 if (Lock::set('poller_worker', 0)) {
118 $stamp = (float)microtime(true);
119 // Count active workers and compare them with a maximum value that depends on the load
120 if (poller_too_much_workers()) {
121 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
126 if ($a->min_memory_reached()) {
127 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
130 Lock::remove('poller_worker');
131 $poller_db_duration += (microtime(true) - $stamp);
134 // Quit the poller once every 5 minutes
135 if (time() > ($starttime + 300)) {
136 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
140 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
144 * @brief Returns the number of non executed entries in the worker queue
146 * @return integer Number of non executed entries in the worker queue
148 function poller_total_entries() {
149 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done`", dbesc(NULL_DATE));
150 if (dbm::is_result($s)) {
151 return $s[0]["total"];
158 * @brief Returns the highest priority in the worker queue that isn't executed
160 * @return integer Number of active poller processes
162 function poller_highest_priority() {
163 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done` ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
164 if (dbm::is_result($s)) {
165 return $s[0]["priority"];
172 * @brief Returns if a process with the given priority is running
174 * @param integer $priority The priority that should be checked
176 * @return integer Is there a process running with that priority?
178 function poller_process_with_priority_active($priority) {
179 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' AND NOT `done` LIMIT 1",
180 intval($priority), dbesc(NULL_DATE));
181 return dbm::is_result($s);
185 * @brief Execute a worker entry
187 * @param array $queue Workerqueue entry
189 * @return boolean "true" if further processing should be stopped
191 function poller_execute($queue) {
192 global $poller_db_duration, $poller_last_update;
198 // Quit when in maintenance
199 if (Config::get('system', 'maintenance', true)) {
200 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
204 // Constantly check the number of parallel database processes
205 if ($a->max_processes_reached()) {
206 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
210 // Constantly check the number of available database connections to let the frontend be accessible at any time
211 if (poller_max_connections_reached()) {
212 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
216 $argv = json_decode($queue["parameter"]);
218 // Check for existance and validity of the include file
221 if (!validate_include($include)) {
222 logger("Include file ".$argv[0]." is not valid!");
223 dba::delete('workerqueue', array('id' => $queue["id"]));
227 require_once($include);
229 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
231 if (function_exists($funcname)) {
233 // We constantly update the "executed" date every minute to avoid being killed too soon
234 if (!isset($poller_last_update)) {
235 $poller_last_update = strtotime($queue["executed"]);
238 $age = (time() - $poller_last_update) / 60;
239 $poller_last_update = time();
242 $stamp = (float)microtime(true);
243 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
244 $poller_db_duration += (microtime(true) - $stamp);
247 poller_exec_function($queue, $funcname, $argv);
249 $stamp = (float)microtime(true);
250 dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]));
251 $poller_db_duration = (microtime(true) - $stamp);
253 logger("Function ".$funcname." does not exist");
254 dba::delete('workerqueue', array('id' => $queue["id"]));
261 * @brief Execute a function from the queue
263 * @param array $queue Workerqueue entry
264 * @param string $funcname name of the function
265 * @param array $argv Array of values to be passed to the function
267 function poller_exec_function($queue, $funcname, $argv) {
268 global $poller_up_start, $poller_db_duration, $poller_lock_duration;
274 $argc = count($argv);
276 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
278 $stamp = (float)microtime(true);
280 // We use the callstack here to analyze the performance of executed worker entries.
281 // For this reason the variables have to be initialized.
282 if (Config::get("system", "profiler")) {
283 $a->performance["start"] = microtime(true);
284 $a->performance["database"] = 0;
285 $a->performance["database_write"] = 0;
286 $a->performance["network"] = 0;
287 $a->performance["file"] = 0;
288 $a->performance["rendering"] = 0;
289 $a->performance["parser"] = 0;
290 $a->performance["marktime"] = 0;
291 $a->performance["markstart"] = microtime(true);
292 $a->callstack = array();
295 // For better logging create a new process id for every worker call
296 // But preserve the old one for the worker
297 $old_process_id = $a->process_id;
298 $a->process_id = uniqid("wrk", true);
301 $up_duration = number_format(microtime(true) - $poller_up_start, 3);
303 $funcname($argv, $argc);
305 $a->process_id = $old_process_id;
308 $duration = number_format(microtime(true) - $stamp, 3);
310 $poller_up_start = microtime(true);
312 /* With these values we can analyze how effective the worker is.
313 * The database and rest time should be low since this is the unproductive time.
314 * The execution time is the productive time.
315 * By changing parameters like the maximum number of workers we can check the effectivness.
317 logger('DB: '.number_format($poller_db_duration, 2).
318 ' - Lock: '.number_format($poller_lock_duration, 2).
319 ' - Rest: '.number_format($up_duration - $poller_db_duration - $poller_lock_duration, 2).
320 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
321 $poller_lock_duration = 0;
323 if ($duration > 3600) {
324 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
325 } elseif ($duration > 600) {
326 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
327 } elseif ($duration > 300) {
328 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
329 } elseif ($duration > 120) {
330 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
333 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
335 // Write down the performance values into the log
336 if (Config::get("system", "profiler")) {
337 $duration = microtime(true)-$a->performance["start"];
339 if (Config::get("rendertime", "callstack")) {
340 if (isset($a->callstack["database"])) {
341 $o = "\nDatabase Read:\n";
342 foreach ($a->callstack["database"] AS $func => $time) {
343 $time = round($time, 3);
345 $o .= $func.": ".$time."\n";
349 if (isset($a->callstack["database_write"])) {
350 $o .= "\nDatabase Write:\n";
351 foreach ($a->callstack["database_write"] AS $func => $time) {
352 $time = round($time, 3);
354 $o .= $func.": ".$time."\n";
358 if (isset($a->callstack["network"])) {
359 $o .= "\nNetwork:\n";
360 foreach ($a->callstack["network"] AS $func => $time) {
361 $time = round($time, 3);
363 $o .= $func.": ".$time."\n";
371 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
372 number_format($a->performance["database"] - $a->performance["database_write"], 2),
373 number_format($a->performance["database_write"], 2),
374 number_format($a->performance["network"], 2),
375 number_format($a->performance["file"], 2),
376 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
377 number_format($duration, 2)),
381 $cooldown = Config::get("system", "worker_cooldown", 0);
384 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
390 * @brief Checks if the number of database connections has reached a critical limit.
392 * @return bool Are more than 3/4 of the maximum connections used?
394 function poller_max_connections_reached() {
396 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
397 $max = Config::get("system", "max_connections");
399 // Fetch the percentage level where the poller will get active
400 $maxlevel = Config::get("system", "max_connections_level", 75);
403 // the maximum number of possible user connections can be a system variable
404 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
405 if (dbm::is_result($r)) {
406 $max = $r[0]["Value"];
408 // Or it can be granted. This overrides the system variable
409 $r = q("SHOW GRANTS");
410 if (dbm::is_result($r)) {
411 foreach ($r AS $grants) {
412 $grant = array_pop($grants);
413 if (stristr($grant, "GRANT USAGE ON")) {
414 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
422 // If $max is set we will use the processlist to determine the current number of connections
423 // The processlist only shows entries of the current user
425 $r = q("SHOW PROCESSLIST");
426 if (!dbm::is_result($r)) {
431 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
433 $level = ($used / $max) * 100;
435 if ($level >= $maxlevel) {
436 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
441 // We will now check for the system values.
442 // This limit could be reached although the user limits are fine.
443 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
444 if (!dbm::is_result($r)) {
447 $max = intval($r[0]["Value"]);
451 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
452 if (!dbm::is_result($r)) {
455 $used = intval($r[0]["Value"]);
459 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
461 $level = $used / $max * 100;
463 if ($level < $maxlevel) {
466 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
471 * @brief fix the queue entry if the worker process died
474 function poller_kill_stale_workers() {
475 $entries = dba::p("SELECT `id`, `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` > ? AND NOT `done` AND `pid` != 0 ORDER BY `priority`, `created`", NULL_DATE);
477 while ($entry = dba::fetch($entries)) {
478 if (!posix_kill($entry["pid"], 0)) {
479 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
480 array('id' => $entry["id"]));
482 // Kill long running processes
483 // Check if the priority is in a valid range
484 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
485 $entry["priority"] = PRIORITY_MEDIUM;
488 // Define the maximum durations
489 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
490 $max_duration = $max_duration_defaults[$entry["priority"]];
492 $argv = json_decode($entry["parameter"]);
493 $argv[0] = basename($argv[0]);
495 // How long is the process already running?
496 $duration = (time() - strtotime($entry["executed"])) / 60;
497 if ($duration > $max_duration) {
498 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
499 posix_kill($entry["pid"], SIGTERM);
501 // We killed the stale process.
502 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
503 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
504 if ($entry["priority"] == PRIORITY_HIGH) {
505 $new_priority = PRIORITY_MEDIUM;
506 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
507 $new_priority = PRIORITY_LOW;
508 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
509 $new_priority = PRIORITY_NEGLIGIBLE;
511 dba::update('workerqueue',
512 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
513 array('id' => $entry["id"]));
515 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
522 * @brief Checks if the number of active workers exceeds the given limits
524 * @return bool Are there too much workers running?
526 function poller_too_much_workers() {
527 $queues = Config::get("system", "worker_queues", 4);
529 $maxqueues = $queues;
531 $active = poller_active_workers();
533 // Decrease the number of workers at higher load
534 $load = current_load();
536 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
538 $maxworkers = $queues;
540 // Some magical mathemathics to reduce the workers
542 $slope = $maxworkers / pow($maxsysload, $exponent);
543 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
545 if (Config::get('system', 'worker_debug')) {
546 // Create a list of queue entries grouped by their priority
549 // Adding all processes with no workerqueue entry
550 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
551 (SELECT id FROM `workerqueue`
552 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
553 if ($process = dba::fetch($processes)) {
554 $listitem[0] = "0:".$process["running"];
556 dba::close($processes);
558 // Now adding all processes with workerqueue entries
559 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
560 while ($entry = dba::fetch($entries)) {
561 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
562 if ($process = dba::fetch($processes)) {
563 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
565 dba::close($processes);
567 dba::close($entries);
569 $intervals = array(1, 10, 60);
570 $jobs_per_minute = array();
571 foreach ($intervals AS $interval) {
572 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
573 if ($job = dba::fetch($jobs)) {
574 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
578 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
581 $entries = poller_total_entries();
583 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
584 $top_priority = poller_highest_priority();
585 $high_running = poller_process_with_priority_active($top_priority);
587 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
588 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
589 $queues = $active + 1;
593 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
595 // Are there fewer workers running as possible? Then fork a new one.
596 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
597 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
598 $args = array("include/poller.php", "no_cron");
599 get_app()->proc_run($args);
603 return $active >= $queues;
607 * @brief Returns the number of active poller processes
609 * @return integer Number of active poller processes
611 function poller_active_workers() {
612 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
614 return $workers[0]["processes"];
618 * @brief Check if we should pass some slow processes
620 * When the active processes of the highest priority are using more than 2/3
621 * of all processes, we let pass slower processes.
623 * @param string $highest_priority Returns the currently highest priority
624 * @return bool We let pass a slower process than $highest_priority
626 function poller_passing_slow(&$highest_priority) {
628 $highest_priority = 0;
630 $r = q("SELECT `priority`
632 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
634 // No active processes at all? Fine
635 if (!dbm::is_result($r)) {
638 $priorities = array();
639 foreach ($r AS $line) {
640 $priorities[] = $line["priority"];
643 if (count($priorities) == 0) {
646 $highest_priority = min($priorities);
648 // The highest process is already the slowest one?
650 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
654 foreach ($priorities AS $priority) {
655 if ($priority == $highest_priority) {
659 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
660 $passing_slow = (($high/count($priorities)) > (2/3));
663 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
665 return $passing_slow;
669 * @brief Find and claim the next worker process for us
671 * @param boolean $passing_slow Returns if we had passed low priority processes
672 * @return boolean Have we found something?
674 function find_worker_processes(&$passing_slow) {
678 // Check if we should pass some low priority process
679 $highest_priority = 0;
681 $passing_slow = false;
683 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
684 // We decrease the limit with the number of entries left in the queue
685 $worker_queues = Config::get("system", "worker_queues", 4);
686 $queue_length = Config::get('system', 'worker_fetch_limit', $worker_queues);
687 $lower_job_limit = $worker_queues * $queue_length * 2;
688 $jobs = poller_total_entries();
692 $slope = $queue_length / pow($lower_job_limit, $exponent);
693 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
695 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
697 if (poller_passing_slow($highest_priority)) {
698 // Are there waiting processes with a higher priority than the currently highest?
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);
712 // Give slower processes some processing time
713 $result = dba::p("SELECT `id` FROM `workerqueue`
714 WHERE `executed` <= ? AND `priority` > ? AND NOT `done`
715 ORDER BY `priority`, `created` LIMIT ".intval($limit),
716 NULL_DATE, $highest_priority);
718 while ($id = dba::fetch($result)) {
723 $found = (count($ids) > 0);
724 $passing_slow = $found;
728 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
730 $result = dba::p("SELECT `id` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done` ORDER BY `priority`, `created` LIMIT ".intval($limit), NULL_DATE);
732 while ($id = dba::fetch($result)) {
737 $found = (count($ids) > 0);
741 $sql = "UPDATE `workerqueue` SET `executed` = ?, `pid` = ? WHERE `id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`;";
742 array_unshift($ids, datetime_convert(), $mypid);
750 * @brief Returns the next worker process
752 * @param boolean $passing_slow Returns if we had passed low priority processes
753 * @return string SQL statement
755 function poller_worker_process(&$passing_slow) {
756 global $poller_db_duration, $poller_lock_duration;
758 $stamp = (float)microtime(true);
760 // There can already be jobs for us in the queue.
761 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
762 if (dbm::is_result($r)) {
763 $poller_db_duration += (microtime(true) - $stamp);
767 $stamp = (float)microtime(true);
768 if (!Lock::set('poller_worker_process')) {
771 $poller_lock_duration = (microtime(true) - $stamp);
773 $stamp = (float)microtime(true);
774 $found = find_worker_processes($passing_slow);
775 $poller_db_duration += (microtime(true) - $stamp);
777 Lock::remove('poller_worker_process');
780 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
786 * @brief Removes a workerqueue entry from the current process
788 function poller_unclaim_process() {
791 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
795 * @brief Call the front end worker
797 function call_worker() {
798 if (!Config::get("system", "frontend_worker")) {
802 $url = App::get_baseurl()."/worker";
803 fetch_url($url, false, $redirects, 1);
807 * @brief Call the front end worker if there aren't any active
809 function call_worker_if_idle() {
810 if (!Config::get("system", "frontend_worker")) {
814 // Do we have "proc_open"? Then we can fork the poller
815 if (function_exists("proc_open")) {
816 // When was the last time that we called the worker?
817 // Less than one minute? Then we quit
818 if ((time() - Config::get("system", "worker_started")) < 60) {
822 set_config("system", "worker_started", time());
824 // Do we have enough running workers? Then we quit here.
825 if (poller_too_much_workers()) {
826 // Cleaning dead processes
827 poller_kill_stale_workers();
828 get_app()->remove_inactive_processes();
835 logger('Call poller', LOGGER_DEBUG);
837 $args = array("include/poller.php", "no_cron");
838 get_app()->proc_run($args);
842 // We cannot execute background processes.
843 // We now run the processes from the frontend.
844 // This won't work with long running processes.
847 clear_worker_processes();
849 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
851 if ($workers[0]["processes"] == 0) {
857 * @brief Removes long running worker processes
859 function clear_worker_processes() {
860 $timeout = Config::get("system", "frontend_worker_timeout", 10);
862 /// @todo We should clean up the corresponding workerqueue entries as well
863 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
864 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
868 * @brief Runs the cron processes
870 function poller_run_cron() {
871 logger('Add cron entries', LOGGER_DEBUG);
873 // Check for spooled items
874 proc_run(PRIORITY_HIGH, "include/spool_post.php");
876 // Run the cron job that calls all other jobs
877 proc_run(PRIORITY_MEDIUM, "include/cron.php");
879 // Run the cronhooks job separately from cron for being able to use a different timing
880 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
882 // Cleaning dead processes
883 poller_kill_stale_workers();
886 if (array_search(__file__,get_included_files())===0){
887 poller_run($_SERVER["argv"],$_SERVER["argc"]);
889 poller_unclaim_process();
891 get_app()->end_process();