3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Process;
12 use Friendica\Util\Lock;
13 use Friendica\Util\Network;
14 use Friendica\Util\Temporal;
18 require_once 'include/dba.php';
21 * @file src/Core/Worker.php
23 * @brief Contains the class for the worker background job processing
27 * @brief Worker methods
31 private static $up_start;
32 private static $db_duration;
33 private static $last_update;
34 private static $lock_duration;
37 * @brief Processes the tasks that are in the workerqueue table
39 * @param boolean $run_cron Should the cron processes be executed?
42 public static function processQueue($run_cron = true)
46 self::$up_start = microtime(true);
48 // At first check the maximum load. We shouldn't continue with a high load
49 if ($a->maxload_reached()) {
50 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
54 // We now start the process. This is done after the load check since this could increase the load.
57 // Kill stale processes every 5 minutes
58 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
59 if (time() > ($last_cleanup + 300)) {
60 Config::set('system', 'poller_last_cleaned', time());
61 self::killStaleWorkers();
64 // Count active workers and compare them with a maximum value that depends on the load
65 if (self::tooMuchWorkers()) {
66 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
70 // Do we have too few memory?
71 if ($a->min_memory_reached()) {
72 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
76 // Possibly there are too much database connections
77 if (self::maxConnectionsReached()) {
78 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
82 // Possibly there are too much database processes that block the system
83 if ($a->max_processes_reached()) {
84 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
88 // Now we start additional cron processes if we should do so
95 // We fetch the next queue entry that is about to be executed
96 while ($r = self::workerProcess($passing_slow)) {
97 // When we are processing jobs with a lower priority, we don't refetch new jobs
98 // Otherwise fast jobs could wait behind slow ones and could be blocked.
99 $refetched = $passing_slow;
101 foreach ($r as $entry) {
102 // Assure that the priority is an integer value
103 $entry['priority'] = (int)$entry['priority'];
105 // The work will be done
106 if (!self::execute($entry)) {
107 logger('Process execution failed, quitting.', LOGGER_DEBUG);
111 // If possible we will fetch new jobs for this worker
112 if (!$refetched && Lock::set('poller_worker_process', 0)) {
113 $stamp = (float)microtime(true);
114 $refetched = self::findWorkerProcesses($passing_slow);
115 self::$db_duration += (microtime(true) - $stamp);
116 Lock::remove('poller_worker_process');
120 // To avoid the quitting of multiple workers only one worker at a time will execute the check
121 if (Lock::set('poller_worker', 0)) {
122 $stamp = (float)microtime(true);
123 // Count active workers and compare them with a maximum value that depends on the load
124 if (self::tooMuchWorkers()) {
125 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
130 if ($a->min_memory_reached()) {
131 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
134 Lock::remove('poller_worker');
135 self::$db_duration += (microtime(true) - $stamp);
138 // Quit the worker once every 5 minutes
139 if (time() > ($starttime + 300)) {
140 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
144 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
148 * @brief Returns the number of non executed entries in the worker queue
150 * @return integer Number of non executed entries in the worker queue
152 private static function totalEntries()
154 $s = dba::fetch_first("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done`", NULL_DATE);
155 if (DBM::is_result($s)) {
163 * @brief Returns the highest priority in the worker queue that isn't executed
165 * @return integer Number of active worker processes
167 private static function highestPriority()
169 $condition = ["`executed` <= ? AND NOT `done`", NULL_DATE];
170 $workerqueue = dba::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
171 if (DBM::is_result($workerqueue)) {
172 return $workerqueue["priority"];
179 * @brief Returns if a process with the given priority is running
181 * @param integer $priority The priority that should be checked
183 * @return integer Is there a process running with that priority?
185 private static function processWithPriorityActive($priority)
187 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE];
188 return dba::exists('workerqueue', $condition);
192 * @brief Execute a worker entry
194 * @param array $queue Workerqueue entry
196 * @return boolean "true" if further processing should be stopped
198 public static function execute($queue)
204 // Quit when in maintenance
205 if (Config::get('system', 'maintenance', true)) {
206 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
210 // Constantly check the number of parallel database processes
211 if ($a->max_processes_reached()) {
212 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
216 // Constantly check the number of available database connections to let the frontend be accessible at any time
217 if (self::maxConnectionsReached()) {
218 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
222 $argv = json_decode($queue["parameter"]);
224 // Check for existance and validity of the include file
227 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
228 // We constantly update the "executed" date every minute to avoid being killed too soon
229 if (!isset(self::$last_update)) {
230 self::$last_update = strtotime($queue["executed"]);
233 $age = (time() - self::$last_update) / 60;
234 self::$last_update = time();
237 $stamp = (float)microtime(true);
238 dba::update('workerqueue', ['executed' => Temporal::convert()], ['pid' => $mypid, 'done' => false]);
239 self::$db_duration += (microtime(true) - $stamp);
244 self::execFunction($queue, $include, $argv, true);
246 $stamp = (float)microtime(true);
247 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
248 Config::set('system', 'last_poller_execution', Temporal::convert());
250 self::$db_duration = (microtime(true) - $stamp);
255 // The script could be provided as full path or only with the function name
256 if ($include == basename($include)) {
257 $include = "include/".$include.".php";
260 if (!validate_include($include)) {
261 logger("Include file ".$argv[0]." is not valid!");
262 dba::delete('workerqueue', ['id' => $queue["id"]]);
266 require_once $include;
268 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
270 if (function_exists($funcname)) {
271 // We constantly update the "executed" date every minute to avoid being killed too soon
272 if (!isset(self::$last_update)) {
273 self::$last_update = strtotime($queue["executed"]);
276 $age = (time() - self::$last_update) / 60;
277 self::$last_update = time();
280 $stamp = (float)microtime(true);
281 dba::update('workerqueue', ['executed' => Temporal::convert()], ['pid' => $mypid, 'done' => false]);
282 self::$db_duration += (microtime(true) - $stamp);
285 self::execFunction($queue, $funcname, $argv, false);
287 $stamp = (float)microtime(true);
288 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
289 Config::set('system', 'last_poller_execution', Temporal::convert());
291 self::$db_duration = (microtime(true) - $stamp);
293 logger("Function ".$funcname." does not exist");
294 dba::delete('workerqueue', ['id' => $queue["id"]]);
301 * @brief Execute a function from the queue
303 * @param array $queue Workerqueue entry
304 * @param string $funcname name of the function
305 * @param array $argv Array of values to be passed to the function
306 * @param boolean $method_call boolean
309 private static function execFunction($queue, $funcname, $argv, $method_call)
315 $argc = count($argv);
317 $new_process_id = uniqid("wrk", true);
319 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
321 $stamp = (float)microtime(true);
323 // We use the callstack here to analyze the performance of executed worker entries.
324 // For this reason the variables have to be initialized.
325 if (Config::get("system", "profiler")) {
326 $a->performance["start"] = microtime(true);
327 $a->performance["database"] = 0;
328 $a->performance["database_write"] = 0;
329 $a->performance["network"] = 0;
330 $a->performance["file"] = 0;
331 $a->performance["rendering"] = 0;
332 $a->performance["parser"] = 0;
333 $a->performance["marktime"] = 0;
334 $a->performance["markstart"] = microtime(true);
338 // For better logging create a new process id for every worker call
339 // But preserve the old one for the worker
340 $old_process_id = $a->process_id;
341 $a->process_id = $new_process_id;
344 $up_duration = number_format(microtime(true) - self::$up_start, 3);
346 // Reset global data to avoid interferences
350 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
352 $funcname($argv, $argc);
355 $a->process_id = $old_process_id;
358 $duration = number_format(microtime(true) - $stamp, 3);
360 self::$up_start = microtime(true);
362 /* With these values we can analyze how effective the worker is.
363 * The database and rest time should be low since this is the unproductive time.
364 * The execution time is the productive time.
365 * By changing parameters like the maximum number of workers we can check the effectivness.
368 'DB: '.number_format(self::$db_duration, 2).
369 ' - Lock: '.number_format(self::$lock_duration, 2).
370 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
371 ' - Execution: '.number_format($duration, 2),
375 self::$lock_duration = 0;
377 if ($duration > 3600) {
378 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
379 } elseif ($duration > 600) {
380 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
381 } elseif ($duration > 300) {
382 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
383 } elseif ($duration > 120) {
384 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
387 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
389 // Write down the performance values into the log
390 if (Config::get("system", "profiler")) {
391 $duration = microtime(true)-$a->performance["start"];
393 if (Config::get("rendertime", "callstack")) {
394 if (isset($a->callstack["database"])) {
395 $o = "\nDatabase Read:\n";
396 foreach ($a->callstack["database"] as $func => $time) {
397 $time = round($time, 3);
399 $o .= $func.": ".$time."\n";
403 if (isset($a->callstack["database_write"])) {
404 $o .= "\nDatabase Write:\n";
405 foreach ($a->callstack["database_write"] as $func => $time) {
406 $time = round($time, 3);
408 $o .= $func.": ".$time."\n";
412 if (isset($a->callstack["network"])) {
413 $o .= "\nNetwork:\n";
414 foreach ($a->callstack["network"] as $func => $time) {
415 $time = round($time, 3);
417 $o .= $func.": ".$time."\n";
426 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
427 "DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
428 number_format($a->performance["database"] - $a->performance["database_write"], 2),
429 number_format($a->performance["database_write"], 2),
430 number_format($a->performance["network"], 2),
431 number_format($a->performance["file"], 2),
432 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
433 number_format($duration, 2)
439 $cooldown = Config::get("system", "worker_cooldown", 0);
442 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
448 * @brief Checks if the number of database connections has reached a critical limit.
450 * @return bool Are more than 3/4 of the maximum connections used?
452 private static function maxConnectionsReached()
454 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
455 $max = Config::get("system", "max_connections");
457 // Fetch the percentage level where the worker will get active
458 $maxlevel = Config::get("system", "max_connections_level", 75);
461 // the maximum number of possible user connections can be a system variable
462 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
463 if (DBM::is_result($r)) {
466 // Or it can be granted. This overrides the system variable
467 $r = dba::p('SHOW GRANTS');
468 while ($grants = dba::fetch($r)) {
469 $grant = array_pop($grants);
470 if (stristr($grant, "GRANT USAGE ON")) {
471 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
479 // If $max is set we will use the processlist to determine the current number of connections
480 // The processlist only shows entries of the current user
482 $r = dba::p('SHOW PROCESSLIST');
483 $used = dba::num_rows($r);
486 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
488 $level = ($used / $max) * 100;
490 if ($level >= $maxlevel) {
491 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
496 // We will now check for the system values.
497 // This limit could be reached although the user limits are fine.
498 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
499 if (!DBM::is_result($r)) {
502 $max = intval($r["Value"]);
506 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
507 if (!DBM::is_result($r)) {
510 $used = intval($r["Value"]);
514 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
516 $level = $used / $max * 100;
518 if ($level < $maxlevel) {
521 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
526 * @brief fix the queue entry if the worker process died
529 private static function killStaleWorkers()
531 $entries = dba::select(
533 ['id', 'pid', 'executed', 'priority', 'parameter'],
534 ['`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE],
535 ['order' => ['priority', 'created']]
538 while ($entry = dba::fetch($entries)) {
539 if (!posix_kill($entry["pid"], 0)) {
542 ['executed' => NULL_DATE, 'pid' => 0],
543 ['id' => $entry["id"]]
546 // Kill long running processes
547 // Check if the priority is in a valid range
548 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
549 $entry["priority"] = PRIORITY_MEDIUM;
552 // Define the maximum durations
553 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
554 $max_duration = $max_duration_defaults[$entry["priority"]];
556 $argv = json_decode($entry["parameter"]);
557 $argv[0] = basename($argv[0]);
559 // How long is the process already running?
560 $duration = (time() - strtotime($entry["executed"])) / 60;
561 if ($duration > $max_duration) {
562 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
563 posix_kill($entry["pid"], SIGTERM);
565 // We killed the stale process.
566 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
567 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
568 if ($entry["priority"] == PRIORITY_HIGH) {
569 $new_priority = PRIORITY_MEDIUM;
570 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
571 $new_priority = PRIORITY_LOW;
572 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
573 $new_priority = PRIORITY_NEGLIGIBLE;
577 ['executed' => NULL_DATE, 'created' => Temporal::convert(), 'priority' => $new_priority, 'pid' => 0],
578 ['id' => $entry["id"]]
581 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
588 * @brief Checks if the number of active workers exceeds the given limits
590 * @return bool Are there too much workers running?
592 public static function tooMuchWorkers()
594 $queues = Config::get("system", "worker_queues", 4);
596 $maxqueues = $queues;
598 $active = self::activeWorkers();
600 // Decrease the number of workers at higher load
601 $load = current_load();
603 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
605 $maxworkers = $queues;
607 // Some magical mathemathics to reduce the workers
609 $slope = $maxworkers / pow($maxsysload, $exponent);
610 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
613 if (Config::get('system', 'worker_debug')) {
614 // Create a list of queue entries grouped by their priority
617 // Adding all processes with no workerqueue entry
619 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
620 (SELECT id FROM `workerqueue`
621 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
625 if ($process = dba::fetch($processes)) {
626 $listitem[0] = "0:".$process["running"];
628 dba::close($processes);
630 // Now adding all processes with workerqueue entries
631 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
632 while ($entry = dba::fetch($entries)) {
633 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
634 if ($process = dba::fetch($processes)) {
635 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
637 dba::close($processes);
639 dba::close($entries);
641 $intervals = [1, 10, 60];
642 $jobs_per_minute = [];
643 foreach ($intervals as $interval) {
644 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
645 if ($job = dba::fetch($jobs)) {
646 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
650 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
653 $entries = self::totalEntries();
655 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
656 $top_priority = self::highestPriority();
657 $high_running = self::processWithPriorityActive($top_priority);
659 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
660 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
661 $queues = $active + 1;
665 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
667 // Are there fewer workers running as possible? Then fork a new one.
668 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
669 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
674 return $active >= $queues;
678 * @brief Returns the number of active worker processes
680 * @return integer Number of active worker processes
682 private static function activeWorkers()
684 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
686 return $workers["processes"];
690 * @brief Check if we should pass some slow processes
692 * When the active processes of the highest priority are using more than 2/3
693 * of all processes, we let pass slower processes.
695 * @param string $highest_priority Returns the currently highest priority
696 * @return bool We let pass a slower process than $highest_priority
698 private static function passingSlow(&$highest_priority)
700 $highest_priority = 0;
705 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
708 // No active processes at all? Fine
709 if (!DBM::is_result($r)) {
713 while ($line = dba::fetch($r)) {
714 $priorities[] = $line["priority"];
719 if (count($priorities) == 0) {
722 $highest_priority = min($priorities);
724 // The highest process is already the slowest one?
726 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
730 foreach ($priorities as $priority) {
731 if ($priority == $highest_priority) {
735 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
736 $passing_slow = (($high/count($priorities)) > (2/3));
739 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
741 return $passing_slow;
745 * @brief Find and claim the next worker process for us
747 * @param boolean $passing_slow Returns if we had passed low priority processes
748 * @return boolean Have we found something?
750 private static function findWorkerProcesses(&$passing_slow)
754 // Check if we should pass some low priority process
755 $highest_priority = 0;
757 $passing_slow = false;
759 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
760 // We decrease the limit with the number of entries left in the queue
761 $worker_queues = Config::get("system", "worker_queues", 4);
762 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
763 $lower_job_limit = $worker_queues * $queue_length * 2;
764 $jobs = self::totalEntries();
768 $slope = $queue_length / pow($lower_job_limit, $exponent);
769 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
771 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
773 if (self::passingSlow($highest_priority)) {
774 // Are there waiting processes with a higher priority than the currently highest?
775 $result = dba::select(
778 ["`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority],
779 ['limit' => $limit, 'order' => ['priority', 'created']]
782 while ($id = dba::fetch($result)) {
787 $found = (count($ids) > 0);
790 // Give slower processes some processing time
791 $result = dba::select(
794 ["`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority],
795 ['limit' => $limit, 'order' => ['priority', 'created']]
798 while ($id = dba::fetch($result)) {
803 $found = (count($ids) > 0);
804 $passing_slow = $found;
808 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
810 $result = dba::select(
813 ["`executed` <= ? AND NOT `done`", NULL_DATE],
814 ['limit' => $limit, 'order' => ['priority', 'created']]
817 while ($id = dba::fetch($result)) {
822 $found = (count($ids) > 0);
826 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
827 array_unshift($ids, $condition);
828 dba::update('workerqueue', ['executed' => Temporal::convert(), 'pid' => $mypid], $ids);
835 * @brief Returns the next worker process
837 * @param boolean $passing_slow Returns if we had passed low priority processes
838 * @return string SQL statement
840 public static function workerProcess(&$passing_slow)
842 $stamp = (float)microtime(true);
844 // There can already be jobs for us in the queue.
845 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
846 if (DBM::is_result($r)) {
847 self::$db_duration += (microtime(true) - $stamp);
848 return dba::inArray($r);
852 $stamp = (float)microtime(true);
853 if (!Lock::set('poller_worker_process')) {
856 self::$lock_duration = (microtime(true) - $stamp);
858 $stamp = (float)microtime(true);
859 $found = self::findWorkerProcesses($passing_slow);
860 self::$db_duration += (microtime(true) - $stamp);
862 Lock::remove('poller_worker_process');
865 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
866 return dba::inArray($r);
872 * @brief Removes a workerqueue entry from the current process
875 public static function unclaimProcess()
879 dba::update('workerqueue', ['executed' => NULL_DATE, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
883 * @brief Call the front end worker
886 public static function callWorker()
888 if (!Config::get("system", "frontend_worker")) {
892 $url = System::baseUrl()."/worker";
893 Network::fetchUrl($url, false, $redirects, 1);
897 * @brief Call the front end worker if there aren't any active
900 public static function executeIfIdle()
902 if (!Config::get("system", "frontend_worker")) {
906 // Do we have "proc_open"? Then we can fork the worker
907 if (function_exists("proc_open")) {
908 // When was the last time that we called the worker?
909 // Less than one minute? Then we quit
910 if ((time() - Config::get("system", "worker_started")) < 60) {
914 Config::set("system", "worker_started", time());
916 // Do we have enough running workers? Then we quit here.
917 if (self::tooMuchWorkers()) {
918 // Cleaning dead processes
919 self::killStaleWorkers();
920 Process::deleteInactive();
927 logger('Call worker', LOGGER_DEBUG);
932 // We cannot execute background processes.
933 // We now run the processes from the frontend.
934 // This won't work with long running processes.
937 self::clearProcesses();
939 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
941 if ($workers["processes"] == 0) {
947 * @brief Removes long running worker processes
950 public static function clearProcesses()
952 $timeout = Config::get("system", "frontend_worker_timeout", 10);
954 /// @todo We should clean up the corresponding workerqueue entries as well
955 $condition = ["`created` < ? AND `command` = 'worker.php'",
956 Temporal::convert("now - ".$timeout." minutes")];
957 dba::delete('process', $condition);
961 * @brief Runs the cron processes
964 private static function runCron()
966 logger('Add cron entries', LOGGER_DEBUG);
968 // Check for spooled items
969 self::add(PRIORITY_HIGH, "SpoolPost");
971 // Run the cron job that calls all other jobs
972 self::add(PRIORITY_MEDIUM, "Cron");
974 // Run the cronhooks job separately from cron for being able to use a different timing
975 self::add(PRIORITY_MEDIUM, "CronHooks");
977 // Cleaning dead processes
978 self::killStaleWorkers();
984 public static function spawnWorker()
986 $args = ["scripts/worker.php", "no_cron"];
987 get_app()->proc_run($args);
991 * @brief Adds tasks to the worker queue
993 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
995 * next args are passed as $cmd command line
996 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
997 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
999 * @note $cmd and string args are surrounded with ""
1004 * @return boolean "false" if proc_run couldn't be executed
1006 public static function add($cmd)
1008 $proc_args = func_get_args();
1011 if (!count($proc_args)) {
1015 // Preserve the first parameter
1016 // It could contain a command, the priority or an parameter array
1017 // If we use the parameter array we have to protect it from the following function
1018 $run_parameter = array_shift($proc_args);
1020 // expand any arrays
1021 foreach ($proc_args as $arg) {
1022 if (is_array($arg)) {
1023 foreach ($arg as $n) {
1031 // Now we add the run parameters back to the array
1032 array_unshift($args, $run_parameter);
1034 $arr = ['args' => $args, 'run_cmd' => true];
1036 Addon::callHooks("proc_run", $arr);
1037 if (!$arr['run_cmd'] || !count($args)) {
1041 $priority = PRIORITY_MEDIUM;
1042 $dont_fork = Config::get("system", "worker_dont_fork");
1043 $created = Temporal::convert();
1045 if (is_int($run_parameter)) {
1046 $priority = $run_parameter;
1047 } elseif (is_array($run_parameter)) {
1048 if (isset($run_parameter['priority'])) {
1049 $priority = $run_parameter['priority'];
1051 if (isset($run_parameter['created'])) {
1052 $created = $run_parameter['created'];
1054 if (isset($run_parameter['dont_fork'])) {
1055 $dont_fork = $run_parameter['dont_fork'];
1062 $parameters = json_encode($argv);
1063 $found = dba::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1065 // Quit if there was a database error - a precaution for the update process to 3.5.3
1066 if (dba::errorNo() != 0) {
1071 dba::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1074 // Should we quit and wait for the worker to be called as a cronjob?
1079 // If there is a lock then we don't have to check for too much worker
1080 if (!Lock::set('poller_worker', 0)) {
1084 // If there are already enough workers running, don't fork another one
1085 $quit = self::tooMuchWorkers();
1086 Lock::remove('poller_worker');
1092 // Now call the worker to execute the jobs that we just added to the queue
1093 self::spawnWorker();
1099 * Log active processes into the "process" table
1101 * @brief Log active processes into the "process" table
1103 public static function startProcess()
1105 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1107 $command = basename($trace[0]['file']);
1109 Process::deleteInactive();
1111 Process::insert($command);
1115 * Remove the active process from the "process" table
1117 * @brief Remove the active process from the "process" table
1120 public static function endProcess()
1122 return Process::deleteByPid();