3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
8 use Friendica\Database\DBM;
9 use Friendica\Model\Process;
10 use Friendica\Util\DateTimeFormat;
11 use Friendica\Util\Network;
13 require_once 'include/dba.php';
16 * @file src/Core/Worker.php
18 * @brief Contains the class for the worker background job processing
22 * @brief Worker methods
26 private static $up_start;
27 private static $db_duration;
28 private static $last_update;
29 private static $lock_duration;
32 * @brief Processes the tasks that are in the workerqueue table
34 * @param boolean $run_cron Should the cron processes be executed?
37 public static function processQueue($run_cron = true)
41 self::$up_start = microtime(true);
43 // At first check the maximum load. We shouldn't continue with a high load
44 if ($a->maxload_reached()) {
45 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
49 // We now start the process. This is done after the load check since this could increase the load.
52 // Kill stale processes every 5 minutes
53 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
54 if (time() > ($last_cleanup + 300)) {
55 Config::set('system', 'worker_last_cleaned', time());
56 self::killStaleWorkers();
59 // Count active workers and compare them with a maximum value that depends on the load
60 if (self::tooMuchWorkers()) {
61 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
65 // Do we have too few memory?
66 if ($a->min_memory_reached()) {
67 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
71 // Possibly there are too much database connections
72 if (self::maxConnectionsReached()) {
73 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
77 // Possibly there are too much database processes that block the system
78 if ($a->max_processes_reached()) {
79 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
83 // Now we start additional cron processes if we should do so
90 // We fetch the next queue entry that is about to be executed
91 while ($r = self::workerProcess($passing_slow)) {
92 // When we are processing jobs with a lower priority, we don't refetch new jobs
93 // Otherwise fast jobs could wait behind slow ones and could be blocked.
94 $refetched = $passing_slow;
96 foreach ($r as $entry) {
97 // Assure that the priority is an integer value
98 $entry['priority'] = (int)$entry['priority'];
100 // The work will be done
101 if (!self::execute($entry)) {
102 logger('Process execution failed, quitting.', LOGGER_DEBUG);
106 // If possible we will fetch new jobs for this worker
107 if (!$refetched && Lock::acquire('worker_process', 0)) {
108 $stamp = (float)microtime(true);
109 $refetched = self::findWorkerProcesses($passing_slow);
110 self::$db_duration += (microtime(true) - $stamp);
111 Lock::release('worker_process');
115 // To avoid the quitting of multiple workers only one worker at a time will execute the check
116 if (Lock::acquire('worker', 0)) {
117 $stamp = (float)microtime(true);
118 // Count active workers and compare them with a maximum value that depends on the load
119 if (self::tooMuchWorkers()) {
120 logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
125 if ($a->min_memory_reached()) {
126 logger('Memory limit reached, quitting.', LOGGER_DEBUG);
129 Lock::release('worker');
130 self::$db_duration += (microtime(true) - $stamp);
133 // Quit the worker once every 5 minutes
134 if (time() > ($starttime + 300)) {
135 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
140 // Cleaning up. Possibly not needed, but it doesn't harm anything.
141 if (Config::get('system', 'worker_daemon_mode', false)) {
142 self::IPCSetJobState(false);
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 return dba::count('workerqueue', ["`executed` <= ? AND NOT `done`", NULL_DATE]);
158 * @brief Returns the highest priority in the worker queue that isn't executed
160 * @return integer Number of active worker processes
162 private static function highestPriority()
164 $condition = ["`executed` <= ? AND NOT `done`", NULL_DATE];
165 $workerqueue = dba::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
166 if (DBM::is_result($workerqueue)) {
167 return $workerqueue["priority"];
174 * @brief Returns if a process with the given priority is running
176 * @param integer $priority The priority that should be checked
178 * @return integer Is there a process running with that priority?
180 private static function processWithPriorityActive($priority)
182 $condition = ["`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE];
183 return dba::exists('workerqueue', $condition);
187 * @brief Execute a worker entry
189 * @param array $queue Workerqueue entry
191 * @return boolean "true" if further processing should be stopped
193 public static function execute($queue)
199 // Quit when in maintenance
200 if (Config::get('system', 'maintenance', false, true)) {
201 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
205 // Constantly check the number of parallel database processes
206 if ($a->max_processes_reached()) {
207 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
211 // Constantly check the number of available database connections to let the frontend be accessible at any time
212 if (self::maxConnectionsReached()) {
213 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
217 $argv = json_decode($queue["parameter"], true);
219 // Check for existance and validity of the include file
222 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
223 // We constantly update the "executed" date every minute to avoid being killed too soon
224 if (!isset(self::$last_update)) {
225 self::$last_update = strtotime($queue["executed"]);
228 $age = (time() - self::$last_update) / 60;
229 self::$last_update = time();
232 $stamp = (float)microtime(true);
233 dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
234 self::$db_duration += (microtime(true) - $stamp);
239 self::execFunction($queue, $include, $argv, true);
241 $stamp = (float)microtime(true);
242 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
243 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
245 self::$db_duration = (microtime(true) - $stamp);
250 // The script could be provided as full path or only with the function name
251 if ($include == basename($include)) {
252 $include = "include/".$include.".php";
255 if (!validate_include($include)) {
256 logger("Include file ".$argv[0]." is not valid!");
257 dba::delete('workerqueue', ['id' => $queue["id"]]);
261 require_once $include;
263 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
265 if (function_exists($funcname)) {
266 // We constantly update the "executed" date every minute to avoid being killed too soon
267 if (!isset(self::$last_update)) {
268 self::$last_update = strtotime($queue["executed"]);
271 $age = (time() - self::$last_update) / 60;
272 self::$last_update = time();
275 $stamp = (float)microtime(true);
276 dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
277 self::$db_duration += (microtime(true) - $stamp);
280 self::execFunction($queue, $funcname, $argv, false);
282 $stamp = (float)microtime(true);
283 if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
284 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
286 self::$db_duration = (microtime(true) - $stamp);
288 logger("Function ".$funcname." does not exist");
289 dba::delete('workerqueue', ['id' => $queue["id"]]);
296 * @brief Execute a function from the queue
298 * @param array $queue Workerqueue entry
299 * @param string $funcname name of the function
300 * @param array $argv Array of values to be passed to the function
301 * @param boolean $method_call boolean
304 private static function execFunction($queue, $funcname, $argv, $method_call)
310 $argc = count($argv);
312 $new_process_id = uniqid("wrk", true);
314 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
316 $stamp = (float)microtime(true);
318 // We use the callstack here to analyze the performance of executed worker entries.
319 // For this reason the variables have to be initialized.
320 if (Config::get("system", "profiler")) {
321 $a->performance["start"] = microtime(true);
322 $a->performance["database"] = 0;
323 $a->performance["database_write"] = 0;
324 $a->performance["cache"] = 0;
325 $a->performance["cache_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"];
391 if (Config::get("rendertime", "callstack")) {
392 if (isset($a->callstack["database"])) {
393 $o .= "\nDatabase Read:\n";
394 foreach ($a->callstack["database"] as $func => $time) {
395 $time = round($time, 3);
397 $o .= $func.": ".$time."\n";
401 if (isset($a->callstack["database_write"])) {
402 $o .= "\nDatabase Write:\n";
403 foreach ($a->callstack["database_write"] as $func => $time) {
404 $time = round($time, 3);
406 $o .= $func.": ".$time."\n";
410 if (isset($a->callstack["dache"])) {
411 $o .= "\nCache Read:\n";
412 foreach ($a->callstack["dache"] as $func => $time) {
413 $time = round($time, 3);
415 $o .= $func.": ".$time."\n";
419 if (isset($a->callstack["dache_write"])) {
420 $o .= "\nCache Write:\n";
421 foreach ($a->callstack["dache_write"] as $func => $time) {
422 $time = round($time, 3);
424 $o .= $func.": ".$time."\n";
428 if (isset($a->callstack["network"])) {
429 $o .= "\nNetwork:\n";
430 foreach ($a->callstack["network"] as $func => $time) {
431 $time = round($time, 3);
433 $o .= $func.": ".$time."\n";
440 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
441 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
442 number_format($a->performance["database"] - $a->performance["database_write"], 2),
443 number_format($a->performance["database_write"], 2),
444 number_format($a->performance["cache"], 2),
445 number_format($a->performance["cache_write"], 2),
446 number_format($a->performance["network"], 2),
447 number_format($a->performance["file"], 2),
448 number_format($duration - ($a->performance["database"]
449 + $a->performance["cache"] + $a->performance["cache_write"]
450 + $a->performance["network"] + $a->performance["file"]), 2),
451 number_format($duration, 2)
457 $cooldown = Config::get("system", "worker_cooldown", 0);
460 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
466 * @brief Checks if the number of database connections has reached a critical limit.
468 * @return bool Are more than 3/4 of the maximum connections used?
470 private static function maxConnectionsReached()
472 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
473 $max = Config::get("system", "max_connections");
475 // Fetch the percentage level where the worker will get active
476 $maxlevel = Config::get("system", "max_connections_level", 75);
479 // the maximum number of possible user connections can be a system variable
480 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
481 if (DBM::is_result($r)) {
484 // Or it can be granted. This overrides the system variable
485 $r = dba::p('SHOW GRANTS');
486 while ($grants = dba::fetch($r)) {
487 $grant = array_pop($grants);
488 if (stristr($grant, "GRANT USAGE ON")) {
489 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
497 // If $max is set we will use the processlist to determine the current number of connections
498 // The processlist only shows entries of the current user
500 $r = dba::p('SHOW PROCESSLIST');
501 $used = dba::num_rows($r);
504 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
506 $level = ($used / $max) * 100;
508 if ($level >= $maxlevel) {
509 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
514 // We will now check for the system values.
515 // This limit could be reached although the user limits are fine.
516 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
517 if (!DBM::is_result($r)) {
520 $max = intval($r["Value"]);
524 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
525 if (!DBM::is_result($r)) {
528 $used = intval($r["Value"]);
532 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
534 $level = $used / $max * 100;
536 if ($level < $maxlevel) {
539 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
544 * @brief fix the queue entry if the worker process died
547 private static function killStaleWorkers()
549 $entries = dba::select(
551 ['id', 'pid', 'executed', 'priority', 'parameter'],
552 ['`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE],
553 ['order' => ['priority', 'created']]
556 while ($entry = dba::fetch($entries)) {
557 if (!posix_kill($entry["pid"], 0)) {
560 ['executed' => NULL_DATE, 'pid' => 0],
561 ['id' => $entry["id"]]
564 // Kill long running processes
565 // Check if the priority is in a valid range
566 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
567 $entry["priority"] = PRIORITY_MEDIUM;
570 // Define the maximum durations
571 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
572 $max_duration = $max_duration_defaults[$entry["priority"]];
574 $argv = json_decode($entry["parameter"], true);
575 $argv[0] = basename($argv[0]);
577 // How long is the process already running?
578 $duration = (time() - strtotime($entry["executed"])) / 60;
579 if ($duration > $max_duration) {
580 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
581 posix_kill($entry["pid"], SIGTERM);
583 // We killed the stale process.
584 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
585 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
586 $new_priority = $entry["priority"];
587 if ($entry["priority"] == PRIORITY_HIGH) {
588 $new_priority = PRIORITY_MEDIUM;
589 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
590 $new_priority = PRIORITY_LOW;
591 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
592 $new_priority = PRIORITY_NEGLIGIBLE;
596 ['executed' => NULL_DATE, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
597 ['id' => $entry["id"]]
600 logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
607 * @brief Checks if the number of active workers exceeds the given limits
609 * @return bool Are there too much workers running?
611 public static function tooMuchWorkers()
613 $queues = Config::get("system", "worker_queues", 4);
615 $maxqueues = $queues;
617 $active = self::activeWorkers();
619 // Decrease the number of workers at higher load
620 $load = current_load();
622 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
624 /* Default exponent 3 causes queues to rapidly decrease as load increases.
625 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
626 * For some environments, this rapid decrease is not needed.
627 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
629 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
630 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
631 $queues = intval(ceil($slope * $maxqueues));
635 if (Config::get('system', 'worker_debug')) {
636 // Create a list of queue entries grouped by their priority
639 // Adding all processes with no workerqueue entry
641 "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
642 (SELECT id FROM `workerqueue`
643 WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
647 if ($process = dba::fetch($processes)) {
648 $listitem[0] = "0:".$process["running"];
650 dba::close($processes);
652 // Now adding all processes with workerqueue entries
653 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
654 while ($entry = dba::fetch($entries)) {
655 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
656 if ($process = dba::fetch($processes)) {
657 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
659 dba::close($processes);
661 dba::close($entries);
663 $intervals = [1, 10, 60];
664 $jobs_per_minute = [];
665 foreach ($intervals as $interval) {
666 $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
667 if ($job = dba::fetch($jobs)) {
668 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
672 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
675 $entries = self::totalEntries();
677 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
678 $top_priority = self::highestPriority();
679 $high_running = self::processWithPriorityActive($top_priority);
681 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
682 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
683 $queues = $active + 1;
687 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
689 // Are there fewer workers running as possible? Then fork a new one.
690 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
691 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
692 if (Config::get('system', 'worker_daemon_mode', false)) {
693 self::IPCSetJobState(true);
700 // if there are too much worker, we don't spawn a new one.
701 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
702 self::IPCSetJobState(false);
705 return $active > $queues;
709 * @brief Returns the number of active worker processes
711 * @return integer Number of active worker processes
713 private static function activeWorkers()
715 return dba::count('process', ['command' => 'Worker.php']);
719 * @brief Check if we should pass some slow processes
721 * When the active processes of the highest priority are using more than 2/3
722 * of all processes, we let pass slower processes.
724 * @param string $highest_priority Returns the currently highest priority
725 * @return bool We let pass a slower process than $highest_priority
727 private static function passingSlow(&$highest_priority)
729 $highest_priority = 0;
734 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
737 // No active processes at all? Fine
738 if (!DBM::is_result($r)) {
742 while ($line = dba::fetch($r)) {
743 $priorities[] = $line["priority"];
748 if (count($priorities) == 0) {
751 $highest_priority = min($priorities);
753 // The highest process is already the slowest one?
755 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
759 foreach ($priorities as $priority) {
760 if ($priority == $highest_priority) {
764 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
765 $passing_slow = (($high/count($priorities)) > (2/3));
768 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
770 return $passing_slow;
774 * @brief Find and claim the next worker process for us
776 * @param boolean $passing_slow Returns if we had passed low priority processes
777 * @return boolean Have we found something?
779 private static function findWorkerProcesses(&$passing_slow)
783 // Check if we should pass some low priority process
784 $highest_priority = 0;
786 $passing_slow = false;
788 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
789 // We decrease the limit with the number of entries left in the queue
790 $worker_queues = Config::get("system", "worker_queues", 4);
791 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
792 $lower_job_limit = $worker_queues * $queue_length * 2;
793 $jobs = self::totalEntries();
797 $slope = $queue_length / pow($lower_job_limit, $exponent);
798 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
800 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
802 if (self::passingSlow($highest_priority)) {
803 // Are there waiting processes with a higher priority than the currently highest?
804 $result = dba::select(
807 ["`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority],
808 ['limit' => $limit, 'order' => ['priority', 'created']]
811 while ($id = dba::fetch($result)) {
816 $found = (count($ids) > 0);
819 // Give slower processes some processing time
820 $result = dba::select(
823 ["`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority],
824 ['limit' => $limit, 'order' => ['priority', 'created']]
827 while ($id = dba::fetch($result)) {
832 $found = (count($ids) > 0);
833 $passing_slow = $found;
837 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
839 $result = dba::select(
842 ["`executed` <= ? AND NOT `done`", NULL_DATE],
843 ['limit' => $limit, 'order' => ['priority', 'created']]
846 while ($id = dba::fetch($result)) {
851 $found = (count($ids) > 0);
855 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
856 array_unshift($ids, $condition);
857 dba::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
864 * @brief Returns the next worker process
866 * @param boolean $passing_slow Returns if we had passed low priority processes
867 * @return string SQL statement
869 public static function workerProcess(&$passing_slow)
871 $stamp = (float)microtime(true);
873 // There can already be jobs for us in the queue.
874 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
875 if (DBM::is_result($r)) {
876 self::$db_duration += (microtime(true) - $stamp);
877 return dba::inArray($r);
881 $stamp = (float)microtime(true);
882 if (!Lock::acquire('worker_process')) {
885 self::$lock_duration = (microtime(true) - $stamp);
887 $stamp = (float)microtime(true);
888 $found = self::findWorkerProcesses($passing_slow);
889 self::$db_duration += (microtime(true) - $stamp);
891 Lock::release('worker_process');
894 $r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
895 return dba::inArray($r);
901 * @brief Removes a workerqueue entry from the current process
904 public static function unclaimProcess()
908 dba::update('workerqueue', ['executed' => NULL_DATE, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
912 * @brief Call the front end worker
915 public static function callWorker()
917 if (!Config::get("system", "frontend_worker")) {
921 $url = System::baseUrl()."/worker";
922 Network::fetchUrl($url, false, $redirects, 1);
926 * @brief Call the front end worker if there aren't any active
929 public static function executeIfIdle()
931 if (!Config::get("system", "frontend_worker")) {
935 // Do we have "proc_open"? Then we can fork the worker
936 if (function_exists("proc_open")) {
937 // When was the last time that we called the worker?
938 // Less than one minute? Then we quit
939 if ((time() - Config::get("system", "worker_started")) < 60) {
943 Config::set("system", "worker_started", time());
945 // Do we have enough running workers? Then we quit here.
946 if (self::tooMuchWorkers()) {
947 // Cleaning dead processes
948 self::killStaleWorkers();
949 Process::deleteInactive();
956 logger('Call worker', LOGGER_DEBUG);
961 // We cannot execute background processes.
962 // We now run the processes from the frontend.
963 // This won't work with long running processes.
966 self::clearProcesses();
968 $workers = self::activeWorkers();
976 * @brief Removes long running worker processes
979 public static function clearProcesses()
981 $timeout = Config::get("system", "frontend_worker_timeout", 10);
983 /// @todo We should clean up the corresponding workerqueue entries as well
984 $condition = ["`created` < ? AND `command` = 'worker.php'",
985 DateTimeFormat::utc("now - ".$timeout." minutes")];
986 dba::delete('process', $condition);
990 * @brief Runs the cron processes
993 private static function runCron()
995 logger('Add cron entries', LOGGER_DEBUG);
997 // Check for spooled items
998 self::add(PRIORITY_HIGH, "SpoolPost");
1000 // Run the cron job that calls all other jobs
1001 self::add(PRIORITY_MEDIUM, "Cron");
1003 // Cleaning dead processes
1004 self::killStaleWorkers();
1008 * @brief Spawns a new worker
1011 public static function spawnWorker($do_cron = false)
1013 $args = ["bin/worker.php"];
1016 $args[] = "no_cron";
1019 get_app()->proc_run($args);
1021 // after spawning we have to remove the flag.
1022 if (Config::get('system', 'worker_daemon_mode', false)) {
1023 self::IPCSetJobState(false);
1028 * @brief Adds tasks to the worker queue
1030 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1032 * next args are passed as $cmd command line
1033 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1034 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1036 * @note $cmd and string args are surrounded with ""
1041 * @return boolean "false" if proc_run couldn't be executed
1043 public static function add($cmd)
1045 $args = func_get_args();
1047 if (!count($args)) {
1051 $arr = ['args' => $args, 'run_cmd' => true];
1053 Addon::callHooks("proc_run", $arr);
1054 if (!$arr['run_cmd'] || !count($args)) {
1058 $priority = PRIORITY_MEDIUM;
1059 $dont_fork = Config::get("system", "worker_dont_fork", false);
1060 $created = DateTimeFormat::utcNow();
1062 $run_parameter = array_shift($args);
1064 if (is_int($run_parameter)) {
1065 $priority = $run_parameter;
1066 } elseif (is_array($run_parameter)) {
1067 if (isset($run_parameter['priority'])) {
1068 $priority = $run_parameter['priority'];
1070 if (isset($run_parameter['created'])) {
1071 $created = $run_parameter['created'];
1073 if (isset($run_parameter['dont_fork'])) {
1074 $dont_fork = $run_parameter['dont_fork'];
1078 $parameters = json_encode($args);
1079 $found = dba::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1081 // Quit if there was a database error - a precaution for the update process to 3.5.3
1082 if (dba::errorNo() != 0) {
1087 dba::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1090 // Should we quit and wait for the worker to be called as a cronjob?
1095 // If there is a lock then we don't have to check for too much worker
1096 if (!Lock::acquire('worker', 0)) {
1100 // If there are already enough workers running, don't fork another one
1101 $quit = self::tooMuchWorkers();
1102 Lock::release('worker');
1108 // We tell the daemon that a new job entry exists
1109 if (Config::get('system', 'worker_daemon_mode', false)) {
1110 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1114 // Now call the worker to execute the jobs that we just added to the queue
1115 self::spawnWorker();
1121 * Log active processes into the "process" table
1123 * @brief Log active processes into the "process" table
1125 public static function startProcess()
1127 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1129 $command = basename($trace[0]['file']);
1131 Process::deleteInactive();
1133 Process::insert($command);
1137 * Remove the active process from the "process" table
1139 * @brief Remove the active process from the "process" table
1142 public static function endProcess()
1144 return Process::deleteByPid();
1148 * Set the flag if some job is waiting
1150 * @brief Set the flag if some job is waiting
1151 * @param boolean $jobs Is there a waiting job?
1153 public static function IPCSetJobState($jobs)
1155 dba::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1159 * Checks if some worker job waits to be executed
1161 * @brief Checks if some worker job waits to be executed
1164 public static function IPCJobsExists()
1166 $row = dba::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1168 // When we don't have a row, no job is running
1169 if (!DBM::is_result($row)) {
1173 return (bool)$row['jobs'];