3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Core\Worker;
11 use Friendica\Database\DBM;
12 use Friendica\Util\Lock;
17 * @file src/Core/Worker.php
19 * @brief Contains the class for the worker background job processing
23 * @brief Worker methods
27 private static $up_start;
28 private static $db_duration;
29 private static $last_update;
30 private static $lock_duration;
33 * @brief Processes the tasks that are in the workerqueue table
35 * @param boolean $run_cron Should the cron processes be executed?
38 public static function processQueue($run_cron = true)
42 self::$up_start = microtime(true);
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 self::killStaleWorkers();
60 // Count active workers and compare them with a maximum value that depends on the load
61 if (self::tooMuchWorkers()) {
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 (self::maxConnectionsReached()) {
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
91 // We fetch the next queue entry that is about to be executed
92 while ($r = self::workerProcess($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 (!self::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 = self::findWorkerProcesses($passing_slow);
111 self::$db_duration += (microtime(true) - $stamp);
112 Lock::remove('poller_worker_process');
116 // To avoid the quitting of multiple workers only one worker 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 (self::tooMuchWorkers()) {
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 self::$db_duration += (microtime(true) - $stamp);
134 // Quit the worker 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 private static function totalEntries()
150 $s = dba::fetch_first("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done`", NULL_DATE);
151 if (DBM::is_result($s)) {
159 * @brief Returns the highest priority in the worker queue that isn't executed
161 * @return integer Number of active worker processes
163 private static function highestPriority()
165 $condition = array("`executed` <= ? AND NOT `done`", NULL_DATE);
166 $s = dba::select('workerqueue', array('priority'), $condition, array('limit' => 1, 'order' => array('priority')));
167 if (DBM::is_result($s)) {
168 return $s["priority"];
175 * @brief Returns if a process with the given priority is running
177 * @param integer $priority The priority that should be checked
179 * @return integer Is there a process running with that priority?
181 private static function processWithPriorityActive($priority)
183 $condition = array("`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE);
184 return dba::exists('workerqueue', $condition);
188 * @brief Execute a worker entry
190 * @param array $queue Workerqueue entry
192 * @return boolean "true" if further processing should be stopped
194 public static function execute($queue)
200 // Quit when in maintenance
201 if (Config::get('system', 'maintenance', true)) {
202 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
206 // Constantly check the number of parallel database processes
207 if ($a->max_processes_reached()) {
208 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
212 // Constantly check the number of available database connections to let the frontend be accessible at any time
213 if (self::maxConnectionsReached()) {
214 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
218 $argv = json_decode($queue["parameter"]);
220 // Check for existance and validity of the include file
223 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
224 // We constantly update the "executed" date every minute to avoid being killed too soon
225 if (!isset(self::$last_update)) {
226 self::$last_update = strtotime($queue["executed"]);
229 $age = (time() - self::$last_update) / 60;
230 self::$last_update = time();
233 $stamp = (float)microtime(true);
234 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
235 self::$db_duration += (microtime(true) - $stamp);
240 self::execFunction($queue, $include, $argv, true);
242 $stamp = (float)microtime(true);
243 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
244 Config::set('system', 'last_poller_execution', datetime_convert());
246 self::$db_duration = (microtime(true) - $stamp);
251 // The script could be provided as full path or only with the function name
252 if ($include == basename($include)) {
253 $include = "include/".$include.".php";
256 if (!validate_include($include)) {
257 logger("Include file ".$argv[0]." is not valid!");
258 dba::delete('workerqueue', array('id' => $queue["id"]));
262 require_once $include;
264 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
266 if (function_exists($funcname)) {
267 // We constantly update the "executed" date every minute to avoid being killed too soon
268 if (!isset(self::$last_update)) {
269 self::$last_update = strtotime($queue["executed"]);
272 $age = (time() - self::$last_update) / 60;
273 self::$last_update = time();
276 $stamp = (float)microtime(true);
277 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
278 self::$db_duration += (microtime(true) - $stamp);
281 self::execFunction($queue, $funcname, $argv, false);
283 $stamp = (float)microtime(true);
284 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
285 Config::set('system', 'last_poller_execution', datetime_convert());
287 self::$db_duration = (microtime(true) - $stamp);
289 logger("Function ".$funcname." does not exist");
290 dba::delete('workerqueue', array('id' => $queue["id"]));
297 * @brief Execute a function from the queue
299 * @param array $queue Workerqueue entry
300 * @param string $funcname name of the function
301 * @param array $argv Array of values to be passed to the function
302 * @param boolean $method_call boolean
305 private static function execFunction($queue, $funcname, $argv, $method_call)
311 $argc = count($argv);
313 $new_process_id = uniqid("wrk", true);
315 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
317 $stamp = (float)microtime(true);
319 // We use the callstack here to analyze the performance of executed worker entries.
320 // For this reason the variables have to be initialized.
321 if (Config::get("system", "profiler")) {
322 $a->performance["start"] = microtime(true);
323 $a->performance["database"] = 0;
324 $a->performance["database_write"] = 0;
325 $a->performance["network"] = 0;
326 $a->performance["file"] = 0;
327 $a->performance["rendering"] = 0;
328 $a->performance["parser"] = 0;
329 $a->performance["marktime"] = 0;
330 $a->performance["markstart"] = microtime(true);
331 $a->callstack = array();
334 // For better logging create a new process id for every worker call
335 // But preserve the old one for the worker
336 $old_process_id = $a->process_id;
337 $a->process_id = $new_process_id;
340 $up_duration = number_format(microtime(true) - self::$up_start, 3);
342 // Reset global data to avoid interferences
346 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
348 $funcname($argv, $argc);
351 $a->process_id = $old_process_id;
354 $duration = number_format(microtime(true) - $stamp, 3);
356 self::$up_start = microtime(true);
358 /* With these values we can analyze how effective the worker is.
359 * The database and rest time should be low since this is the unproductive time.
360 * The execution time is the productive time.
361 * By changing parameters like the maximum number of workers we can check the effectivness.
364 'DB: '.number_format(self::$db_duration, 2).
365 ' - Lock: '.number_format(self::$lock_duration, 2).
366 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
367 ' - Execution: '.number_format($duration, 2),
371 self::$lock_duration = 0;
373 if ($duration > 3600) {
374 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
375 } elseif ($duration > 600) {
376 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
377 } elseif ($duration > 300) {
378 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
379 } elseif ($duration > 120) {
380 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
383 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
385 // Write down the performance values into the log
386 if (Config::get("system", "profiler")) {
387 $duration = microtime(true)-$a->performance["start"];
389 if (Config::get("rendertime", "callstack")) {
390 if (isset($a->callstack["database"])) {
391 $o = "\nDatabase Read:\n";
392 foreach ($a->callstack["database"] as $func => $time) {
393 $time = round($time, 3);
395 $o .= $func.": ".$time."\n";
399 if (isset($a->callstack["database_write"])) {
400 $o .= "\nDatabase Write:\n";
401 foreach ($a->callstack["database_write"] as $func => $time) {
402 $time = round($time, 3);
404 $o .= $func.": ".$time."\n";
408 if (isset($a->callstack["network"])) {
409 $o .= "\nNetwork:\n";
410 foreach ($a->callstack["network"] as $func => $time) {
411 $time = round($time, 3);
413 $o .= $func.": ".$time."\n";
422 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
423 "DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
424 number_format($a->performance["database"] - $a->performance["database_write"], 2),
425 number_format($a->performance["database_write"], 2),
426 number_format($a->performance["network"], 2),
427 number_format($a->performance["file"], 2),
428 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
429 number_format($duration, 2)
435 $cooldown = Config::get("system", "worker_cooldown", 0);
438 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
444 * @brief Checks if the number of database connections has reached a critical limit.
446 * @return bool Are more than 3/4 of the maximum connections used?
448 private static function maxConnectionsReached()
450 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
451 $max = Config::get("system", "max_connections");
453 // Fetch the percentage level where the worker will get active
454 $maxlevel = Config::get("system", "max_connections_level", 75);
457 // the maximum number of possible user connections can be a system variable
458 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
459 if (DBM::is_result($r)) {
462 // Or it can be granted. This overrides the system variable
463 $r = dba::p('SHOW GRANTS');
464 while ($grants = dba::fetch($r)) {
465 $grant = array_pop($grants);
466 if (stristr($grant, "GRANT USAGE ON")) {
467 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
475 // If $max is set we will use the processlist to determine the current number of connections
476 // The processlist only shows entries of the current user
478 $r = dba::p('SHOW PROCESSLIST');
479 $used = dba::num_rows($r);
482 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
484 $level = ($used / $max) * 100;
486 if ($level >= $maxlevel) {
487 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
492 // We will now check for the system values.
493 // This limit could be reached although the user limits are fine.
494 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
495 if (!DBM::is_result($r)) {
498 $max = intval($r["Value"]);
502 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
503 if (!DBM::is_result($r)) {
506 $used = intval($r["Value"]);
510 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
512 $level = $used / $max * 100;
514 if ($level < $maxlevel) {
517 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
522 * @brief fix the queue entry if the worker process died
525 private static function killStaleWorkers()
527 $entries = dba::select(
529 array('id', 'pid', 'executed', 'priority', 'parameter'),
530 array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
531 array('order' => array('priority', 'created'))
534 while ($entry = dba::fetch($entries)) {
535 if (!posix_kill($entry["pid"], 0)) {
538 array('executed' => NULL_DATE, 'pid' => 0),
539 array('id' => $entry["id"])
542 // Kill long running processes
543 // Check if the priority is in a valid range
544 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
545 $entry["priority"] = PRIORITY_MEDIUM;
548 // Define the maximum durations
549 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
550 $max_duration = $max_duration_defaults[$entry["priority"]];
552 $argv = json_decode($entry["parameter"]);
553 $argv[0] = basename($argv[0]);
555 // How long is the process already running?
556 $duration = (time() - strtotime($entry["executed"])) / 60;
557 if ($duration > $max_duration) {
558 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
559 posix_kill($entry["pid"], SIGTERM);
561 // We killed the stale process.
562 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
563 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
564 if ($entry["priority"] == PRIORITY_HIGH) {
565 $new_priority = PRIORITY_MEDIUM;
566 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
567 $new_priority = PRIORITY_LOW;
568 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
569 $new_priority = PRIORITY_NEGLIGIBLE;
573 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
574 array('id' => $entry["id"])
577 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
584 * @brief Checks if the number of active workers exceeds the given limits
586 * @return bool Are there too much workers running?
588 public static function tooMuchWorkers()
590 $queues = Config::get("system", "worker_queues", 4);
592 $maxqueues = $queues;
594 $active = self::activeWorkers();
596 // Decrease the number of workers at higher load
597 $load = current_load();
599 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
601 $maxworkers = $queues;
603 // Some magical mathemathics to reduce the workers
605 $slope = $maxworkers / pow($maxsysload, $exponent);
606 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
608 if (Config::get('system', 'worker_debug')) {
609 // Create a list of queue entries grouped by their priority
612 // Adding all processes with no workerqueue entry
614 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
615 (SELECT id FROM `workerqueue`
616 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
620 if ($process = dba::fetch($processes)) {
621 $listitem[0] = "0:".$process["running"];
623 dba::close($processes);
625 // Now adding all processes with workerqueue entries
626 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
627 while ($entry = dba::fetch($entries)) {
628 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
629 if ($process = dba::fetch($processes)) {
630 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
632 dba::close($processes);
634 dba::close($entries);
636 $intervals = array(1, 10, 60);
637 $jobs_per_minute = array();
638 foreach ($intervals as $interval) {
639 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
640 if ($job = dba::fetch($jobs)) {
641 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
645 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
648 $entries = self::totalEntries();
650 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
651 $top_priority = self::highestPriority();
652 $high_running = self::processWithPriorityActive($top_priority);
654 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
655 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
656 $queues = $active + 1;
660 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
662 // Are there fewer workers running as possible? Then fork a new one.
663 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
664 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
669 return $active >= $queues;
673 * @brief Returns the number of active worker processes
675 * @return integer Number of active worker processes
677 private static function activeWorkers()
679 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
681 return $workers["processes"];
685 * @brief Check if we should pass some slow processes
687 * When the active processes of the highest priority are using more than 2/3
688 * of all processes, we let pass slower processes.
690 * @param string $highest_priority Returns the currently highest priority
691 * @return bool We let pass a slower process than $highest_priority
693 private static function passingSlow(&$highest_priority)
695 $highest_priority = 0;
700 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
703 // No active processes at all? Fine
704 if (!DBM::is_result($r)) {
707 $priorities = array();
708 while ($line = dba::fetch($r)) {
709 $priorities[] = $line["priority"];
714 if (count($priorities) == 0) {
717 $highest_priority = min($priorities);
719 // The highest process is already the slowest one?
721 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
725 foreach ($priorities as $priority) {
726 if ($priority == $highest_priority) {
730 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
731 $passing_slow = (($high/count($priorities)) > (2/3));
734 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
736 return $passing_slow;
740 * @brief Find and claim the next worker process for us
742 * @param boolean $passing_slow Returns if we had passed low priority processes
743 * @return boolean Have we found something?
745 private static function findWorkerProcesses(&$passing_slow)
749 // Check if we should pass some low priority process
750 $highest_priority = 0;
752 $passing_slow = false;
754 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
755 // We decrease the limit with the number of entries left in the queue
756 $worker_queues = Config::get("system", "worker_queues", 4);
757 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
758 $lower_job_limit = $worker_queues * $queue_length * 2;
759 $jobs = self::totalEntries();
763 $slope = $queue_length / pow($lower_job_limit, $exponent);
764 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
766 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
768 if (self::passingSlow($highest_priority)) {
769 // Are there waiting processes with a higher priority than the currently highest?
770 $result = dba::select(
773 array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority),
774 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true)
777 while ($id = dba::fetch($result)) {
782 $found = (count($ids) > 0);
785 // Give slower processes some processing time
786 $result = dba::select(
789 array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority),
790 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true)
793 while ($id = dba::fetch($result)) {
798 $found = (count($ids) > 0);
799 $passing_slow = $found;
803 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
805 $result = dba::select(
808 array("`executed` <= ? AND NOT `done`", NULL_DATE),
809 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true)
812 while ($id = dba::fetch($result)) {
817 $found = (count($ids) > 0);
821 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
822 array_unshift($ids, $condition);
823 dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
830 * @brief Returns the next worker process
832 * @param boolean $passing_slow Returns if we had passed low priority processes
833 * @return string SQL statement
835 public static function workerProcess(&$passing_slow)
837 $stamp = (float)microtime(true);
839 // There can already be jobs for us in the queue.
840 $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
841 if (DBM::is_result($r)) {
842 self::$db_duration += (microtime(true) - $stamp);
843 return dba::inArray($r);
847 $stamp = (float)microtime(true);
848 if (!Lock::set('poller_worker_process')) {
851 self::$lock_duration = (microtime(true) - $stamp);
853 $stamp = (float)microtime(true);
854 $found = self::findWorkerProcesses($passing_slow);
855 self::$db_duration += (microtime(true) - $stamp);
857 Lock::remove('poller_worker_process');
860 $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
861 return dba::inArray($r);
867 * @brief Removes a workerqueue entry from the current process
870 public static function unclaimProcess()
874 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
878 * @brief Call the front end worker
881 public static function callWorker()
883 if (!Config::get("system", "frontend_worker")) {
887 $url = System::baseUrl()."/worker";
888 fetch_url($url, false, $redirects, 1);
892 * @brief Call the front end worker if there aren't any active
895 public static function executeIfIdle()
897 if (!Config::get("system", "frontend_worker")) {
901 // Do we have "proc_open"? Then we can fork the worker
902 if (function_exists("proc_open")) {
903 // When was the last time that we called the worker?
904 // Less than one minute? Then we quit
905 if ((time() - Config::get("system", "worker_started")) < 60) {
909 Config::set("system", "worker_started", time());
911 // Do we have enough running workers? Then we quit here.
912 if (self::tooMuchWorkers()) {
913 // Cleaning dead processes
914 self::killStaleWorkers();
915 get_app()->remove_inactive_processes();
922 logger('Call worker', LOGGER_DEBUG);
927 // We cannot execute background processes.
928 // We now run the processes from the frontend.
929 // This won't work with long running processes.
932 self::clearProcesses();
934 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
936 if ($workers["processes"] == 0) {
942 * @brief Removes long running worker processes
945 public static function clearProcesses()
947 $timeout = Config::get("system", "frontend_worker_timeout", 10);
949 /// @todo We should clean up the corresponding workerqueue entries as well
950 $condition = array("`created` < ? AND `command` = 'worker.php'",
951 datetime_convert('UTC', 'UTC', "now - ".$timeout." minutes"));
952 dba::delete('process', $condition);
956 * @brief Runs the cron processes
959 private static function runCron()
961 logger('Add cron entries', LOGGER_DEBUG);
963 // Check for spooled items
964 self::add(PRIORITY_HIGH, "SpoolPost");
966 // Run the cron job that calls all other jobs
967 self::add(PRIORITY_MEDIUM, "Cron");
969 // Run the cronhooks job separately from cron for being able to use a different timing
970 self::add(PRIORITY_MEDIUM, "CronHooks");
972 // Cleaning dead processes
973 self::killStaleWorkers();
979 public static function spawnWorker()
981 $args = array("scripts/worker.php", "no_cron");
982 get_app()->proc_run($args);
986 * @brief Adds tasks to the worker queue
988 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
990 * next args are passed as $cmd command line
991 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
992 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
994 * @note $cmd and string args are surrounded with ""
999 * @return boolean "false" if proc_run couldn't be executed
1001 public static function add($cmd)
1003 $proc_args = func_get_args();
1006 if (!count($proc_args)) {
1010 // Preserve the first parameter
1011 // It could contain a command, the priority or an parameter array
1012 // If we use the parameter array we have to protect it from the following function
1013 $run_parameter = array_shift($proc_args);
1015 // expand any arrays
1016 foreach ($proc_args as $arg) {
1017 if (is_array($arg)) {
1018 foreach ($arg as $n) {
1026 // Now we add the run parameters back to the array
1027 array_unshift($args, $run_parameter);
1029 $arr = array('args' => $args, 'run_cmd' => true);
1031 call_hooks("proc_run", $arr);
1032 if (!$arr['run_cmd'] || !count($args)) {
1036 $priority = PRIORITY_MEDIUM;
1037 $dont_fork = Config::get("system", "worker_dont_fork");
1038 $created = datetime_convert();
1040 if (is_int($run_parameter)) {
1041 $priority = $run_parameter;
1042 } elseif (is_array($run_parameter)) {
1043 if (isset($run_parameter['priority'])) {
1044 $priority = $run_parameter['priority'];
1046 if (isset($run_parameter['created'])) {
1047 $created = $run_parameter['created'];
1049 if (isset($run_parameter['dont_fork'])) {
1050 $dont_fork = $run_parameter['dont_fork'];
1057 $parameters = json_encode($argv);
1058 $found = dba::exists('workerqueue', array('parameter' => $parameters, 'done' => false));
1060 // Quit if there was a database error - a precaution for the update process to 3.5.3
1061 if (dba::errorNo() != 0) {
1066 dba::insert('workerqueue', array('parameter' => $parameters, 'created' => $created, 'priority' => $priority));
1069 // Should we quit and wait for the worker to be called as a cronjob?
1074 // If there is a lock then we don't have to check for too much worker
1075 if (!Lock::set('poller_worker', 0)) {
1079 // If there are already enough workers running, don't fork another one
1080 $quit = self::tooMuchWorkers();
1081 Lock::remove('poller_worker');
1087 // Now call the worker to execute the jobs that we just added to the queue
1088 self::spawnWorker();