2 namespace Friendica\Core;
5 use Friendica\Core\System;
6 use Friendica\Core\Config;
7 use Friendica\Core\Worker;
8 use Friendica\Util\Lock;
14 * @file src/Core/Worker.php
16 * @brief Contains the class for the worker background job processing
20 * @brief Worker methods
23 private static $up_start;
24 private static $db_duration;
25 private static $last_update;
26 private static $lock_duration;
29 * @brief Processes the tasks that are in the workerqueue table
31 * @param boolean $run_cron Should the cron processes be executed?
33 public static function processQueue($run_cron = true) {
36 self::$up_start = microtime(true);
38 // At first check the maximum load. We shouldn't continue with a high load
39 if ($a->maxload_reached()) {
40 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
44 // We now start the process. This is done after the load check since this could increase the load.
47 // Kill stale processes every 5 minutes
48 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
49 if (time() > ($last_cleanup + 300)) {
50 Config::set('system', 'poller_last_cleaned', time());
51 self::killStaleWorkers();
54 // Count active workers and compare them with a maximum value that depends on the load
55 if (self::tooMuchWorkers()) {
56 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
60 // Do we have too few memory?
61 if ($a->min_memory_reached()) {
62 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
66 // Possibly there are too much database connections
67 if (self::maxConnectionsReached()) {
68 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
72 // Possibly there are too much database processes that block the system
73 if ($a->max_processes_reached()) {
74 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
78 // Now we start additional cron processes if we should do so
85 // We fetch the next queue entry that is about to be executed
86 while ($r = self::workerProcess($passing_slow)) {
88 // When we are processing jobs with a lower priority, we don't refetch new jobs
89 // Otherwise fast jobs could wait behind slow ones and could be blocked.
90 $refetched = $passing_slow;
92 foreach ($r AS $entry) {
93 // Assure that the priority is an integer value
94 $entry['priority'] = (int)$entry['priority'];
96 // The work will be done
97 if (!self::execute($entry)) {
98 logger('Process execution failed, quitting.', LOGGER_DEBUG);
102 // If possible we will fetch new jobs for this worker
103 if (!$refetched && Lock::set('poller_worker_process', 0)) {
104 $stamp = (float)microtime(true);
105 $refetched = self::findWorkerProcesses($passing_slow);
106 self::$db_duration += (microtime(true) - $stamp);
107 Lock::remove('poller_worker_process');
111 // To avoid the quitting of multiple pollers only one poller at a time will execute the check
112 if (Lock::set('poller_worker', 0)) {
113 $stamp = (float)microtime(true);
114 // Count active workers and compare them with a maximum value that depends on the load
115 if (self::tooMuchWorkers()) {
116 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
121 if ($a->min_memory_reached()) {
122 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
125 Lock::remove('poller_worker');
126 self::$db_duration += (microtime(true) - $stamp);
129 // Quit the poller once every 5 minutes
130 if (time() > ($starttime + 300)) {
131 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
135 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
139 * @brief Returns the number of non executed entries in the worker queue
141 * @return integer Number of non executed entries in the worker queue
143 private static function totalEntries() {
144 $s = dba::fetch_first("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done`", NULL_DATE);
145 if (dbm::is_result($s)) {
153 * @brief Returns the highest priority in the worker queue that isn't executed
155 * @return integer Number of active poller processes
157 private static function highestPriority() {
158 $condition = array("`executed` <= ? AND NOT `done`", NULL_DATE);
159 $s = dba::select('workerqueue', array('priority'), $condition, array('limit' => 1, 'order' => array('priority')));
160 if (dbm::is_result($s)) {
161 return $s["priority"];
168 * @brief Returns if a process with the given priority is running
170 * @param integer $priority The priority that should be checked
172 * @return integer Is there a process running with that priority?
174 private static function processWithPriorityActive($priority) {
175 $condition = array("`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE);
176 return dba::exists('workerqueue', $condition);
180 * @brief Execute a worker entry
182 * @param array $queue Workerqueue entry
184 * @return boolean "true" if further processing should be stopped
186 public static function execute($queue) {
191 // Quit when in maintenance
192 if (Config::get('system', 'maintenance', true)) {
193 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
197 // Constantly check the number of parallel database processes
198 if ($a->max_processes_reached()) {
199 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
203 // Constantly check the number of available database connections to let the frontend be accessible at any time
204 if (self::maxConnectionsReached()) {
205 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
209 $argv = json_decode($queue["parameter"]);
211 // Check for existance and validity of the include file
214 // The script could be provided as full path or only with the function name
215 if ($include == basename($include)) {
216 $include = "include/".$include.".php";
219 if (!validate_include($include)) {
220 logger("Include file ".$argv[0]." is not valid!");
221 dba::delete('workerqueue', array('id' => $queue["id"]));
225 require_once($include);
227 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
229 if (function_exists($funcname)) {
231 // We constantly update the "executed" date every minute to avoid being killed too soon
232 if (!isset(self::$last_update)) {
233 self::$last_update = strtotime($queue["executed"]);
236 $age = (time() - self::$last_update) / 60;
237 self::$last_update = time();
240 $stamp = (float)microtime(true);
241 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
242 self::$db_duration += (microtime(true) - $stamp);
245 self::execFunction($queue, $funcname, $argv);
247 $stamp = (float)microtime(true);
248 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
249 Config::set('system', 'last_poller_execution', datetime_convert());
251 self::$db_duration = (microtime(true) - $stamp);
253 logger("Function ".$funcname." does not exist");
254 dba::delete('workerqueue', array('id' => $queue["id"]));
261 * @brief Execute a function from the queue
263 * @param array $queue Workerqueue entry
264 * @param string $funcname name of the function
265 * @param array $argv Array of values to be passed to the function
267 private static function execFunction($queue, $funcname, $argv) {
272 $argc = count($argv);
274 $new_process_id = uniqid("wrk", true);
276 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
278 $stamp = (float)microtime(true);
280 // We use the callstack here to analyze the performance of executed worker entries.
281 // For this reason the variables have to be initialized.
282 if (Config::get("system", "profiler")) {
283 $a->performance["start"] = microtime(true);
284 $a->performance["database"] = 0;
285 $a->performance["database_write"] = 0;
286 $a->performance["network"] = 0;
287 $a->performance["file"] = 0;
288 $a->performance["rendering"] = 0;
289 $a->performance["parser"] = 0;
290 $a->performance["marktime"] = 0;
291 $a->performance["markstart"] = microtime(true);
292 $a->callstack = array();
295 // For better logging create a new process id for every worker call
296 // But preserve the old one for the worker
297 $old_process_id = $a->process_id;
298 $a->process_id = $new_process_id;
301 $up_duration = number_format(microtime(true) - self::$up_start, 3);
303 // Reset global data to avoid interferences
306 $funcname($argv, $argc);
308 $a->process_id = $old_process_id;
311 $duration = number_format(microtime(true) - $stamp, 3);
313 self::$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(self::$db_duration, 2).
321 ' - Lock: '.number_format(self::$lock_duration, 2).
322 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
323 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
324 self::$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 private static function maxConnectionsReached() {
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 = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
408 if (dbm::is_result($r)) {
411 // Or it can be granted. This overrides the system variable
412 $r = dba::p('SHOW GRANTS');
413 while ($grants = dba::fetch($r)) {
414 $grant = array_pop($grants);
415 if (stristr($grant, "GRANT USAGE ON")) {
416 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
424 // If $max is set we will use the processlist to determine the current number of connections
425 // The processlist only shows entries of the current user
427 $r = dba::p('SHOW PROCESSLIST');
428 $used = dba::num_rows($r);
431 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
433 $level = ($used / $max) * 100;
435 if ($level >= $maxlevel) {
436 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
441 // We will now check for the system values.
442 // This limit could be reached although the user limits are fine.
443 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
444 if (!dbm::is_result($r)) {
447 $max = intval($r["Value"]);
451 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
452 if (!dbm::is_result($r)) {
455 $used = intval($r["Value"]);
459 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
461 $level = $used / $max * 100;
463 if ($level < $maxlevel) {
466 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
471 * @brief fix the queue entry if the worker process died
474 private static function killStaleWorkers() {
475 $entries = dba::select('workerqueue', array('id', 'pid', 'executed', 'priority', 'parameter'),
476 array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
477 array('order' => array('priority', 'created')));
478 while ($entry = dba::fetch($entries)) {
479 if (!posix_kill($entry["pid"], 0)) {
480 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
481 array('id' => $entry["id"]));
483 // Kill long running processes
484 // Check if the priority is in a valid range
485 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
486 $entry["priority"] = PRIORITY_MEDIUM;
489 // Define the maximum durations
490 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
491 $max_duration = $max_duration_defaults[$entry["priority"]];
493 $argv = json_decode($entry["parameter"]);
494 $argv[0] = basename($argv[0]);
496 // How long is the process already running?
497 $duration = (time() - strtotime($entry["executed"])) / 60;
498 if ($duration > $max_duration) {
499 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
500 posix_kill($entry["pid"], SIGTERM);
502 // We killed the stale process.
503 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
504 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
505 if ($entry["priority"] == PRIORITY_HIGH) {
506 $new_priority = PRIORITY_MEDIUM;
507 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
508 $new_priority = PRIORITY_LOW;
509 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
510 $new_priority = PRIORITY_NEGLIGIBLE;
512 dba::update('workerqueue',
513 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
514 array('id' => $entry["id"]));
516 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
523 * @brief Checks if the number of active workers exceeds the given limits
525 * @return bool Are there too much workers running?
527 public static function tooMuchWorkers() {
528 $queues = Config::get("system", "worker_queues", 4);
530 $maxqueues = $queues;
532 $active = self::activeWorkers();
534 // Decrease the number of workers at higher load
535 $load = current_load();
537 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
539 $maxworkers = $queues;
541 // Some magical mathemathics to reduce the workers
543 $slope = $maxworkers / pow($maxsysload, $exponent);
544 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
546 if (Config::get('system', 'worker_debug')) {
547 // Create a list of queue entries grouped by their priority
550 // Adding all processes with no workerqueue entry
551 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
552 (SELECT id FROM `workerqueue`
553 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
554 if ($process = dba::fetch($processes)) {
555 $listitem[0] = "0:".$process["running"];
557 dba::close($processes);
559 // Now adding all processes with workerqueue entries
560 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
561 while ($entry = dba::fetch($entries)) {
562 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
563 if ($process = dba::fetch($processes)) {
564 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
566 dba::close($processes);
568 dba::close($entries);
570 $intervals = array(1, 10, 60);
571 $jobs_per_minute = array();
572 foreach ($intervals AS $interval) {
573 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
574 if ($job = dba::fetch($jobs)) {
575 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
579 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
582 $entries = self::totalEntries();
584 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
585 $top_priority = self::highestPriority();
586 $high_running = self::processWithPriorityActive($top_priority);
588 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
589 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
590 $queues = $active + 1;
594 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
596 // Are there fewer workers running as possible? Then fork a new one.
597 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
598 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
603 return $active >= $queues;
607 * @brief Returns the number of active poller processes
609 * @return integer Number of active poller processes
611 private static function activeWorkers() {
612 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
614 return $workers["processes"];
618 * @brief Check if we should pass some slow processes
620 * When the active processes of the highest priority are using more than 2/3
621 * of all processes, we let pass slower processes.
623 * @param string $highest_priority Returns the currently highest priority
624 * @return bool We let pass a slower process than $highest_priority
626 private static function passingSlow(&$highest_priority) {
627 $highest_priority = 0;
629 $r = dba::p("SELECT `priority`
631 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
633 // No active processes at all? Fine
634 if (!dbm::is_result($r)) {
637 $priorities = array();
638 while ($line = dba::fetch($r)) {
639 $priorities[] = $line["priority"];
644 if (count($priorities) == 0) {
647 $highest_priority = min($priorities);
649 // The highest process is already the slowest one?
651 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
655 foreach ($priorities AS $priority) {
656 if ($priority == $highest_priority) {
660 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
661 $passing_slow = (($high/count($priorities)) > (2/3));
664 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
666 return $passing_slow;
670 * @brief Find and claim the next worker process for us
672 * @param boolean $passing_slow Returns if we had passed low priority processes
673 * @return boolean Have we found something?
675 private static function findWorkerProcesses(&$passing_slow) {
678 // Check if we should pass some low priority process
679 $highest_priority = 0;
681 $passing_slow = false;
683 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
684 // We decrease the limit with the number of entries left in the queue
685 $worker_queues = Config::get("system", "worker_queues", 4);
686 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
687 $lower_job_limit = $worker_queues * $queue_length * 2;
688 $jobs = self::totalEntries();
692 $slope = $queue_length / pow($lower_job_limit, $exponent);
693 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
695 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
697 if (self::passingSlow($highest_priority)) {
698 // Are there waiting processes with a higher priority than the currently highest?
699 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority),
700 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
702 while ($id = dba::fetch($result)) {
707 $found = (count($ids) > 0);
710 // Give slower processes some processing time
711 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority),
712 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
714 while ($id = dba::fetch($result)) {
719 $found = (count($ids) > 0);
720 $passing_slow = $found;
724 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
726 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND NOT `done`", NULL_DATE),
727 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
729 while ($id = dba::fetch($result)) {
734 $found = (count($ids) > 0);
738 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
739 array_unshift($ids, $condition);
740 dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
747 * @brief Returns the next worker process
749 * @param boolean $passing_slow Returns if we had passed low priority processes
750 * @return string SQL statement
752 public static function workerProcess(&$passing_slow) {
753 $stamp = (float)microtime(true);
755 // There can already be jobs for us in the queue.
756 $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
757 if (dbm::is_result($r)) {
758 self::$db_duration += (microtime(true) - $stamp);
759 return dba::inArray($r);
763 $stamp = (float)microtime(true);
764 if (!Lock::set('poller_worker_process')) {
767 self::$lock_duration = (microtime(true) - $stamp);
769 $stamp = (float)microtime(true);
770 $found = self::findWorkerProcesses($passing_slow);
771 self::$db_duration += (microtime(true) - $stamp);
773 Lock::remove('poller_worker_process');
776 $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
777 return dba::inArray($r);
783 * @brief Removes a workerqueue entry from the current process
785 public static function unclaimProcess() {
788 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
792 * @brief Call the front end worker
794 public static function callWorker() {
795 if (!Config::get("system", "frontend_worker")) {
799 $url = System::baseUrl()."/worker";
800 fetch_url($url, false, $redirects, 1);
804 * @brief Call the front end worker if there aren't any active
806 public static function executeIfIdle() {
807 if (!Config::get("system", "frontend_worker")) {
811 // Do we have "proc_open"? Then we can fork the poller
812 if (function_exists("proc_open")) {
813 // When was the last time that we called the worker?
814 // Less than one minute? Then we quit
815 if ((time() - Config::get("system", "worker_started")) < 60) {
819 Config::set("system", "worker_started", time());
821 // Do we have enough running workers? Then we quit here.
822 if (self::tooMuchWorkers()) {
823 // Cleaning dead processes
824 self::killStaleWorkers();
825 get_app()->remove_inactive_processes();
832 logger('Call poller', LOGGER_DEBUG);
837 // We cannot execute background processes.
838 // We now run the processes from the frontend.
839 // This won't work with long running processes.
842 self::clearProcesses();
844 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
846 if ($workers["processes"] == 0) {
852 * @brief Removes long running worker processes
854 public static function clearProcesses() {
855 $timeout = Config::get("system", "frontend_worker_timeout", 10);
857 /// @todo We should clean up the corresponding workerqueue entries as well
858 $condition = array("`created` < ? AND `command` = 'worker.php'",
859 datetime_convert('UTC','UTC',"now - ".$timeout." minutes"));
860 dba::delete('process', $condition);
864 * @brief Runs the cron processes
866 private static function runCron() {
867 logger('Add cron entries', LOGGER_DEBUG);
869 // Check for spooled items
870 self::add(PRIORITY_HIGH, "spool_post");
872 // Run the cron job that calls all other jobs
873 self::add(PRIORITY_MEDIUM, "cron");
875 // Run the cronhooks job separately from cron for being able to use a different timing
876 self::add(PRIORITY_MEDIUM, "cronhooks");
878 // Cleaning dead processes
879 self::killStaleWorkers();
882 public static function spawnWorker() {
883 $args = array("include/poller.php", "no_cron");
884 get_app()->proc_run($args);
888 * @brief Adds tasks to the worker queue
890 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
892 * next args are passed as $cmd command line
893 * or: Worker::add(PRIORITY_HIGH, "notifier", "drop", $drop_id);
894 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "create_shadowentry", $post_id);
896 * @note $cmd and string args are surrounded with ""
901 * @return boolean "false" if proc_run couldn't be executed
903 public static function add($cmd) {
904 $proc_args = func_get_args();
907 if (!count($proc_args)) {
911 // Preserve the first parameter
912 // It could contain a command, the priority or an parameter array
913 // If we use the parameter array we have to protect it from the following function
914 $run_parameter = array_shift($proc_args);
917 foreach ($proc_args as $arg) {
918 if (is_array($arg)) {
919 foreach ($arg as $n) {
927 // Now we add the run parameters back to the array
928 array_unshift($args, $run_parameter);
930 $arr = array('args' => $args, 'run_cmd' => true);
932 call_hooks("proc_run", $arr);
933 if (!$arr['run_cmd'] || !count($args)) {
937 $priority = PRIORITY_MEDIUM;
938 $dont_fork = Config::get("system", "worker_dont_fork");
939 $created = datetime_convert();
941 if (is_int($run_parameter)) {
942 $priority = $run_parameter;
943 } elseif (is_array($run_parameter)) {
944 if (isset($run_parameter['priority'])) {
945 $priority = $run_parameter['priority'];
947 if (isset($run_parameter['created'])) {
948 $created = $run_parameter['created'];
950 if (isset($run_parameter['dont_fork'])) {
951 $dont_fork = $run_parameter['dont_fork'];
958 $parameters = json_encode($argv);
959 $found = dba::exists('workerqueue', array('parameter' => $parameters, 'done' => false));
961 // Quit if there was a database error - a precaution for the update process to 3.5.3
962 if (dba::errorNo() != 0) {
967 dba::insert('workerqueue', array('parameter' => $parameters, 'created' => $created, 'priority' => $priority));
970 // Should we quit and wait for the poller to be called as a cronjob?
975 // If there is a lock then we don't have to check for too much worker
976 if (!Lock::set('poller_worker', 0)) {
980 // If there are already enough workers running, don't fork another one
981 $quit = self::tooMuchWorkers();
982 Lock::remove('poller_worker');
988 // Now call the poller to execute the jobs that we just added to the queue