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 dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]));
252 $poller_db_duration = (microtime(true) - $stamp);
254 logger("Function ".$funcname." does not exist");
255 dba::delete('workerqueue', array('id' => $queue["id"]));
262 * @brief Execute a function from the queue
264 * @param array $queue Workerqueue entry
265 * @param string $funcname name of the function
266 * @param array $argv Array of values to be passed to the function
268 function poller_exec_function($queue, $funcname, $argv) {
269 global $poller_up_start, $poller_db_duration, $poller_lock_duration;
275 $argc = count($argv);
277 $new_process_id = uniqid("wrk", true);
279 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
281 $stamp = (float)microtime(true);
283 // We use the callstack here to analyze the performance of executed worker entries.
284 // For this reason the variables have to be initialized.
285 if (Config::get("system", "profiler")) {
286 $a->performance["start"] = microtime(true);
287 $a->performance["database"] = 0;
288 $a->performance["database_write"] = 0;
289 $a->performance["network"] = 0;
290 $a->performance["file"] = 0;
291 $a->performance["rendering"] = 0;
292 $a->performance["parser"] = 0;
293 $a->performance["marktime"] = 0;
294 $a->performance["markstart"] = microtime(true);
295 $a->callstack = array();
298 // For better logging create a new process id for every worker call
299 // But preserve the old one for the worker
300 $old_process_id = $a->process_id;
301 $a->process_id = $new_process_id;
304 $up_duration = number_format(microtime(true) - $poller_up_start, 3);
306 $funcname($argv, $argc);
308 $a->process_id = $old_process_id;
311 $duration = number_format(microtime(true) - $stamp, 3);
313 $poller_up_start = microtime(true);
315 /* With these values we can analyze how effective the worker is.
316 * The database and rest time should be low since this is the unproductive time.
317 * The execution time is the productive time.
318 * By changing parameters like the maximum number of workers we can check the effectivness.
320 logger('DB: '.number_format($poller_db_duration, 2).
321 ' - Lock: '.number_format($poller_lock_duration, 2).
322 ' - Rest: '.number_format($up_duration - $poller_db_duration - $poller_lock_duration, 2).
323 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
324 $poller_lock_duration = 0;
326 if ($duration > 3600) {
327 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
328 } elseif ($duration > 600) {
329 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
330 } elseif ($duration > 300) {
331 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
332 } elseif ($duration > 120) {
333 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
336 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
338 // Write down the performance values into the log
339 if (Config::get("system", "profiler")) {
340 $duration = microtime(true)-$a->performance["start"];
342 if (Config::get("rendertime", "callstack")) {
343 if (isset($a->callstack["database"])) {
344 $o = "\nDatabase Read:\n";
345 foreach ($a->callstack["database"] AS $func => $time) {
346 $time = round($time, 3);
348 $o .= $func.": ".$time."\n";
352 if (isset($a->callstack["database_write"])) {
353 $o .= "\nDatabase Write:\n";
354 foreach ($a->callstack["database_write"] AS $func => $time) {
355 $time = round($time, 3);
357 $o .= $func.": ".$time."\n";
361 if (isset($a->callstack["network"])) {
362 $o .= "\nNetwork:\n";
363 foreach ($a->callstack["network"] AS $func => $time) {
364 $time = round($time, 3);
366 $o .= $func.": ".$time."\n";
374 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
375 number_format($a->performance["database"] - $a->performance["database_write"], 2),
376 number_format($a->performance["database_write"], 2),
377 number_format($a->performance["network"], 2),
378 number_format($a->performance["file"], 2),
379 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
380 number_format($duration, 2)),
384 $cooldown = Config::get("system", "worker_cooldown", 0);
387 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
393 * @brief Checks if the number of database connections has reached a critical limit.
395 * @return bool Are more than 3/4 of the maximum connections used?
397 function poller_max_connections_reached() {
399 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
400 $max = Config::get("system", "max_connections");
402 // Fetch the percentage level where the poller will get active
403 $maxlevel = Config::get("system", "max_connections_level", 75);
406 // the maximum number of possible user connections can be a system variable
407 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
408 if (dbm::is_result($r)) {
409 $max = $r[0]["Value"];
411 // Or it can be granted. This overrides the system variable
412 $r = q("SHOW GRANTS");
413 if (dbm::is_result($r)) {
414 foreach ($r AS $grants) {
415 $grant = array_pop($grants);
416 if (stristr($grant, "GRANT USAGE ON")) {
417 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
425 // If $max is set we will use the processlist to determine the current number of connections
426 // The processlist only shows entries of the current user
428 $r = q("SHOW PROCESSLIST");
429 if (!dbm::is_result($r)) {
434 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
436 $level = ($used / $max) * 100;
438 if ($level >= $maxlevel) {
439 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
444 // We will now check for the system values.
445 // This limit could be reached although the user limits are fine.
446 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
447 if (!dbm::is_result($r)) {
450 $max = intval($r[0]["Value"]);
454 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
455 if (!dbm::is_result($r)) {
458 $used = intval($r[0]["Value"]);
462 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
464 $level = $used / $max * 100;
466 if ($level < $maxlevel) {
469 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
474 * @brief fix the queue entry if the worker process died
477 function poller_kill_stale_workers() {
478 $entries = dba::select('workerqueue', array('id', 'pid', 'executed', 'priority', 'parameter'),
479 array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
480 array('order' => array('priority', 'created')));
481 while ($entry = dba::fetch($entries)) {
482 if (!posix_kill($entry["pid"], 0)) {
483 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
484 array('id' => $entry["id"]));
486 // Kill long running processes
487 // Check if the priority is in a valid range
488 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
489 $entry["priority"] = PRIORITY_MEDIUM;
492 // Define the maximum durations
493 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
494 $max_duration = $max_duration_defaults[$entry["priority"]];
496 $argv = json_decode($entry["parameter"]);
497 $argv[0] = basename($argv[0]);
499 // How long is the process already running?
500 $duration = (time() - strtotime($entry["executed"])) / 60;
501 if ($duration > $max_duration) {
502 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
503 posix_kill($entry["pid"], SIGTERM);
505 // We killed the stale process.
506 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
507 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
508 if ($entry["priority"] == PRIORITY_HIGH) {
509 $new_priority = PRIORITY_MEDIUM;
510 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
511 $new_priority = PRIORITY_LOW;
512 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
513 $new_priority = PRIORITY_NEGLIGIBLE;
515 dba::update('workerqueue',
516 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
517 array('id' => $entry["id"]));
519 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
526 * @brief Checks if the number of active workers exceeds the given limits
528 * @return bool Are there too much workers running?
530 function poller_too_much_workers() {
531 $queues = Config::get("system", "worker_queues", 4);
533 $maxqueues = $queues;
535 $active = poller_active_workers();
537 // Decrease the number of workers at higher load
538 $load = current_load();
540 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
542 $maxworkers = $queues;
544 // Some magical mathemathics to reduce the workers
546 $slope = $maxworkers / pow($maxsysload, $exponent);
547 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
549 if (Config::get('system', 'worker_debug')) {
550 // Create a list of queue entries grouped by their priority
553 // Adding all processes with no workerqueue entry
554 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
555 (SELECT id FROM `workerqueue`
556 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
557 if ($process = dba::fetch($processes)) {
558 $listitem[0] = "0:".$process["running"];
560 dba::close($processes);
562 // Now adding all processes with workerqueue entries
563 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
564 while ($entry = dba::fetch($entries)) {
565 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
566 if ($process = dba::fetch($processes)) {
567 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
569 dba::close($processes);
571 dba::close($entries);
573 $intervals = array(1, 10, 60);
574 $jobs_per_minute = array();
575 foreach ($intervals AS $interval) {
576 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
577 if ($job = dba::fetch($jobs)) {
578 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
582 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
585 $entries = poller_total_entries();
587 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
588 $top_priority = poller_highest_priority();
589 $high_running = poller_process_with_priority_active($top_priority);
591 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
592 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
593 $queues = $active + 1;
597 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
599 // Are there fewer workers running as possible? Then fork a new one.
600 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
601 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
602 $args = array("include/poller.php", "no_cron");
603 get_app()->proc_run($args);
607 return $active >= $queues;
611 * @brief Returns the number of active poller processes
613 * @return integer Number of active poller processes
615 function poller_active_workers() {
616 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
618 return $workers[0]["processes"];
622 * @brief Check if we should pass some slow processes
624 * When the active processes of the highest priority are using more than 2/3
625 * of all processes, we let pass slower processes.
627 * @param string $highest_priority Returns the currently highest priority
628 * @return bool We let pass a slower process than $highest_priority
630 function poller_passing_slow(&$highest_priority) {
632 $highest_priority = 0;
634 $r = q("SELECT `priority`
636 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
638 // No active processes at all? Fine
639 if (!dbm::is_result($r)) {
642 $priorities = array();
643 foreach ($r AS $line) {
644 $priorities[] = $line["priority"];
647 if (count($priorities) == 0) {
650 $highest_priority = min($priorities);
652 // The highest process is already the slowest one?
654 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
658 foreach ($priorities AS $priority) {
659 if ($priority == $highest_priority) {
663 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
664 $passing_slow = (($high/count($priorities)) > (2/3));
667 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
669 return $passing_slow;
673 * @brief Find and claim the next worker process for us
675 * @param boolean $passing_slow Returns if we had passed low priority processes
676 * @return boolean Have we found something?
678 function find_worker_processes(&$passing_slow) {
682 // Check if we should pass some low priority process
683 $highest_priority = 0;
685 $passing_slow = false;
687 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
688 // We decrease the limit with the number of entries left in the queue
689 $worker_queues = Config::get("system", "worker_queues", 4);
690 $queue_length = Config::get('system', 'worker_fetch_limit', $worker_queues);
691 $lower_job_limit = $worker_queues * $queue_length * 2;
692 $jobs = poller_total_entries();
696 $slope = $queue_length / pow($lower_job_limit, $exponent);
697 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
699 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
701 if (poller_passing_slow($highest_priority)) {
702 // Are there waiting processes with a higher priority than the currently highest?
703 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority),
704 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
706 while ($id = dba::fetch($result)) {
711 $found = (count($ids) > 0);
714 // Give slower processes some processing time
715 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority),
716 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
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::select('workerqueue', array('id'), array("`executed` <= ? AND NOT `done`", NULL_DATE),
731 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
733 while ($id = dba::fetch($result)) {
738 $found = (count($ids) > 0);
742 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
743 array_unshift($ids, $condition);
744 dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
751 * @brief Returns the next worker process
753 * @param boolean $passing_slow Returns if we had passed low priority processes
754 * @return string SQL statement
756 function poller_worker_process(&$passing_slow) {
757 global $poller_db_duration, $poller_lock_duration;
759 $stamp = (float)microtime(true);
761 // There can already be jobs for us in the queue.
762 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
763 if (dbm::is_result($r)) {
764 $poller_db_duration += (microtime(true) - $stamp);
768 $stamp = (float)microtime(true);
769 if (!Lock::set('poller_worker_process')) {
772 $poller_lock_duration = (microtime(true) - $stamp);
774 $stamp = (float)microtime(true);
775 $found = find_worker_processes($passing_slow);
776 $poller_db_duration += (microtime(true) - $stamp);
778 Lock::remove('poller_worker_process');
781 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
787 * @brief Removes a workerqueue entry from the current process
789 function poller_unclaim_process() {
792 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
796 * @brief Call the front end worker
798 function call_worker() {
799 if (!Config::get("system", "frontend_worker")) {
803 $url = System::baseUrl()."/worker";
804 fetch_url($url, false, $redirects, 1);
808 * @brief Call the front end worker if there aren't any active
810 function call_worker_if_idle() {
811 if (!Config::get("system", "frontend_worker")) {
815 // Do we have "proc_open"? Then we can fork the poller
816 if (function_exists("proc_open")) {
817 // When was the last time that we called the worker?
818 // Less than one minute? Then we quit
819 if ((time() - Config::get("system", "worker_started")) < 60) {
823 set_config("system", "worker_started", time());
825 // Do we have enough running workers? Then we quit here.
826 if (poller_too_much_workers()) {
827 // Cleaning dead processes
828 poller_kill_stale_workers();
829 get_app()->remove_inactive_processes();
836 logger('Call poller', LOGGER_DEBUG);
838 $args = array("include/poller.php", "no_cron");
839 get_app()->proc_run($args);
843 // We cannot execute background processes.
844 // We now run the processes from the frontend.
845 // This won't work with long running processes.
848 clear_worker_processes();
850 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
852 if ($workers[0]["processes"] == 0) {
858 * @brief Removes long running worker processes
860 function clear_worker_processes() {
861 $timeout = Config::get("system", "frontend_worker_timeout", 10);
863 /// @todo We should clean up the corresponding workerqueue entries as well
864 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
865 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
869 * @brief Runs the cron processes
871 function poller_run_cron() {
872 logger('Add cron entries', LOGGER_DEBUG);
874 // Check for spooled items
875 proc_run(PRIORITY_HIGH, "include/spool_post.php");
877 // Run the cron job that calls all other jobs
878 proc_run(PRIORITY_MEDIUM, "include/cron.php");
880 // Run the cronhooks job separately from cron for being able to use a different timing
881 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
883 // Cleaning dead processes
884 poller_kill_stale_workers();
887 if (array_search(__file__,get_included_files())===0){
888 poller_run($_SERVER["argv"],$_SERVER["argc"]);
890 poller_unclaim_process();
892 get_app()->end_process();