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 $new_process_id = uniqid("wrk", true);
278 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
280 $stamp = (float)microtime(true);
282 // We use the callstack here to analyze the performance of executed worker entries.
283 // For this reason the variables have to be initialized.
284 if (Config::get("system", "profiler")) {
285 $a->performance["start"] = microtime(true);
286 $a->performance["database"] = 0;
287 $a->performance["database_write"] = 0;
288 $a->performance["network"] = 0;
289 $a->performance["file"] = 0;
290 $a->performance["rendering"] = 0;
291 $a->performance["parser"] = 0;
292 $a->performance["marktime"] = 0;
293 $a->performance["markstart"] = microtime(true);
294 $a->callstack = array();
297 // For better logging create a new process id for every worker call
298 // But preserve the old one for the worker
299 $old_process_id = $a->process_id;
300 $a->process_id = $new_process_id;
303 $up_duration = number_format(microtime(true) - $poller_up_start, 3);
305 $funcname($argv, $argc);
307 $a->process_id = $old_process_id;
310 $duration = number_format(microtime(true) - $stamp, 3);
312 $poller_up_start = microtime(true);
314 /* With these values we can analyze how effective the worker is.
315 * The database and rest time should be low since this is the unproductive time.
316 * The execution time is the productive time.
317 * By changing parameters like the maximum number of workers we can check the effectivness.
319 logger('DB: '.number_format($poller_db_duration, 2).
320 ' - Lock: '.number_format($poller_lock_duration, 2).
321 ' - Rest: '.number_format($up_duration - $poller_db_duration - $poller_lock_duration, 2).
322 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
323 $poller_lock_duration = 0;
325 if ($duration > 3600) {
326 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
327 } elseif ($duration > 600) {
328 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
329 } elseif ($duration > 300) {
330 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
331 } elseif ($duration > 120) {
332 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
335 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
337 // Write down the performance values into the log
338 if (Config::get("system", "profiler")) {
339 $duration = microtime(true)-$a->performance["start"];
341 if (Config::get("rendertime", "callstack")) {
342 if (isset($a->callstack["database"])) {
343 $o = "\nDatabase Read:\n";
344 foreach ($a->callstack["database"] AS $func => $time) {
345 $time = round($time, 3);
347 $o .= $func.": ".$time."\n";
351 if (isset($a->callstack["database_write"])) {
352 $o .= "\nDatabase Write:\n";
353 foreach ($a->callstack["database_write"] AS $func => $time) {
354 $time = round($time, 3);
356 $o .= $func.": ".$time."\n";
360 if (isset($a->callstack["network"])) {
361 $o .= "\nNetwork:\n";
362 foreach ($a->callstack["network"] AS $func => $time) {
363 $time = round($time, 3);
365 $o .= $func.": ".$time."\n";
373 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
374 number_format($a->performance["database"] - $a->performance["database_write"], 2),
375 number_format($a->performance["database_write"], 2),
376 number_format($a->performance["network"], 2),
377 number_format($a->performance["file"], 2),
378 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
379 number_format($duration, 2)),
383 $cooldown = Config::get("system", "worker_cooldown", 0);
386 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
392 * @brief Checks if the number of database connections has reached a critical limit.
394 * @return bool Are more than 3/4 of the maximum connections used?
396 function poller_max_connections_reached() {
398 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
399 $max = Config::get("system", "max_connections");
401 // Fetch the percentage level where the poller will get active
402 $maxlevel = Config::get("system", "max_connections_level", 75);
405 // the maximum number of possible user connections can be a system variable
406 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
407 if (dbm::is_result($r)) {
408 $max = $r[0]["Value"];
410 // Or it can be granted. This overrides the system variable
411 $r = q("SHOW GRANTS");
412 if (dbm::is_result($r)) {
413 foreach ($r AS $grants) {
414 $grant = array_pop($grants);
415 if (stristr($grant, "GRANT USAGE ON")) {
416 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
424 // If $max is set we will use the processlist to determine the current number of connections
425 // The processlist only shows entries of the current user
427 $r = q("SHOW PROCESSLIST");
428 if (!dbm::is_result($r)) {
433 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
435 $level = ($used / $max) * 100;
437 if ($level >= $maxlevel) {
438 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
443 // We will now check for the system values.
444 // This limit could be reached although the user limits are fine.
445 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
446 if (!dbm::is_result($r)) {
449 $max = intval($r[0]["Value"]);
453 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
454 if (!dbm::is_result($r)) {
457 $used = intval($r[0]["Value"]);
461 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
463 $level = $used / $max * 100;
465 if ($level < $maxlevel) {
468 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
473 * @brief fix the queue entry if the worker process died
476 function poller_kill_stale_workers() {
477 $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);
479 while ($entry = dba::fetch($entries)) {
480 if (!posix_kill($entry["pid"], 0)) {
481 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
482 array('id' => $entry["id"]));
484 // Kill long running processes
485 // Check if the priority is in a valid range
486 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
487 $entry["priority"] = PRIORITY_MEDIUM;
490 // Define the maximum durations
491 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
492 $max_duration = $max_duration_defaults[$entry["priority"]];
494 $argv = json_decode($entry["parameter"]);
495 $argv[0] = basename($argv[0]);
497 // How long is the process already running?
498 $duration = (time() - strtotime($entry["executed"])) / 60;
499 if ($duration > $max_duration) {
500 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
501 posix_kill($entry["pid"], SIGTERM);
503 // We killed the stale process.
504 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
505 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
506 if ($entry["priority"] == PRIORITY_HIGH) {
507 $new_priority = PRIORITY_MEDIUM;
508 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
509 $new_priority = PRIORITY_LOW;
510 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
511 $new_priority = PRIORITY_NEGLIGIBLE;
513 dba::update('workerqueue',
514 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
515 array('id' => $entry["id"]));
517 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
524 * @brief Checks if the number of active workers exceeds the given limits
526 * @return bool Are there too much workers running?
528 function poller_too_much_workers() {
529 $queues = Config::get("system", "worker_queues", 4);
531 $maxqueues = $queues;
533 $active = poller_active_workers();
535 // Decrease the number of workers at higher load
536 $load = current_load();
538 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
540 $maxworkers = $queues;
542 // Some magical mathemathics to reduce the workers
544 $slope = $maxworkers / pow($maxsysload, $exponent);
545 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
547 if (Config::get('system', 'worker_debug')) {
548 // Create a list of queue entries grouped by their priority
551 // Adding all processes with no workerqueue entry
552 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
553 (SELECT id FROM `workerqueue`
554 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
555 if ($process = dba::fetch($processes)) {
556 $listitem[0] = "0:".$process["running"];
558 dba::close($processes);
560 // Now adding all processes with workerqueue entries
561 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
562 while ($entry = dba::fetch($entries)) {
563 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
564 if ($process = dba::fetch($processes)) {
565 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
567 dba::close($processes);
569 dba::close($entries);
571 $intervals = array(1, 10, 60);
572 $jobs_per_minute = array();
573 foreach ($intervals AS $interval) {
574 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
575 if ($job = dba::fetch($jobs)) {
576 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
580 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
583 $entries = poller_total_entries();
585 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
586 $top_priority = poller_highest_priority();
587 $high_running = poller_process_with_priority_active($top_priority);
589 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
590 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
591 $queues = $active + 1;
595 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
597 // Are there fewer workers running as possible? Then fork a new one.
598 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
599 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
600 $args = array("include/poller.php", "no_cron");
601 get_app()->proc_run($args);
605 return $active >= $queues;
609 * @brief Returns the number of active poller processes
611 * @return integer Number of active poller processes
613 function poller_active_workers() {
614 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
616 return $workers[0]["processes"];
620 * @brief Check if we should pass some slow processes
622 * When the active processes of the highest priority are using more than 2/3
623 * of all processes, we let pass slower processes.
625 * @param string $highest_priority Returns the currently highest priority
626 * @return bool We let pass a slower process than $highest_priority
628 function poller_passing_slow(&$highest_priority) {
630 $highest_priority = 0;
632 $r = q("SELECT `priority`
634 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
636 // No active processes at all? Fine
637 if (!dbm::is_result($r)) {
640 $priorities = array();
641 foreach ($r AS $line) {
642 $priorities[] = $line["priority"];
645 if (count($priorities) == 0) {
648 $highest_priority = min($priorities);
650 // The highest process is already the slowest one?
652 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
656 foreach ($priorities AS $priority) {
657 if ($priority == $highest_priority) {
661 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
662 $passing_slow = (($high/count($priorities)) > (2/3));
665 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
667 return $passing_slow;
671 * @brief Find and claim the next worker process for us
673 * @param boolean $passing_slow Returns if we had passed low priority processes
674 * @return boolean Have we found something?
676 function find_worker_processes(&$passing_slow) {
680 // Check if we should pass some low priority process
681 $highest_priority = 0;
683 $passing_slow = false;
685 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
686 // We decrease the limit with the number of entries left in the queue
687 $worker_queues = Config::get("system", "worker_queues", 4);
688 $queue_length = Config::get('system', 'worker_fetch_limit', $worker_queues);
689 $lower_job_limit = $worker_queues * $queue_length * 2;
690 $jobs = poller_total_entries();
694 $slope = $queue_length / pow($lower_job_limit, $exponent);
695 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
697 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
699 if (poller_passing_slow($highest_priority)) {
700 // Are there waiting processes with a higher priority than the currently highest?
701 $result = dba::p("SELECT `id` FROM `workerqueue`
702 WHERE `executed` <= ? AND `priority` < ? AND NOT `done`
703 ORDER BY `priority`, `created` LIMIT ".intval($limit),
704 NULL_DATE, $highest_priority);
706 while ($id = dba::fetch($result)) {
711 $found = (count($ids) > 0);
714 // Give slower processes some processing time
715 $result = dba::p("SELECT `id` FROM `workerqueue`
716 WHERE `executed` <= ? AND `priority` > ? AND NOT `done`
717 ORDER BY `priority`, `created` LIMIT ".intval($limit),
718 NULL_DATE, $highest_priority);
720 while ($id = dba::fetch($result)) {
725 $found = (count($ids) > 0);
726 $passing_slow = $found;
730 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
732 $result = dba::p("SELECT `id` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done` ORDER BY `priority`, `created` LIMIT ".intval($limit), NULL_DATE);
734 while ($id = dba::fetch($result)) {
739 $found = (count($ids) > 0);
743 $sql = "UPDATE `workerqueue` SET `executed` = ?, `pid` = ? WHERE `id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`;";
744 array_unshift($ids, datetime_convert(), $mypid);
752 * @brief Returns the next worker process
754 * @param boolean $passing_slow Returns if we had passed low priority processes
755 * @return string SQL statement
757 function poller_worker_process(&$passing_slow) {
758 global $poller_db_duration, $poller_lock_duration;
760 $stamp = (float)microtime(true);
762 // There can already be jobs for us in the queue.
763 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
764 if (dbm::is_result($r)) {
765 $poller_db_duration += (microtime(true) - $stamp);
769 $stamp = (float)microtime(true);
770 if (!Lock::set('poller_worker_process')) {
773 $poller_lock_duration = (microtime(true) - $stamp);
775 $stamp = (float)microtime(true);
776 $found = find_worker_processes($passing_slow);
777 $poller_db_duration += (microtime(true) - $stamp);
779 Lock::remove('poller_worker_process');
782 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
788 * @brief Removes a workerqueue entry from the current process
790 function poller_unclaim_process() {
793 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
797 * @brief Call the front end worker
799 function call_worker() {
800 if (!Config::get("system", "frontend_worker")) {
804 $url = App::get_baseurl()."/worker";
805 fetch_url($url, false, $redirects, 1);
809 * @brief Call the front end worker if there aren't any active
811 function call_worker_if_idle() {
812 if (!Config::get("system", "frontend_worker")) {
816 // Do we have "proc_open"? Then we can fork the poller
817 if (function_exists("proc_open")) {
818 // When was the last time that we called the worker?
819 // Less than one minute? Then we quit
820 if ((time() - Config::get("system", "worker_started")) < 60) {
824 set_config("system", "worker_started", time());
826 // Do we have enough running workers? Then we quit here.
827 if (poller_too_much_workers()) {
828 // Cleaning dead processes
829 poller_kill_stale_workers();
830 get_app()->remove_inactive_processes();
837 logger('Call poller', LOGGER_DEBUG);
839 $args = array("include/poller.php", "no_cron");
840 get_app()->proc_run($args);
844 // We cannot execute background processes.
845 // We now run the processes from the frontend.
846 // This won't work with long running processes.
849 clear_worker_processes();
851 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
853 if ($workers[0]["processes"] == 0) {
859 * @brief Removes long running worker processes
861 function clear_worker_processes() {
862 $timeout = Config::get("system", "frontend_worker_timeout", 10);
864 /// @todo We should clean up the corresponding workerqueue entries as well
865 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
866 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
870 * @brief Runs the cron processes
872 function poller_run_cron() {
873 logger('Add cron entries', LOGGER_DEBUG);
875 // Check for spooled items
876 proc_run(PRIORITY_HIGH, "include/spool_post.php");
878 // Run the cron job that calls all other jobs
879 proc_run(PRIORITY_MEDIUM, "include/cron.php");
881 // Run the cronhooks job separately from cron for being able to use a different timing
882 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
884 // Cleaning dead processes
885 poller_kill_stale_workers();
888 if (array_search(__file__,get_included_files())===0){
889 poller_run($_SERVER["argv"],$_SERVER["argc"]);
891 poller_unclaim_process();
893 get_app()->end_process();