2 namespace Friendica\Core;
5 use Friendica\Core\System;
6 use Friendica\Core\Config;
7 use Friendica\Util\Lock;
13 * @file src/Core/Worker.php
15 * @brief Contains the class for all worker relevant stuff
19 * @brief Worker methods
22 private static $up_start;
23 private static $db_duration;
24 private static $last_update;
25 private static $lock_duration;
28 * @brief Processes the tasks that are in the workerqueue table
30 * @param boolean $run_cron Should the cron processes be executed?
32 public static function processQueue($run_cron = true) {
35 self::$up_start = microtime(true);
37 // Kill stale processes every 5 minutes
38 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
39 if (time() > ($last_cleanup + 300)) {
40 Config::set('system', 'poller_last_cleaned', time());
41 self::killStaleWorkers();
44 // Count active workers and compare them with a maximum value that depends on the load
45 if (self::tooMuchWorkers()) {
46 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
50 // Do we have too few memory?
51 if ($a->min_memory_reached()) {
52 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
56 // Possibly there are too much database connections
57 if (self::maxConnectionsReached()) {
58 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
62 // Possibly there are too much database processes that block the system
63 if ($a->max_processes_reached()) {
64 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
68 // Now we start additional cron processes if we should do so
75 // We fetch the next queue entry that is about to be executed
76 while ($r = self::workerProcess($passing_slow)) {
78 // When we are processing jobs with a lower priority, we don't refetch new jobs
79 // Otherwise fast jobs could wait behind slow ones and could be blocked.
80 $refetched = $passing_slow;
82 foreach ($r AS $entry) {
83 // Assure that the priority is an integer value
84 $entry['priority'] = (int)$entry['priority'];
86 // The work will be done
87 if (!self::execute($entry)) {
88 logger('Process execution failed, quitting.', LOGGER_DEBUG);
92 // If possible we will fetch new jobs for this worker
93 if (!$refetched && Lock::set('poller_worker_process', 0)) {
94 $stamp = (float)microtime(true);
95 $refetched = self::findWorkerProcesses($passing_slow);
96 self::$db_duration += (microtime(true) - $stamp);
97 Lock::remove('poller_worker_process');
101 // To avoid the quitting of multiple pollers only one poller at a time will execute the check
102 if (Lock::set('poller_worker', 0)) {
103 $stamp = (float)microtime(true);
104 // Count active workers and compare them with a maximum value that depends on the load
105 if (self::tooMuchWorkers()) {
106 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
111 if ($a->min_memory_reached()) {
112 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
115 Lock::remove('poller_worker');
116 self::$db_duration += (microtime(true) - $stamp);
119 // Quit the poller once every 5 minutes
120 if (time() > ($starttime + 300)) {
121 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
125 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
129 * @brief Returns the number of non executed entries in the worker queue
131 * @return integer Number of non executed entries in the worker queue
133 private static function totalEntries() {
134 $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done`", dbesc(NULL_DATE));
135 if (dbm::is_result($s)) {
136 return $s[0]["total"];
143 * @brief Returns the highest priority in the worker queue that isn't executed
145 * @return integer Number of active poller processes
147 private static function highestPriority() {
148 $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done` ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
149 if (dbm::is_result($s)) {
150 return $s[0]["priority"];
157 * @brief Returns if a process with the given priority is running
159 * @param integer $priority The priority that should be checked
161 * @return integer Is there a process running with that priority?
163 private static function processWithPriorityActive($priority) {
164 $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' AND NOT `done` LIMIT 1",
165 intval($priority), dbesc(NULL_DATE));
166 return dbm::is_result($s);
170 * @brief Execute a worker entry
172 * @param array $queue Workerqueue entry
174 * @return boolean "true" if further processing should be stopped
176 public static function execute($queue) {
181 // Quit when in maintenance
182 if (Config::get('system', 'maintenance', true)) {
183 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
187 // Constantly check the number of parallel database processes
188 if ($a->max_processes_reached()) {
189 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
193 // Constantly check the number of available database connections to let the frontend be accessible at any time
194 if (self::maxConnectionsReached()) {
195 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
199 $argv = json_decode($queue["parameter"]);
201 // Check for existance and validity of the include file
204 // The script could be provided as full path or only with the function name
205 if ($include == basename($include)) {
206 $include = "include/".$include.".php";
209 if (!validate_include($include)) {
210 logger("Include file ".$argv[0]." is not valid!");
211 dba::delete('workerqueue', array('id' => $queue["id"]));
215 require_once($include);
217 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
219 if (function_exists($funcname)) {
221 // We constantly update the "executed" date every minute to avoid being killed too soon
222 if (!isset(self::$last_update)) {
223 self::$last_update = strtotime($queue["executed"]);
226 $age = (time() - self::$last_update) / 60;
227 self::$last_update = time();
230 $stamp = (float)microtime(true);
231 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
232 self::$db_duration += (microtime(true) - $stamp);
235 self::execFunction($queue, $funcname, $argv);
237 $stamp = (float)microtime(true);
238 if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
239 Config::set('system', 'last_poller_execution', datetime_convert());
241 self::$db_duration = (microtime(true) - $stamp);
243 logger("Function ".$funcname." does not exist");
244 dba::delete('workerqueue', array('id' => $queue["id"]));
251 * @brief Execute a function from the queue
253 * @param array $queue Workerqueue entry
254 * @param string $funcname name of the function
255 * @param array $argv Array of values to be passed to the function
257 private static function execFunction($queue, $funcname, $argv) {
262 $argc = count($argv);
264 $new_process_id = uniqid("wrk", true);
266 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
268 $stamp = (float)microtime(true);
270 // We use the callstack here to analyze the performance of executed worker entries.
271 // For this reason the variables have to be initialized.
272 if (Config::get("system", "profiler")) {
273 $a->performance["start"] = microtime(true);
274 $a->performance["database"] = 0;
275 $a->performance["database_write"] = 0;
276 $a->performance["network"] = 0;
277 $a->performance["file"] = 0;
278 $a->performance["rendering"] = 0;
279 $a->performance["parser"] = 0;
280 $a->performance["marktime"] = 0;
281 $a->performance["markstart"] = microtime(true);
282 $a->callstack = array();
285 // For better logging create a new process id for every worker call
286 // But preserve the old one for the worker
287 $old_process_id = $a->process_id;
288 $a->process_id = $new_process_id;
291 $up_duration = number_format(microtime(true) - self::$up_start, 3);
293 // Reset global data to avoid interferences
296 $funcname($argv, $argc);
298 $a->process_id = $old_process_id;
301 $duration = number_format(microtime(true) - $stamp, 3);
303 self::$up_start = microtime(true);
305 /* With these values we can analyze how effective the worker is.
306 * The database and rest time should be low since this is the unproductive time.
307 * The execution time is the productive time.
308 * By changing parameters like the maximum number of workers we can check the effectivness.
310 logger('DB: '.number_format(self::$db_duration, 2).
311 ' - Lock: '.number_format(self::$lock_duration, 2).
312 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
313 ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
314 self::$lock_duration = 0;
316 if ($duration > 3600) {
317 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
318 } elseif ($duration > 600) {
319 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
320 } elseif ($duration > 300) {
321 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
322 } elseif ($duration > 120) {
323 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
326 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
328 // Write down the performance values into the log
329 if (Config::get("system", "profiler")) {
330 $duration = microtime(true)-$a->performance["start"];
332 if (Config::get("rendertime", "callstack")) {
333 if (isset($a->callstack["database"])) {
334 $o = "\nDatabase Read:\n";
335 foreach ($a->callstack["database"] AS $func => $time) {
336 $time = round($time, 3);
338 $o .= $func.": ".$time."\n";
342 if (isset($a->callstack["database_write"])) {
343 $o .= "\nDatabase Write:\n";
344 foreach ($a->callstack["database_write"] AS $func => $time) {
345 $time = round($time, 3);
347 $o .= $func.": ".$time."\n";
351 if (isset($a->callstack["network"])) {
352 $o .= "\nNetwork:\n";
353 foreach ($a->callstack["network"] AS $func => $time) {
354 $time = round($time, 3);
356 $o .= $func.": ".$time."\n";
364 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
365 number_format($a->performance["database"] - $a->performance["database_write"], 2),
366 number_format($a->performance["database_write"], 2),
367 number_format($a->performance["network"], 2),
368 number_format($a->performance["file"], 2),
369 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
370 number_format($duration, 2)),
374 $cooldown = Config::get("system", "worker_cooldown", 0);
377 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
383 * @brief Checks if the number of database connections has reached a critical limit.
385 * @return bool Are more than 3/4 of the maximum connections used?
387 private static function maxConnectionsReached() {
389 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
390 $max = Config::get("system", "max_connections");
392 // Fetch the percentage level where the poller will get active
393 $maxlevel = Config::get("system", "max_connections_level", 75);
396 // the maximum number of possible user connections can be a system variable
397 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
398 if (dbm::is_result($r)) {
399 $max = $r[0]["Value"];
401 // Or it can be granted. This overrides the system variable
402 $r = q("SHOW GRANTS");
403 if (dbm::is_result($r)) {
404 foreach ($r AS $grants) {
405 $grant = array_pop($grants);
406 if (stristr($grant, "GRANT USAGE ON")) {
407 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
415 // If $max is set we will use the processlist to determine the current number of connections
416 // The processlist only shows entries of the current user
418 $r = q("SHOW PROCESSLIST");
419 if (!dbm::is_result($r)) {
424 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
426 $level = ($used / $max) * 100;
428 if ($level >= $maxlevel) {
429 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
434 // We will now check for the system values.
435 // This limit could be reached although the user limits are fine.
436 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
437 if (!dbm::is_result($r)) {
440 $max = intval($r[0]["Value"]);
444 $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
445 if (!dbm::is_result($r)) {
448 $used = intval($r[0]["Value"]);
452 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
454 $level = $used / $max * 100;
456 if ($level < $maxlevel) {
459 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
464 * @brief fix the queue entry if the worker process died
467 private static function killStaleWorkers() {
468 $entries = dba::select('workerqueue', array('id', 'pid', 'executed', 'priority', 'parameter'),
469 array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
470 array('order' => array('priority', 'created')));
471 while ($entry = dba::fetch($entries)) {
472 if (!posix_kill($entry["pid"], 0)) {
473 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
474 array('id' => $entry["id"]));
476 // Kill long running processes
477 // Check if the priority is in a valid range
478 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
479 $entry["priority"] = PRIORITY_MEDIUM;
482 // Define the maximum durations
483 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
484 $max_duration = $max_duration_defaults[$entry["priority"]];
486 $argv = json_decode($entry["parameter"]);
487 $argv[0] = basename($argv[0]);
489 // How long is the process already running?
490 $duration = (time() - strtotime($entry["executed"])) / 60;
491 if ($duration > $max_duration) {
492 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
493 posix_kill($entry["pid"], SIGTERM);
495 // We killed the stale process.
496 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
497 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
498 if ($entry["priority"] == PRIORITY_HIGH) {
499 $new_priority = PRIORITY_MEDIUM;
500 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
501 $new_priority = PRIORITY_LOW;
502 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
503 $new_priority = PRIORITY_NEGLIGIBLE;
505 dba::update('workerqueue',
506 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
507 array('id' => $entry["id"]));
509 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
516 * @brief Checks if the number of active workers exceeds the given limits
518 * @return bool Are there too much workers running?
520 public static function tooMuchWorkers() {
521 $queues = Config::get("system", "worker_queues", 4);
523 $maxqueues = $queues;
525 $active = self::activeWorkers();
527 // Decrease the number of workers at higher load
528 $load = current_load();
530 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
532 $maxworkers = $queues;
534 // Some magical mathemathics to reduce the workers
536 $slope = $maxworkers / pow($maxsysload, $exponent);
537 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
539 if (Config::get('system', 'worker_debug')) {
540 // Create a list of queue entries grouped by their priority
543 // Adding all processes with no workerqueue entry
544 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
545 (SELECT id FROM `workerqueue`
546 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
547 if ($process = dba::fetch($processes)) {
548 $listitem[0] = "0:".$process["running"];
550 dba::close($processes);
552 // Now adding all processes with workerqueue entries
553 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
554 while ($entry = dba::fetch($entries)) {
555 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
556 if ($process = dba::fetch($processes)) {
557 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
559 dba::close($processes);
561 dba::close($entries);
563 $intervals = array(1, 10, 60);
564 $jobs_per_minute = array();
565 foreach ($intervals AS $interval) {
566 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
567 if ($job = dba::fetch($jobs)) {
568 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
572 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
575 $entries = self::totalEntries();
577 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
578 $top_priority = self::highestPriority();
579 $high_running = self::processWithPriorityActive($top_priority);
581 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
582 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
583 $queues = $active + 1;
587 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
589 // Are there fewer workers running as possible? Then fork a new one.
590 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
591 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
592 $args = array("include/poller.php", "no_cron");
593 get_app()->proc_run($args);
597 return $active >= $queues;
601 * @brief Returns the number of active poller processes
603 * @return integer Number of active poller processes
605 private static function activeWorkers() {
606 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
608 return $workers[0]["processes"];
612 * @brief Check if we should pass some slow processes
614 * When the active processes of the highest priority are using more than 2/3
615 * of all processes, we let pass slower processes.
617 * @param string $highest_priority Returns the currently highest priority
618 * @return bool We let pass a slower process than $highest_priority
620 private static function passingSlow(&$highest_priority) {
622 $highest_priority = 0;
624 $r = q("SELECT `priority`
626 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
628 // No active processes at all? Fine
629 if (!dbm::is_result($r)) {
632 $priorities = array();
633 foreach ($r AS $line) {
634 $priorities[] = $line["priority"];
637 if (count($priorities) == 0) {
640 $highest_priority = min($priorities);
642 // The highest process is already the slowest one?
644 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
648 foreach ($priorities AS $priority) {
649 if ($priority == $highest_priority) {
653 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
654 $passing_slow = (($high/count($priorities)) > (2/3));
657 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
659 return $passing_slow;
663 * @brief Find and claim the next worker process for us
665 * @param boolean $passing_slow Returns if we had passed low priority processes
666 * @return boolean Have we found something?
668 private static function findWorkerProcesses(&$passing_slow) {
671 // Check if we should pass some low priority process
672 $highest_priority = 0;
674 $passing_slow = false;
676 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
677 // We decrease the limit with the number of entries left in the queue
678 $worker_queues = Config::get("system", "worker_queues", 4);
679 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
680 $lower_job_limit = $worker_queues * $queue_length * 2;
681 $jobs = self::totalEntries();
685 $slope = $queue_length / pow($lower_job_limit, $exponent);
686 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
688 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
690 if (self::passingSlow($highest_priority)) {
691 // Are there waiting processes with a higher priority than the currently highest?
692 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority),
693 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
695 while ($id = dba::fetch($result)) {
700 $found = (count($ids) > 0);
703 // Give slower processes some processing time
704 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority),
705 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
707 while ($id = dba::fetch($result)) {
712 $found = (count($ids) > 0);
713 $passing_slow = $found;
717 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
719 $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND NOT `done`", NULL_DATE),
720 array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
722 while ($id = dba::fetch($result)) {
727 $found = (count($ids) > 0);
731 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
732 array_unshift($ids, $condition);
733 dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
740 * @brief Returns the next worker process
742 * @param boolean $passing_slow Returns if we had passed low priority processes
743 * @return string SQL statement
745 public static function workerProcess(&$passing_slow) {
746 $stamp = (float)microtime(true);
748 // There can already be jobs for us in the queue.
749 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
750 if (dbm::is_result($r)) {
751 self::$db_duration += (microtime(true) - $stamp);
755 $stamp = (float)microtime(true);
756 if (!Lock::set('poller_worker_process')) {
759 self::$lock_duration = (microtime(true) - $stamp);
761 $stamp = (float)microtime(true);
762 $found = self::findWorkerProcesses($passing_slow);
763 self::$db_duration += (microtime(true) - $stamp);
765 Lock::remove('poller_worker_process');
768 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
774 * @brief Removes a workerqueue entry from the current process
776 public static function unclaimProcess() {
779 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
783 * @brief Call the front end worker
785 public static function callWorker() {
786 if (!Config::get("system", "frontend_worker")) {
790 $url = System::baseUrl()."/worker";
791 fetch_url($url, false, $redirects, 1);
795 * @brief Call the front end worker if there aren't any active
797 public static function executeIfIdle() {
798 if (!Config::get("system", "frontend_worker")) {
802 // Do we have "proc_open"? Then we can fork the poller
803 if (function_exists("proc_open")) {
804 // When was the last time that we called the worker?
805 // Less than one minute? Then we quit
806 if ((time() - Config::get("system", "worker_started")) < 60) {
810 set_config("system", "worker_started", time());
812 // Do we have enough running workers? Then we quit here.
813 if (self::tooMuchWorkers()) {
814 // Cleaning dead processes
815 self::killStaleWorkers();
816 get_app()->remove_inactive_processes();
823 logger('Call poller', LOGGER_DEBUG);
825 $args = array("include/poller.php", "no_cron");
826 get_app()->proc_run($args);
830 // We cannot execute background processes.
831 // We now run the processes from the frontend.
832 // This won't work with long running processes.
835 self::clearProcesses();
837 $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
839 if ($workers[0]["processes"] == 0) {
845 * @brief Removes long running worker processes
847 public static function clearProcesses() {
848 $timeout = Config::get("system", "frontend_worker_timeout", 10);
850 /// @todo We should clean up the corresponding workerqueue entries as well
851 q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
852 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
856 * @brief Runs the cron processes
858 private static function runCron() {
859 logger('Add cron entries', LOGGER_DEBUG);
861 // Check for spooled items
862 self::add(PRIORITY_HIGH, "spool_post");
864 // Run the cron job that calls all other jobs
865 self::add(PRIORITY_MEDIUM, "cron");
867 // Run the cronhooks job separately from cron for being able to use a different timing
868 self::add(PRIORITY_MEDIUM, "cronhooks");
870 // Cleaning dead processes
871 self::killStaleWorkers();
875 * @brief Adds tasks to the worker queue
877 * @param (integer|array) priority or parameter array, $cmd atrings are deprecated and are ignored
879 * next args are passed as $cmd command line
880 * or: Worker::add(PRIORITY_HIGH, "notifier", "drop", $drop_id);
881 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "create_shadowentry", $post_id);
883 * @note $cmd and string args are surrounded with ""
888 * @return boolean "false" if proc_run couldn't be executed
890 public static function add($cmd) {
891 $proc_args = func_get_args();
894 if (!count($proc_args)) {
898 // Preserve the first parameter
899 // It could contain a command, the priority or an parameter array
900 // If we use the parameter array we have to protect it from the following function
901 $run_parameter = array_shift($proc_args);
904 foreach ($proc_args as $arg) {
905 if (is_array($arg)) {
906 foreach ($arg as $n) {
914 // Now we add the run parameters back to the array
915 array_unshift($args, $run_parameter);
917 $arr = array('args' => $args, 'run_cmd' => true);
919 call_hooks("proc_run", $arr);
920 if (!$arr['run_cmd'] || !count($args)) {
924 $priority = PRIORITY_MEDIUM;
925 $dont_fork = get_config("system", "worker_dont_fork");
926 $created = datetime_convert();
928 if (is_int($run_parameter)) {
929 $priority = $run_parameter;
930 } elseif (is_array($run_parameter)) {
931 if (isset($run_parameter['priority'])) {
932 $priority = $run_parameter['priority'];
934 if (isset($run_parameter['created'])) {
935 $created = $run_parameter['created'];
937 if (isset($run_parameter['dont_fork'])) {
938 $dont_fork = $run_parameter['dont_fork'];
945 $parameters = json_encode($argv);
946 $found = dba::exists('workerqueue', array('parameter' => $parameters, 'done' => false));
948 // Quit if there was a database error - a precaution for the update process to 3.5.3
949 if (dba::errorNo() != 0) {
954 dba::insert('workerqueue', array('parameter' => $parameters, 'created' => $created, 'priority' => $priority));
957 // Should we quit and wait for the poller to be called as a cronjob?
962 // If there is a lock then we don't have to check for too much worker
963 if (!Lock::set('poller_worker', 0)) {
967 // If there are already enough workers running, don't fork another one
968 $quit = self::tooMuchWorkers();
969 Lock::remove('poller_worker');
975 // Now call the poller to execute the jobs that we just added to the queue
976 $args = array("include/poller.php", "no_cron");
977 get_app()->proc_run($args);