2 namespace Friendica\Core;
5 use Friendica\Core\System;
6 use Friendica\Core\Config;
7 use Friendica\Core\Worker;
8 use Friendica\Database\DBM;
9 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 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
215 // We constantly update the "executed" date every minute to avoid being killed too soon
216 if (!isset(self::$last_update)) {
217 self::$last_update = strtotime($queue["executed"]);
220 $age = (time() - self::$last_update) / 60;
221 self::$last_update = time();
224 $stamp = (float)microtime(true);
225 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
226 self::$db_duration += (microtime(true) - $stamp);
231 self::execFunction($queue, $include, $argv, true);
233 $stamp = (float)microtime(true);
234 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
235 Config::set('system', 'last_poller_execution', datetime_convert());
237 self::$db_duration = (microtime(true) - $stamp);
242 // The script could be provided as full path or only with the function name
243 if ($include == basename($include)) {
244 $include = "include/".$include.".php";
247 if (!validate_include($include)) {
248 logger("Include file ".$argv[0]." is not valid!");
249 dba::delete('workerqueue', array('id' => $queue["id"]));
253 require_once($include);
255 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
257 if (function_exists($funcname)) {
259 // We constantly update the "executed" date every minute to avoid being killed too soon
260 if (!isset(self::$last_update)) {
261 self::$last_update = strtotime($queue["executed"]);
264 $age = (time() - self::$last_update) / 60;
265 self::$last_update = time();
268 $stamp = (float)microtime(true);
269 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
270 self::$db_duration += (microtime(true) - $stamp);
273 self::execFunction($queue, $funcname, $argv, false);
275 $stamp = (float)microtime(true);
276 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
277 Config::set('system', 'last_poller_execution', datetime_convert());
279 self::$db_duration = (microtime(true) - $stamp);
281 logger("Function ".$funcname." does not exist");
282 dba::delete('workerqueue', array('id' => $queue["id"]));
289 * @brief Execute a function from the queue
291 * @param array $queue Workerqueue entry
292 * @param string $funcname name of the function
293 * @param array $argv Array of values to be passed to the function
295 private static function execFunction($queue, $funcname, $argv, $method_call) {
300 $argc = count($argv);
302 $new_process_id = uniqid("wrk", true);
304 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
306 $stamp = (float)microtime(true);
308 // We use the callstack here to analyze the performance of executed worker entries.
309 // For this reason the variables have to be initialized.
310 if (Config::get("system", "profiler")) {
311 $a->performance["start"] = microtime(true);
312 $a->performance["database"] = 0;
313 $a->performance["database_write"] = 0;
314 $a->performance["network"] = 0;
315 $a->performance["file"] = 0;
316 $a->performance["rendering"] = 0;
317 $a->performance["parser"] = 0;
318 $a->performance["marktime"] = 0;
319 $a->performance["markstart"] = microtime(true);
320 $a->callstack = array();
323 // For better logging create a new process id for every worker call
324 // But preserve the old one for the worker
325 $old_process_id = $a->process_id;
326 $a->process_id = $new_process_id;
329 $up_duration = number_format(microtime(true) - self::$up_start, 3);
331 // Reset global data to avoid interferences
335 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
337 $funcname($argv, $argc);
340 $a->process_id = $old_process_id;
343 $duration = number_format(microtime(true) - $stamp, 3);
345 self::$up_start = microtime(true);
347 /* With these values we can analyze how effective the worker is.
348 * The database and rest time should be low since this is the unproductive time.
349 * The execution time is the productive time.
350 * By changing parameters like the maximum number of workers we can check the effectivness.
352 logger('DB: '.number_format(self::$db_duration, 2).
353 ' - Lock: '.number_format(self::$lock_duration, 2).
354 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
355 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
356 self::$lock_duration = 0;
358 if ($duration > 3600) {
359 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
360 } elseif ($duration > 600) {
361 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
362 } elseif ($duration > 300) {
363 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
364 } elseif ($duration > 120) {
365 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
368 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
370 // Write down the performance values into the log
371 if (Config::get("system", "profiler")) {
372 $duration = microtime(true)-$a->performance["start"];
374 if (Config::get("rendertime", "callstack")) {
375 if (isset($a->callstack["database"])) {
376 $o = "\nDatabase Read:\n";
377 foreach ($a->callstack["database"] AS $func => $time) {
378 $time = round($time, 3);
380 $o .= $func.": ".$time."\n";
384 if (isset($a->callstack["database_write"])) {
385 $o .= "\nDatabase Write:\n";
386 foreach ($a->callstack["database_write"] AS $func => $time) {
387 $time = round($time, 3);
389 $o .= $func.": ".$time."\n";
393 if (isset($a->callstack["network"])) {
394 $o .= "\nNetwork:\n";
395 foreach ($a->callstack["network"] AS $func => $time) {
396 $time = round($time, 3);
398 $o .= $func.": ".$time."\n";
406 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
407 number_format($a->performance["database"] - $a->performance["database_write"], 2),
408 number_format($a->performance["database_write"], 2),
409 number_format($a->performance["network"], 2),
410 number_format($a->performance["file"], 2),
411 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
412 number_format($duration, 2)),
416 $cooldown = Config::get("system", "worker_cooldown", 0);
419 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
425 * @brief Checks if the number of database connections has reached a critical limit.
427 * @return bool Are more than 3/4 of the maximum connections used?
429 private static function maxConnectionsReached() {
431 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
432 $max = Config::get("system", "max_connections");
434 // Fetch the percentage level where the poller will get active
435 $maxlevel = Config::get("system", "max_connections_level", 75);
438 // the maximum number of possible user connections can be a system variable
439 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
440 if (DBM::is_result($r)) {
443 // Or it can be granted. This overrides the system variable
444 $r = dba::p('SHOW GRANTS');
445 while ($grants = dba::fetch($r)) {
446 $grant = array_pop($grants);
447 if (stristr($grant, "GRANT USAGE ON")) {
448 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
456 // If $max is set we will use the processlist to determine the current number of connections
457 // The processlist only shows entries of the current user
459 $r = dba::p('SHOW PROCESSLIST');
460 $used = dba::num_rows($r);
463 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
465 $level = ($used / $max) * 100;
467 if ($level >= $maxlevel) {
468 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
473 // We will now check for the system values.
474 // This limit could be reached although the user limits are fine.
475 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
476 if (!DBM::is_result($r)) {
479 $max = intval($r["Value"]);
483 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
484 if (!DBM::is_result($r)) {
487 $used = intval($r["Value"]);
491 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
493 $level = $used / $max * 100;
495 if ($level < $maxlevel) {
498 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
503 * @brief fix the queue entry if the worker process died
506 private static function killStaleWorkers() {
507 $entries = dba::select('workerqueue', array('id', 'pid', 'executed', 'priority', 'parameter'),
508 array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
509 array('order' => array('priority', 'created')));
510 while ($entry = dba::fetch($entries)) {
511 if (!posix_kill($entry["pid"], 0)) {
512 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
513 array('id' => $entry["id"]));
515 // Kill long running processes
516 // Check if the priority is in a valid range
517 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
518 $entry["priority"] = PRIORITY_MEDIUM;
521 // Define the maximum durations
522 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
523 $max_duration = $max_duration_defaults[$entry["priority"]];
525 $argv = json_decode($entry["parameter"]);
526 $argv[0] = basename($argv[0]);
528 // How long is the process already running?
529 $duration = (time() - strtotime($entry["executed"])) / 60;
530 if ($duration > $max_duration) {
531 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
532 posix_kill($entry["pid"], SIGTERM);
534 // We killed the stale process.
535 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
536 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
537 if ($entry["priority"] == PRIORITY_HIGH) {
538 $new_priority = PRIORITY_MEDIUM;
539 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
540 $new_priority = PRIORITY_LOW;
541 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
542 $new_priority = PRIORITY_NEGLIGIBLE;
544 dba::update('workerqueue',
545 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
546 array('id' => $entry["id"]));
548 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
555 * @brief Checks if the number of active workers exceeds the given limits
557 * @return bool Are there too much workers running?
559 public static function tooMuchWorkers() {
560 $queues = Config::get("system", "worker_queues", 4);
562 $maxqueues = $queues;
564 $active = self::activeWorkers();
566 // Decrease the number of workers at higher load
567 $load = current_load();
569 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
571 $maxworkers = $queues;
573 // Some magical mathemathics to reduce the workers
575 $slope = $maxworkers / pow($maxsysload, $exponent);
576 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
578 if (Config::get('system', 'worker_debug')) {
579 // Create a list of queue entries grouped by their priority
582 // Adding all processes with no workerqueue entry
583 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
584 (SELECT id FROM `workerqueue`
585 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
586 if ($process = dba::fetch($processes)) {
587 $listitem[0] = "0:".$process["running"];
589 dba::close($processes);
591 // Now adding all processes with workerqueue entries
592 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
593 while ($entry = dba::fetch($entries)) {
594 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
595 if ($process = dba::fetch($processes)) {
596 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
598 dba::close($processes);
600 dba::close($entries);
602 $intervals = array(1, 10, 60);
603 $jobs_per_minute = array();
604 foreach ($intervals AS $interval) {
605 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
606 if ($job = dba::fetch($jobs)) {
607 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
611 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
614 $entries = self::totalEntries();
616 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
617 $top_priority = self::highestPriority();
618 $high_running = self::processWithPriorityActive($top_priority);
620 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
621 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
622 $queues = $active + 1;
626 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
628 // Are there fewer workers running as possible? Then fork a new one.
629 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
630 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
635 return $active >= $queues;
639 * @brief Returns the number of active poller processes
641 * @return integer Number of active poller processes
643 private static function activeWorkers() {
644 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
646 return $workers["processes"];
650 * @brief Check if we should pass some slow processes
652 * When the active processes of the highest priority are using more than 2/3
653 * of all processes, we let pass slower processes.
655 * @param string $highest_priority Returns the currently highest priority
656 * @return bool We let pass a slower process than $highest_priority
658 private static function passingSlow(&$highest_priority) {
659 $highest_priority = 0;
661 $r = dba::p("SELECT `priority`
663 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
665 // No active processes at all? Fine
666 if (!DBM::is_result($r)) {
669 $priorities = array();
670 while ($line = dba::fetch($r)) {
671 $priorities[] = $line["priority"];
676 if (count($priorities) == 0) {
679 $highest_priority = min($priorities);
681 // The highest process is already the slowest one?
683 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
687 foreach ($priorities AS $priority) {
688 if ($priority == $highest_priority) {
692 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
693 $passing_slow = (($high/count($priorities)) > (2/3));
696 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
698 return $passing_slow;
702 * @brief Find and claim the next worker process for us
704 * @param boolean $passing_slow Returns if we had passed low priority processes
705 * @return boolean Have we found something?
707 private static function findWorkerProcesses(&$passing_slow) {
710 // Check if we should pass some low priority process
711 $highest_priority = 0;
713 $passing_slow = false;
715 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
716 // We decrease the limit with the number of entries left in the queue
717 $worker_queues = Config::get("system", "worker_queues", 4);
718 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
719 $lower_job_limit = $worker_queues * $queue_length * 2;
720 $jobs = self::totalEntries();
724 $slope = $queue_length / pow($lower_job_limit, $exponent);
725 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
727 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
729 if (self::passingSlow($highest_priority)) {
730 // Are there waiting processes with a higher priority than the currently highest?
731 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority),
732 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
734 while ($id = dba::fetch($result)) {
739 $found = (count($ids) > 0);
742 // Give slower processes some processing time
743 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority),
744 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
746 while ($id = dba::fetch($result)) {
751 $found = (count($ids) > 0);
752 $passing_slow = $found;
756 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
758 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND NOT `done`", NULL_DATE),
759 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
761 while ($id = dba::fetch($result)) {
766 $found = (count($ids) > 0);
770 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
771 array_unshift($ids, $condition);
772 dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
779 * @brief Returns the next worker process
781 * @param boolean $passing_slow Returns if we had passed low priority processes
782 * @return string SQL statement
784 public static function workerProcess(&$passing_slow) {
785 $stamp = (float)microtime(true);
787 // There can already be jobs for us in the queue.
788 $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
789 if (DBM::is_result($r)) {
790 self::$db_duration += (microtime(true) - $stamp);
791 return dba::inArray($r);
795 $stamp = (float)microtime(true);
796 if (!Lock::set('poller_worker_process')) {
799 self::$lock_duration = (microtime(true) - $stamp);
801 $stamp = (float)microtime(true);
802 $found = self::findWorkerProcesses($passing_slow);
803 self::$db_duration += (microtime(true) - $stamp);
805 Lock::remove('poller_worker_process');
808 $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
809 return dba::inArray($r);
815 * @brief Removes a workerqueue entry from the current process
817 public static function unclaimProcess() {
820 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
824 * @brief Call the front end worker
826 public static function callWorker() {
827 if (!Config::get("system", "frontend_worker")) {
831 $url = System::baseUrl()."/worker";
832 fetch_url($url, false, $redirects, 1);
836 * @brief Call the front end worker if there aren't any active
838 public static function executeIfIdle() {
839 if (!Config::get("system", "frontend_worker")) {
843 // Do we have "proc_open"? Then we can fork the poller
844 if (function_exists("proc_open")) {
845 // When was the last time that we called the worker?
846 // Less than one minute? Then we quit
847 if ((time() - Config::get("system", "worker_started")) < 60) {
851 Config::set("system", "worker_started", time());
853 // Do we have enough running workers? Then we quit here.
854 if (self::tooMuchWorkers()) {
855 // Cleaning dead processes
856 self::killStaleWorkers();
857 get_app()->remove_inactive_processes();
864 logger('Call poller', LOGGER_DEBUG);
869 // We cannot execute background processes.
870 // We now run the processes from the frontend.
871 // This won't work with long running processes.
874 self::clearProcesses();
876 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
878 if ($workers["processes"] == 0) {
884 * @brief Removes long running worker processes
886 public static function clearProcesses() {
887 $timeout = Config::get("system", "frontend_worker_timeout", 10);
889 /// @todo We should clean up the corresponding workerqueue entries as well
890 $condition = array("`created` < ? AND `command` = 'worker.php'",
891 datetime_convert('UTC','UTC',"now - ".$timeout." minutes"));
892 dba::delete('process', $condition);
896 * @brief Runs the cron processes
898 private static function runCron() {
899 logger('Add cron entries', LOGGER_DEBUG);
901 // Check for spooled items
902 self::add(PRIORITY_HIGH, "spool_post");
904 // Run the cron job that calls all other jobs
905 self::add(PRIORITY_MEDIUM, "Cron");
907 // Run the cronhooks job separately from cron for being able to use a different timing
908 self::add(PRIORITY_MEDIUM, "CronHooks");
910 // Cleaning dead processes
911 self::killStaleWorkers();
914 public static function spawnWorker() {
915 $args = array("include/poller.php", "no_cron");
916 get_app()->proc_run($args);
920 * @brief Adds tasks to the worker queue
922 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
924 * next args are passed as $cmd command line
925 * or: Worker::add(PRIORITY_HIGH, "notifier", "drop", $drop_id);
926 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "create_shadowentry", $post_id);
928 * @note $cmd and string args are surrounded with ""
933 * @return boolean "false" if proc_run couldn't be executed
935 public static function add($cmd) {
936 $proc_args = func_get_args();
939 if (!count($proc_args)) {
943 // Preserve the first parameter
944 // It could contain a command, the priority or an parameter array
945 // If we use the parameter array we have to protect it from the following function
946 $run_parameter = array_shift($proc_args);
949 foreach ($proc_args as $arg) {
950 if (is_array($arg)) {
951 foreach ($arg as $n) {
959 // Now we add the run parameters back to the array
960 array_unshift($args, $run_parameter);
962 $arr = array('args' => $args, 'run_cmd' => true);
964 call_hooks("proc_run", $arr);
965 if (!$arr['run_cmd'] || !count($args)) {
969 $priority = PRIORITY_MEDIUM;
970 $dont_fork = Config::get("system", "worker_dont_fork");
971 $created = datetime_convert();
973 if (is_int($run_parameter)) {
974 $priority = $run_parameter;
975 } elseif (is_array($run_parameter)) {
976 if (isset($run_parameter['priority'])) {
977 $priority = $run_parameter['priority'];
979 if (isset($run_parameter['created'])) {
980 $created = $run_parameter['created'];
982 if (isset($run_parameter['dont_fork'])) {
983 $dont_fork = $run_parameter['dont_fork'];
990 $parameters = json_encode($argv);
991 $found = dba::exists('workerqueue', array('parameter' => $parameters, 'done' => false));
993 // Quit if there was a database error - a precaution for the update process to 3.5.3
994 if (dba::errorNo() != 0) {
999 dba::insert('workerqueue', array('parameter' => $parameters, 'created' => $created, 'priority' => $priority));
1002 // Should we quit and wait for the poller to be called as a cronjob?
1007 // If there is a lock then we don't have to check for too much worker
1008 if (!Lock::set('poller_worker', 0)) {
1012 // If there are already enough workers running, don't fork another one
1013 $quit = self::tooMuchWorkers();
1014 Lock::remove('poller_worker');
1020 // Now call the poller to execute the jobs that we just added to the queue
1021 self::spawnWorker();