3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
7 use Friendica\Core\Config;
8 use Friendica\Core\System;
9 use Friendica\Database\DBM;
10 use Friendica\Model\Process;
11 use Friendica\Util\Lock;
15 require_once 'include/dba.php';
18 * @file src/Core/Worker.php
20 * @brief Contains the class for the worker background job processing
24 * @brief Worker methods
28 private static $up_start;
29 private static $db_duration;
30 private static $last_update;
31 private static $lock_duration;
34 * @brief Processes the tasks that are in the workerqueue table
36 * @param boolean $run_cron Should the cron processes be executed?
39 public static function processQueue($run_cron = true)
43 self::$up_start = microtime(true);
45 // At first check the maximum load. We shouldn't continue with a high load
46 if ($a->maxload_reached()) {
47 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
51 // We now start the process. This is done after the load check since this could increase the load.
54 // Kill stale processes every 5 minutes
55 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
56 if (time() > ($last_cleanup + 300)) {
57 Config::set('system', 'poller_last_cleaned', time());
58 self::killStaleWorkers();
61 // Count active workers and compare them with a maximum value that depends on the load
62 if (self::tooMuchWorkers()) {
63 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
67 // Do we have too few memory?
68 if ($a->min_memory_reached()) {
69 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
73 // Possibly there are too much database connections
74 if (self::maxConnectionsReached()) {
75 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
79 // Possibly there are too much database processes that block the system
80 if ($a->max_processes_reached()) {
81 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
85 // Now we start additional cron processes if we should do so
92 // We fetch the next queue entry that is about to be executed
93 while ($r = self::workerProcess($passing_slow)) {
94 // When we are processing jobs with a lower priority, we don't refetch new jobs
95 // Otherwise fast jobs could wait behind slow ones and could be blocked.
96 $refetched = $passing_slow;
98 foreach ($r as $entry) {
99 // Assure that the priority is an integer value
100 $entry['priority'] = (int)$entry['priority'];
102 // The work will be done
103 if (!self::execute($entry)) {
104 logger('Process execution failed, quitting.', LOGGER_DEBUG);
108 // If possible we will fetch new jobs for this worker
109 if (!$refetched && Lock::set('poller_worker_process', 0)) {
110 $stamp = (float)microtime(true);
111 $refetched = self::findWorkerProcesses($passing_slow);
112 self::$db_duration += (microtime(true) - $stamp);
113 Lock::remove('poller_worker_process');
117 // To avoid the quitting of multiple workers only one worker at a time will execute the check
118 if (Lock::set('poller_worker', 0)) {
119 $stamp = (float)microtime(true);
120 // Count active workers and compare them with a maximum value that depends on the load
121 if (self::tooMuchWorkers()) {
122 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
127 if ($a->min_memory_reached()) {
128 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
131 Lock::remove('poller_worker');
132 self::$db_duration += (microtime(true) - $stamp);
135 // Quit the worker once every 5 minutes
136 if (time() > ($starttime + 300)) {
137 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
141 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
145 * @brief Returns the number of non executed entries in the worker queue
147 * @return integer Number of non executed entries in the worker queue
149 private static function totalEntries()
151 $s = dba::fetch_first("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done`", NULL_DATE);
152 if (DBM::is_result($s)) {
160 * @brief Returns the highest priority in the worker queue that isn't executed
162 * @return integer Number of active worker processes
164 private static function highestPriority()
166 $condition = ["`executed` <= ? AND NOT `done`", NULL_DATE];
167 $workerqueue = dba::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
168 if (DBM::is_result($workerqueue)) {
169 return $workerqueue["priority"];
176 * @brief Returns if a process with the given priority is running
178 * @param integer $priority The priority that should be checked
180 * @return integer Is there a process running with that priority?
182 private static function processWithPriorityActive($priority)
184 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE];
185 return dba::exists('workerqueue', $condition);
189 * @brief Execute a worker entry
191 * @param array $queue Workerqueue entry
193 * @return boolean "true" if further processing should be stopped
195 public static function execute($queue)
201 // Quit when in maintenance
202 if (Config::get('system', 'maintenance', true)) {
203 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
207 // Constantly check the number of parallel database processes
208 if ($a->max_processes_reached()) {
209 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
213 // Constantly check the number of available database connections to let the frontend be accessible at any time
214 if (self::maxConnectionsReached()) {
215 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
219 $argv = json_decode($queue["parameter"]);
221 // Check for existance and validity of the include file
224 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
225 // We constantly update the "executed" date every minute to avoid being killed too soon
226 if (!isset(self::$last_update)) {
227 self::$last_update = strtotime($queue["executed"]);
230 $age = (time() - self::$last_update) / 60;
231 self::$last_update = time();
234 $stamp = (float)microtime(true);
235 dba::update('workerqueue', ['executed' => datetime_convert()], ['pid' => $mypid, 'done' => false]);
236 self::$db_duration += (microtime(true) - $stamp);
241 self::execFunction($queue, $include, $argv, true);
243 $stamp = (float)microtime(true);
244 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
245 Config::set('system', 'last_poller_execution', datetime_convert());
247 self::$db_duration = (microtime(true) - $stamp);
252 // The script could be provided as full path or only with the function name
253 if ($include == basename($include)) {
254 $include = "include/".$include.".php";
257 if (!validate_include($include)) {
258 logger("Include file ".$argv[0]." is not valid!");
259 dba::delete('workerqueue', ['id' => $queue["id"]]);
263 require_once $include;
265 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
267 if (function_exists($funcname)) {
268 // We constantly update the "executed" date every minute to avoid being killed too soon
269 if (!isset(self::$last_update)) {
270 self::$last_update = strtotime($queue["executed"]);
273 $age = (time() - self::$last_update) / 60;
274 self::$last_update = time();
277 $stamp = (float)microtime(true);
278 dba::update('workerqueue', ['executed' => datetime_convert()], ['pid' => $mypid, 'done' => false]);
279 self::$db_duration += (microtime(true) - $stamp);
282 self::execFunction($queue, $funcname, $argv, false);
284 $stamp = (float)microtime(true);
285 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
286 Config::set('system', 'last_poller_execution', datetime_convert());
288 self::$db_duration = (microtime(true) - $stamp);
290 logger("Function ".$funcname." does not exist");
291 dba::delete('workerqueue', ['id' => $queue["id"]]);
298 * @brief Execute a function from the queue
300 * @param array $queue Workerqueue entry
301 * @param string $funcname name of the function
302 * @param array $argv Array of values to be passed to the function
303 * @param boolean $method_call boolean
306 private static function execFunction($queue, $funcname, $argv, $method_call)
312 $argc = count($argv);
314 $new_process_id = uniqid("wrk", true);
316 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
318 $stamp = (float)microtime(true);
320 // We use the callstack here to analyze the performance of executed worker entries.
321 // For this reason the variables have to be initialized.
322 if (Config::get("system", "profiler")) {
323 $a->performance["start"] = microtime(true);
324 $a->performance["database"] = 0;
325 $a->performance["database_write"] = 0;
326 $a->performance["network"] = 0;
327 $a->performance["file"] = 0;
328 $a->performance["rendering"] = 0;
329 $a->performance["parser"] = 0;
330 $a->performance["marktime"] = 0;
331 $a->performance["markstart"] = microtime(true);
335 // For better logging create a new process id for every worker call
336 // But preserve the old one for the worker
337 $old_process_id = $a->process_id;
338 $a->process_id = $new_process_id;
341 $up_duration = number_format(microtime(true) - self::$up_start, 3);
343 // Reset global data to avoid interferences
347 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
349 $funcname($argv, $argc);
352 $a->process_id = $old_process_id;
355 $duration = number_format(microtime(true) - $stamp, 3);
357 self::$up_start = microtime(true);
359 /* With these values we can analyze how effective the worker is.
360 * The database and rest time should be low since this is the unproductive time.
361 * The execution time is the productive time.
362 * By changing parameters like the maximum number of workers we can check the effectivness.
365 'DB: '.number_format(self::$db_duration, 2).
366 ' - Lock: '.number_format(self::$lock_duration, 2).
367 ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
368 ' - Execution: '.number_format($duration, 2),
372 self::$lock_duration = 0;
374 if ($duration > 3600) {
375 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
376 } elseif ($duration > 600) {
377 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
378 } elseif ($duration > 300) {
379 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
380 } elseif ($duration > 120) {
381 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
384 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
386 // Write down the performance values into the log
387 if (Config::get("system", "profiler")) {
388 $duration = microtime(true)-$a->performance["start"];
390 if (Config::get("rendertime", "callstack")) {
391 if (isset($a->callstack["database"])) {
392 $o = "\nDatabase Read:\n";
393 foreach ($a->callstack["database"] as $func => $time) {
394 $time = round($time, 3);
396 $o .= $func.": ".$time."\n";
400 if (isset($a->callstack["database_write"])) {
401 $o .= "\nDatabase Write:\n";
402 foreach ($a->callstack["database_write"] as $func => $time) {
403 $time = round($time, 3);
405 $o .= $func.": ".$time."\n";
409 if (isset($a->callstack["network"])) {
410 $o .= "\nNetwork:\n";
411 foreach ($a->callstack["network"] as $func => $time) {
412 $time = round($time, 3);
414 $o .= $func.": ".$time."\n";
423 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
424 "DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
425 number_format($a->performance["database"] - $a->performance["database_write"], 2),
426 number_format($a->performance["database_write"], 2),
427 number_format($a->performance["network"], 2),
428 number_format($a->performance["file"], 2),
429 number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
430 number_format($duration, 2)
436 $cooldown = Config::get("system", "worker_cooldown", 0);
439 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
445 * @brief Checks if the number of database connections has reached a critical limit.
447 * @return bool Are more than 3/4 of the maximum connections used?
449 private static function maxConnectionsReached()
451 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
452 $max = Config::get("system", "max_connections");
454 // Fetch the percentage level where the worker will get active
455 $maxlevel = Config::get("system", "max_connections_level", 75);
458 // the maximum number of possible user connections can be a system variable
459 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
460 if (DBM::is_result($r)) {
463 // Or it can be granted. This overrides the system variable
464 $r = dba::p('SHOW GRANTS');
465 while ($grants = dba::fetch($r)) {
466 $grant = array_pop($grants);
467 if (stristr($grant, "GRANT USAGE ON")) {
468 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
476 // If $max is set we will use the processlist to determine the current number of connections
477 // The processlist only shows entries of the current user
479 $r = dba::p('SHOW PROCESSLIST');
480 $used = dba::num_rows($r);
483 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
485 $level = ($used / $max) * 100;
487 if ($level >= $maxlevel) {
488 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
493 // We will now check for the system values.
494 // This limit could be reached although the user limits are fine.
495 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
496 if (!DBM::is_result($r)) {
499 $max = intval($r["Value"]);
503 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
504 if (!DBM::is_result($r)) {
507 $used = intval($r["Value"]);
511 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
513 $level = $used / $max * 100;
515 if ($level < $maxlevel) {
518 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
523 * @brief fix the queue entry if the worker process died
526 private static function killStaleWorkers()
528 $entries = dba::select(
530 ['id', 'pid', 'executed', 'priority', 'parameter'],
531 ['`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE],
532 ['order' => ['priority', 'created']]
535 while ($entry = dba::fetch($entries)) {
536 if (!posix_kill($entry["pid"], 0)) {
539 ['executed' => NULL_DATE, 'pid' => 0],
540 ['id' => $entry["id"]]
543 // Kill long running processes
544 // Check if the priority is in a valid range
545 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
546 $entry["priority"] = PRIORITY_MEDIUM;
549 // Define the maximum durations
550 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
551 $max_duration = $max_duration_defaults[$entry["priority"]];
553 $argv = json_decode($entry["parameter"]);
554 $argv[0] = basename($argv[0]);
556 // How long is the process already running?
557 $duration = (time() - strtotime($entry["executed"])) / 60;
558 if ($duration > $max_duration) {
559 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
560 posix_kill($entry["pid"], SIGTERM);
562 // We killed the stale process.
563 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
564 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
565 if ($entry["priority"] == PRIORITY_HIGH) {
566 $new_priority = PRIORITY_MEDIUM;
567 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
568 $new_priority = PRIORITY_LOW;
569 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
570 $new_priority = PRIORITY_NEGLIGIBLE;
574 ['executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0],
575 ['id' => $entry["id"]]
578 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
585 * @brief Checks if the number of active workers exceeds the given limits
587 * @return bool Are there too much workers running?
589 public static function tooMuchWorkers()
591 $queues = Config::get("system", "worker_queues", 4);
593 $maxqueues = $queues;
595 $active = self::activeWorkers();
597 // Decrease the number of workers at higher load
598 $load = current_load();
600 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
602 $maxworkers = $queues;
604 // Some magical mathemathics to reduce the workers
606 $slope = $maxworkers / pow($maxsysload, $exponent);
607 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
610 if (Config::get('system', 'worker_debug')) {
611 // Create a list of queue entries grouped by their priority
614 // Adding all processes with no workerqueue entry
616 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
617 (SELECT id FROM `workerqueue`
618 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
622 if ($process = dba::fetch($processes)) {
623 $listitem[0] = "0:".$process["running"];
625 dba::close($processes);
627 // Now adding all processes with workerqueue entries
628 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
629 while ($entry = dba::fetch($entries)) {
630 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
631 if ($process = dba::fetch($processes)) {
632 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
634 dba::close($processes);
636 dba::close($entries);
638 $intervals = [1, 10, 60];
639 $jobs_per_minute = [];
640 foreach ($intervals as $interval) {
641 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
642 if ($job = dba::fetch($jobs)) {
643 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
647 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
650 $entries = self::totalEntries();
652 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
653 $top_priority = self::highestPriority();
654 $high_running = self::processWithPriorityActive($top_priority);
656 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
657 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
658 $queues = $active + 1;
662 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
664 // Are there fewer workers running as possible? Then fork a new one.
665 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
666 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
671 return $active >= $queues;
675 * @brief Returns the number of active worker processes
677 * @return integer Number of active worker processes
679 private static function activeWorkers()
681 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
683 return $workers["processes"];
687 * @brief Check if we should pass some slow processes
689 * When the active processes of the highest priority are using more than 2/3
690 * of all processes, we let pass slower processes.
692 * @param string $highest_priority Returns the currently highest priority
693 * @return bool We let pass a slower process than $highest_priority
695 private static function passingSlow(&$highest_priority)
697 $highest_priority = 0;
702 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
705 // No active processes at all? Fine
706 if (!DBM::is_result($r)) {
710 while ($line = dba::fetch($r)) {
711 $priorities[] = $line["priority"];
716 if (count($priorities) == 0) {
719 $highest_priority = min($priorities);
721 // The highest process is already the slowest one?
723 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
727 foreach ($priorities as $priority) {
728 if ($priority == $highest_priority) {
732 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
733 $passing_slow = (($high/count($priorities)) > (2/3));
736 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
738 return $passing_slow;
742 * @brief Find and claim the next worker process for us
744 * @param boolean $passing_slow Returns if we had passed low priority processes
745 * @return boolean Have we found something?
747 private static function findWorkerProcesses(&$passing_slow)
751 // Check if we should pass some low priority process
752 $highest_priority = 0;
754 $passing_slow = false;
756 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
757 // We decrease the limit with the number of entries left in the queue
758 $worker_queues = Config::get("system", "worker_queues", 4);
759 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
760 $lower_job_limit = $worker_queues * $queue_length * 2;
761 $jobs = self::totalEntries();
765 $slope = $queue_length / pow($lower_job_limit, $exponent);
766 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
768 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
770 if (self::passingSlow($highest_priority)) {
771 // Are there waiting processes with a higher priority than the currently highest?
772 $result = dba::select(
775 ["`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority],
776 ['limit' => $limit, 'order' => ['priority', 'created']]
779 while ($id = dba::fetch($result)) {
784 $found = (count($ids) > 0);
787 // Give slower processes some processing time
788 $result = dba::select(
791 ["`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority],
792 ['limit' => $limit, 'order' => ['priority', 'created']]
795 while ($id = dba::fetch($result)) {
800 $found = (count($ids) > 0);
801 $passing_slow = $found;
805 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
807 $result = dba::select(
810 ["`executed` <= ? AND NOT `done`", NULL_DATE],
811 ['limit' => $limit, 'order' => ['priority', 'created']]
814 while ($id = dba::fetch($result)) {
819 $found = (count($ids) > 0);
823 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
824 array_unshift($ids, $condition);
825 dba::update('workerqueue', ['executed' => datetime_convert(), 'pid' => $mypid], $ids);
832 * @brief Returns the next worker process
834 * @param boolean $passing_slow Returns if we had passed low priority processes
835 * @return string SQL statement
837 public static function workerProcess(&$passing_slow)
839 $stamp = (float)microtime(true);
841 // There can already be jobs for us in the queue.
842 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
843 if (DBM::is_result($r)) {
844 self::$db_duration += (microtime(true) - $stamp);
845 return dba::inArray($r);
849 $stamp = (float)microtime(true);
850 if (!Lock::set('poller_worker_process')) {
853 self::$lock_duration = (microtime(true) - $stamp);
855 $stamp = (float)microtime(true);
856 $found = self::findWorkerProcesses($passing_slow);
857 self::$db_duration += (microtime(true) - $stamp);
859 Lock::remove('poller_worker_process');
862 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
863 return dba::inArray($r);
869 * @brief Removes a workerqueue entry from the current process
872 public static function unclaimProcess()
876 dba::update('workerqueue', ['executed' => NULL_DATE, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
880 * @brief Call the front end worker
883 public static function callWorker()
885 if (!Config::get("system", "frontend_worker")) {
889 $url = System::baseUrl()."/worker";
890 fetch_url($url, false, $redirects, 1);
894 * @brief Call the front end worker if there aren't any active
897 public static function executeIfIdle()
899 if (!Config::get("system", "frontend_worker")) {
903 // Do we have "proc_open"? Then we can fork the worker
904 if (function_exists("proc_open")) {
905 // When was the last time that we called the worker?
906 // Less than one minute? Then we quit
907 if ((time() - Config::get("system", "worker_started")) < 60) {
911 Config::set("system", "worker_started", time());
913 // Do we have enough running workers? Then we quit here.
914 if (self::tooMuchWorkers()) {
915 // Cleaning dead processes
916 self::killStaleWorkers();
917 Process::deleteInactive();
924 logger('Call worker', LOGGER_DEBUG);
929 // We cannot execute background processes.
930 // We now run the processes from the frontend.
931 // This won't work with long running processes.
934 self::clearProcesses();
936 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
938 if ($workers["processes"] == 0) {
944 * @brief Removes long running worker processes
947 public static function clearProcesses()
949 $timeout = Config::get("system", "frontend_worker_timeout", 10);
951 /// @todo We should clean up the corresponding workerqueue entries as well
952 $condition = ["`created` < ? AND `command` = 'worker.php'",
953 datetime_convert('UTC', 'UTC', "now - ".$timeout." minutes")];
954 dba::delete('process', $condition);
958 * @brief Runs the cron processes
961 private static function runCron()
963 logger('Add cron entries', LOGGER_DEBUG);
965 // Check for spooled items
966 self::add(PRIORITY_HIGH, "SpoolPost");
968 // Run the cron job that calls all other jobs
969 self::add(PRIORITY_MEDIUM, "Cron");
971 // Run the cronhooks job separately from cron for being able to use a different timing
972 self::add(PRIORITY_MEDIUM, "CronHooks");
974 // Cleaning dead processes
975 self::killStaleWorkers();
981 public static function spawnWorker()
983 $args = ["scripts/worker.php", "no_cron"];
984 get_app()->proc_run($args);
988 * @brief Adds tasks to the worker queue
990 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
992 * next args are passed as $cmd command line
993 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
994 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
996 * @note $cmd and string args are surrounded with ""
1001 * @return boolean "false" if proc_run couldn't be executed
1003 public static function add($cmd)
1005 $proc_args = func_get_args();
1008 if (!count($proc_args)) {
1012 // Preserve the first parameter
1013 // It could contain a command, the priority or an parameter array
1014 // If we use the parameter array we have to protect it from the following function
1015 $run_parameter = array_shift($proc_args);
1017 // expand any arrays
1018 foreach ($proc_args as $arg) {
1019 if (is_array($arg)) {
1020 foreach ($arg as $n) {
1028 // Now we add the run parameters back to the array
1029 array_unshift($args, $run_parameter);
1031 $arr = ['args' => $args, 'run_cmd' => true];
1033 call_hooks("proc_run", $arr);
1034 if (!$arr['run_cmd'] || !count($args)) {
1038 $priority = PRIORITY_MEDIUM;
1039 $dont_fork = Config::get("system", "worker_dont_fork");
1040 $created = datetime_convert();
1042 if (is_int($run_parameter)) {
1043 $priority = $run_parameter;
1044 } elseif (is_array($run_parameter)) {
1045 if (isset($run_parameter['priority'])) {
1046 $priority = $run_parameter['priority'];
1048 if (isset($run_parameter['created'])) {
1049 $created = $run_parameter['created'];
1051 if (isset($run_parameter['dont_fork'])) {
1052 $dont_fork = $run_parameter['dont_fork'];
1059 $parameters = json_encode($argv);
1060 $found = dba::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1062 // Quit if there was a database error - a precaution for the update process to 3.5.3
1063 if (dba::errorNo() != 0) {
1068 dba::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1071 // Should we quit and wait for the worker to be called as a cronjob?
1076 // If there is a lock then we don't have to check for too much worker
1077 if (!Lock::set('poller_worker', 0)) {
1081 // If there are already enough workers running, don't fork another one
1082 $quit = self::tooMuchWorkers();
1083 Lock::remove('poller_worker');
1089 // Now call the worker to execute the jobs that we just added to the queue
1090 self::spawnWorker();
1096 * Log active processes into the "process" table
1098 * @brief Log active processes into the "process" table
1100 public static function startProcess()
1102 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1104 $command = basename($trace[0]['file']);
1106 Process::deleteInactive();
1108 Process::insert($command);
1112 * Remove the active process from the "process" table
1114 * @brief Remove the active process from the "process" table
1117 public static function endProcess()
1119 return Process::deleteByPid();