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;
16 require_once 'include/dba.php';
19 * @file src/Core/Worker.php
21 * @brief Contains the class for the worker background job processing
25 * @brief Worker methods
29 private static $up_start;
30 private static $db_duration;
31 private static $last_update;
32 private static $lock_duration;
35 * @brief Processes the tasks that are in the workerqueue table
37 * @param boolean $run_cron Should the cron processes be executed?
40 public static function processQueue($run_cron = true)
44 self::$up_start = microtime(true);
46 // At first check the maximum load. We shouldn't continue with a high load
47 if ($a->maxload_reached()) {
48 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
52 // We now start the process. This is done after the load check since this could increase the load.
55 // Kill stale processes every 5 minutes
56 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
57 if (time() > ($last_cleanup + 300)) {
58 Config::set('system', 'poller_last_cleaned', time());
59 self::killStaleWorkers();
62 // Count active workers and compare them with a maximum value that depends on the load
63 if (self::tooMuchWorkers()) {
64 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
68 // Do we have too few memory?
69 if ($a->min_memory_reached()) {
70 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
74 // Possibly there are too much database connections
75 if (self::maxConnectionsReached()) {
76 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
80 // Possibly there are too much database processes that block the system
81 if ($a->max_processes_reached()) {
82 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
86 // Now we start additional cron processes if we should do so
93 // We fetch the next queue entry that is about to be executed
94 while ($r = self::workerProcess($passing_slow)) {
95 // When we are processing jobs with a lower priority, we don't refetch new jobs
96 // Otherwise fast jobs could wait behind slow ones and could be blocked.
97 $refetched = $passing_slow;
99 foreach ($r as $entry) {
100 // Assure that the priority is an integer value
101 $entry['priority'] = (int)$entry['priority'];
103 // The work will be done
104 if (!self::execute($entry)) {
105 logger('Process execution failed, quitting.', LOGGER_DEBUG);
109 // If possible we will fetch new jobs for this worker
110 if (!$refetched && Lock::set('poller_worker_process', 0)) {
111 $stamp = (float)microtime(true);
112 $refetched = self::findWorkerProcesses($passing_slow);
113 self::$db_duration += (microtime(true) - $stamp);
114 Lock::remove('poller_worker_process');
118 // To avoid the quitting of multiple workers only one worker at a time will execute the check
119 if (Lock::set('poller_worker', 0)) {
120 $stamp = (float)microtime(true);
121 // Count active workers and compare them with a maximum value that depends on the load
122 if (self::tooMuchWorkers()) {
123 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
128 if ($a->min_memory_reached()) {
129 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
132 Lock::remove('poller_worker');
133 self::$db_duration += (microtime(true) - $stamp);
136 // Quit the worker once every 5 minutes
137 if (time() > ($starttime + 300)) {
138 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
142 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
146 * @brief Returns the number of non executed entries in the worker queue
148 * @return integer Number of non executed entries in the worker queue
150 private static function totalEntries()
152 $s = dba::fetch_first("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done`", NULL_DATE);
153 if (DBM::is_result($s)) {
161 * @brief Returns the highest priority in the worker queue that isn't executed
163 * @return integer Number of active worker processes
165 private static function highestPriority()
167 $condition = array("`executed` <= ? AND NOT `done`", NULL_DATE);
168 $s = dba::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
169 if (DBM::is_result($s)) {
170 return $s["priority"];
177 * @brief Returns if a process with the given priority is running
179 * @param integer $priority The priority that should be checked
181 * @return integer Is there a process running with that priority?
183 private static function processWithPriorityActive($priority)
185 $condition = array("`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE);
186 return dba::exists('workerqueue', $condition);
190 * @brief Execute a worker entry
192 * @param array $queue Workerqueue entry
194 * @return boolean "true" if further processing should be stopped
196 public static function execute($queue)
202 // Quit when in maintenance
203 if (Config::get('system', 'maintenance', true)) {
204 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
208 // Constantly check the number of parallel database processes
209 if ($a->max_processes_reached()) {
210 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
214 // Constantly check the number of available database connections to let the frontend be accessible at any time
215 if (self::maxConnectionsReached()) {
216 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
220 $argv = json_decode($queue["parameter"]);
222 // Check for existance and validity of the include file
225 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
226 // We constantly update the "executed" date every minute to avoid being killed too soon
227 if (!isset(self::$last_update)) {
228 self::$last_update = strtotime($queue["executed"]);
231 $age = (time() - self::$last_update) / 60;
232 self::$last_update = time();
235 $stamp = (float)microtime(true);
236 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
237 self::$db_duration += (microtime(true) - $stamp);
242 self::execFunction($queue, $include, $argv, true);
244 $stamp = (float)microtime(true);
245 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
246 Config::set('system', 'last_poller_execution', datetime_convert());
248 self::$db_duration = (microtime(true) - $stamp);
253 // The script could be provided as full path or only with the function name
254 if ($include == basename($include)) {
255 $include = "include/".$include.".php";
258 if (!validate_include($include)) {
259 logger("Include file ".$argv[0]." is not valid!");
260 dba::delete('workerqueue', array('id' => $queue["id"]));
264 require_once $include;
266 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
268 if (function_exists($funcname)) {
269 // We constantly update the "executed" date every minute to avoid being killed too soon
270 if (!isset(self::$last_update)) {
271 self::$last_update = strtotime($queue["executed"]);
274 $age = (time() - self::$last_update) / 60;
275 self::$last_update = time();
278 $stamp = (float)microtime(true);
279 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
280 self::$db_duration += (microtime(true) - $stamp);
283 self::execFunction($queue, $funcname, $argv, false);
285 $stamp = (float)microtime(true);
286 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
287 Config::set('system', 'last_poller_execution', datetime_convert());
289 self::$db_duration = (microtime(true) - $stamp);
291 logger("Function ".$funcname." does not exist");
292 dba::delete('workerqueue', array('id' => $queue["id"]));
299 * @brief Execute a function from the queue
301 * @param array $queue Workerqueue entry
302 * @param string $funcname name of the function
303 * @param array $argv Array of values to be passed to the function
304 * @param boolean $method_call boolean
307 private static function execFunction($queue, $funcname, $argv, $method_call)
313 $argc = count($argv);
315 $new_process_id = uniqid("wrk", true);
317 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
319 $stamp = (float)microtime(true);
321 // We use the callstack here to analyze the performance of executed worker entries.
322 // For this reason the variables have to be initialized.
323 if (Config::get("system", "profiler")) {
324 $a->performance["start"] = microtime(true);
325 $a->performance["database"] = 0;
326 $a->performance["database_write"] = 0;
327 $a->performance["network"] = 0;
328 $a->performance["file"] = 0;
329 $a->performance["rendering"] = 0;
330 $a->performance["parser"] = 0;
331 $a->performance["marktime"] = 0;
332 $a->performance["markstart"] = microtime(true);
333 $a->callstack = array();
336 // For better logging create a new process id for every worker call
337 // But preserve the old one for the worker
338 $old_process_id = $a->process_id;
339 $a->process_id = $new_process_id;
342 $up_duration = number_format(microtime(true) - self::$up_start, 3);
344 // Reset global data to avoid interferences
348 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
350 $funcname($argv, $argc);
353 $a->process_id = $old_process_id;
356 $duration = number_format(microtime(true) - $stamp, 3);
358 self::$up_start = microtime(true);
360 /* With these values we can analyze how effective the worker is.
361 * The database and rest time should be low since this is the unproductive time.
362 * The execution time is the productive time.
363 * By changing parameters like the maximum number of workers we can check the effectivness.
366 'DB: '.number_format(self::$db_duration, 2).
367 ' - Lock: '.number_format(self::$lock_duration, 2).
368 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
369 ' - Execution: '.number_format($duration, 2),
373 self::$lock_duration = 0;
375 if ($duration > 3600) {
376 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
377 } elseif ($duration > 600) {
378 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
379 } elseif ($duration > 300) {
380 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
381 } elseif ($duration > 120) {
382 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
385 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
387 // Write down the performance values into the log
388 if (Config::get("system", "profiler")) {
389 $duration = microtime(true)-$a->performance["start"];
391 if (Config::get("rendertime", "callstack")) {
392 if (isset($a->callstack["database"])) {
393 $o = "\nDatabase Read:\n";
394 foreach ($a->callstack["database"] as $func => $time) {
395 $time = round($time, 3);
397 $o .= $func.": ".$time."\n";
401 if (isset($a->callstack["database_write"])) {
402 $o .= "\nDatabase Write:\n";
403 foreach ($a->callstack["database_write"] as $func => $time) {
404 $time = round($time, 3);
406 $o .= $func.": ".$time."\n";
410 if (isset($a->callstack["network"])) {
411 $o .= "\nNetwork:\n";
412 foreach ($a->callstack["network"] as $func => $time) {
413 $time = round($time, 3);
415 $o .= $func.": ".$time."\n";
424 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
425 "DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
426 number_format($a->performance["database"] - $a->performance["database_write"], 2),
427 number_format($a->performance["database_write"], 2),
428 number_format($a->performance["network"], 2),
429 number_format($a->performance["file"], 2),
430 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
431 number_format($duration, 2)
437 $cooldown = Config::get("system", "worker_cooldown", 0);
440 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
446 * @brief Checks if the number of database connections has reached a critical limit.
448 * @return bool Are more than 3/4 of the maximum connections used?
450 private static function maxConnectionsReached()
452 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
453 $max = Config::get("system", "max_connections");
455 // Fetch the percentage level where the worker will get active
456 $maxlevel = Config::get("system", "max_connections_level", 75);
459 // the maximum number of possible user connections can be a system variable
460 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
461 if (DBM::is_result($r)) {
464 // Or it can be granted. This overrides the system variable
465 $r = dba::p('SHOW GRANTS');
466 while ($grants = dba::fetch($r)) {
467 $grant = array_pop($grants);
468 if (stristr($grant, "GRANT USAGE ON")) {
469 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
477 // If $max is set we will use the processlist to determine the current number of connections
478 // The processlist only shows entries of the current user
480 $r = dba::p('SHOW PROCESSLIST');
481 $used = dba::num_rows($r);
484 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
486 $level = ($used / $max) * 100;
488 if ($level >= $maxlevel) {
489 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
494 // We will now check for the system values.
495 // This limit could be reached although the user limits are fine.
496 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
497 if (!DBM::is_result($r)) {
500 $max = intval($r["Value"]);
504 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
505 if (!DBM::is_result($r)) {
508 $used = intval($r["Value"]);
512 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
514 $level = $used / $max * 100;
516 if ($level < $maxlevel) {
519 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
524 * @brief fix the queue entry if the worker process died
527 private static function killStaleWorkers()
529 $entries = dba::select(
531 array('id', 'pid', 'executed', 'priority', 'parameter'),
532 array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
533 array('order' => array('priority', 'created'))
536 while ($entry = dba::fetch($entries)) {
537 if (!posix_kill($entry["pid"], 0)) {
540 array('executed' => NULL_DATE, 'pid' => 0),
541 array('id' => $entry["id"])
544 // Kill long running processes
545 // Check if the priority is in a valid range
546 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
547 $entry["priority"] = PRIORITY_MEDIUM;
550 // Define the maximum durations
551 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
552 $max_duration = $max_duration_defaults[$entry["priority"]];
554 $argv = json_decode($entry["parameter"]);
555 $argv[0] = basename($argv[0]);
557 // How long is the process already running?
558 $duration = (time() - strtotime($entry["executed"])) / 60;
559 if ($duration > $max_duration) {
560 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
561 posix_kill($entry["pid"], SIGTERM);
563 // We killed the stale process.
564 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
565 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
566 if ($entry["priority"] == PRIORITY_HIGH) {
567 $new_priority = PRIORITY_MEDIUM;
568 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
569 $new_priority = PRIORITY_LOW;
570 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
571 $new_priority = PRIORITY_NEGLIGIBLE;
575 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
576 array('id' => $entry["id"])
579 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
586 * @brief Checks if the number of active workers exceeds the given limits
588 * @return bool Are there too much workers running?
590 public static function tooMuchWorkers()
592 $queues = Config::get("system", "worker_queues", 4);
594 $maxqueues = $queues;
596 $active = self::activeWorkers();
598 // Decrease the number of workers at higher load
599 $load = current_load();
601 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
603 $maxworkers = $queues;
605 // Some magical mathemathics to reduce the workers
607 $slope = $maxworkers / pow($maxsysload, $exponent);
608 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
611 if (Config::get('system', 'worker_debug')) {
612 // Create a list of queue entries grouped by their priority
615 // Adding all processes with no workerqueue entry
617 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
618 (SELECT id FROM `workerqueue`
619 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
623 if ($process = dba::fetch($processes)) {
624 $listitem[0] = "0:".$process["running"];
626 dba::close($processes);
628 // Now adding all processes with workerqueue entries
629 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
630 while ($entry = dba::fetch($entries)) {
631 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
632 if ($process = dba::fetch($processes)) {
633 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
635 dba::close($processes);
637 dba::close($entries);
639 $intervals = array(1, 10, 60);
640 $jobs_per_minute = array();
641 foreach ($intervals as $interval) {
642 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
643 if ($job = dba::fetch($jobs)) {
644 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
648 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
651 $entries = self::totalEntries();
653 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
654 $top_priority = self::highestPriority();
655 $high_running = self::processWithPriorityActive($top_priority);
657 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
658 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
659 $queues = $active + 1;
663 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
665 // Are there fewer workers running as possible? Then fork a new one.
666 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
667 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
672 return $active >= $queues;
676 * @brief Returns the number of active worker processes
678 * @return integer Number of active worker processes
680 private static function activeWorkers()
682 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
684 return $workers["processes"];
688 * @brief Check if we should pass some slow processes
690 * When the active processes of the highest priority are using more than 2/3
691 * of all processes, we let pass slower processes.
693 * @param string $highest_priority Returns the currently highest priority
694 * @return bool We let pass a slower process than $highest_priority
696 private static function passingSlow(&$highest_priority)
698 $highest_priority = 0;
703 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
706 // No active processes at all? Fine
707 if (!DBM::is_result($r)) {
710 $priorities = array();
711 while ($line = dba::fetch($r)) {
712 $priorities[] = $line["priority"];
717 if (count($priorities) == 0) {
720 $highest_priority = min($priorities);
722 // The highest process is already the slowest one?
724 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
728 foreach ($priorities as $priority) {
729 if ($priority == $highest_priority) {
733 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
734 $passing_slow = (($high/count($priorities)) > (2/3));
737 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
739 return $passing_slow;
743 * @brief Find and claim the next worker process for us
745 * @param boolean $passing_slow Returns if we had passed low priority processes
746 * @return boolean Have we found something?
748 private static function findWorkerProcesses(&$passing_slow)
752 // Check if we should pass some low priority process
753 $highest_priority = 0;
755 $passing_slow = false;
757 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
758 // We decrease the limit with the number of entries left in the queue
759 $worker_queues = Config::get("system", "worker_queues", 4);
760 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
761 $lower_job_limit = $worker_queues * $queue_length * 2;
762 $jobs = self::totalEntries();
766 $slope = $queue_length / pow($lower_job_limit, $exponent);
767 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
769 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
771 if (self::passingSlow($highest_priority)) {
772 // Are there waiting processes with a higher priority than the currently highest?
773 $result = dba::select(
776 ["`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority],
777 ['limit' => $limit, 'order' => ['priority', 'created']]
780 while ($id = dba::fetch($result)) {
785 $found = (count($ids) > 0);
788 // Give slower processes some processing time
789 $result = dba::select(
792 ["`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority],
793 ['limit' => $limit, 'order' => ['priority', 'created']]
796 while ($id = dba::fetch($result)) {
801 $found = (count($ids) > 0);
802 $passing_slow = $found;
806 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
808 $result = dba::select(
811 ["`executed` <= ? AND NOT `done`", NULL_DATE],
812 ['limit' => $limit, 'order' => ['priority', 'created']]
815 while ($id = dba::fetch($result)) {
820 $found = (count($ids) > 0);
824 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
825 array_unshift($ids, $condition);
826 dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
833 * @brief Returns the next worker process
835 * @param boolean $passing_slow Returns if we had passed low priority processes
836 * @return string SQL statement
838 public static function workerProcess(&$passing_slow)
840 $stamp = (float)microtime(true);
842 // There can already be jobs for us in the queue.
843 $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
844 if (DBM::is_result($r)) {
845 self::$db_duration += (microtime(true) - $stamp);
846 return dba::inArray($r);
850 $stamp = (float)microtime(true);
851 if (!Lock::set('poller_worker_process')) {
854 self::$lock_duration = (microtime(true) - $stamp);
856 $stamp = (float)microtime(true);
857 $found = self::findWorkerProcesses($passing_slow);
858 self::$db_duration += (microtime(true) - $stamp);
860 Lock::remove('poller_worker_process');
863 $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
864 return dba::inArray($r);
870 * @brief Removes a workerqueue entry from the current process
873 public static function unclaimProcess()
877 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
881 * @brief Call the front end worker
884 public static function callWorker()
886 if (!Config::get("system", "frontend_worker")) {
890 $url = System::baseUrl()."/worker";
891 fetch_url($url, false, $redirects, 1);
895 * @brief Call the front end worker if there aren't any active
898 public static function executeIfIdle()
900 if (!Config::get("system", "frontend_worker")) {
904 // Do we have "proc_open"? Then we can fork the worker
905 if (function_exists("proc_open")) {
906 // When was the last time that we called the worker?
907 // Less than one minute? Then we quit
908 if ((time() - Config::get("system", "worker_started")) < 60) {
912 Config::set("system", "worker_started", time());
914 // Do we have enough running workers? Then we quit here.
915 if (self::tooMuchWorkers()) {
916 // Cleaning dead processes
917 self::killStaleWorkers();
918 get_app()->remove_inactive_processes();
925 logger('Call worker', LOGGER_DEBUG);
930 // We cannot execute background processes.
931 // We now run the processes from the frontend.
932 // This won't work with long running processes.
935 self::clearProcesses();
937 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
939 if ($workers["processes"] == 0) {
945 * @brief Removes long running worker processes
948 public static function clearProcesses()
950 $timeout = Config::get("system", "frontend_worker_timeout", 10);
952 /// @todo We should clean up the corresponding workerqueue entries as well
953 $condition = array("`created` < ? AND `command` = 'worker.php'",
954 datetime_convert('UTC', 'UTC', "now - ".$timeout." minutes"));
955 dba::delete('process', $condition);
959 * @brief Runs the cron processes
962 private static function runCron()
964 logger('Add cron entries', LOGGER_DEBUG);
966 // Check for spooled items
967 self::add(PRIORITY_HIGH, "SpoolPost");
969 // Run the cron job that calls all other jobs
970 self::add(PRIORITY_MEDIUM, "Cron");
972 // Run the cronhooks job separately from cron for being able to use a different timing
973 self::add(PRIORITY_MEDIUM, "CronHooks");
975 // Cleaning dead processes
976 self::killStaleWorkers();
982 public static function spawnWorker()
984 $args = array("scripts/worker.php", "no_cron");
985 get_app()->proc_run($args);
989 * @brief Adds tasks to the worker queue
991 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
993 * next args are passed as $cmd command line
994 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
995 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
997 * @note $cmd and string args are surrounded with ""
1002 * @return boolean "false" if proc_run couldn't be executed
1004 public static function add($cmd)
1006 $proc_args = func_get_args();
1009 if (!count($proc_args)) {
1013 // Preserve the first parameter
1014 // It could contain a command, the priority or an parameter array
1015 // If we use the parameter array we have to protect it from the following function
1016 $run_parameter = array_shift($proc_args);
1018 // expand any arrays
1019 foreach ($proc_args as $arg) {
1020 if (is_array($arg)) {
1021 foreach ($arg as $n) {
1029 // Now we add the run parameters back to the array
1030 array_unshift($args, $run_parameter);
1032 $arr = array('args' => $args, 'run_cmd' => true);
1034 call_hooks("proc_run", $arr);
1035 if (!$arr['run_cmd'] || !count($args)) {
1039 $priority = PRIORITY_MEDIUM;
1040 $dont_fork = Config::get("system", "worker_dont_fork");
1041 $created = datetime_convert();
1043 if (is_int($run_parameter)) {
1044 $priority = $run_parameter;
1045 } elseif (is_array($run_parameter)) {
1046 if (isset($run_parameter['priority'])) {
1047 $priority = $run_parameter['priority'];
1049 if (isset($run_parameter['created'])) {
1050 $created = $run_parameter['created'];
1052 if (isset($run_parameter['dont_fork'])) {
1053 $dont_fork = $run_parameter['dont_fork'];
1060 $parameters = json_encode($argv);
1061 $found = dba::exists('workerqueue', array('parameter' => $parameters, 'done' => false));
1063 // Quit if there was a database error - a precaution for the update process to 3.5.3
1064 if (dba::errorNo() != 0) {
1069 dba::insert('workerqueue', array('parameter' => $parameters, 'created' => $created, 'priority' => $priority));
1072 // Should we quit and wait for the worker to be called as a cronjob?
1077 // If there is a lock then we don't have to check for too much worker
1078 if (!Lock::set('poller_worker', 0)) {
1082 // If there are already enough workers running, don't fork another one
1083 $quit = self::tooMuchWorkers();
1084 Lock::remove('poller_worker');
1090 // Now call the worker to execute the jobs that we just added to the queue
1091 self::spawnWorker();