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 // Quit when in maintenance
36 if (Config::get('system', 'maintenance', true)) {
40 $a->set_baseurl(Config::get('system', 'url'));
44 // At first check the maximum load. We shouldn't continue with a high load
45 if ($a->maxload_reached()) {
46 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
50 // We now start the process. This is done after the load check since this could increase the load.
53 // Kill stale processes every 5 minutes
54 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
55 if (time() > ($last_cleanup + 300)) {
56 Config::set('system', 'poller_last_cleaned', time());
57 poller_kill_stale_workers();
60 // Count active workers and compare them with a maximum value that depends on the load
61 if (poller_too_much_workers()) {
62 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
66 // Do we have too few memory?
67 if ($a->min_memory_reached()) {
68 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
72 // Possibly there are too much database connections
73 if (poller_max_connections_reached()) {
74 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
78 // Possibly there are too much database processes that block the system
79 if ($a->max_processes_reached()) {
80 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
84 // Now we start additional cron processes if we should do so
85 if (($argc <= 1) || ($argv[1] != "no_cron")) {
91 // We fetch the next queue entry that is about to be executed
92 while ($r = poller_worker_process($passing_slow)) {
94 // When we are processing jobs with a lower priority, we don't refetch new jobs
95 // Otherwise fast jobs could wait behind slow ones and could be blocked.
96 $refetched = $passing_slow;
98 foreach ($r AS $entry) {
99 // Assure that the priority is an integer value
100 $entry['priority'] = (int)$entry['priority'];
102 // The work will be done
103 if (!poller_execute($entry)) {
104 logger('Process execution failed, quitting.', LOGGER_DEBUG);
108 // If possible we will fetch new jobs for this worker
109 if (!$refetched && Lock::set('poller_worker_process', 0)) {
110 $stamp = (float)microtime(true);
111 $refetched = find_worker_processes($passing_slow);
112 $poller_db_duration += (microtime(true) - $stamp);
113 Lock::remove('poller_worker_process');
117 // To avoid the quitting of multiple pollers only one poller at a time will execute the check
118 if (Lock::set('poller_worker', 0)) {
119 $stamp = (float)microtime(true);
120 // Count active workers and compare them with a maximum value that depends on the load
121 if (poller_too_much_workers()) {
122 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
127 if ($a->min_memory_reached()) {
128 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
131 Lock::remove('poller_worker');
132 $poller_db_duration += (microtime(true) - $stamp);
135 // Quit the poller once every 5 minutes
136 if (time() > ($starttime + 300)) {
137 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
141 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
145 * @brief Returns the number of non executed entries in the worker queue
147 * @return integer Number of non executed entries in the worker queue
149 function poller_total_entries() {
150 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done`", dbesc(NULL_DATE));
151 if (dbm::is_result($s)) {
152 return $s[0]["total"];
159 * @brief Returns the highest priority in the worker queue that isn't executed
161 * @return integer Number of active poller processes
163 function poller_highest_priority() {
164 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done` ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
165 if (dbm::is_result($s)) {
166 return $s[0]["priority"];
173 * @brief Returns if a process with the given priority is running
175 * @param integer $priority The priority that should be checked
177 * @return integer Is there a process running with that priority?
179 function poller_process_with_priority_active($priority) {
180 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' AND NOT `done` LIMIT 1",
181 intval($priority), dbesc(NULL_DATE));
182 return dbm::is_result($s);
186 * @brief Execute a worker entry
188 * @param array $queue Workerqueue entry
190 * @return boolean "true" if further processing should be stopped
192 function poller_execute($queue) {
193 global $poller_db_duration, $poller_last_update;
199 // Quit when in maintenance
200 if (Config::get('system', 'maintenance', true)) {
201 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
205 // Constantly check the number of parallel database processes
206 if ($a->max_processes_reached()) {
207 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
211 // Constantly check the number of available database connections to let the frontend be accessible at any time
212 if (poller_max_connections_reached()) {
213 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
217 $argv = json_decode($queue["parameter"]);
219 // Check for existance and validity of the include file
222 if (!validate_include($include)) {
223 logger("Include file ".$argv[0]." is not valid!");
224 dba::delete('workerqueue', array('id' => $queue["id"]));
228 require_once($include);
230 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
232 if (function_exists($funcname)) {
234 // We constantly update the "executed" date every minute to avoid being killed too soon
235 if (!isset($poller_last_update)) {
236 $poller_last_update = strtotime($queue["executed"]);
239 $age = (time() - $poller_last_update) / 60;
240 $poller_last_update = time();
243 $stamp = (float)microtime(true);
244 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
245 $poller_db_duration += (microtime(true) - $stamp);
248 poller_exec_function($queue, $funcname, $argv);
250 $stamp = (float)microtime(true);
251 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
252 Config::set('system', 'last_poller_execution', datetime_convert());
254 $poller_db_duration = (microtime(true) - $stamp);
256 logger("Function ".$funcname." does not exist");
257 dba::delete('workerqueue', array('id' => $queue["id"]));
264 * @brief Execute a function from the queue
266 * @param array $queue Workerqueue entry
267 * @param string $funcname name of the function
268 * @param array $argv Array of values to be passed to the function
270 function poller_exec_function($queue, $funcname, $argv) {
271 global $poller_up_start, $poller_db_duration, $poller_lock_duration;
277 $argc = count($argv);
279 $new_process_id = uniqid("wrk", true);
281 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
283 $stamp = (float)microtime(true);
285 // We use the callstack here to analyze the performance of executed worker entries.
286 // For this reason the variables have to be initialized.
287 if (Config::get("system", "profiler")) {
288 $a->performance["start"] = microtime(true);
289 $a->performance["database"] = 0;
290 $a->performance["database_write"] = 0;
291 $a->performance["network"] = 0;
292 $a->performance["file"] = 0;
293 $a->performance["rendering"] = 0;
294 $a->performance["parser"] = 0;
295 $a->performance["marktime"] = 0;
296 $a->performance["markstart"] = microtime(true);
297 $a->callstack = array();
300 // For better logging create a new process id for every worker call
301 // But preserve the old one for the worker
302 $old_process_id = $a->process_id;
303 $a->process_id = $new_process_id;
306 $up_duration = number_format(microtime(true) - $poller_up_start, 3);
308 // Reset global data to avoid interferences
311 $funcname($argv, $argc);
313 $a->process_id = $old_process_id;
316 $duration = number_format(microtime(true) - $stamp, 3);
318 $poller_up_start = microtime(true);
320 /* With these values we can analyze how effective the worker is.
321 * The database and rest time should be low since this is the unproductive time.
322 * The execution time is the productive time.
323 * By changing parameters like the maximum number of workers we can check the effectivness.
325 logger('DB: '.number_format($poller_db_duration, 2).
326 ' - Lock: '.number_format($poller_lock_duration, 2).
327 ' - Rest: '.number_format($up_duration - $poller_db_duration - $poller_lock_duration, 2).
328 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
329 $poller_lock_duration = 0;
331 if ($duration > 3600) {
332 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
333 } elseif ($duration > 600) {
334 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
335 } elseif ($duration > 300) {
336 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
337 } elseif ($duration > 120) {
338 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
341 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
343 // Write down the performance values into the log
344 if (Config::get("system", "profiler")) {
345 $duration = microtime(true)-$a->performance["start"];
347 if (Config::get("rendertime", "callstack")) {
348 if (isset($a->callstack["database"])) {
349 $o = "\nDatabase Read:\n";
350 foreach ($a->callstack["database"] AS $func => $time) {
351 $time = round($time, 3);
353 $o .= $func.": ".$time."\n";
357 if (isset($a->callstack["database_write"])) {
358 $o .= "\nDatabase Write:\n";
359 foreach ($a->callstack["database_write"] AS $func => $time) {
360 $time = round($time, 3);
362 $o .= $func.": ".$time."\n";
366 if (isset($a->callstack["network"])) {
367 $o .= "\nNetwork:\n";
368 foreach ($a->callstack["network"] AS $func => $time) {
369 $time = round($time, 3);
371 $o .= $func.": ".$time."\n";
379 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
380 number_format($a->performance["database"] - $a->performance["database_write"], 2),
381 number_format($a->performance["database_write"], 2),
382 number_format($a->performance["network"], 2),
383 number_format($a->performance["file"], 2),
384 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
385 number_format($duration, 2)),
389 $cooldown = Config::get("system", "worker_cooldown", 0);
392 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
398 * @brief Checks if the number of database connections has reached a critical limit.
400 * @return bool Are more than 3/4 of the maximum connections used?
402 function poller_max_connections_reached() {
404 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
405 $max = Config::get("system", "max_connections");
407 // Fetch the percentage level where the poller will get active
408 $maxlevel = Config::get("system", "max_connections_level", 75);
411 // the maximum number of possible user connections can be a system variable
412 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
413 if (dbm::is_result($r)) {
414 $max = $r[0]["Value"];
416 // Or it can be granted. This overrides the system variable
417 $r = q("SHOW GRANTS");
418 if (dbm::is_result($r)) {
419 foreach ($r AS $grants) {
420 $grant = array_pop($grants);
421 if (stristr($grant, "GRANT USAGE ON")) {
422 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
430 // If $max is set we will use the processlist to determine the current number of connections
431 // The processlist only shows entries of the current user
433 $r = q("SHOW PROCESSLIST");
434 if (!dbm::is_result($r)) {
439 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
441 $level = ($used / $max) * 100;
443 if ($level >= $maxlevel) {
444 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
449 // We will now check for the system values.
450 // This limit could be reached although the user limits are fine.
451 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
452 if (!dbm::is_result($r)) {
455 $max = intval($r[0]["Value"]);
459 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
460 if (!dbm::is_result($r)) {
463 $used = intval($r[0]["Value"]);
467 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
469 $level = $used / $max * 100;
471 if ($level < $maxlevel) {
474 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
479 * @brief fix the queue entry if the worker process died
482 function poller_kill_stale_workers() {
483 $entries = dba::select('workerqueue', array('id', 'pid', 'executed', 'priority', 'parameter'),
484 array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
485 array('order' => array('priority', 'created')));
486 while ($entry = dba::fetch($entries)) {
487 if (!posix_kill($entry["pid"], 0)) {
488 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
489 array('id' => $entry["id"]));
491 // Kill long running processes
492 // Check if the priority is in a valid range
493 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
494 $entry["priority"] = PRIORITY_MEDIUM;
497 // Define the maximum durations
498 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
499 $max_duration = $max_duration_defaults[$entry["priority"]];
501 $argv = json_decode($entry["parameter"]);
502 $argv[0] = basename($argv[0]);
504 // How long is the process already running?
505 $duration = (time() - strtotime($entry["executed"])) / 60;
506 if ($duration > $max_duration) {
507 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
508 posix_kill($entry["pid"], SIGTERM);
510 // We killed the stale process.
511 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
512 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
513 if ($entry["priority"] == PRIORITY_HIGH) {
514 $new_priority = PRIORITY_MEDIUM;
515 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
516 $new_priority = PRIORITY_LOW;
517 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
518 $new_priority = PRIORITY_NEGLIGIBLE;
520 dba::update('workerqueue',
521 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
522 array('id' => $entry["id"]));
524 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
531 * @brief Checks if the number of active workers exceeds the given limits
533 * @return bool Are there too much workers running?
535 function poller_too_much_workers() {
536 $queues = Config::get("system", "worker_queues", 4);
538 $maxqueues = $queues;
540 $active = poller_active_workers();
542 // Decrease the number of workers at higher load
543 $load = current_load();
545 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
547 $maxworkers = $queues;
549 // Some magical mathemathics to reduce the workers
551 $slope = $maxworkers / pow($maxsysload, $exponent);
552 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
554 if (Config::get('system', 'worker_debug')) {
555 // Create a list of queue entries grouped by their priority
558 // Adding all processes with no workerqueue entry
559 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
560 (SELECT id FROM `workerqueue`
561 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
562 if ($process = dba::fetch($processes)) {
563 $listitem[0] = "0:".$process["running"];
565 dba::close($processes);
567 // Now adding all processes with workerqueue entries
568 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
569 while ($entry = dba::fetch($entries)) {
570 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
571 if ($process = dba::fetch($processes)) {
572 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
574 dba::close($processes);
576 dba::close($entries);
578 $intervals = array(1, 10, 60);
579 $jobs_per_minute = array();
580 foreach ($intervals AS $interval) {
581 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
582 if ($job = dba::fetch($jobs)) {
583 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
587 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
590 $entries = poller_total_entries();
592 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
593 $top_priority = poller_highest_priority();
594 $high_running = poller_process_with_priority_active($top_priority);
596 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
597 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
598 $queues = $active + 1;
602 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
604 // Are there fewer workers running as possible? Then fork a new one.
605 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
606 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
607 $args = array("include/poller.php", "no_cron");
608 get_app()->proc_run($args);
612 return $active >= $queues;
616 * @brief Returns the number of active poller processes
618 * @return integer Number of active poller processes
620 function poller_active_workers() {
621 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
623 return $workers[0]["processes"];
627 * @brief Check if we should pass some slow processes
629 * When the active processes of the highest priority are using more than 2/3
630 * of all processes, we let pass slower processes.
632 * @param string $highest_priority Returns the currently highest priority
633 * @return bool We let pass a slower process than $highest_priority
635 function poller_passing_slow(&$highest_priority) {
637 $highest_priority = 0;
639 $r = q("SELECT `priority`
641 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
643 // No active processes at all? Fine
644 if (!dbm::is_result($r)) {
647 $priorities = array();
648 foreach ($r AS $line) {
649 $priorities[] = $line["priority"];
652 if (count($priorities) == 0) {
655 $highest_priority = min($priorities);
657 // The highest process is already the slowest one?
659 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
663 foreach ($priorities AS $priority) {
664 if ($priority == $highest_priority) {
668 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
669 $passing_slow = (($high/count($priorities)) > (2/3));
672 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
674 return $passing_slow;
678 * @brief Find and claim the next worker process for us
680 * @param boolean $passing_slow Returns if we had passed low priority processes
681 * @return boolean Have we found something?
683 function find_worker_processes(&$passing_slow) {
687 // Check if we should pass some low priority process
688 $highest_priority = 0;
690 $passing_slow = false;
692 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
693 // We decrease the limit with the number of entries left in the queue
694 $worker_queues = Config::get("system", "worker_queues", 4);
695 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
696 $lower_job_limit = $worker_queues * $queue_length * 2;
697 $jobs = poller_total_entries();
701 $slope = $queue_length / pow($lower_job_limit, $exponent);
702 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
704 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
706 if (poller_passing_slow($highest_priority)) {
707 // Are there waiting processes with a higher priority than the currently highest?
708 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority),
709 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
711 while ($id = dba::fetch($result)) {
716 $found = (count($ids) > 0);
719 // Give slower processes some processing time
720 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority),
721 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
723 while ($id = dba::fetch($result)) {
728 $found = (count($ids) > 0);
729 $passing_slow = $found;
733 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
735 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND NOT `done`", NULL_DATE),
736 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
738 while ($id = dba::fetch($result)) {
743 $found = (count($ids) > 0);
747 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
748 array_unshift($ids, $condition);
749 dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
756 * @brief Returns the next worker process
758 * @param boolean $passing_slow Returns if we had passed low priority processes
759 * @return string SQL statement
761 function poller_worker_process(&$passing_slow) {
762 global $poller_db_duration, $poller_lock_duration;
764 $stamp = (float)microtime(true);
766 // There can already be jobs for us in the queue.
767 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
768 if (dbm::is_result($r)) {
769 $poller_db_duration += (microtime(true) - $stamp);
773 $stamp = (float)microtime(true);
774 if (!Lock::set('poller_worker_process')) {
777 $poller_lock_duration = (microtime(true) - $stamp);
779 $stamp = (float)microtime(true);
780 $found = find_worker_processes($passing_slow);
781 $poller_db_duration += (microtime(true) - $stamp);
783 Lock::remove('poller_worker_process');
786 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
792 * @brief Removes a workerqueue entry from the current process
794 function poller_unclaim_process() {
797 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
801 * @brief Call the front end worker
803 function call_worker() {
804 if (!Config::get("system", "frontend_worker")) {
808 $url = System::baseUrl()."/worker";
809 fetch_url($url, false, $redirects, 1);
813 * @brief Call the front end worker if there aren't any active
815 function call_worker_if_idle() {
816 if (!Config::get("system", "frontend_worker")) {
820 // Do we have "proc_open"? Then we can fork the poller
821 if (function_exists("proc_open")) {
822 // When was the last time that we called the worker?
823 // Less than one minute? Then we quit
824 if ((time() - Config::get("system", "worker_started")) < 60) {
828 set_config("system", "worker_started", time());
830 // Do we have enough running workers? Then we quit here.
831 if (poller_too_much_workers()) {
832 // Cleaning dead processes
833 poller_kill_stale_workers();
834 get_app()->remove_inactive_processes();
841 logger('Call poller', LOGGER_DEBUG);
843 $args = array("include/poller.php", "no_cron");
844 get_app()->proc_run($args);
848 // We cannot execute background processes.
849 // We now run the processes from the frontend.
850 // This won't work with long running processes.
853 clear_worker_processes();
855 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
857 if ($workers[0]["processes"] == 0) {
863 * @brief Removes long running worker processes
865 function clear_worker_processes() {
866 $timeout = Config::get("system", "frontend_worker_timeout", 10);
868 /// @todo We should clean up the corresponding workerqueue entries as well
869 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
870 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
874 * @brief Runs the cron processes
876 function poller_run_cron() {
877 logger('Add cron entries', LOGGER_DEBUG);
879 // Check for spooled items
880 proc_run(PRIORITY_HIGH, "include/spool_post.php");
882 // Run the cron job that calls all other jobs
883 proc_run(PRIORITY_MEDIUM, "include/cron.php");
885 // Run the cronhooks job separately from cron for being able to use a different timing
886 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
888 // Cleaning dead processes
889 poller_kill_stale_workers();
892 if (array_search(__file__,get_included_files())===0){
893 poller_run($_SERVER["argv"],$_SERVER["argc"]);
895 poller_unclaim_process();
897 get_app()->end_process();