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, $poller_up_start, $poller_db_duration;
24 $poller_up_start = microtime(true);
27 $a = new App(dirname(__DIR__));
30 require_once ".htconfig.php";
31 require_once "include/dba.php";
32 dba::connect($db_host, $db_user, $db_pass, $db_data);
33 unset($db_host, $db_user, $db_pass, $db_data);
37 // Check the database structure and possibly fixes it
40 // Quit when in maintenance
41 if (Config::get('system', 'maintenance', true)) {
45 $a->set_baseurl(Config::get('system', 'url'));
49 // At first check the maximum load. We shouldn't continue with a high load
50 if ($a->maxload_reached()) {
51 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
55 // We now start the process. This is done after the load check since this could increase the load.
58 // Kill stale processes every 5 minutes
59 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
60 if (time() > ($last_cleanup + 300)) {
61 Config::set('system', 'poller_last_cleaned', time());
62 poller_kill_stale_workers();
65 // Count active workers and compare them with a maximum value that depends on the load
66 if (poller_too_much_workers()) {
67 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
71 // Do we have too few memory?
72 if ($a->min_memory_reached()) {
73 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
77 // Possibly there are too much database connections
78 if (poller_max_connections_reached()) {
79 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
83 // Possibly there are too much database processes that block the system
84 if ($a->max_processes_reached()) {
85 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
89 // Now we start additional cron processes if we should do so
90 if (($argc <= 1) || ($argv[1] != "no_cron")) {
96 // We fetch the next queue entry that is about to be executed
97 while ($r = poller_worker_process($passing_slow)) {
99 // When we are processing jobs with a lower priority, we don't refetch new jobs
100 // Otherwise fast jobs could wait behind slow ones and could be blocked.
101 $refetched = $passing_slow;
103 foreach ($r AS $entry) {
104 // Assure that the priority is an integer value
105 $entry['priority'] = (int)$entry['priority'];
107 // The work will be done
108 if (!poller_execute($entry)) {
109 logger('Process execution failed, quitting.', LOGGER_DEBUG);
113 // If possible we will fetch new jobs for this worker
114 if (!$refetched && Lock::set('poller_worker_process', 0)) {
115 $stamp = (float)microtime(true);
116 $refetched = find_worker_processes($passing_slow);
117 $poller_db_duration += (microtime(true) - $stamp);
118 Lock::remove('poller_worker_process');
122 // To avoid the quitting of multiple pollers only one poller at a time will execute the check
123 if (Lock::set('poller_worker', 0)) {
124 $stamp = (float)microtime(true);
125 // Count active workers and compare them with a maximum value that depends on the load
126 if (poller_too_much_workers()) {
127 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
132 if ($a->min_memory_reached()) {
133 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
136 Lock::remove('poller_worker');
137 $poller_db_duration += (microtime(true) - $stamp);
140 // Quit the poller once every 5 minutes
141 if (time() > ($starttime + 300)) {
142 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
146 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
150 * @brief Returns the number of non executed entries in the worker queue
152 * @return integer Number of non executed entries in the worker queue
154 function poller_total_entries() {
155 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done`", dbesc(NULL_DATE));
156 if (dbm::is_result($s)) {
157 return $s[0]["total"];
164 * @brief Returns the highest priority in the worker queue that isn't executed
166 * @return integer Number of active poller processes
168 function poller_highest_priority() {
169 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done` ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
170 if (dbm::is_result($s)) {
171 return $s[0]["priority"];
178 * @brief Returns if a process with the given priority is running
180 * @param integer $priority The priority that should be checked
182 * @return integer Is there a process running with that priority?
184 function poller_process_with_priority_active($priority) {
185 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' AND NOT `done` LIMIT 1",
186 intval($priority), dbesc(NULL_DATE));
187 return dbm::is_result($s);
191 * @brief Execute a worker entry
193 * @param array $queue Workerqueue entry
195 * @return boolean "true" if further processing should be stopped
197 function poller_execute($queue) {
198 global $poller_db_duration, $poller_last_update;
204 // Quit when in maintenance
205 if (Config::get('system', 'maintenance', true)) {
206 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
210 // Constantly check the number of parallel database processes
211 if ($a->max_processes_reached()) {
212 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
216 // Constantly check the number of available database connections to let the frontend be accessible at any time
217 if (poller_max_connections_reached()) {
218 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
222 $argv = json_decode($queue["parameter"]);
224 // Check for existance and validity of the include file
227 if (!validate_include($include)) {
228 logger("Include file ".$argv[0]." is not valid!");
229 dba::delete('workerqueue', array('id' => $queue["id"]));
233 require_once($include);
235 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
237 if (function_exists($funcname)) {
239 // We constantly update the "executed" date every minute to avoid being killed too soon
240 if (!isset($poller_last_update)) {
241 $poller_last_update = strtotime($queue["executed"]);
244 $age = (time() - $poller_last_update) / 60;
245 $poller_last_update = time();
248 $stamp = (float)microtime(true);
249 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
250 $poller_db_duration += (microtime(true) - $stamp);
253 poller_exec_function($queue, $funcname, $argv);
255 $stamp = (float)microtime(true);
256 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
257 Config::set('system', 'last_poller_execution', datetime_convert());
259 $poller_db_duration = (microtime(true) - $stamp);
261 logger("Function ".$funcname." does not exist");
262 dba::delete('workerqueue', array('id' => $queue["id"]));
269 * @brief Execute a function from the queue
271 * @param array $queue Workerqueue entry
272 * @param string $funcname name of the function
273 * @param array $argv Array of values to be passed to the function
275 function poller_exec_function($queue, $funcname, $argv) {
276 global $poller_up_start, $poller_db_duration, $poller_lock_duration;
282 $argc = count($argv);
284 $new_process_id = uniqid("wrk", true);
286 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
288 $stamp = (float)microtime(true);
290 // We use the callstack here to analyze the performance of executed worker entries.
291 // For this reason the variables have to be initialized.
292 if (Config::get("system", "profiler")) {
293 $a->performance["start"] = microtime(true);
294 $a->performance["database"] = 0;
295 $a->performance["database_write"] = 0;
296 $a->performance["network"] = 0;
297 $a->performance["file"] = 0;
298 $a->performance["rendering"] = 0;
299 $a->performance["parser"] = 0;
300 $a->performance["marktime"] = 0;
301 $a->performance["markstart"] = microtime(true);
302 $a->callstack = array();
305 // For better logging create a new process id for every worker call
306 // But preserve the old one for the worker
307 $old_process_id = $a->process_id;
308 $a->process_id = $new_process_id;
311 $up_duration = number_format(microtime(true) - $poller_up_start, 3);
313 // Reset global data to avoid interferences
316 $funcname($argv, $argc);
318 $a->process_id = $old_process_id;
321 $duration = number_format(microtime(true) - $stamp, 3);
323 $poller_up_start = microtime(true);
325 /* With these values we can analyze how effective the worker is.
326 * The database and rest time should be low since this is the unproductive time.
327 * The execution time is the productive time.
328 * By changing parameters like the maximum number of workers we can check the effectivness.
330 logger('DB: '.number_format($poller_db_duration, 2).
331 ' - Lock: '.number_format($poller_lock_duration, 2).
332 ' - Rest: '.number_format($up_duration - $poller_db_duration - $poller_lock_duration, 2).
333 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
334 $poller_lock_duration = 0;
336 if ($duration > 3600) {
337 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
338 } elseif ($duration > 600) {
339 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
340 } elseif ($duration > 300) {
341 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
342 } elseif ($duration > 120) {
343 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
346 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
348 // Write down the performance values into the log
349 if (Config::get("system", "profiler")) {
350 $duration = microtime(true)-$a->performance["start"];
352 if (Config::get("rendertime", "callstack")) {
353 if (isset($a->callstack["database"])) {
354 $o = "\nDatabase Read:\n";
355 foreach ($a->callstack["database"] AS $func => $time) {
356 $time = round($time, 3);
358 $o .= $func.": ".$time."\n";
362 if (isset($a->callstack["database_write"])) {
363 $o .= "\nDatabase Write:\n";
364 foreach ($a->callstack["database_write"] AS $func => $time) {
365 $time = round($time, 3);
367 $o .= $func.": ".$time."\n";
371 if (isset($a->callstack["network"])) {
372 $o .= "\nNetwork:\n";
373 foreach ($a->callstack["network"] AS $func => $time) {
374 $time = round($time, 3);
376 $o .= $func.": ".$time."\n";
384 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
385 number_format($a->performance["database"] - $a->performance["database_write"], 2),
386 number_format($a->performance["database_write"], 2),
387 number_format($a->performance["network"], 2),
388 number_format($a->performance["file"], 2),
389 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
390 number_format($duration, 2)),
394 $cooldown = Config::get("system", "worker_cooldown", 0);
397 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
403 * @brief Checks if the number of database connections has reached a critical limit.
405 * @return bool Are more than 3/4 of the maximum connections used?
407 function poller_max_connections_reached() {
409 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
410 $max = Config::get("system", "max_connections");
412 // Fetch the percentage level where the poller will get active
413 $maxlevel = Config::get("system", "max_connections_level", 75);
416 // the maximum number of possible user connections can be a system variable
417 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
418 if (dbm::is_result($r)) {
419 $max = $r[0]["Value"];
421 // Or it can be granted. This overrides the system variable
422 $r = q("SHOW GRANTS");
423 if (dbm::is_result($r)) {
424 foreach ($r AS $grants) {
425 $grant = array_pop($grants);
426 if (stristr($grant, "GRANT USAGE ON")) {
427 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
435 // If $max is set we will use the processlist to determine the current number of connections
436 // The processlist only shows entries of the current user
438 $r = q("SHOW PROCESSLIST");
439 if (!dbm::is_result($r)) {
444 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
446 $level = ($used / $max) * 100;
448 if ($level >= $maxlevel) {
449 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
454 // We will now check for the system values.
455 // This limit could be reached although the user limits are fine.
456 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
457 if (!dbm::is_result($r)) {
460 $max = intval($r[0]["Value"]);
464 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
465 if (!dbm::is_result($r)) {
468 $used = intval($r[0]["Value"]);
472 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
474 $level = $used / $max * 100;
476 if ($level < $maxlevel) {
479 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
484 * @brief fix the queue entry if the worker process died
487 function poller_kill_stale_workers() {
488 $entries = dba::select('workerqueue', array('id', 'pid', 'executed', 'priority', 'parameter'),
489 array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
490 array('order' => array('priority', 'created')));
491 while ($entry = dba::fetch($entries)) {
492 if (!posix_kill($entry["pid"], 0)) {
493 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
494 array('id' => $entry["id"]));
496 // Kill long running processes
497 // Check if the priority is in a valid range
498 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
499 $entry["priority"] = PRIORITY_MEDIUM;
502 // Define the maximum durations
503 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
504 $max_duration = $max_duration_defaults[$entry["priority"]];
506 $argv = json_decode($entry["parameter"]);
507 $argv[0] = basename($argv[0]);
509 // How long is the process already running?
510 $duration = (time() - strtotime($entry["executed"])) / 60;
511 if ($duration > $max_duration) {
512 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
513 posix_kill($entry["pid"], SIGTERM);
515 // We killed the stale process.
516 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
517 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
518 if ($entry["priority"] == PRIORITY_HIGH) {
519 $new_priority = PRIORITY_MEDIUM;
520 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
521 $new_priority = PRIORITY_LOW;
522 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
523 $new_priority = PRIORITY_NEGLIGIBLE;
525 dba::update('workerqueue',
526 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
527 array('id' => $entry["id"]));
529 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
536 * @brief Checks if the number of active workers exceeds the given limits
538 * @return bool Are there too much workers running?
540 function poller_too_much_workers() {
541 $queues = Config::get("system", "worker_queues", 4);
543 $maxqueues = $queues;
545 $active = poller_active_workers();
547 // Decrease the number of workers at higher load
548 $load = current_load();
550 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
552 $maxworkers = $queues;
554 // Some magical mathemathics to reduce the workers
556 $slope = $maxworkers / pow($maxsysload, $exponent);
557 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
559 if (Config::get('system', 'worker_debug')) {
560 // Create a list of queue entries grouped by their priority
563 // Adding all processes with no workerqueue entry
564 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
565 (SELECT id FROM `workerqueue`
566 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
567 if ($process = dba::fetch($processes)) {
568 $listitem[0] = "0:".$process["running"];
570 dba::close($processes);
572 // Now adding all processes with workerqueue entries
573 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
574 while ($entry = dba::fetch($entries)) {
575 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
576 if ($process = dba::fetch($processes)) {
577 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
579 dba::close($processes);
581 dba::close($entries);
583 $intervals = array(1, 10, 60);
584 $jobs_per_minute = array();
585 foreach ($intervals AS $interval) {
586 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
587 if ($job = dba::fetch($jobs)) {
588 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
592 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
595 $entries = poller_total_entries();
597 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
598 $top_priority = poller_highest_priority();
599 $high_running = poller_process_with_priority_active($top_priority);
601 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
602 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
603 $queues = $active + 1;
607 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
609 // Are there fewer workers running as possible? Then fork a new one.
610 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
611 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
612 $args = array("include/poller.php", "no_cron");
613 get_app()->proc_run($args);
617 return $active >= $queues;
621 * @brief Returns the number of active poller processes
623 * @return integer Number of active poller processes
625 function poller_active_workers() {
626 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
628 return $workers[0]["processes"];
632 * @brief Check if we should pass some slow processes
634 * When the active processes of the highest priority are using more than 2/3
635 * of all processes, we let pass slower processes.
637 * @param string $highest_priority Returns the currently highest priority
638 * @return bool We let pass a slower process than $highest_priority
640 function poller_passing_slow(&$highest_priority) {
642 $highest_priority = 0;
644 $r = q("SELECT `priority`
646 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
648 // No active processes at all? Fine
649 if (!dbm::is_result($r)) {
652 $priorities = array();
653 foreach ($r AS $line) {
654 $priorities[] = $line["priority"];
657 if (count($priorities) == 0) {
660 $highest_priority = min($priorities);
662 // The highest process is already the slowest one?
664 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
668 foreach ($priorities AS $priority) {
669 if ($priority == $highest_priority) {
673 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
674 $passing_slow = (($high/count($priorities)) > (2/3));
677 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
679 return $passing_slow;
683 * @brief Find and claim the next worker process for us
685 * @param boolean $passing_slow Returns if we had passed low priority processes
686 * @return boolean Have we found something?
688 function find_worker_processes(&$passing_slow) {
692 // Check if we should pass some low priority process
693 $highest_priority = 0;
695 $passing_slow = false;
697 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
698 // We decrease the limit with the number of entries left in the queue
699 $worker_queues = Config::get("system", "worker_queues", 4);
700 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
701 $lower_job_limit = $worker_queues * $queue_length * 2;
702 $jobs = poller_total_entries();
706 $slope = $queue_length / pow($lower_job_limit, $exponent);
707 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
709 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
711 if (poller_passing_slow($highest_priority)) {
712 // Are there waiting processes with a higher priority than the currently highest?
713 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority),
714 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
716 while ($id = dba::fetch($result)) {
721 $found = (count($ids) > 0);
724 // Give slower processes some processing time
725 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority),
726 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
728 while ($id = dba::fetch($result)) {
733 $found = (count($ids) > 0);
734 $passing_slow = $found;
738 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
740 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND NOT `done`", NULL_DATE),
741 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
743 while ($id = dba::fetch($result)) {
748 $found = (count($ids) > 0);
752 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
753 array_unshift($ids, $condition);
754 dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
761 * @brief Returns the next worker process
763 * @param boolean $passing_slow Returns if we had passed low priority processes
764 * @return string SQL statement
766 function poller_worker_process(&$passing_slow) {
767 global $poller_db_duration, $poller_lock_duration;
769 $stamp = (float)microtime(true);
771 // There can already be jobs for us in the queue.
772 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
773 if (dbm::is_result($r)) {
774 $poller_db_duration += (microtime(true) - $stamp);
778 $stamp = (float)microtime(true);
779 if (!Lock::set('poller_worker_process')) {
782 $poller_lock_duration = (microtime(true) - $stamp);
784 $stamp = (float)microtime(true);
785 $found = find_worker_processes($passing_slow);
786 $poller_db_duration += (microtime(true) - $stamp);
788 Lock::remove('poller_worker_process');
791 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
797 * @brief Removes a workerqueue entry from the current process
799 function poller_unclaim_process() {
802 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
806 * @brief Call the front end worker
808 function call_worker() {
809 if (!Config::get("system", "frontend_worker")) {
813 $url = System::baseUrl()."/worker";
814 fetch_url($url, false, $redirects, 1);
818 * @brief Call the front end worker if there aren't any active
820 function call_worker_if_idle() {
821 if (!Config::get("system", "frontend_worker")) {
825 // Do we have "proc_open"? Then we can fork the poller
826 if (function_exists("proc_open")) {
827 // When was the last time that we called the worker?
828 // Less than one minute? Then we quit
829 if ((time() - Config::get("system", "worker_started")) < 60) {
833 set_config("system", "worker_started", time());
835 // Do we have enough running workers? Then we quit here.
836 if (poller_too_much_workers()) {
837 // Cleaning dead processes
838 poller_kill_stale_workers();
839 get_app()->remove_inactive_processes();
846 logger('Call poller', LOGGER_DEBUG);
848 $args = array("include/poller.php", "no_cron");
849 get_app()->proc_run($args);
853 // We cannot execute background processes.
854 // We now run the processes from the frontend.
855 // This won't work with long running processes.
858 clear_worker_processes();
860 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
862 if ($workers[0]["processes"] == 0) {
868 * @brief Removes long running worker processes
870 function clear_worker_processes() {
871 $timeout = Config::get("system", "frontend_worker_timeout", 10);
873 /// @todo We should clean up the corresponding workerqueue entries as well
874 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
875 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
879 * @brief Runs the cron processes
881 function poller_run_cron() {
882 logger('Add cron entries', LOGGER_DEBUG);
884 // Check for spooled items
885 proc_run(PRIORITY_HIGH, "include/spool_post.php");
887 // Run the cron job that calls all other jobs
888 proc_run(PRIORITY_MEDIUM, "include/cron.php");
890 // Run the cronhooks job separately from cron for being able to use a different timing
891 proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
893 // Cleaning dead processes
894 poller_kill_stale_workers();
897 if (array_search(__file__,get_included_files())===0) {
898 poller_run($_SERVER["argv"],$_SERVER["argc"]);
900 poller_unclaim_process();
902 get_app()->end_process();