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\Logger\WorkerLogger;
12 use Friendica\Util\Network;
15 * @file src/Core/Worker.php
17 * @brief Contains the class for the worker background job processing
21 * @brief Worker methods
25 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
26 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
27 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
28 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
30 private static $up_start;
31 private static $db_duration = 0;
32 private static $db_duration_count = 0;
33 private static $db_duration_write = 0;
34 private static $db_duration_stat = 0;
35 private static $lock_duration = 0;
36 private static $last_update;
37 private static $state;
40 * @brief Processes the tasks that are in the workerqueue table
42 * @param boolean $run_cron Should the cron processes be executed?
44 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
46 public static function processQueue($run_cron = true)
50 // Ensure that all "strtotime" operations do run timezone independent
51 date_default_timezone_set('UTC');
53 self::$up_start = microtime(true);
55 // At first check the maximum load. We shouldn't continue with a high load
56 if ($a->isMaxLoadReached()) {
57 Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
61 // We now start the process. This is done after the load check since this could increase the load.
64 // Kill stale processes every 5 minutes
65 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
66 if (time() > ($last_cleanup + 300)) {
67 Config::set('system', 'worker_last_cleaned', time());
68 self::killStaleWorkers();
71 // Count active workers and compare them with a maximum value that depends on the load
72 if (self::tooMuchWorkers()) {
73 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
77 // Do we have too few memory?
78 if ($a->isMinMemoryReached()) {
79 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
83 // Possibly there are too much database connections
84 if (self::maxConnectionsReached()) {
85 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
89 // Possibly there are too much database processes that block the system
90 if ($a->isMaxProcessesReached()) {
91 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
95 // Now we start additional cron processes if we should do so
101 self::$state = self::STATE_STARTUP;
103 // We fetch the next queue entry that is about to be executed
104 while ($r = self::workerProcess()) {
106 foreach ($r as $entry) {
107 // Assure that the priority is an integer value
108 $entry['priority'] = (int)$entry['priority'];
110 // The work will be done
111 if (!self::execute($entry)) {
112 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
116 // Trying to fetch new processes - but only once when successful
117 if (!$refetched && Lock::acquire('worker_process', 0)) {
118 self::findWorkerProcesses();
119 Lock::release('worker_process');
120 self::$state = self::STATE_REFETCH;
123 self::$state = self::STATE_SHORT_LOOP;
127 // To avoid the quitting of multiple workers only one worker at a time will execute the check
128 if (!self::getWaitingJobForPID()) {
129 self::$state = self::STATE_LONG_LOOP;
131 if (Lock::acquire('worker', 0)) {
132 // Count active workers and compare them with a maximum value that depends on the load
133 if (self::tooMuchWorkers()) {
134 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
135 Lock::release('worker');
140 if ($a->isMinMemoryReached()) {
141 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
142 Lock::release('worker');
145 Lock::release('worker');
149 // Quit the worker once every cron interval
150 if (time() > ($starttime + (Config::get('system', 'cron_interval') * 60))) {
151 Logger::info('Process lifetime reached, respawning.');
157 // Cleaning up. Possibly not needed, but it doesn't harm anything.
158 if (Config::get('system', 'worker_daemon_mode', false)) {
159 self::IPCSetJobState(false);
161 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
165 * @brief Check if non executed tasks do exist in the worker queue
167 * @return boolean Returns "true" if tasks are existing
170 private static function entriesExists()
172 $stamp = (float)microtime(true);
173 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
174 self::$db_duration += (microtime(true) - $stamp);
179 * @brief Returns the number of deferred entries in the worker queue
181 * @return integer Number of deferred entries in the worker queue
184 private static function deferredEntries()
186 $stamp = (float)microtime(true);
187 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` > ?", DateTimeFormat::utcNow()]);
188 self::$db_duration += (microtime(true) - $stamp);
189 self::$db_duration_count += (microtime(true) - $stamp);
194 * @brief Returns the number of non executed entries in the worker queue
196 * @return integer Number of non executed entries in the worker queue
199 private static function totalEntries()
201 $stamp = (float)microtime(true);
202 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
203 self::$db_duration += (microtime(true) - $stamp);
204 self::$db_duration_count += (microtime(true) - $stamp);
209 * @brief Returns the highest priority in the worker queue that isn't executed
211 * @return integer Number of active worker processes
214 private static function highestPriority()
216 $stamp = (float)microtime(true);
217 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
218 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
219 self::$db_duration += (microtime(true) - $stamp);
220 if (DBA::isResult($workerqueue)) {
221 return $workerqueue["priority"];
228 * @brief Returns if a process with the given priority is running
230 * @param integer $priority The priority that should be checked
232 * @return integer Is there a process running with that priority?
235 private static function processWithPriorityActive($priority)
237 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
238 return DBA::exists('workerqueue', $condition);
242 * @brief Execute a worker entry
244 * @param array $queue Workerqueue entry
246 * @return boolean "true" if further processing should be stopped
247 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
249 public static function execute($queue)
255 // Quit when in maintenance
256 if (Config::get('system', 'maintenance', false, true)) {
257 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
261 // Constantly check the number of parallel database processes
262 if ($a->isMaxProcessesReached()) {
263 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
267 // Constantly check the number of available database connections to let the frontend be accessible at any time
268 if (self::maxConnectionsReached()) {
269 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
273 $argv = json_decode($queue["parameter"], true);
275 // Check for existance and validity of the include file
278 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
279 // We constantly update the "executed" date every minute to avoid being killed too soon
280 if (!isset(self::$last_update)) {
281 self::$last_update = strtotime($queue["executed"]);
284 $age = (time() - self::$last_update) / 60;
285 self::$last_update = time();
288 $stamp = (float)microtime(true);
289 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
290 self::$db_duration += (microtime(true) - $stamp);
291 self::$db_duration_write += (microtime(true) - $stamp);
296 self::execFunction($queue, $include, $argv, true);
298 $stamp = (float)microtime(true);
299 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
300 if (DBA::update('workerqueue', ['done' => true], $condition)) {
301 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
303 self::$db_duration = (microtime(true) - $stamp);
304 self::$db_duration_write += (microtime(true) - $stamp);
309 // The script could be provided as full path or only with the function name
310 if ($include == basename($include)) {
311 $include = "include/".$include.".php";
314 if (!validate_include($include)) {
315 Logger::log("Include file ".$argv[0]." is not valid!");
316 $stamp = (float)microtime(true);
317 DBA::delete('workerqueue', ['id' => $queue["id"]]);
318 self::$db_duration = (microtime(true) - $stamp);
319 self::$db_duration_write += (microtime(true) - $stamp);
323 require_once $include;
325 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
327 if (function_exists($funcname)) {
328 // We constantly update the "executed" date every minute to avoid being killed too soon
329 if (!isset(self::$last_update)) {
330 self::$last_update = strtotime($queue["executed"]);
333 $age = (time() - self::$last_update) / 60;
334 self::$last_update = time();
337 $stamp = (float)microtime(true);
338 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
339 self::$db_duration += (microtime(true) - $stamp);
340 self::$db_duration_write += (microtime(true) - $stamp);
343 self::execFunction($queue, $funcname, $argv, false);
345 $stamp = (float)microtime(true);
346 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
347 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
349 self::$db_duration = (microtime(true) - $stamp);
350 self::$db_duration_write += (microtime(true) - $stamp);
352 Logger::log("Function ".$funcname." does not exist");
353 $stamp = (float)microtime(true);
354 DBA::delete('workerqueue', ['id' => $queue["id"]]);
355 self::$db_duration = (microtime(true) - $stamp);
356 self::$db_duration_write += (microtime(true) - $stamp);
363 * @brief Execute a function from the queue
365 * @param array $queue Workerqueue entry
366 * @param string $funcname name of the function
367 * @param array $argv Array of values to be passed to the function
368 * @param boolean $method_call boolean
370 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
372 private static function execFunction($queue, $funcname, $argv, $method_call)
376 $argc = count($argv);
378 $logger = $a->getLogger();
379 $workerLogger = new WorkerLogger($logger, $funcname);
381 $workerLogger ->info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
383 $stamp = (float)microtime(true);
385 // We use the callstack here to analyze the performance of executed worker entries.
386 // For this reason the variables have to be initialized.
387 $a->getProfiler()->reset();
391 $up_duration = microtime(true) - self::$up_start;
393 // Reset global data to avoid interferences
396 // Set the workerLogger as new default logger
397 Logger::init($workerLogger);
399 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
401 $funcname($argv, $argc);
403 Logger::init($logger);
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.
414 $dbtotal = round(self::$db_duration, 2);
415 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
416 $dbcount = round(self::$db_duration_count, 2);
417 $dbstat = round(self::$db_duration_stat, 2);
418 $dbwrite = round(self::$db_duration_write, 2);
419 $dblock = round(self::$lock_duration, 2);
420 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
421 $exec = round($duration, 2);
423 $logger->info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
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->info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
434 } elseif ($duration > 600) {
435 $logger->info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
436 } elseif ($duration > 300) {
437 $logger->info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
438 } elseif ($duration > 120) {
439 $logger->info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
442 $workerLogger->info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
444 $a->getProfiler()->saveLog($a->getLogger(), "ID " . $queue["id"] . ": " . $funcname);
446 $cooldown = Config::get("system", "worker_cooldown", 0);
449 $logger->info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
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 * @return bool Are there too much workers running?
613 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
615 private static function tooMuchWorkers()
617 $queues = Config::get("system", "worker_queues", 10);
619 $maxqueues = $queues;
621 $active = self::activeWorkers();
623 // Decrease the number of workers at higher load
624 $load = System::currentLoad();
626 $maxsysload = intval(Config::get("system", "maxloadavg", 20));
628 /* Default exponent 3 causes queues to rapidly decrease as load increases.
629 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
630 * For some environments, this rapid decrease is not needed.
631 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
633 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
634 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
635 $queues = intval(ceil($slope * $maxqueues));
639 if (Config::get('system', 'worker_jpm')) {
640 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
641 $jobs_per_minute = [];
642 foreach ($intervals as $interval) {
643 if ($interval == 0) {
646 $interval = (int)$interval;
649 $stamp = (float)microtime(true);
650 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
651 self::$db_duration += (microtime(true) - $stamp);
652 self::$db_duration_stat += (microtime(true) - $stamp);
653 if ($job = DBA::fetch($jobs)) {
654 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
658 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
661 // Create a list of queue entries grouped by their priority
662 $listitem = [0 => ''];
664 $idle_workers = $active;
666 $deferred = self::deferredEntries();
668 if (Config::get('system', 'worker_debug')) {
669 $waiting_processes = 0;
670 // Now adding all processes with workerqueue entries
671 $stamp = (float)microtime(true);
672 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
673 self::$db_duration += (microtime(true) - $stamp);
674 self::$db_duration_stat += (microtime(true) - $stamp);
675 while ($entry = DBA::fetch($jobs)) {
676 $stamp = (float)microtime(true);
677 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
678 self::$db_duration += (microtime(true) - $stamp);
679 self::$db_duration_stat += (microtime(true) - $stamp);
680 if ($process = DBA::fetch($processes)) {
681 $idle_workers -= $process["running"];
682 $waiting_processes += $entry["entries"];
683 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
685 DBA::close($processes);
688 $entries = $deferred + $waiting_processes;
690 $entries = self::totalEntries();
691 $waiting_processes = max(0, $entries - $deferred);
692 $stamp = (float)microtime(true);
693 $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`");
694 self::$db_duration += (microtime(true) - $stamp);
695 self::$db_duration_stat += (microtime(true) - $stamp);
697 while ($entry = DBA::fetch($jobs)) {
698 $idle_workers -= $entry["running"];
699 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
704 $listitem[0] = "0:" . max(0, $idle_workers);
706 $processlist .= ' ('.implode(', ', $listitem).')';
708 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
709 $top_priority = self::highestPriority();
710 $high_running = self::processWithPriorityActive($top_priority);
712 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
713 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
714 $queues = $active + 1;
718 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
720 // Are there fewer workers running as possible? Then fork a new one.
721 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
722 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
723 if (Config::get('system', 'worker_daemon_mode', false)) {
724 self::IPCSetJobState(true);
731 // if there are too much worker, we don't spawn a new one.
732 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
733 self::IPCSetJobState(false);
736 return $active > $queues;
740 * @brief Returns the number of active worker processes
742 * @return integer Number of active worker processes
745 private static function activeWorkers()
747 $stamp = (float)microtime(true);
748 $count = DBA::count('process', ['command' => 'Worker.php']);
749 self::$db_duration += (microtime(true) - $stamp);
754 * @brief Returns waiting jobs for the current process id
756 * @return array waiting workerqueue jobs
759 private static function getWaitingJobForPID()
761 $stamp = (float)microtime(true);
762 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
763 self::$db_duration += (microtime(true) - $stamp);
764 if (DBA::isResult($r)) {
765 return DBA::toArray($r);
773 * @brief Returns the next jobs that should be executed
775 * @return array array with next jobs
778 private static function nextProcess()
780 $priority = self::nextPriority();
781 if (empty($priority)) {
782 Logger::info('No tasks found');
786 if ($priority <= PRIORITY_MEDIUM) {
787 $limit = Config::get('system', 'worker_fetch_limit', 1);
793 $stamp = (float)microtime(true);
794 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
795 $tasks = DBA::select('workerqueue', ['id'], $condition, ['limit' => $limit, 'order' => ['created']]);
796 self::$db_duration += (microtime(true) - $stamp);
797 while ($task = DBA::fetch($tasks)) {
798 $ids[] = $task['id'];
802 Logger::info('Found:', ['id' => $ids, 'priority' => $priority]);
807 * @brief Returns the priority of the next workerqueue job
809 * @return string priority
812 private static function nextPriority()
815 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
816 foreach ($priorities as $priority) {
817 $stamp = (float)microtime(true);
818 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
819 $waiting[$priority] = true;
821 self::$db_duration += (microtime(true) - $stamp);
824 if (!empty($waiting[PRIORITY_CRITICAL])) {
825 return PRIORITY_CRITICAL;
830 $stamp = (float)microtime(true);
831 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
832 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
833 WHERE NOT `done` GROUP BY `priority`");
834 self::$db_duration += (microtime(true) - $stamp);
835 while ($process = DBA::fetch($processes)) {
836 $running[$process['priority']] = $process['running'];
837 $running_total += $process['running'];
839 DBA::close($processes);
841 foreach ($priorities as $priority) {
842 if (!empty($waiting[$priority]) && empty($running[$priority])) {
843 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
848 $active = max(self::activeWorkers(), $running_total);
849 $priorities = max(count($waiting), count($running));
853 for ($i = 1; $i <= $priorities; ++$i) {
854 $total += pow($i, $exponent);
858 for ($i = 1; $i <= $priorities; ++$i) {
859 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
863 foreach ($running as $priority => $workers) {
864 if ($workers < $limit[$i++]) {
865 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
870 if (!empty($waiting)) {
871 $priority = array_keys($waiting)[0];
872 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
880 * @brief Find and claim the next worker process for us
882 * @return boolean Have we found something?
883 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
885 private static function findWorkerProcesses()
889 $ids = self::nextProcess();
891 // If there is no result we check without priority limit
893 $stamp = (float)microtime(true);
894 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
895 $result = DBA::select('workerqueue', ['id'], $condition, ['limit' => 1, 'order' => ['priority', 'created']]);
896 self::$db_duration += (microtime(true) - $stamp);
898 while ($id = DBA::fetch($result)) {
905 $stamp = (float)microtime(true);
906 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
907 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
908 self::$db_duration += (microtime(true) - $stamp);
909 self::$db_duration_write += (microtime(true) - $stamp);
916 * @brief Returns the next worker process
918 * @return string SQL statement
919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
921 public static function workerProcess()
923 // There can already be jobs for us in the queue.
924 $waiting = self::getWaitingJobForPID();
925 if (!empty($waiting)) {
929 $stamp = (float)microtime(true);
930 if (!Lock::acquire('worker_process')) {
933 self::$lock_duration += (microtime(true) - $stamp);
935 $found = self::findWorkerProcesses();
937 Lock::release('worker_process');
940 $stamp = (float)microtime(true);
941 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
942 self::$db_duration += (microtime(true) - $stamp);
943 return DBA::toArray($r);
949 * @brief Removes a workerqueue entry from the current process
953 public static function unclaimProcess()
957 $stamp = (float)microtime(true);
958 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
959 self::$db_duration += (microtime(true) - $stamp);
960 self::$db_duration_write += (microtime(true) - $stamp);
964 * @brief Call the front end worker
966 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
968 public static function callWorker()
970 if (!Config::get("system", "frontend_worker")) {
974 $url = System::baseUrl()."/worker";
975 Network::fetchUrl($url, false, $redirects, 1);
979 * @brief Call the front end worker if there aren't any active
981 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
983 public static function executeIfIdle()
985 if (!Config::get("system", "frontend_worker")) {
989 // Do we have "proc_open"? Then we can fork the worker
990 if (function_exists("proc_open")) {
991 // When was the last time that we called the worker?
992 // Less than one minute? Then we quit
993 if ((time() - Config::get("system", "worker_started")) < 60) {
997 Config::set("system", "worker_started", time());
999 // Do we have enough running workers? Then we quit here.
1000 if (self::tooMuchWorkers()) {
1001 // Cleaning dead processes
1002 self::killStaleWorkers();
1003 Process::deleteInactive();
1010 Logger::log('Call worker', Logger::DEBUG);
1011 self::spawnWorker();
1015 // We cannot execute background processes.
1016 // We now run the processes from the frontend.
1017 // This won't work with long running processes.
1020 self::clearProcesses();
1022 $workers = self::activeWorkers();
1024 if ($workers == 0) {
1030 * @brief Removes long running worker processes
1032 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1034 public static function clearProcesses()
1036 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1038 /// @todo We should clean up the corresponding workerqueue entries as well
1039 $stamp = (float)microtime(true);
1040 $condition = ["`created` < ? AND `command` = 'worker.php'",
1041 DateTimeFormat::utc("now - ".$timeout." minutes")];
1042 DBA::delete('process', $condition);
1043 self::$db_duration = (microtime(true) - $stamp);
1044 self::$db_duration_write += (microtime(true) - $stamp);
1048 * @brief Runs the cron processes
1050 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1052 private static function runCron()
1054 Logger::log('Add cron entries', Logger::DEBUG);
1056 // Check for spooled items
1057 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1059 // Run the cron job that calls all other jobs
1060 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1062 // Cleaning dead processes
1063 self::killStaleWorkers();
1067 * @brief Spawns a new worker
1068 * @param bool $do_cron
1070 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1072 public static function spawnWorker($do_cron = false)
1074 $command = 'bin/worker.php';
1076 $args = ['no_cron' => !$do_cron];
1078 get_app()->proc_run($command, $args);
1080 // after spawning we have to remove the flag.
1081 if (Config::get('system', 'worker_daemon_mode', false)) {
1082 self::IPCSetJobState(false);
1087 * @brief Adds tasks to the worker queue
1089 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1091 * next args are passed as $cmd command line
1092 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1093 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1095 * @return boolean "false" if proc_run couldn't be executed
1096 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1097 * @note $cmd and string args are surrounded with ""
1103 public static function add($cmd)
1105 $args = func_get_args();
1107 if (!count($args)) {
1111 $arr = ['args' => $args, 'run_cmd' => true];
1113 Hook::callAll("proc_run", $arr);
1114 if (!$arr['run_cmd'] || !count($args)) {
1118 $priority = PRIORITY_MEDIUM;
1119 $dont_fork = Config::get("system", "worker_dont_fork", false);
1120 $created = DateTimeFormat::utcNow();
1121 $force_priority = false;
1123 $run_parameter = array_shift($args);
1125 if (is_int($run_parameter)) {
1126 $priority = $run_parameter;
1127 } elseif (is_array($run_parameter)) {
1128 if (isset($run_parameter['priority'])) {
1129 $priority = $run_parameter['priority'];
1131 if (isset($run_parameter['created'])) {
1132 $created = $run_parameter['created'];
1134 if (isset($run_parameter['dont_fork'])) {
1135 $dont_fork = $run_parameter['dont_fork'];
1137 if (isset($run_parameter['force_priority'])) {
1138 $force_priority = $run_parameter['force_priority'];
1142 $parameters = json_encode($args);
1143 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1145 // Quit if there was a database error - a precaution for the update process to 3.5.3
1146 if (DBA::errorNo() != 0) {
1151 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1152 } elseif ($force_priority) {
1153 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1156 // Should we quit and wait for the worker to be called as a cronjob?
1161 // If there is a lock then we don't have to check for too much worker
1162 if (!Lock::acquire('worker', 0)) {
1166 // If there are already enough workers running, don't fork another one
1167 $quit = self::tooMuchWorkers();
1168 Lock::release('worker');
1174 // We tell the daemon that a new job entry exists
1175 if (Config::get('system', 'worker_daemon_mode', false)) {
1176 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1180 // Now call the worker to execute the jobs that we just added to the queue
1181 self::spawnWorker();
1187 * Defers the current worker entry
1189 public static function defer()
1191 if (empty(BaseObject::getApp()->queue)) {
1195 $queue = BaseObject::getApp()->queue;
1197 $retrial = $queue['retrial'];
1199 $priority = $queue['priority'];
1201 if ($retrial > 14) {
1202 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1206 // Calculate the delay until the next trial
1207 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1208 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1210 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1211 $priority = PRIORITY_MEDIUM;
1212 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1213 $priority = PRIORITY_LOW;
1214 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1215 $priority = PRIORITY_NEGLIGIBLE;
1218 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1220 $stamp = (float)microtime(true);
1221 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1222 DBA::update('workerqueue', $fields, ['id' => $id]);
1223 self::$db_duration += (microtime(true) - $stamp);
1224 self::$db_duration_write += (microtime(true) - $stamp);
1228 * Log active processes into the "process" table
1230 * @brief Log active processes into the "process" table
1232 public static function startProcess()
1234 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1236 $command = basename($trace[0]['file']);
1238 Process::deleteInactive();
1240 Process::insert($command);
1244 * Remove the active process from the "process" table
1246 * @brief Remove the active process from the "process" table
1248 * @throws \Exception
1250 public static function endProcess()
1252 return Process::deleteByPid();
1256 * Set the flag if some job is waiting
1258 * @brief Set the flag if some job is waiting
1259 * @param boolean $jobs Is there a waiting job?
1260 * @throws \Exception
1262 public static function IPCSetJobState($jobs)
1264 $stamp = (float)microtime(true);
1265 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1266 self::$db_duration += (microtime(true) - $stamp);
1267 self::$db_duration_write += (microtime(true) - $stamp);
1271 * Checks if some worker job waits to be executed
1273 * @brief Checks if some worker job waits to be executed
1275 * @throws \Exception
1277 public static function IPCJobsExists()
1279 $stamp = (float)microtime(true);
1280 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1281 self::$db_duration += (microtime(true) - $stamp);
1283 // When we don't have a row, no job is running
1284 if (!DBA::isResult($row)) {
1288 return (bool)$row['jobs'];