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 $a->getProfiler()->reset();
385 // For better logging create a new process id for every worker call
386 // But preserve the old one for the worker
387 $old_process_id = $a->process_id;
388 $a->process_id = $new_process_id;
391 $up_duration = microtime(true) - self::$up_start;
393 // Reset global data to avoid interferences
397 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
399 $funcname($argv, $argc);
402 $a->process_id = $old_process_id;
405 $duration = (microtime(true) - $stamp);
407 /* With these values we can analyze how effective the worker is.
408 * The database and rest time should be low since this is the unproductive time.
409 * The execution time is the productive time.
410 * By changing parameters like the maximum number of workers we can check the effectivness.
413 'DB: '.number_format(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 4).
414 ' - DB-Count: '.number_format(self::$db_duration_count, 4).
415 ' - DB-Stat: '.number_format(self::$db_duration_stat, 4).
416 ' - DB-Write: '.number_format(self::$db_duration_write, 4).
417 ' - Lock: '.number_format(self::$lock_duration, 4).
418 ' - Rest: '.number_format(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 4).
419 ' - Execution: '.number_format($duration, 4),
423 self::$up_start = microtime(true);
424 self::$db_duration = 0;
425 self::$db_duration_count = 0;
426 self::$db_duration_stat = 0;
427 self::$db_duration_write = 0;
428 self::$lock_duration = 0;
430 if ($duration > 3600) {
431 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
432 } elseif ($duration > 600) {
433 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
434 } elseif ($duration > 300) {
435 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
436 } elseif ($duration > 120) {
437 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
440 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".number_format($duration, 4)." seconds. Process PID: ".$new_process_id);
442 $a->getProfiler()->saveLog($a->getLogger(), "ID " . $queue["id"] . ": " . $funcname);
444 $cooldown = Config::get("system", "worker_cooldown", 0);
447 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
453 * @brief Checks if the number of database connections has reached a critical limit.
455 * @return bool Are more than 3/4 of the maximum connections used?
456 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
458 private static function maxConnectionsReached()
460 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
461 $max = Config::get("system", "max_connections");
463 // Fetch the percentage level where the worker will get active
464 $maxlevel = Config::get("system", "max_connections_level", 75);
467 // the maximum number of possible user connections can be a system variable
468 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
469 if (DBA::isResult($r)) {
472 // Or it can be granted. This overrides the system variable
473 $stamp = (float)microtime(true);
474 $r = DBA::p('SHOW GRANTS');
475 self::$db_duration += (microtime(true) - $stamp);
476 while ($grants = DBA::fetch($r)) {
477 $grant = array_pop($grants);
478 if (stristr($grant, "GRANT USAGE ON")) {
479 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
487 // If $max is set we will use the processlist to determine the current number of connections
488 // The processlist only shows entries of the current user
490 $stamp = (float)microtime(true);
491 $r = DBA::p('SHOW PROCESSLIST');
492 self::$db_duration += (microtime(true) - $stamp);
493 $used = DBA::numRows($r);
496 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
498 $level = ($used / $max) * 100;
500 if ($level >= $maxlevel) {
501 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
506 // We will now check for the system values.
507 // This limit could be reached although the user limits are fine.
508 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
509 if (!DBA::isResult($r)) {
512 $max = intval($r["Value"]);
516 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
517 if (!DBA::isResult($r)) {
520 $used = intval($r["Value"]);
524 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
526 $level = $used / $max * 100;
528 if ($level < $maxlevel) {
531 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
536 * @brief fix the queue entry if the worker process died
540 private static function killStaleWorkers()
542 $stamp = (float)microtime(true);
543 $entries = DBA::select(
545 ['id', 'pid', 'executed', 'priority', 'parameter'],
546 ['NOT `done` AND `pid` != 0'],
547 ['order' => ['priority', 'created']]
549 self::$db_duration += (microtime(true) - $stamp);
551 while ($entry = DBA::fetch($entries)) {
552 if (!posix_kill($entry["pid"], 0)) {
553 $stamp = (float)microtime(true);
556 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
557 ['id' => $entry["id"]]
559 self::$db_duration += (microtime(true) - $stamp);
560 self::$db_duration_write += (microtime(true) - $stamp);
562 // Kill long running processes
563 // Check if the priority is in a valid range
564 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
565 $entry["priority"] = PRIORITY_MEDIUM;
568 // Define the maximum durations
569 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
570 $max_duration = $max_duration_defaults[$entry["priority"]];
572 $argv = json_decode($entry["parameter"], true);
573 $argv[0] = basename($argv[0]);
575 // How long is the process already running?
576 $duration = (time() - strtotime($entry["executed"])) / 60;
577 if ($duration > $max_duration) {
578 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
579 posix_kill($entry["pid"], SIGTERM);
581 // We killed the stale process.
582 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
583 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
584 $new_priority = $entry["priority"];
585 if ($entry["priority"] == PRIORITY_HIGH) {
586 $new_priority = PRIORITY_MEDIUM;
587 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
588 $new_priority = PRIORITY_LOW;
589 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
590 $new_priority = PRIORITY_NEGLIGIBLE;
592 $stamp = (float)microtime(true);
595 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
596 ['id' => $entry["id"]]
598 self::$db_duration += (microtime(true) - $stamp);
599 self::$db_duration_write += (microtime(true) - $stamp);
601 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);
608 * @brief Checks if the number of active workers exceeds the given limits
610 * @param integer $entries Total number of queue entries
611 * @param integer $deferred Number of deferred queue entries
613 * @return bool Are there too much workers running?
614 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
616 public static function tooMuchWorkers($entries = 0, $deferred = 0)
618 $queues = Config::get("system", "worker_queues", 4);
620 $maxqueues = $queues;
622 $active = self::activeWorkers();
624 // Decrease the number of workers at higher load
625 $load = System::currentLoad();
627 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
629 /* Default exponent 3 causes queues to rapidly decrease as load increases.
630 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
631 * For some environments, this rapid decrease is not needed.
632 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
634 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
635 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
636 $queues = intval(ceil($slope * $maxqueues));
640 if (Config::get('system', 'worker_jpm')) {
641 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
642 $jobs_per_minute = [];
643 foreach ($intervals as $interval) {
644 if ($interval == 0) {
647 $interval = (int)$interval;
650 $stamp = (float)microtime(true);
651 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
652 self::$db_duration += (microtime(true) - $stamp);
653 self::$db_duration_stat += (microtime(true) - $stamp);
654 if ($job = DBA::fetch($jobs)) {
655 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
659 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
662 // Create a list of queue entries grouped by their priority
663 $listitem = [0 => ''];
665 $idle_workers = $active;
667 if (empty($deferred) && empty($entries)) {
668 $deferred = self::deferredEntries();
669 $entries = max(self::totalEntries() - $deferred, 0);
672 $waiting_processes = max(0, $entries - $deferred);
674 if (Config::get('system', 'worker_debug')) {
675 $waiting_processes = 0;
676 // Now adding all processes with workerqueue entries
677 $stamp = (float)microtime(true);
678 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
679 self::$db_duration += (microtime(true) - $stamp);
680 self::$db_duration_stat += (microtime(true) - $stamp);
681 while ($entry = DBA::fetch($jobs)) {
682 $stamp = (float)microtime(true);
683 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
684 self::$db_duration += (microtime(true) - $stamp);
685 self::$db_duration_stat += (microtime(true) - $stamp);
686 if ($process = DBA::fetch($processes)) {
687 $idle_workers -= $process["running"];
688 $waiting_processes += $entry["entries"];
689 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
691 DBA::close($processes);
695 $stamp = (float)microtime(true);
696 $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`");
697 self::$db_duration += (microtime(true) - $stamp);
699 while ($entry = DBA::fetch($jobs)) {
700 $idle_workers -= $entry["running"];
701 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
706 $listitem[0] = "0:" . max(0, $idle_workers);
708 $processlist .= ' ('.implode(', ', $listitem).')';
710 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && self::entriesExists() && ($active >= $queues)) {
711 $top_priority = self::highestPriority();
712 $high_running = self::processWithPriorityActive($top_priority);
714 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
715 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
716 $queues = $active + 1;
720 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
722 // Are there fewer workers running as possible? Then fork a new one.
723 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
724 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
725 if (Config::get('system', 'worker_daemon_mode', false)) {
726 self::IPCSetJobState(true);
733 // if there are too much worker, we don't spawn a new one.
734 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
735 self::IPCSetJobState(false);
738 return $active > $queues;
742 * @brief Returns the number of active worker processes
744 * @return integer Number of active worker processes
747 private static function activeWorkers()
749 $stamp = (float)microtime(true);
750 $count = DBA::count('process', ['command' => 'Worker.php']);
751 self::$db_duration += (microtime(true) - $stamp);
756 * @brief Check if we should pass some slow processes
758 * When the active processes of the highest priority are using more than 2/3
759 * of all processes, we let pass slower processes.
761 * @param string $highest_priority Returns the currently highest priority
762 * @return bool We let pass a slower process than $highest_priority
765 private static function passingSlow(&$highest_priority)
767 $highest_priority = 0;
769 $stamp = (float)microtime(true);
773 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
775 self::$db_duration += (microtime(true) - $stamp);
777 // No active processes at all? Fine
778 if (!DBA::isResult($r)) {
782 while ($line = DBA::fetch($r)) {
783 $priorities[] = $line["priority"];
788 if (count($priorities) == 0) {
791 $highest_priority = min($priorities);
793 // The highest process is already the slowest one?
795 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
799 foreach ($priorities as $priority) {
800 if ($priority == $highest_priority) {
804 Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
805 $passing_slow = (($high/count($priorities)) > (2/3));
808 Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
810 return $passing_slow;
814 * @brief Find and claim the next worker process for us
816 * @param boolean $passing_slow Returns if we had passed low priority processes
817 * @param integer $entries Total number of queue entries
818 * @param integer $deferred Number of deferred queue entries
819 * @return boolean Have we found something?
820 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
822 private static function findWorkerProcesses(&$passing_slow, $entries, $deferred)
826 // Check if we should pass some low priority process
827 $highest_priority = 0;
829 $passing_slow = false;
831 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
832 // We decrease the limit with the number of entries left in the queue
833 $worker_queues = Config::get("system", "worker_queues", 4);
834 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
835 $lower_job_limit = $worker_queues * $queue_length * 2;
836 $entries = max($entries - $deferred, 0);
840 $slope = $queue_length / pow($lower_job_limit, $exponent);
841 $limit = min($queue_length, ceil($slope * pow($entries, $exponent)));
843 Logger::log('Deferred: ' . $deferred . ' - Total: ' . $entries . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
845 if (self::passingSlow($highest_priority)) {
846 // Are there waiting processes with a higher priority than the currently highest?
847 $stamp = (float)microtime(true);
848 $result = DBA::select(
851 ["`pid` = 0 AND `priority` < ? AND NOT `done` AND `next_try` < ?",
852 $highest_priority, DateTimeFormat::utcNow()],
853 ['limit' => 1, 'order' => ['priority', 'created']]
855 self::$db_duration += (microtime(true) - $stamp);
857 while ($id = DBA::fetch($result)) {
862 $found = (count($ids) > 0);
865 // Give slower processes some processing time
866 $stamp = (float)microtime(true);
867 $result = DBA::select(
870 ["`pid` = 0 AND `priority` > ? AND NOT `done` AND `next_try` < ?",
871 $highest_priority, DateTimeFormat::utcNow()],
872 ['limit' => 1, 'order' => ['priority', 'created']]
874 self::$db_duration += (microtime(true) - $stamp);
876 while ($id = DBA::fetch($result)) {
881 $found = (count($ids) > 0);
882 $passing_slow = $found;
886 // At first try to fetch a bunch of high or medium tasks
887 if (!$found && ($limit > 1)) {
888 $stamp = (float)microtime(true);
889 $result = DBA::select(
892 ["`pid` = 0 AND NOT `done` AND `priority` <= ? AND `next_try` < ? AND `retrial` = 0",
893 PRIORITY_MEDIUM, DateTimeFormat::utcNow()],
894 ['limit' => $limit, 'order' => ['created']]
896 self::$db_duration += (microtime(true) - $stamp);
898 while ($id = DBA::fetch($result)) {
903 $found = (count($ids) > 0);
906 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
908 $stamp = (float)microtime(true);
909 $result = DBA::select(
912 ["`pid` = 0 AND NOT `done` AND `next_try` < ?",
913 DateTimeFormat::utcNow()],
914 ['limit' => 1, 'order' => ['priority', 'created']]
916 self::$db_duration += (microtime(true) - $stamp);
918 while ($id = DBA::fetch($result)) {
923 $found = (count($ids) > 0);
927 $stamp = (float)microtime(true);
928 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
929 array_unshift($ids, $condition);
930 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
931 self::$db_duration += (microtime(true) - $stamp);
932 self::$db_duration_write += (microtime(true) - $stamp);
939 * @brief Returns the next worker process
941 * @param boolean $passing_slow Returns if we had passed low priority processes
942 * @param integer $entries Returns total number of queue entries
943 * @param integer $deferred Returns number of deferred queue entries
945 * @return string SQL statement
946 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
948 public static function workerProcess(&$passing_slow, &$entries, &$deferred)
950 // There can already be jobs for us in the queue.
951 $stamp = (float)microtime(true);
952 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
953 self::$db_duration += (microtime(true) - $stamp);
954 if (DBA::isResult($r)) {
955 return DBA::toArray($r);
959 // Counting the rows outside the lock reduces the lock time
960 $entries = self::totalEntries();
961 $deferred = self::deferredEntries();
963 $stamp = (float)microtime(true);
964 if (!Lock::acquire('worker_process')) {
967 self::$lock_duration += (microtime(true) - $stamp);
969 $found = self::findWorkerProcesses($passing_slow, $entries, $deferred);
971 Lock::release('worker_process');
974 $stamp = (float)microtime(true);
975 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
976 self::$db_duration += (microtime(true) - $stamp);
977 return DBA::toArray($r);
983 * @brief Removes a workerqueue entry from the current process
987 public static function unclaimProcess()
991 $stamp = (float)microtime(true);
992 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
993 self::$db_duration += (microtime(true) - $stamp);
994 self::$db_duration_write += (microtime(true) - $stamp);
998 * @brief Call the front end worker
1000 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1002 public static function callWorker()
1004 if (!Config::get("system", "frontend_worker")) {
1008 $url = System::baseUrl()."/worker";
1009 Network::fetchUrl($url, false, $redirects, 1);
1013 * @brief Call the front end worker if there aren't any active
1015 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1017 public static function executeIfIdle()
1019 if (!Config::get("system", "frontend_worker")) {
1023 // Do we have "proc_open"? Then we can fork the worker
1024 if (function_exists("proc_open")) {
1025 // When was the last time that we called the worker?
1026 // Less than one minute? Then we quit
1027 if ((time() - Config::get("system", "worker_started")) < 60) {
1031 Config::set("system", "worker_started", time());
1033 // Do we have enough running workers? Then we quit here.
1034 if (self::tooMuchWorkers()) {
1035 // Cleaning dead processes
1036 self::killStaleWorkers();
1037 Process::deleteInactive();
1044 Logger::log('Call worker', Logger::DEBUG);
1045 self::spawnWorker();
1049 // We cannot execute background processes.
1050 // We now run the processes from the frontend.
1051 // This won't work with long running processes.
1054 self::clearProcesses();
1056 $workers = self::activeWorkers();
1058 if ($workers == 0) {
1064 * @brief Removes long running worker processes
1066 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1068 public static function clearProcesses()
1070 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1072 /// @todo We should clean up the corresponding workerqueue entries as well
1073 $stamp = (float)microtime(true);
1074 $condition = ["`created` < ? AND `command` = 'worker.php'",
1075 DateTimeFormat::utc("now - ".$timeout." minutes")];
1076 DBA::delete('process', $condition);
1077 self::$db_duration = (microtime(true) - $stamp);
1078 self::$db_duration_write += (microtime(true) - $stamp);
1082 * @brief Runs the cron processes
1084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1086 private static function runCron()
1088 Logger::log('Add cron entries', Logger::DEBUG);
1090 // Check for spooled items
1091 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1093 // Run the cron job that calls all other jobs
1094 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1096 // Cleaning dead processes
1097 self::killStaleWorkers();
1101 * @brief Spawns a new worker
1102 * @param bool $do_cron
1104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1106 public static function spawnWorker($do_cron = false)
1108 $command = 'bin/worker.php';
1110 $args = ['no_cron' => !$do_cron];
1112 get_app()->proc_run($command, $args);
1114 // after spawning we have to remove the flag.
1115 if (Config::get('system', 'worker_daemon_mode', false)) {
1116 self::IPCSetJobState(false);
1121 * @brief Adds tasks to the worker queue
1123 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1125 * next args are passed as $cmd command line
1126 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1127 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1129 * @return boolean "false" if proc_run couldn't be executed
1130 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1131 * @note $cmd and string args are surrounded with ""
1137 public static function add($cmd)
1139 $args = func_get_args();
1141 if (!count($args)) {
1145 $arr = ['args' => $args, 'run_cmd' => true];
1147 Hook::callAll("proc_run", $arr);
1148 if (!$arr['run_cmd'] || !count($args)) {
1152 $priority = PRIORITY_MEDIUM;
1153 $dont_fork = Config::get("system", "worker_dont_fork", false);
1154 $created = DateTimeFormat::utcNow();
1155 $force_priority = false;
1157 $run_parameter = array_shift($args);
1159 if (is_int($run_parameter)) {
1160 $priority = $run_parameter;
1161 } elseif (is_array($run_parameter)) {
1162 if (isset($run_parameter['priority'])) {
1163 $priority = $run_parameter['priority'];
1165 if (isset($run_parameter['created'])) {
1166 $created = $run_parameter['created'];
1168 if (isset($run_parameter['dont_fork'])) {
1169 $dont_fork = $run_parameter['dont_fork'];
1171 if (isset($run_parameter['force_priority'])) {
1172 $force_priority = $run_parameter['force_priority'];
1176 $parameters = json_encode($args);
1177 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1179 // Quit if there was a database error - a precaution for the update process to 3.5.3
1180 if (DBA::errorNo() != 0) {
1185 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1186 } elseif ($force_priority) {
1187 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1190 // Should we quit and wait for the worker to be called as a cronjob?
1195 // If there is a lock then we don't have to check for too much worker
1196 if (!Lock::acquire('worker', 0)) {
1200 // If there are already enough workers running, don't fork another one
1201 $quit = self::tooMuchWorkers();
1202 Lock::release('worker');
1208 // We tell the daemon that a new job entry exists
1209 if (Config::get('system', 'worker_daemon_mode', false)) {
1210 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1214 // Now call the worker to execute the jobs that we just added to the queue
1215 self::spawnWorker();
1221 * Defers the current worker entry
1223 public static function defer()
1225 if (empty(BaseObject::getApp()->queue)) {
1229 $queue = BaseObject::getApp()->queue;
1231 $retrial = $queue['retrial'];
1233 $priority = $queue['priority'];
1235 if ($retrial > 14) {
1236 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1240 // Calculate the delay until the next trial
1241 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1242 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1244 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1245 $priority = PRIORITY_MEDIUM;
1246 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1247 $priority = PRIORITY_LOW;
1248 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1249 $priority = PRIORITY_NEGLIGIBLE;
1252 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1254 $stamp = (float)microtime(true);
1255 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1256 DBA::update('workerqueue', $fields, ['id' => $id]);
1257 self::$db_duration += (microtime(true) - $stamp);
1258 self::$db_duration_write += (microtime(true) - $stamp);
1262 * Log active processes into the "process" table
1264 * @brief Log active processes into the "process" table
1266 public static function startProcess()
1268 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1270 $command = basename($trace[0]['file']);
1272 Process::deleteInactive();
1274 Process::insert($command);
1278 * Remove the active process from the "process" table
1280 * @brief Remove the active process from the "process" table
1282 * @throws \Exception
1284 public static function endProcess()
1286 return Process::deleteByPid();
1290 * Set the flag if some job is waiting
1292 * @brief Set the flag if some job is waiting
1293 * @param boolean $jobs Is there a waiting job?
1294 * @throws \Exception
1296 public static function IPCSetJobState($jobs)
1298 $stamp = (float)microtime(true);
1299 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1300 self::$db_duration += (microtime(true) - $stamp);
1301 self::$db_duration_write += (microtime(true) - $stamp);
1305 * Checks if some worker job waits to be executed
1307 * @brief Checks if some worker job waits to be executed
1309 * @throws \Exception
1311 public static function IPCJobsExists()
1313 $stamp = (float)microtime(true);
1314 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1315 self::$db_duration += (microtime(true) - $stamp);
1317 // When we don't have a row, no job is running
1318 if (!DBA::isResult($row)) {
1322 return (bool)$row['jobs'];