3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Model\Process;
10 use Friendica\Util\DateTimeFormat;
11 use Friendica\Util\Network;
14 * @file src/Core/Worker.php
16 * @brief Contains the class for the worker background job processing
20 * @brief Worker methods
24 private static $up_start;
25 private static $db_duration = 0;
26 private static $db_duration_count = 0;
27 private static $db_duration_write = 0;
28 private static $db_duration_stat = 0;
29 private static $lock_duration = 0;
30 private static $last_update;
33 * @brief Processes the tasks that are in the workerqueue table
35 * @param boolean $run_cron Should the cron processes be executed?
37 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
39 public static function processQueue($run_cron = true)
43 // Ensure that all "strtotime" operations do run timezone independent
44 date_default_timezone_set('UTC');
46 self::$up_start = microtime(true);
48 // At first check the maximum load. We shouldn't continue with a high load
49 if ($a->isMaxLoadReached()) {
50 Logger::log('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', 'worker_last_cleaned', 0);
59 if (time() > ($last_cleanup + 300)) {
60 Config::set('system', 'worker_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::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
70 // Do we have too few memory?
71 if ($a->isMinMemoryReached()) {
72 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
76 // Possibly there are too much database connections
77 if (self::maxConnectionsReached()) {
78 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
82 // Possibly there are too much database processes that block the system
83 if ($a->isMaxProcessesReached()) {
84 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
88 // Now we start additional cron processes if we should do so
98 // We fetch the next queue entry that is about to be executed
99 while ($r = self::workerProcess($passing_slow, $entries, $deferred)) {
100 // When we are processing jobs with a lower priority, we don't refetch new jobs
101 // Otherwise fast jobs could wait behind slow ones and could be blocked.
102 $refetched = $passing_slow;
104 foreach ($r as $entry) {
105 // Assure that the priority is an integer value
106 $entry['priority'] = (int)$entry['priority'];
108 // The work will be done
109 if (!self::execute($entry)) {
110 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
114 // If possible we will fetch new jobs for this worker
116 $entries = self::totalEntries();
117 $deferred = self::deferredEntries();
118 if (Lock::acquire('worker_process', 0)) {
119 $refetched = self::findWorkerProcesses($passing_slow, $entries, $deferred);
120 Lock::release('worker_process');
125 // To avoid the quitting of multiple workers only one worker at a time will execute the check
126 if (Lock::acquire('worker', 0)) {
127 // Count active workers and compare them with a maximum value that depends on the load
128 if (self::tooMuchWorkers($entries, $deferred)) {
129 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
130 Lock::release('worker');
135 if ($a->isMinMemoryReached()) {
136 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
137 Lock::release('worker');
140 Lock::release('worker');
143 // Quit the worker once every 5 minutes
144 if (time() > ($starttime + 300)) {
145 Logger::log('Process lifetime reached, quitting.', Logger::DEBUG);
150 // Cleaning up. Possibly not needed, but it doesn't harm anything.
151 if (Config::get('system', 'worker_daemon_mode', false)) {
152 self::IPCSetJobState(false);
154 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
158 * @brief Check if non executed tasks do exist in the worker queue
160 * @return boolean Returns "true" if tasks are existing
163 private static function entriesExists()
165 $stamp = (float)microtime(true);
166 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
167 self::$db_duration += (microtime(true) - $stamp);
172 * @brief Returns the number of deferred entries in the worker queue
174 * @return integer Number of deferred entries in the worker queue
177 private static function deferredEntries()
179 $stamp = (float)microtime(true);
180 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` > ?", DateTimeFormat::utcNow()]);
181 self::$db_duration += (microtime(true) - $stamp);
182 self::$db_duration_count += (microtime(true) - $stamp);
187 * @brief Returns the number of non executed entries in the worker queue
189 * @return integer Number of non executed entries in the worker queue
192 private static function totalEntries()
194 $stamp = (float)microtime(true);
195 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
196 self::$db_duration += (microtime(true) - $stamp);
197 self::$db_duration_count += (microtime(true) - $stamp);
202 * @brief Returns the highest priority in the worker queue that isn't executed
204 * @return integer Number of active worker processes
207 private static function highestPriority()
209 $stamp = (float)microtime(true);
210 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
211 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
212 self::$db_duration += (microtime(true) - $stamp);
213 if (DBA::isResult($workerqueue)) {
214 return $workerqueue["priority"];
221 * @brief Returns if a process with the given priority is running
223 * @param integer $priority The priority that should be checked
225 * @return integer Is there a process running with that priority?
228 private static function processWithPriorityActive($priority)
230 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
231 return DBA::exists('workerqueue', $condition);
235 * @brief Execute a worker entry
237 * @param array $queue Workerqueue entry
239 * @return boolean "true" if further processing should be stopped
240 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
242 public static function execute($queue)
248 // Quit when in maintenance
249 if (Config::get('system', 'maintenance', false, true)) {
250 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
254 // Constantly check the number of parallel database processes
255 if ($a->isMaxProcessesReached()) {
256 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
260 // Constantly check the number of available database connections to let the frontend be accessible at any time
261 if (self::maxConnectionsReached()) {
262 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
266 $argv = json_decode($queue["parameter"], true);
268 // Check for existance and validity of the include file
271 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
272 // We constantly update the "executed" date every minute to avoid being killed too soon
273 if (!isset(self::$last_update)) {
274 self::$last_update = strtotime($queue["executed"]);
277 $age = (time() - self::$last_update) / 60;
278 self::$last_update = time();
281 $stamp = (float)microtime(true);
282 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
283 self::$db_duration += (microtime(true) - $stamp);
284 self::$db_duration_write += (microtime(true) - $stamp);
289 self::execFunction($queue, $include, $argv, true);
291 $stamp = (float)microtime(true);
292 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
293 if (DBA::update('workerqueue', ['done' => true], $condition)) {
294 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
296 self::$db_duration = (microtime(true) - $stamp);
297 self::$db_duration_write += (microtime(true) - $stamp);
302 // The script could be provided as full path or only with the function name
303 if ($include == basename($include)) {
304 $include = "include/".$include.".php";
307 if (!validate_include($include)) {
308 Logger::log("Include file ".$argv[0]." is not valid!");
309 $stamp = (float)microtime(true);
310 DBA::delete('workerqueue', ['id' => $queue["id"]]);
311 self::$db_duration = (microtime(true) - $stamp);
312 self::$db_duration_write += (microtime(true) - $stamp);
316 require_once $include;
318 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
320 if (function_exists($funcname)) {
321 // We constantly update the "executed" date every minute to avoid being killed too soon
322 if (!isset(self::$last_update)) {
323 self::$last_update = strtotime($queue["executed"]);
326 $age = (time() - self::$last_update) / 60;
327 self::$last_update = time();
330 $stamp = (float)microtime(true);
331 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
332 self::$db_duration += (microtime(true) - $stamp);
333 self::$db_duration_write += (microtime(true) - $stamp);
336 self::execFunction($queue, $funcname, $argv, false);
338 $stamp = (float)microtime(true);
339 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
340 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
342 self::$db_duration = (microtime(true) - $stamp);
343 self::$db_duration_write += (microtime(true) - $stamp);
345 Logger::log("Function ".$funcname." does not exist");
346 $stamp = (float)microtime(true);
347 DBA::delete('workerqueue', ['id' => $queue["id"]]);
348 self::$db_duration = (microtime(true) - $stamp);
349 self::$db_duration_write += (microtime(true) - $stamp);
356 * @brief Execute a function from the queue
358 * @param array $queue Workerqueue entry
359 * @param string $funcname name of the function
360 * @param array $argv Array of values to be passed to the function
361 * @param boolean $method_call boolean
363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
365 private static function execFunction($queue, $funcname, $argv, $method_call)
371 $argc = count($argv);
373 // Currently deactivated, since the new logger doesn't support this
374 //$new_process_id = System::processID("wrk");
375 $new_process_id = '';
377 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
379 $stamp = (float)microtime(true);
381 // We use the callstack here to analyze the performance of executed worker entries.
382 // For this reason the variables have to be initialized.
383 if (Config::get("system", "profiler")) {
384 $a->performance["start"] = microtime(true);
385 $a->performance["database"] = 0;
386 $a->performance["database_write"] = 0;
387 $a->performance["cache"] = 0;
388 $a->performance["cache_write"] = 0;
389 $a->performance["network"] = 0;
390 $a->performance["file"] = 0;
391 $a->performance["rendering"] = 0;
392 $a->performance["parser"] = 0;
393 $a->performance["marktime"] = 0;
394 $a->performance["markstart"] = microtime(true);
398 // For better logging create a new process id for every worker call
399 // But preserve the old one for the worker
400 $old_process_id = $a->process_id;
401 $a->process_id = $new_process_id;
404 $up_duration = microtime(true) - self::$up_start;
406 // Reset global data to avoid interferences
410 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
412 $funcname($argv, $argc);
415 $a->process_id = $old_process_id;
418 $duration = (microtime(true) - $stamp);
420 /* With these values we can analyze how effective the worker is.
421 * The database and rest time should be low since this is the unproductive time.
422 * The execution time is the productive time.
423 * By changing parameters like the maximum number of workers we can check the effectivness.
426 'DB: '.number_format(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 4).
427 ' - DB-Count: '.number_format(self::$db_duration_count, 4).
428 ' - DB-Stat: '.number_format(self::$db_duration_stat, 4).
429 ' - DB-Write: '.number_format(self::$db_duration_write, 4).
430 ' - Lock: '.number_format(self::$lock_duration, 4).
431 ' - Rest: '.number_format(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 4).
432 ' - Execution: '.number_format($duration, 4),
436 self::$up_start = microtime(true);
437 self::$db_duration = 0;
438 self::$db_duration_count = 0;
439 self::$db_duration_stat = 0;
440 self::$db_duration_write = 0;
441 self::$lock_duration = 0;
443 if ($duration > 3600) {
444 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
445 } elseif ($duration > 600) {
446 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
447 } elseif ($duration > 300) {
448 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
449 } elseif ($duration > 120) {
450 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
453 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".number_format($duration, 4)." seconds. Process PID: ".$new_process_id);
455 // Write down the performance values into the log
456 if (Config::get("system", "profiler")) {
457 $duration = microtime(true)-$a->performance["start"];
460 if (Config::get("rendertime", "callstack")) {
461 if (isset($a->callstack["database"])) {
462 $o .= "\nDatabase Read:\n";
463 foreach ($a->callstack["database"] as $func => $time) {
464 $time = round($time, 3);
466 $o .= $func.": ".$time."\n";
470 if (isset($a->callstack["database_write"])) {
471 $o .= "\nDatabase Write:\n";
472 foreach ($a->callstack["database_write"] as $func => $time) {
473 $time = round($time, 3);
475 $o .= $func.": ".$time."\n";
479 if (isset($a->callstack["dache"])) {
480 $o .= "\nCache Read:\n";
481 foreach ($a->callstack["dache"] as $func => $time) {
482 $time = round($time, 3);
484 $o .= $func.": ".$time."\n";
488 if (isset($a->callstack["dache_write"])) {
489 $o .= "\nCache Write:\n";
490 foreach ($a->callstack["dache_write"] as $func => $time) {
491 $time = round($time, 3);
493 $o .= $func.": ".$time."\n";
497 if (isset($a->callstack["network"])) {
498 $o .= "\nNetwork:\n";
499 foreach ($a->callstack["network"] as $func => $time) {
500 $time = round($time, 3);
502 $o .= $func.": ".$time."\n";
509 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
510 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
511 number_format($a->performance["database"] - $a->performance["database_write"], 2),
512 number_format($a->performance["database_write"], 2),
513 number_format($a->performance["cache"], 2),
514 number_format($a->performance["cache_write"], 2),
515 number_format($a->performance["network"], 2),
516 number_format($a->performance["file"], 2),
517 number_format($duration - ($a->performance["database"]
518 + $a->performance["cache"] + $a->performance["cache_write"]
519 + $a->performance["network"] + $a->performance["file"]), 2),
520 number_format($duration, 2)
526 $cooldown = Config::get("system", "worker_cooldown", 0);
529 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
535 * @brief Checks if the number of database connections has reached a critical limit.
537 * @return bool Are more than 3/4 of the maximum connections used?
538 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
540 private static function maxConnectionsReached()
542 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
543 $max = Config::get("system", "max_connections");
545 // Fetch the percentage level where the worker will get active
546 $maxlevel = Config::get("system", "max_connections_level", 75);
549 // the maximum number of possible user connections can be a system variable
550 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
551 if (DBA::isResult($r)) {
554 // Or it can be granted. This overrides the system variable
555 $stamp = (float)microtime(true);
556 $r = DBA::p('SHOW GRANTS');
557 self::$db_duration += (microtime(true) - $stamp);
558 while ($grants = DBA::fetch($r)) {
559 $grant = array_pop($grants);
560 if (stristr($grant, "GRANT USAGE ON")) {
561 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
569 // If $max is set we will use the processlist to determine the current number of connections
570 // The processlist only shows entries of the current user
572 $stamp = (float)microtime(true);
573 $r = DBA::p('SHOW PROCESSLIST');
574 self::$db_duration += (microtime(true) - $stamp);
575 $used = DBA::numRows($r);
578 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
580 $level = ($used / $max) * 100;
582 if ($level >= $maxlevel) {
583 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
588 // We will now check for the system values.
589 // This limit could be reached although the user limits are fine.
590 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
591 if (!DBA::isResult($r)) {
594 $max = intval($r["Value"]);
598 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
599 if (!DBA::isResult($r)) {
602 $used = intval($r["Value"]);
606 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
608 $level = $used / $max * 100;
610 if ($level < $maxlevel) {
613 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
618 * @brief fix the queue entry if the worker process died
622 private static function killStaleWorkers()
624 $stamp = (float)microtime(true);
625 $entries = DBA::select(
627 ['id', 'pid', 'executed', 'priority', 'parameter'],
628 ['NOT `done` AND `pid` != 0'],
629 ['order' => ['priority', 'created']]
631 self::$db_duration += (microtime(true) - $stamp);
633 while ($entry = DBA::fetch($entries)) {
634 if (!posix_kill($entry["pid"], 0)) {
635 $stamp = (float)microtime(true);
638 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
639 ['id' => $entry["id"]]
641 self::$db_duration += (microtime(true) - $stamp);
642 self::$db_duration_write += (microtime(true) - $stamp);
644 // Kill long running processes
645 // Check if the priority is in a valid range
646 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
647 $entry["priority"] = PRIORITY_MEDIUM;
650 // Define the maximum durations
651 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
652 $max_duration = $max_duration_defaults[$entry["priority"]];
654 $argv = json_decode($entry["parameter"], true);
655 $argv[0] = basename($argv[0]);
657 // How long is the process already running?
658 $duration = (time() - strtotime($entry["executed"])) / 60;
659 if ($duration > $max_duration) {
660 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
661 posix_kill($entry["pid"], SIGTERM);
663 // We killed the stale process.
664 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
665 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
666 $new_priority = $entry["priority"];
667 if ($entry["priority"] == PRIORITY_HIGH) {
668 $new_priority = PRIORITY_MEDIUM;
669 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
670 $new_priority = PRIORITY_LOW;
671 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
672 $new_priority = PRIORITY_NEGLIGIBLE;
674 $stamp = (float)microtime(true);
677 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
678 ['id' => $entry["id"]]
680 self::$db_duration += (microtime(true) - $stamp);
681 self::$db_duration_write += (microtime(true) - $stamp);
683 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", Logger::DEBUG);
690 * @brief Checks if the number of active workers exceeds the given limits
692 * @param integer $entries Total number of queue entries
693 * @param integer $deferred Number of deferred queue entries
695 * @return bool Are there too much workers running?
696 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
698 public static function tooMuchWorkers($entries = 0, $deferred = 0)
700 $queues = Config::get("system", "worker_queues", 4);
702 $maxqueues = $queues;
704 $active = self::activeWorkers();
706 // Decrease the number of workers at higher load
707 $load = System::currentLoad();
709 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
711 /* Default exponent 3 causes queues to rapidly decrease as load increases.
712 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
713 * For some environments, this rapid decrease is not needed.
714 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
716 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
717 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
718 $queues = intval(ceil($slope * $maxqueues));
722 if (Config::get('system', 'worker_jpm')) {
723 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
724 $jobs_per_minute = [];
725 foreach ($intervals as $interval) {
726 if ($interval == 0) {
729 $interval = (int)$interval;
732 $stamp = (float)microtime(true);
733 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
734 self::$db_duration += (microtime(true) - $stamp);
735 self::$db_duration_stat += (microtime(true) - $stamp);
736 if ($job = DBA::fetch($jobs)) {
737 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
741 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
744 // Create a list of queue entries grouped by their priority
745 $listitem = [0 => ''];
747 $idle_workers = $active;
749 if (empty($deferred) && empty($entries)) {
750 $deferred = self::deferredEntries();
751 $entries = max(self::totalEntries() - $deferred, 0);
754 $waiting_processes = max(0, $entries - $deferred);
756 if (Config::get('system', 'worker_debug')) {
757 $waiting_processes = 0;
758 // Now adding all processes with workerqueue entries
759 $stamp = (float)microtime(true);
760 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
761 self::$db_duration += (microtime(true) - $stamp);
762 self::$db_duration_stat += (microtime(true) - $stamp);
763 while ($entry = DBA::fetch($jobs)) {
764 $stamp = (float)microtime(true);
765 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
766 self::$db_duration += (microtime(true) - $stamp);
767 self::$db_duration_stat += (microtime(true) - $stamp);
768 if ($process = DBA::fetch($processes)) {
769 $idle_workers -= $process["running"];
770 $waiting_processes += $entry["entries"];
771 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
773 DBA::close($processes);
777 $stamp = (float)microtime(true);
778 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` GROUP BY `priority` ORDER BY `priority`");
779 self::$db_duration += (microtime(true) - $stamp);
781 while ($entry = DBA::fetch($jobs)) {
782 $idle_workers -= $entry["running"];
783 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
788 $listitem[0] = "0:" . max(0, $idle_workers);
790 $processlist .= ' ('.implode(', ', $listitem).')';
792 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && self::entriesExists() && ($active >= $queues)) {
793 $top_priority = self::highestPriority();
794 $high_running = self::processWithPriorityActive($top_priority);
796 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
797 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
798 $queues = $active + 1;
802 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
804 // Are there fewer workers running as possible? Then fork a new one.
805 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
806 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
807 if (Config::get('system', 'worker_daemon_mode', false)) {
808 self::IPCSetJobState(true);
815 // if there are too much worker, we don't spawn a new one.
816 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
817 self::IPCSetJobState(false);
820 return $active > $queues;
824 * @brief Returns the number of active worker processes
826 * @return integer Number of active worker processes
829 private static function activeWorkers()
831 $stamp = (float)microtime(true);
832 $count = DBA::count('process', ['command' => 'Worker.php']);
833 self::$db_duration += (microtime(true) - $stamp);
837 public static function nextProcess()
839 $priority = self::nextPriority();
840 if (empty($priority)) {
841 Logger::log('No tasks found', Logger::DEBUG);
845 if ($priority <= PRIORITY_MEDIUM) {
846 $limit = Config::get('system', 'worker_fetch_limit', 1);
852 $stamp = (float)microtime(true);
853 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
854 $tasks = DBA::select('workerqueue', ['id'], $condition, ['limit' => $limit, 'order' => ['created']]);
855 self::$db_duration += (microtime(true) - $stamp);
856 while ($task = DBA::fetch($tasks)) {
857 $ids[] = $task['id'];
861 Logger::log('Found task(s) ' . implode(', ', $ids) . ' with priority ' .$priority, Logger::DEBUG);
865 public static function nextPriority()
868 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
869 foreach ($priorities as $priority) {
870 $stamp = (float)microtime(true);
871 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
872 $waiting[$priority] = true;
874 self::$db_duration += (microtime(true) - $stamp);
877 if (!empty($waiting[PRIORITY_CRITICAL])) {
878 return PRIORITY_CRITICAL;
883 $stamp = (float)microtime(true);
884 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
885 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
886 WHERE NOT `done` GROUP BY `priority`");
887 self::$db_duration += (microtime(true) - $stamp);
888 while ($process = DBA::fetch($processes)) {
889 $running[$process['priority']] = $process['running'];
890 $running_total += $process['running'];
892 DBA::close($processes);
894 foreach ($priorities as $priority) {
895 if (!empty($waiting[$priority]) && empty($running[$priority])) {
896 Logger::log('No running worker found with priority ' . $priority . ' - assigning it.', Logger::DEBUG);
901 $active = max(self::activeWorkers(), $running_total);
902 $priorities = max(count($waiting), count($running));
906 for ($i = 1; $i <= $priorities; ++$i) {
907 $total += pow($i, $exponent);
911 for ($i = 1; $i <= $priorities; ++$i) {
912 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
916 foreach ($running as $priority => $workers) {
917 if ($workers < $limit[$i++]) {
918 Logger::log('Priority ' . $priority . ' has got ' . $workers . ' workers out of a limit of ' . $limit[$i - 1], Logger::DEBUG);
923 if (!empty($waiting)) {
924 $priority = array_shift(array_keys($waiting));
925 Logger::log('No underassigned priority found, now taking the highest priority (' . $priority . ').', Logger::DEBUG);
933 * @brief Find and claim the next worker process for us
935 * @param boolean $passing_slow Returns if we had passed low priority processes
936 * @param integer $entries Total number of queue entries
937 * @param integer $deferred Number of deferred queue entries
938 * @return boolean Have we found something?
939 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
941 private static function findWorkerProcesses(&$passing_slow, $entries, $deferred)
945 $passing_slow = false;
947 $ids = self::nextProcess();
948 $found = (count($ids) > 0);
950 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
952 $stamp = (float)microtime(true);
953 $result = DBA::select(
956 ["`pid` = 0 AND NOT `done` AND `next_try` < ?",
957 DateTimeFormat::utcNow()],
958 ['limit' => 1, 'order' => ['priority', 'created']]
960 self::$db_duration += (microtime(true) - $stamp);
962 while ($id = DBA::fetch($result)) {
967 $found = (count($ids) > 0);
971 $stamp = (float)microtime(true);
972 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
973 array_unshift($ids, $condition);
974 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
975 self::$db_duration += (microtime(true) - $stamp);
976 self::$db_duration_write += (microtime(true) - $stamp);
983 * @brief Returns the next worker process
985 * @param boolean $passing_slow Returns if we had passed low priority processes
986 * @param integer $entries Returns total number of queue entries
987 * @param integer $deferred Returns number of deferred queue entries
989 * @return string SQL statement
990 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
992 public static function workerProcess(&$passing_slow, &$entries, &$deferred)
994 // There can already be jobs for us in the queue.
995 $stamp = (float)microtime(true);
996 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
997 self::$db_duration += (microtime(true) - $stamp);
998 if (DBA::isResult($r)) {
999 return DBA::toArray($r);
1003 // Counting the rows outside the lock reduces the lock time
1004 $entries = self::totalEntries();
1005 $deferred = self::deferredEntries();
1007 $stamp = (float)microtime(true);
1008 if (!Lock::acquire('worker_process')) {
1011 self::$lock_duration += (microtime(true) - $stamp);
1013 $found = self::findWorkerProcesses($passing_slow, $entries, $deferred);
1015 Lock::release('worker_process');
1018 $stamp = (float)microtime(true);
1019 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1020 self::$db_duration += (microtime(true) - $stamp);
1021 return DBA::toArray($r);
1027 * @brief Removes a workerqueue entry from the current process
1029 * @throws \Exception
1031 public static function unclaimProcess()
1033 $mypid = getmypid();
1035 $stamp = (float)microtime(true);
1036 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1037 self::$db_duration += (microtime(true) - $stamp);
1038 self::$db_duration_write += (microtime(true) - $stamp);
1042 * @brief Call the front end worker
1044 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1046 public static function callWorker()
1048 if (!Config::get("system", "frontend_worker")) {
1052 $url = System::baseUrl()."/worker";
1053 Network::fetchUrl($url, false, $redirects, 1);
1057 * @brief Call the front end worker if there aren't any active
1059 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1061 public static function executeIfIdle()
1063 if (!Config::get("system", "frontend_worker")) {
1067 // Do we have "proc_open"? Then we can fork the worker
1068 if (function_exists("proc_open")) {
1069 // When was the last time that we called the worker?
1070 // Less than one minute? Then we quit
1071 if ((time() - Config::get("system", "worker_started")) < 60) {
1075 Config::set("system", "worker_started", time());
1077 // Do we have enough running workers? Then we quit here.
1078 if (self::tooMuchWorkers()) {
1079 // Cleaning dead processes
1080 self::killStaleWorkers();
1081 Process::deleteInactive();
1088 Logger::log('Call worker', Logger::DEBUG);
1089 self::spawnWorker();
1093 // We cannot execute background processes.
1094 // We now run the processes from the frontend.
1095 // This won't work with long running processes.
1098 self::clearProcesses();
1100 $workers = self::activeWorkers();
1102 if ($workers == 0) {
1108 * @brief Removes long running worker processes
1110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1112 public static function clearProcesses()
1114 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1116 /// @todo We should clean up the corresponding workerqueue entries as well
1117 $stamp = (float)microtime(true);
1118 $condition = ["`created` < ? AND `command` = 'worker.php'",
1119 DateTimeFormat::utc("now - ".$timeout." minutes")];
1120 DBA::delete('process', $condition);
1121 self::$db_duration = (microtime(true) - $stamp);
1122 self::$db_duration_write += (microtime(true) - $stamp);
1126 * @brief Runs the cron processes
1128 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1130 private static function runCron()
1132 Logger::log('Add cron entries', Logger::DEBUG);
1134 // Check for spooled items
1135 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1137 // Run the cron job that calls all other jobs
1138 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1140 // Cleaning dead processes
1141 self::killStaleWorkers();
1145 * @brief Spawns a new worker
1146 * @param bool $do_cron
1148 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1150 public static function spawnWorker($do_cron = false)
1152 $command = 'bin/worker.php';
1154 $args = ['no_cron' => !$do_cron];
1156 get_app()->proc_run($command, $args);
1158 // after spawning we have to remove the flag.
1159 if (Config::get('system', 'worker_daemon_mode', false)) {
1160 self::IPCSetJobState(false);
1165 * @brief Adds tasks to the worker queue
1167 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1169 * next args are passed as $cmd command line
1170 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1171 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1173 * @return boolean "false" if proc_run couldn't be executed
1174 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1175 * @note $cmd and string args are surrounded with ""
1181 public static function add($cmd)
1183 $args = func_get_args();
1185 if (!count($args)) {
1189 $arr = ['args' => $args, 'run_cmd' => true];
1191 Hook::callAll("proc_run", $arr);
1192 if (!$arr['run_cmd'] || !count($args)) {
1196 $priority = PRIORITY_MEDIUM;
1197 $dont_fork = Config::get("system", "worker_dont_fork", false);
1198 $created = DateTimeFormat::utcNow();
1199 $force_priority = false;
1201 $run_parameter = array_shift($args);
1203 if (is_int($run_parameter)) {
1204 $priority = $run_parameter;
1205 } elseif (is_array($run_parameter)) {
1206 if (isset($run_parameter['priority'])) {
1207 $priority = $run_parameter['priority'];
1209 if (isset($run_parameter['created'])) {
1210 $created = $run_parameter['created'];
1212 if (isset($run_parameter['dont_fork'])) {
1213 $dont_fork = $run_parameter['dont_fork'];
1215 if (isset($run_parameter['force_priority'])) {
1216 $force_priority = $run_parameter['force_priority'];
1220 $parameters = json_encode($args);
1221 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1223 // Quit if there was a database error - a precaution for the update process to 3.5.3
1224 if (DBA::errorNo() != 0) {
1229 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1230 } elseif ($force_priority) {
1231 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1234 // Should we quit and wait for the worker to be called as a cronjob?
1239 // If there is a lock then we don't have to check for too much worker
1240 if (!Lock::acquire('worker', 0)) {
1244 // If there are already enough workers running, don't fork another one
1245 $quit = self::tooMuchWorkers();
1246 Lock::release('worker');
1252 // We tell the daemon that a new job entry exists
1253 if (Config::get('system', 'worker_daemon_mode', false)) {
1254 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1258 // Now call the worker to execute the jobs that we just added to the queue
1259 self::spawnWorker();
1265 * Defers the current worker entry
1267 public static function defer()
1269 if (empty(BaseObject::getApp()->queue)) {
1273 $queue = BaseObject::getApp()->queue;
1275 $retrial = $queue['retrial'];
1277 $priority = $queue['priority'];
1279 if ($retrial > 14) {
1280 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1284 // Calculate the delay until the next trial
1285 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1286 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1288 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1289 $priority = PRIORITY_MEDIUM;
1290 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1291 $priority = PRIORITY_LOW;
1292 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1293 $priority = PRIORITY_NEGLIGIBLE;
1296 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1298 $stamp = (float)microtime(true);
1299 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1300 DBA::update('workerqueue', $fields, ['id' => $id]);
1301 self::$db_duration += (microtime(true) - $stamp);
1302 self::$db_duration_write += (microtime(true) - $stamp);
1306 * Log active processes into the "process" table
1308 * @brief Log active processes into the "process" table
1310 public static function startProcess()
1312 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1314 $command = basename($trace[0]['file']);
1316 Process::deleteInactive();
1318 Process::insert($command);
1322 * Remove the active process from the "process" table
1324 * @brief Remove the active process from the "process" table
1326 * @throws \Exception
1328 public static function endProcess()
1330 return Process::deleteByPid();
1334 * Set the flag if some job is waiting
1336 * @brief Set the flag if some job is waiting
1337 * @param boolean $jobs Is there a waiting job?
1338 * @throws \Exception
1340 public static function IPCSetJobState($jobs)
1342 $stamp = (float)microtime(true);
1343 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1344 self::$db_duration += (microtime(true) - $stamp);
1345 self::$db_duration_write += (microtime(true) - $stamp);
1349 * Checks if some worker job waits to be executed
1351 * @brief Checks if some worker job waits to be executed
1353 * @throws \Exception
1355 public static function IPCJobsExists()
1357 $stamp = (float)microtime(true);
1358 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1359 self::$db_duration += (microtime(true) - $stamp);
1361 // When we don't have a row, no job is running
1362 if (!DBA::isResult($row)) {
1366 return (bool)$row['jobs'];