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();
280 Logger::alert('last_update', ['age' => $age, 'last_update' => self::$last_update]);
283 $stamp = (float)microtime(true);
284 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
285 self::$db_duration += (microtime(true) - $stamp);
286 self::$db_duration_write += (microtime(true) - $stamp);
291 self::execFunction($queue, $include, $argv, true);
293 $stamp = (float)microtime(true);
294 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
295 if (DBA::update('workerqueue', ['done' => true], $condition)) {
296 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
298 self::$db_duration = (microtime(true) - $stamp);
299 self::$db_duration_write += (microtime(true) - $stamp);
304 // The script could be provided as full path or only with the function name
305 if ($include == basename($include)) {
306 $include = "include/".$include.".php";
309 if (!validate_include($include)) {
310 Logger::log("Include file ".$argv[0]." is not valid!");
311 $stamp = (float)microtime(true);
312 DBA::delete('workerqueue', ['id' => $queue["id"]]);
313 self::$db_duration = (microtime(true) - $stamp);
314 self::$db_duration_write += (microtime(true) - $stamp);
318 require_once $include;
320 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
322 if (function_exists($funcname)) {
323 // We constantly update the "executed" date every minute to avoid being killed too soon
324 if (!isset(self::$last_update)) {
325 self::$last_update = strtotime($queue["executed"]);
328 $age = (time() - self::$last_update) / 60;
329 self::$last_update = time();
332 $stamp = (float)microtime(true);
333 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
334 self::$db_duration += (microtime(true) - $stamp);
335 self::$db_duration_write += (microtime(true) - $stamp);
338 self::execFunction($queue, $funcname, $argv, false);
340 $stamp = (float)microtime(true);
341 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
342 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
344 self::$db_duration = (microtime(true) - $stamp);
345 self::$db_duration_write += (microtime(true) - $stamp);
347 Logger::log("Function ".$funcname." does not exist");
348 $stamp = (float)microtime(true);
349 DBA::delete('workerqueue', ['id' => $queue["id"]]);
350 self::$db_duration = (microtime(true) - $stamp);
351 self::$db_duration_write += (microtime(true) - $stamp);
358 * @brief Execute a function from the queue
360 * @param array $queue Workerqueue entry
361 * @param string $funcname name of the function
362 * @param array $argv Array of values to be passed to the function
363 * @param boolean $method_call boolean
365 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
367 private static function execFunction($queue, $funcname, $argv, $method_call)
373 $argc = count($argv);
375 // Currently deactivated, since the new logger doesn't support this
376 //$new_process_id = System::processID("wrk");
377 $new_process_id = '';
379 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
381 $stamp = (float)microtime(true);
383 // We use the callstack here to analyze the performance of executed worker entries.
384 // For this reason the variables have to be initialized.
385 $a->getProfiler()->reset();
387 // For better logging create a new process id for every worker call
388 // But preserve the old one for the worker
389 $old_process_id = $a->process_id;
390 $a->process_id = $new_process_id;
393 $up_duration = microtime(true) - self::$up_start;
395 // Reset global data to avoid interferences
399 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
401 $funcname($argv, $argc);
404 $a->process_id = $old_process_id;
407 $duration = (microtime(true) - $stamp);
409 /* With these values we can analyze how effective the worker is.
410 * The database and rest time should be low since this is the unproductive time.
411 * The execution time is the productive time.
412 * By changing parameters like the maximum number of workers we can check the effectivness.
415 'DB: '.number_format(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 4).
416 ' - DB-Count: '.number_format(self::$db_duration_count, 4).
417 ' - DB-Stat: '.number_format(self::$db_duration_stat, 4).
418 ' - DB-Write: '.number_format(self::$db_duration_write, 4).
419 ' - Lock: '.number_format(self::$lock_duration, 4).
420 ' - Rest: '.number_format(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 4).
421 ' - Execution: '.number_format($duration, 4),
425 self::$up_start = microtime(true);
426 self::$db_duration = 0;
427 self::$db_duration_count = 0;
428 self::$db_duration_stat = 0;
429 self::$db_duration_write = 0;
430 self::$lock_duration = 0;
432 if ($duration > 3600) {
433 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
434 } elseif ($duration > 600) {
435 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
436 } elseif ($duration > 300) {
437 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
438 } elseif ($duration > 120) {
439 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
442 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".number_format($duration, 4)." seconds. Process PID: ".$new_process_id);
444 $a->getProfiler()->saveLog($a->getLogger(), "ID " . $queue["id"] . ": " . $funcname);
446 $cooldown = Config::get("system", "worker_cooldown", 0);
449 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
455 * @brief Checks if the number of database connections has reached a critical limit.
457 * @return bool Are more than 3/4 of the maximum connections used?
458 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
460 private static function maxConnectionsReached()
462 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
463 $max = Config::get("system", "max_connections");
465 // Fetch the percentage level where the worker will get active
466 $maxlevel = Config::get("system", "max_connections_level", 75);
469 // the maximum number of possible user connections can be a system variable
470 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
471 if (DBA::isResult($r)) {
474 // Or it can be granted. This overrides the system variable
475 $stamp = (float)microtime(true);
476 $r = DBA::p('SHOW GRANTS');
477 self::$db_duration += (microtime(true) - $stamp);
478 while ($grants = DBA::fetch($r)) {
479 $grant = array_pop($grants);
480 if (stristr($grant, "GRANT USAGE ON")) {
481 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
489 // If $max is set we will use the processlist to determine the current number of connections
490 // The processlist only shows entries of the current user
492 $stamp = (float)microtime(true);
493 $r = DBA::p('SHOW PROCESSLIST');
494 self::$db_duration += (microtime(true) - $stamp);
495 $used = DBA::numRows($r);
498 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
500 $level = ($used / $max) * 100;
502 if ($level >= $maxlevel) {
503 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
508 // We will now check for the system values.
509 // This limit could be reached although the user limits are fine.
510 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
511 if (!DBA::isResult($r)) {
514 $max = intval($r["Value"]);
518 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
519 if (!DBA::isResult($r)) {
522 $used = intval($r["Value"]);
526 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
528 $level = $used / $max * 100;
530 if ($level < $maxlevel) {
533 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
538 * @brief fix the queue entry if the worker process died
542 private static function killStaleWorkers()
544 $stamp = (float)microtime(true);
545 $entries = DBA::select(
547 ['id', 'pid', 'executed', 'priority', 'parameter'],
548 ['NOT `done` AND `pid` != 0'],
549 ['order' => ['priority', 'created']]
551 self::$db_duration += (microtime(true) - $stamp);
553 while ($entry = DBA::fetch($entries)) {
554 if (!posix_kill($entry["pid"], 0)) {
555 $stamp = (float)microtime(true);
558 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
559 ['id' => $entry["id"]]
561 self::$db_duration += (microtime(true) - $stamp);
562 self::$db_duration_write += (microtime(true) - $stamp);
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::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") 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;
594 $stamp = (float)microtime(true);
597 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
598 ['id' => $entry["id"]]
600 self::$db_duration += (microtime(true) - $stamp);
601 self::$db_duration_write += (microtime(true) - $stamp);
603 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);
610 * @brief Checks if the number of active workers exceeds the given limits
612 * @param integer $entries Total number of queue entries
613 * @param integer $deferred Number of deferred queue entries
615 * @return bool Are there too much workers running?
616 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
618 public static function tooMuchWorkers($entries = 0, $deferred = 0)
620 $queues = Config::get("system", "worker_queues", 4);
622 $maxqueues = $queues;
624 $active = self::activeWorkers();
626 // Decrease the number of workers at higher load
627 $load = System::currentLoad();
629 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
631 /* Default exponent 3 causes queues to rapidly decrease as load increases.
632 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
633 * For some environments, this rapid decrease is not needed.
634 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
636 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
637 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
638 $queues = intval(ceil($slope * $maxqueues));
642 if (Config::get('system', 'worker_jpm')) {
643 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
644 $jobs_per_minute = [];
645 foreach ($intervals as $interval) {
646 if ($interval == 0) {
649 $interval = (int)$interval;
652 $stamp = (float)microtime(true);
653 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
654 self::$db_duration += (microtime(true) - $stamp);
655 self::$db_duration_stat += (microtime(true) - $stamp);
656 if ($job = DBA::fetch($jobs)) {
657 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
661 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
664 // Create a list of queue entries grouped by their priority
665 $listitem = [0 => ''];
667 $idle_workers = $active;
669 if (empty($deferred) && empty($entries)) {
670 $deferred = self::deferredEntries();
671 $entries = max(self::totalEntries() - $deferred, 0);
674 $waiting_processes = max(0, $entries - $deferred);
676 if (Config::get('system', 'worker_debug')) {
677 $waiting_processes = 0;
678 // Now adding all processes with workerqueue entries
679 $stamp = (float)microtime(true);
680 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
681 self::$db_duration += (microtime(true) - $stamp);
682 self::$db_duration_stat += (microtime(true) - $stamp);
683 while ($entry = DBA::fetch($jobs)) {
684 $stamp = (float)microtime(true);
685 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
686 self::$db_duration += (microtime(true) - $stamp);
687 self::$db_duration_stat += (microtime(true) - $stamp);
688 if ($process = DBA::fetch($processes)) {
689 $idle_workers -= $process["running"];
690 $waiting_processes += $entry["entries"];
691 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
693 DBA::close($processes);
697 $stamp = (float)microtime(true);
698 $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`");
699 self::$db_duration += (microtime(true) - $stamp);
701 while ($entry = DBA::fetch($jobs)) {
702 $idle_workers -= $entry["running"];
703 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
708 $listitem[0] = "0:" . max(0, $idle_workers);
710 $processlist .= ' ('.implode(', ', $listitem).')';
712 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && self::entriesExists() && ($active >= $queues)) {
713 $top_priority = self::highestPriority();
714 $high_running = self::processWithPriorityActive($top_priority);
716 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
717 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
718 $queues = $active + 1;
722 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
724 // Are there fewer workers running as possible? Then fork a new one.
725 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
726 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
727 if (Config::get('system', 'worker_daemon_mode', false)) {
728 self::IPCSetJobState(true);
735 // if there are too much worker, we don't spawn a new one.
736 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
737 self::IPCSetJobState(false);
740 return $active > $queues;
744 * @brief Returns the number of active worker processes
746 * @return integer Number of active worker processes
749 private static function activeWorkers()
751 $stamp = (float)microtime(true);
752 $count = DBA::count('process', ['command' => 'Worker.php']);
753 self::$db_duration += (microtime(true) - $stamp);
758 * @brief Check if we should pass some slow processes
760 * When the active processes of the highest priority are using more than 2/3
761 * of all processes, we let pass slower processes.
763 * @param string $highest_priority Returns the currently highest priority
764 * @return bool We let pass a slower process than $highest_priority
767 private static function passingSlow(&$highest_priority)
769 $highest_priority = 0;
771 $stamp = (float)microtime(true);
775 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
777 self::$db_duration += (microtime(true) - $stamp);
779 // No active processes at all? Fine
780 if (!DBA::isResult($r)) {
784 while ($line = DBA::fetch($r)) {
785 $priorities[] = $line["priority"];
790 if (count($priorities) == 0) {
793 $highest_priority = min($priorities);
795 // The highest process is already the slowest one?
797 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
801 foreach ($priorities as $priority) {
802 if ($priority == $highest_priority) {
806 Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
807 $passing_slow = (($high/count($priorities)) > (2/3));
810 Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
812 return $passing_slow;
816 * @brief Find and claim the next worker process for us
818 * @param boolean $passing_slow Returns if we had passed low priority processes
819 * @param integer $entries Total number of queue entries
820 * @param integer $deferred Number of deferred queue entries
821 * @return boolean Have we found something?
822 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
824 private static function findWorkerProcesses(&$passing_slow, $entries, $deferred)
828 // Check if we should pass some low priority process
829 $highest_priority = 0;
831 $passing_slow = false;
833 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
834 // We decrease the limit with the number of entries left in the queue
835 $worker_queues = Config::get("system", "worker_queues", 4);
836 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
837 $lower_job_limit = $worker_queues * $queue_length * 2;
838 $entries = max($entries - $deferred, 0);
842 $slope = $queue_length / pow($lower_job_limit, $exponent);
843 $limit = min($queue_length, ceil($slope * pow($entries, $exponent)));
845 Logger::log('Deferred: ' . $deferred . ' - Total: ' . $entries . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
847 if (self::passingSlow($highest_priority)) {
848 // Are there waiting processes with a higher priority than the currently highest?
849 $stamp = (float)microtime(true);
850 $result = DBA::select(
853 ["`pid` = 0 AND `priority` < ? AND NOT `done` AND `next_try` < ?",
854 $highest_priority, DateTimeFormat::utcNow()],
855 ['limit' => 1, 'order' => ['priority', 'created']]
857 self::$db_duration += (microtime(true) - $stamp);
859 while ($id = DBA::fetch($result)) {
864 $found = (count($ids) > 0);
867 // Give slower processes some processing time
868 $stamp = (float)microtime(true);
869 $result = DBA::select(
872 ["`pid` = 0 AND `priority` > ? AND NOT `done` AND `next_try` < ?",
873 $highest_priority, DateTimeFormat::utcNow()],
874 ['limit' => 1, 'order' => ['priority', 'created']]
876 self::$db_duration += (microtime(true) - $stamp);
878 while ($id = DBA::fetch($result)) {
883 $found = (count($ids) > 0);
884 $passing_slow = $found;
888 // At first try to fetch a bunch of high or medium tasks
889 if (!$found && ($limit > 1)) {
890 $stamp = (float)microtime(true);
891 $result = DBA::select(
894 ["`pid` = 0 AND NOT `done` AND `priority` <= ? AND `next_try` < ? AND `retrial` = 0",
895 PRIORITY_MEDIUM, DateTimeFormat::utcNow()],
896 ['limit' => $limit, 'order' => ['created']]
898 self::$db_duration += (microtime(true) - $stamp);
900 while ($id = DBA::fetch($result)) {
905 $found = (count($ids) > 0);
908 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
910 $stamp = (float)microtime(true);
911 $result = DBA::select(
914 ["`pid` = 0 AND NOT `done` AND `next_try` < ?",
915 DateTimeFormat::utcNow()],
916 ['limit' => 1, 'order' => ['priority', 'created']]
918 self::$db_duration += (microtime(true) - $stamp);
920 while ($id = DBA::fetch($result)) {
925 $found = (count($ids) > 0);
929 $stamp = (float)microtime(true);
930 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
931 array_unshift($ids, $condition);
932 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
933 self::$db_duration += (microtime(true) - $stamp);
934 self::$db_duration_write += (microtime(true) - $stamp);
941 * @brief Returns the next worker process
943 * @param boolean $passing_slow Returns if we had passed low priority processes
944 * @param integer $entries Returns total number of queue entries
945 * @param integer $deferred Returns number of deferred queue entries
947 * @return string SQL statement
948 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
950 public static function workerProcess(&$passing_slow, &$entries, &$deferred)
952 // There can already be jobs for us in the queue.
953 $stamp = (float)microtime(true);
954 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
955 self::$db_duration += (microtime(true) - $stamp);
956 if (DBA::isResult($r)) {
957 return DBA::toArray($r);
961 // Counting the rows outside the lock reduces the lock time
962 $entries = self::totalEntries();
963 $deferred = self::deferredEntries();
965 $stamp = (float)microtime(true);
966 if (!Lock::acquire('worker_process')) {
969 self::$lock_duration += (microtime(true) - $stamp);
971 $found = self::findWorkerProcesses($passing_slow, $entries, $deferred);
973 Lock::release('worker_process');
976 $stamp = (float)microtime(true);
977 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
978 self::$db_duration += (microtime(true) - $stamp);
979 return DBA::toArray($r);
985 * @brief Removes a workerqueue entry from the current process
989 public static function unclaimProcess()
993 $stamp = (float)microtime(true);
994 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
995 self::$db_duration += (microtime(true) - $stamp);
996 self::$db_duration_write += (microtime(true) - $stamp);
1000 * @brief Call the front end worker
1002 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1004 public static function callWorker()
1006 if (!Config::get("system", "frontend_worker")) {
1010 $url = System::baseUrl()."/worker";
1011 Network::fetchUrl($url, false, $redirects, 1);
1015 * @brief Call the front end worker if there aren't any active
1017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1019 public static function executeIfIdle()
1021 if (!Config::get("system", "frontend_worker")) {
1025 // Do we have "proc_open"? Then we can fork the worker
1026 if (function_exists("proc_open")) {
1027 // When was the last time that we called the worker?
1028 // Less than one minute? Then we quit
1029 if ((time() - Config::get("system", "worker_started")) < 60) {
1033 Config::set("system", "worker_started", time());
1035 // Do we have enough running workers? Then we quit here.
1036 if (self::tooMuchWorkers()) {
1037 // Cleaning dead processes
1038 self::killStaleWorkers();
1039 Process::deleteInactive();
1046 Logger::log('Call worker', Logger::DEBUG);
1047 self::spawnWorker();
1051 // We cannot execute background processes.
1052 // We now run the processes from the frontend.
1053 // This won't work with long running processes.
1056 self::clearProcesses();
1058 $workers = self::activeWorkers();
1060 if ($workers == 0) {
1066 * @brief Removes long running worker processes
1068 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1070 public static function clearProcesses()
1072 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1074 /// @todo We should clean up the corresponding workerqueue entries as well
1075 $stamp = (float)microtime(true);
1076 $condition = ["`created` < ? AND `command` = 'worker.php'",
1077 DateTimeFormat::utc("now - ".$timeout." minutes")];
1078 DBA::delete('process', $condition);
1079 self::$db_duration = (microtime(true) - $stamp);
1080 self::$db_duration_write += (microtime(true) - $stamp);
1084 * @brief Runs the cron processes
1086 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1088 private static function runCron()
1090 Logger::log('Add cron entries', Logger::DEBUG);
1092 // Check for spooled items
1093 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1095 // Run the cron job that calls all other jobs
1096 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1098 // Cleaning dead processes
1099 self::killStaleWorkers();
1103 * @brief Spawns a new worker
1104 * @param bool $do_cron
1106 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1108 public static function spawnWorker($do_cron = false)
1110 $command = 'bin/worker.php';
1112 $args = ['no_cron' => !$do_cron];
1114 get_app()->proc_run($command, $args);
1116 // after spawning we have to remove the flag.
1117 if (Config::get('system', 'worker_daemon_mode', false)) {
1118 self::IPCSetJobState(false);
1123 * @brief Adds tasks to the worker queue
1125 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1127 * next args are passed as $cmd command line
1128 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1129 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1131 * @return boolean "false" if proc_run couldn't be executed
1132 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1133 * @note $cmd and string args are surrounded with ""
1139 public static function add($cmd)
1141 $args = func_get_args();
1143 if (!count($args)) {
1147 $arr = ['args' => $args, 'run_cmd' => true];
1149 Hook::callAll("proc_run", $arr);
1150 if (!$arr['run_cmd'] || !count($args)) {
1154 $priority = PRIORITY_MEDIUM;
1155 $dont_fork = Config::get("system", "worker_dont_fork", false);
1156 $created = DateTimeFormat::utcNow();
1157 $force_priority = false;
1159 $run_parameter = array_shift($args);
1161 if (is_int($run_parameter)) {
1162 $priority = $run_parameter;
1163 } elseif (is_array($run_parameter)) {
1164 if (isset($run_parameter['priority'])) {
1165 $priority = $run_parameter['priority'];
1167 if (isset($run_parameter['created'])) {
1168 $created = $run_parameter['created'];
1170 if (isset($run_parameter['dont_fork'])) {
1171 $dont_fork = $run_parameter['dont_fork'];
1173 if (isset($run_parameter['force_priority'])) {
1174 $force_priority = $run_parameter['force_priority'];
1178 $parameters = json_encode($args);
1179 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1181 // Quit if there was a database error - a precaution for the update process to 3.5.3
1182 if (DBA::errorNo() != 0) {
1187 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1188 } elseif ($force_priority) {
1189 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1192 // Should we quit and wait for the worker to be called as a cronjob?
1197 // If there is a lock then we don't have to check for too much worker
1198 if (!Lock::acquire('worker', 0)) {
1202 // If there are already enough workers running, don't fork another one
1203 $quit = self::tooMuchWorkers();
1204 Lock::release('worker');
1210 // We tell the daemon that a new job entry exists
1211 if (Config::get('system', 'worker_daemon_mode', false)) {
1212 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1216 // Now call the worker to execute the jobs that we just added to the queue
1217 self::spawnWorker();
1223 * Defers the current worker entry
1225 public static function defer()
1227 if (empty(BaseObject::getApp()->queue)) {
1231 $queue = BaseObject::getApp()->queue;
1233 $retrial = $queue['retrial'];
1235 $priority = $queue['priority'];
1237 if ($retrial > 14) {
1238 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1242 // Calculate the delay until the next trial
1243 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1244 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1246 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1247 $priority = PRIORITY_MEDIUM;
1248 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1249 $priority = PRIORITY_LOW;
1250 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1251 $priority = PRIORITY_NEGLIGIBLE;
1254 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1256 $stamp = (float)microtime(true);
1257 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1258 DBA::update('workerqueue', $fields, ['id' => $id]);
1259 self::$db_duration += (microtime(true) - $stamp);
1260 self::$db_duration_write += (microtime(true) - $stamp);
1264 * Log active processes into the "process" table
1266 * @brief Log active processes into the "process" table
1268 public static function startProcess()
1270 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1272 $command = basename($trace[0]['file']);
1274 Process::deleteInactive();
1276 Process::insert($command);
1280 * Remove the active process from the "process" table
1282 * @brief Remove the active process from the "process" table
1284 * @throws \Exception
1286 public static function endProcess()
1288 return Process::deleteByPid();
1292 * Set the flag if some job is waiting
1294 * @brief Set the flag if some job is waiting
1295 * @param boolean $jobs Is there a waiting job?
1296 * @throws \Exception
1298 public static function IPCSetJobState($jobs)
1300 $stamp = (float)microtime(true);
1301 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1302 self::$db_duration += (microtime(true) - $stamp);
1303 self::$db_duration_write += (microtime(true) - $stamp);
1307 * Checks if some worker job waits to be executed
1309 * @brief Checks if some worker job waits to be executed
1311 * @throws \Exception
1313 public static function IPCJobsExists()
1315 $stamp = (float)microtime(true);
1316 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1317 self::$db_duration += (microtime(true) - $stamp);
1319 // When we don't have a row, no job is running
1320 if (!DBA::isResult($row)) {
1324 return (bool)$row['jobs'];