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_SHORT_LOOP = 2; // Worker is processing preassigned jobs, thus saving much time.
27 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
28 const STATE_LONG_LOOP = 4; // Worker is processing the whole - long - loop.
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()) {
105 foreach ($r as $entry) {
106 // Assure that the priority is an integer value
107 $entry['priority'] = (int)$entry['priority'];
109 // The work will be done
110 if (!self::execute($entry)) {
111 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
115 // If possible we will fetch new jobs for this worker
116 if (!self::getWaitingJobForPID() && Lock::acquire('worker_process', 0)) {
117 self::findWorkerProcesses();
118 Lock::release('worker_process');
119 self::$state = self::STATE_REFETCH;
123 if (self::$state != self::STATE_REFETCH) {
124 self::$state = self::STATE_LONG_LOOP;
127 // To avoid the quitting of multiple workers only one worker at a time will execute the check
128 if (Lock::acquire('worker', 0)) {
129 // Count active workers and compare them with a maximum value that depends on the load
130 if (self::tooMuchWorkers()) {
131 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
132 Lock::release('worker');
137 if ($a->isMinMemoryReached()) {
138 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
139 Lock::release('worker');
142 Lock::release('worker');
145 // Quit the worker once every cron interval
146 if (time() > ($starttime + (Config::get('system', 'cron_interval') * 60))) {
147 Logger::info('Process lifetime reached, respawning.');
153 // Cleaning up. Possibly not needed, but it doesn't harm anything.
154 if (Config::get('system', 'worker_daemon_mode', false)) {
155 self::IPCSetJobState(false);
157 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
161 * @brief Check if non executed tasks do exist in the worker queue
163 * @return boolean Returns "true" if tasks are existing
166 private static function entriesExists()
168 $stamp = (float)microtime(true);
169 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
170 self::$db_duration += (microtime(true) - $stamp);
175 * @brief Returns the number of deferred entries in the worker queue
177 * @return integer Number of deferred entries in the worker queue
180 private static function deferredEntries()
182 $stamp = (float)microtime(true);
183 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` > ?", DateTimeFormat::utcNow()]);
184 self::$db_duration += (microtime(true) - $stamp);
185 self::$db_duration_count += (microtime(true) - $stamp);
190 * @brief Returns the number of non executed entries in the worker queue
192 * @return integer Number of non executed entries in the worker queue
195 private static function totalEntries()
197 $stamp = (float)microtime(true);
198 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
199 self::$db_duration += (microtime(true) - $stamp);
200 self::$db_duration_count += (microtime(true) - $stamp);
205 * @brief Returns the highest priority in the worker queue that isn't executed
207 * @return integer Number of active worker processes
210 private static function highestPriority()
212 $stamp = (float)microtime(true);
213 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
214 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
215 self::$db_duration += (microtime(true) - $stamp);
216 if (DBA::isResult($workerqueue)) {
217 return $workerqueue["priority"];
224 * @brief Returns if a process with the given priority is running
226 * @param integer $priority The priority that should be checked
228 * @return integer Is there a process running with that priority?
231 private static function processWithPriorityActive($priority)
233 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
234 return DBA::exists('workerqueue', $condition);
238 * @brief Execute a worker entry
240 * @param array $queue Workerqueue entry
242 * @return boolean "true" if further processing should be stopped
243 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
245 public static function execute($queue)
251 // Quit when in maintenance
252 if (Config::get('system', 'maintenance', false, true)) {
253 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
257 // Constantly check the number of parallel database processes
258 if ($a->isMaxProcessesReached()) {
259 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
263 // Constantly check the number of available database connections to let the frontend be accessible at any time
264 if (self::maxConnectionsReached()) {
265 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
269 $argv = json_decode($queue["parameter"], true);
271 // Check for existance and validity of the include file
274 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
275 // We constantly update the "executed" date every minute to avoid being killed too soon
276 if (!isset(self::$last_update)) {
277 self::$last_update = strtotime($queue["executed"]);
280 $age = (time() - self::$last_update) / 60;
281 self::$last_update = time();
284 $stamp = (float)microtime(true);
285 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
286 self::$db_duration += (microtime(true) - $stamp);
287 self::$db_duration_write += (microtime(true) - $stamp);
292 self::execFunction($queue, $include, $argv, true);
294 $stamp = (float)microtime(true);
295 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
296 if (DBA::update('workerqueue', ['done' => true], $condition)) {
297 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
299 self::$db_duration = (microtime(true) - $stamp);
300 self::$db_duration_write += (microtime(true) - $stamp);
305 // The script could be provided as full path or only with the function name
306 if ($include == basename($include)) {
307 $include = "include/".$include.".php";
310 if (!validate_include($include)) {
311 Logger::log("Include file ".$argv[0]." is not valid!");
312 $stamp = (float)microtime(true);
313 DBA::delete('workerqueue', ['id' => $queue["id"]]);
314 self::$db_duration = (microtime(true) - $stamp);
315 self::$db_duration_write += (microtime(true) - $stamp);
319 require_once $include;
321 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
323 if (function_exists($funcname)) {
324 // We constantly update the "executed" date every minute to avoid being killed too soon
325 if (!isset(self::$last_update)) {
326 self::$last_update = strtotime($queue["executed"]);
329 $age = (time() - self::$last_update) / 60;
330 self::$last_update = time();
333 $stamp = (float)microtime(true);
334 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
335 self::$db_duration += (microtime(true) - $stamp);
336 self::$db_duration_write += (microtime(true) - $stamp);
339 self::execFunction($queue, $funcname, $argv, false);
341 $stamp = (float)microtime(true);
342 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
343 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
345 self::$db_duration = (microtime(true) - $stamp);
346 self::$db_duration_write += (microtime(true) - $stamp);
348 Logger::log("Function ".$funcname." does not exist");
349 $stamp = (float)microtime(true);
350 DBA::delete('workerqueue', ['id' => $queue["id"]]);
351 self::$db_duration = (microtime(true) - $stamp);
352 self::$db_duration_write += (microtime(true) - $stamp);
359 * @brief Execute a function from the queue
361 * @param array $queue Workerqueue entry
362 * @param string $funcname name of the function
363 * @param array $argv Array of values to be passed to the function
364 * @param boolean $method_call boolean
366 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
368 private static function execFunction($queue, $funcname, $argv, $method_call)
372 $argc = count($argv);
374 $logger = $a->getLogger();
375 $workerLogger = new WorkerLogger($logger, $funcname);
377 $workerLogger ->info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["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();
387 $up_duration = microtime(true) - self::$up_start;
389 // Reset global data to avoid interferences
392 // Set the workerLogger as new default logger
393 Logger::init($workerLogger);
395 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
397 $funcname($argv, $argc);
399 Logger::init($logger);
403 $duration = (microtime(true) - $stamp);
405 /* With these values we can analyze how effective the worker is.
406 * The database and rest time should be low since this is the unproductive time.
407 * The execution time is the productive time.
408 * By changing parameters like the maximum number of workers we can check the effectivness.
410 $dbtotal = round(self::$db_duration, 2);
411 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
412 $dbcount = round(self::$db_duration_count, 2);
413 $dbstat = round(self::$db_duration_stat, 2);
414 $dbwrite = round(self::$db_duration_write, 2);
415 $dblock = round(self::$lock_duration, 2);
416 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
417 $exec = round($duration, 2);
419 $logger->info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
421 self::$up_start = microtime(true);
422 self::$db_duration = 0;
423 self::$db_duration_count = 0;
424 self::$db_duration_stat = 0;
425 self::$db_duration_write = 0;
426 self::$lock_duration = 0;
427 self::$state = self::STATE_SHORT_LOOP;
429 if ($duration > 3600) {
430 $logger->info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
431 } elseif ($duration > 600) {
432 $logger->info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
433 } elseif ($duration > 300) {
434 $logger->info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
435 } elseif ($duration > 120) {
436 $logger->info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
439 $workerLogger->info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
441 $a->getProfiler()->saveLog($a->getLogger(), "ID " . $queue["id"] . ": " . $funcname);
443 $cooldown = Config::get("system", "worker_cooldown", 0);
446 $logger->info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
452 * @brief Checks if the number of database connections has reached a critical limit.
454 * @return bool Are more than 3/4 of the maximum connections used?
455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457 private static function maxConnectionsReached()
459 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
460 $max = Config::get("system", "max_connections");
462 // Fetch the percentage level where the worker will get active
463 $maxlevel = Config::get("system", "max_connections_level", 75);
466 // the maximum number of possible user connections can be a system variable
467 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
468 if (DBA::isResult($r)) {
471 // Or it can be granted. This overrides the system variable
472 $stamp = (float)microtime(true);
473 $r = DBA::p('SHOW GRANTS');
474 self::$db_duration += (microtime(true) - $stamp);
475 while ($grants = DBA::fetch($r)) {
476 $grant = array_pop($grants);
477 if (stristr($grant, "GRANT USAGE ON")) {
478 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
486 // If $max is set we will use the processlist to determine the current number of connections
487 // The processlist only shows entries of the current user
489 $stamp = (float)microtime(true);
490 $r = DBA::p('SHOW PROCESSLIST');
491 self::$db_duration += (microtime(true) - $stamp);
492 $used = DBA::numRows($r);
495 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
497 $level = ($used / $max) * 100;
499 if ($level >= $maxlevel) {
500 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
505 // We will now check for the system values.
506 // This limit could be reached although the user limits are fine.
507 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
508 if (!DBA::isResult($r)) {
511 $max = intval($r["Value"]);
515 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
516 if (!DBA::isResult($r)) {
519 $used = intval($r["Value"]);
523 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
525 $level = $used / $max * 100;
527 if ($level < $maxlevel) {
530 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
535 * @brief fix the queue entry if the worker process died
539 private static function killStaleWorkers()
541 $stamp = (float)microtime(true);
542 $entries = DBA::select(
544 ['id', 'pid', 'executed', 'priority', 'parameter'],
545 ['NOT `done` AND `pid` != 0'],
546 ['order' => ['priority', 'created']]
548 self::$db_duration += (microtime(true) - $stamp);
550 while ($entry = DBA::fetch($entries)) {
551 if (!posix_kill($entry["pid"], 0)) {
552 $stamp = (float)microtime(true);
555 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
556 ['id' => $entry["id"]]
558 self::$db_duration += (microtime(true) - $stamp);
559 self::$db_duration_write += (microtime(true) - $stamp);
561 // Kill long running processes
562 // Check if the priority is in a valid range
563 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
564 $entry["priority"] = PRIORITY_MEDIUM;
567 // Define the maximum durations
568 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
569 $max_duration = $max_duration_defaults[$entry["priority"]];
571 $argv = json_decode($entry["parameter"], true);
572 $argv[0] = basename($argv[0]);
574 // How long is the process already running?
575 $duration = (time() - strtotime($entry["executed"])) / 60;
576 if ($duration > $max_duration) {
577 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
578 posix_kill($entry["pid"], SIGTERM);
580 // We killed the stale process.
581 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
582 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
583 $new_priority = $entry["priority"];
584 if ($entry["priority"] == PRIORITY_HIGH) {
585 $new_priority = PRIORITY_MEDIUM;
586 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
587 $new_priority = PRIORITY_LOW;
588 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
589 $new_priority = PRIORITY_NEGLIGIBLE;
591 $stamp = (float)microtime(true);
594 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
595 ['id' => $entry["id"]]
597 self::$db_duration += (microtime(true) - $stamp);
598 self::$db_duration_write += (microtime(true) - $stamp);
600 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);
607 * @brief Checks if the number of active workers exceeds the given limits
609 * @return bool Are there too much workers running?
610 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
612 private static function tooMuchWorkers()
614 $queues = Config::get("system", "worker_queues", 10);
616 $maxqueues = $queues;
618 $active = self::activeWorkers();
620 // Decrease the number of workers at higher load
621 $load = System::currentLoad();
623 $maxsysload = intval(Config::get("system", "maxloadavg", 20));
625 /* Default exponent 3 causes queues to rapidly decrease as load increases.
626 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
627 * For some environments, this rapid decrease is not needed.
628 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
630 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
631 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
632 $queues = intval(ceil($slope * $maxqueues));
636 if (Config::get('system', 'worker_jpm')) {
637 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
638 $jobs_per_minute = [];
639 foreach ($intervals as $interval) {
640 if ($interval == 0) {
643 $interval = (int)$interval;
646 $stamp = (float)microtime(true);
647 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
648 self::$db_duration += (microtime(true) - $stamp);
649 self::$db_duration_stat += (microtime(true) - $stamp);
650 if ($job = DBA::fetch($jobs)) {
651 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
655 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
658 // Create a list of queue entries grouped by their priority
659 $listitem = [0 => ''];
661 $idle_workers = $active;
663 $deferred = self::deferredEntries();
665 if (Config::get('system', 'worker_debug')) {
666 $waiting_processes = 0;
667 // Now adding all processes with workerqueue entries
668 $stamp = (float)microtime(true);
669 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
670 self::$db_duration += (microtime(true) - $stamp);
671 self::$db_duration_stat += (microtime(true) - $stamp);
672 while ($entry = DBA::fetch($jobs)) {
673 $stamp = (float)microtime(true);
674 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
675 self::$db_duration += (microtime(true) - $stamp);
676 self::$db_duration_stat += (microtime(true) - $stamp);
677 if ($process = DBA::fetch($processes)) {
678 $idle_workers -= $process["running"];
679 $waiting_processes += $entry["entries"];
680 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
682 DBA::close($processes);
685 $entries = $deferred + $waiting_processes;
687 $entries = self::totalEntries();
688 $waiting_processes = max(0, $entries - $deferred);
689 $stamp = (float)microtime(true);
690 $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`");
691 self::$db_duration += (microtime(true) - $stamp);
692 self::$db_duration_stat += (microtime(true) - $stamp);
694 while ($entry = DBA::fetch($jobs)) {
695 $idle_workers -= $entry["running"];
696 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
701 $listitem[0] = "0:" . max(0, $idle_workers);
703 $processlist .= ' ('.implode(', ', $listitem).')';
705 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && self::entriesExists() && ($active >= $queues)) {
706 $top_priority = self::highestPriority();
707 $high_running = self::processWithPriorityActive($top_priority);
709 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
710 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
711 $queues = $active + 1;
715 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
717 // Are there fewer workers running as possible? Then fork a new one.
718 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
719 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
720 if (Config::get('system', 'worker_daemon_mode', false)) {
721 self::IPCSetJobState(true);
728 // if there are too much worker, we don't spawn a new one.
729 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
730 self::IPCSetJobState(false);
733 return $active > $queues;
737 * @brief Returns the number of active worker processes
739 * @return integer Number of active worker processes
742 private static function activeWorkers()
744 $stamp = (float)microtime(true);
745 $count = DBA::count('process', ['command' => 'Worker.php']);
746 self::$db_duration += (microtime(true) - $stamp);
751 * @brief Returns waiting jobs for the current process id
753 * @return array waiting workerqueue jobs
756 private static function getWaitingJobForPID()
758 $stamp = (float)microtime(true);
759 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
760 self::$db_duration += (microtime(true) - $stamp);
761 if (DBA::isResult($r)) {
762 return DBA::toArray($r);
770 * @brief Returns the next jobs that should be executed
772 * @return array array with next jobs
775 private static function nextProcess()
777 $priority = self::nextPriority();
778 if (empty($priority)) {
779 Logger::info('No tasks found');
783 if ($priority <= PRIORITY_MEDIUM) {
784 $limit = Config::get('system', 'worker_fetch_limit', 1);
790 $stamp = (float)microtime(true);
791 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
792 $tasks = DBA::select('workerqueue', ['id'], $condition, ['limit' => $limit, 'order' => ['created']]);
793 self::$db_duration += (microtime(true) - $stamp);
794 while ($task = DBA::fetch($tasks)) {
795 $ids[] = $task['id'];
799 Logger::info('Found:', ['id' => $ids, 'priority' => $priority]);
804 * @brief Returns the priority of the next workerqueue job
806 * @return string priority
809 private static function nextPriority()
812 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
813 foreach ($priorities as $priority) {
814 $stamp = (float)microtime(true);
815 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
816 $waiting[$priority] = true;
818 self::$db_duration += (microtime(true) - $stamp);
821 if (!empty($waiting[PRIORITY_CRITICAL])) {
822 return PRIORITY_CRITICAL;
827 $stamp = (float)microtime(true);
828 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
829 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
830 WHERE NOT `done` GROUP BY `priority`");
831 self::$db_duration += (microtime(true) - $stamp);
832 while ($process = DBA::fetch($processes)) {
833 $running[$process['priority']] = $process['running'];
834 $running_total += $process['running'];
836 DBA::close($processes);
838 foreach ($priorities as $priority) {
839 if (!empty($waiting[$priority]) && empty($running[$priority])) {
840 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
845 $active = max(self::activeWorkers(), $running_total);
846 $priorities = max(count($waiting), count($running));
850 for ($i = 1; $i <= $priorities; ++$i) {
851 $total += pow($i, $exponent);
855 for ($i = 1; $i <= $priorities; ++$i) {
856 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
860 foreach ($running as $priority => $workers) {
861 if ($workers < $limit[$i++]) {
862 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
867 if (!empty($waiting)) {
868 $priority = array_keys($waiting)[0];
869 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
877 * @brief Find and claim the next worker process for us
879 * @return boolean Have we found something?
880 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
882 private static function findWorkerProcesses()
886 $ids = self::nextProcess();
888 // If there is no result we check without priority limit
890 $stamp = (float)microtime(true);
891 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
892 $result = DBA::select('workerqueue', ['id'], $condition, ['limit' => 1, 'order' => ['priority', 'created']]);
893 self::$db_duration += (microtime(true) - $stamp);
895 while ($id = DBA::fetch($result)) {
902 $stamp = (float)microtime(true);
903 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
904 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
905 self::$db_duration += (microtime(true) - $stamp);
906 self::$db_duration_write += (microtime(true) - $stamp);
913 * @brief Returns the next worker process
915 * @return string SQL statement
916 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
918 public static function workerProcess()
920 // There can already be jobs for us in the queue.
921 $waiting = self::getWaitingJobForPID();
922 if (!empty($waiting)) {
926 $stamp = (float)microtime(true);
927 if (!Lock::acquire('worker_process')) {
930 self::$lock_duration += (microtime(true) - $stamp);
932 $found = self::findWorkerProcesses();
934 Lock::release('worker_process');
937 $stamp = (float)microtime(true);
938 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
939 self::$db_duration += (microtime(true) - $stamp);
940 return DBA::toArray($r);
946 * @brief Removes a workerqueue entry from the current process
950 public static function unclaimProcess()
954 $stamp = (float)microtime(true);
955 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
956 self::$db_duration += (microtime(true) - $stamp);
957 self::$db_duration_write += (microtime(true) - $stamp);
961 * @brief Call the front end worker
963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
965 public static function callWorker()
967 if (!Config::get("system", "frontend_worker")) {
971 $url = System::baseUrl()."/worker";
972 Network::fetchUrl($url, false, $redirects, 1);
976 * @brief Call the front end worker if there aren't any active
978 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
980 public static function executeIfIdle()
982 if (!Config::get("system", "frontend_worker")) {
986 // Do we have "proc_open"? Then we can fork the worker
987 if (function_exists("proc_open")) {
988 // When was the last time that we called the worker?
989 // Less than one minute? Then we quit
990 if ((time() - Config::get("system", "worker_started")) < 60) {
994 Config::set("system", "worker_started", time());
996 // Do we have enough running workers? Then we quit here.
997 if (self::tooMuchWorkers()) {
998 // Cleaning dead processes
999 self::killStaleWorkers();
1000 Process::deleteInactive();
1007 Logger::log('Call worker', Logger::DEBUG);
1008 self::spawnWorker();
1012 // We cannot execute background processes.
1013 // We now run the processes from the frontend.
1014 // This won't work with long running processes.
1017 self::clearProcesses();
1019 $workers = self::activeWorkers();
1021 if ($workers == 0) {
1027 * @brief Removes long running worker processes
1029 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1031 public static function clearProcesses()
1033 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1035 /// @todo We should clean up the corresponding workerqueue entries as well
1036 $stamp = (float)microtime(true);
1037 $condition = ["`created` < ? AND `command` = 'worker.php'",
1038 DateTimeFormat::utc("now - ".$timeout." minutes")];
1039 DBA::delete('process', $condition);
1040 self::$db_duration = (microtime(true) - $stamp);
1041 self::$db_duration_write += (microtime(true) - $stamp);
1045 * @brief Runs the cron processes
1047 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1049 private static function runCron()
1051 Logger::log('Add cron entries', Logger::DEBUG);
1053 // Check for spooled items
1054 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1056 // Run the cron job that calls all other jobs
1057 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1059 // Cleaning dead processes
1060 self::killStaleWorkers();
1064 * @brief Spawns a new worker
1065 * @param bool $do_cron
1067 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1069 public static function spawnWorker($do_cron = false)
1071 $command = 'bin/worker.php';
1073 $args = ['no_cron' => !$do_cron];
1075 get_app()->proc_run($command, $args);
1077 // after spawning we have to remove the flag.
1078 if (Config::get('system', 'worker_daemon_mode', false)) {
1079 self::IPCSetJobState(false);
1084 * @brief Adds tasks to the worker queue
1086 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1088 * next args are passed as $cmd command line
1089 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1090 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1092 * @return boolean "false" if proc_run couldn't be executed
1093 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1094 * @note $cmd and string args are surrounded with ""
1100 public static function add($cmd)
1102 $args = func_get_args();
1104 if (!count($args)) {
1108 $arr = ['args' => $args, 'run_cmd' => true];
1110 Hook::callAll("proc_run", $arr);
1111 if (!$arr['run_cmd'] || !count($args)) {
1115 $priority = PRIORITY_MEDIUM;
1116 $dont_fork = Config::get("system", "worker_dont_fork", false);
1117 $created = DateTimeFormat::utcNow();
1118 $force_priority = false;
1120 $run_parameter = array_shift($args);
1122 if (is_int($run_parameter)) {
1123 $priority = $run_parameter;
1124 } elseif (is_array($run_parameter)) {
1125 if (isset($run_parameter['priority'])) {
1126 $priority = $run_parameter['priority'];
1128 if (isset($run_parameter['created'])) {
1129 $created = $run_parameter['created'];
1131 if (isset($run_parameter['dont_fork'])) {
1132 $dont_fork = $run_parameter['dont_fork'];
1134 if (isset($run_parameter['force_priority'])) {
1135 $force_priority = $run_parameter['force_priority'];
1139 $parameters = json_encode($args);
1140 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1142 // Quit if there was a database error - a precaution for the update process to 3.5.3
1143 if (DBA::errorNo() != 0) {
1148 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1149 } elseif ($force_priority) {
1150 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1153 // Should we quit and wait for the worker to be called as a cronjob?
1158 // If there is a lock then we don't have to check for too much worker
1159 if (!Lock::acquire('worker', 0)) {
1163 // If there are already enough workers running, don't fork another one
1164 $quit = self::tooMuchWorkers();
1165 Lock::release('worker');
1171 // We tell the daemon that a new job entry exists
1172 if (Config::get('system', 'worker_daemon_mode', false)) {
1173 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1177 // Now call the worker to execute the jobs that we just added to the queue
1178 self::spawnWorker();
1184 * Defers the current worker entry
1186 public static function defer()
1188 if (empty(BaseObject::getApp()->queue)) {
1192 $queue = BaseObject::getApp()->queue;
1194 $retrial = $queue['retrial'];
1196 $priority = $queue['priority'];
1198 if ($retrial > 14) {
1199 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1203 // Calculate the delay until the next trial
1204 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1205 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1207 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1208 $priority = PRIORITY_MEDIUM;
1209 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1210 $priority = PRIORITY_LOW;
1211 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1212 $priority = PRIORITY_NEGLIGIBLE;
1215 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1217 $stamp = (float)microtime(true);
1218 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1219 DBA::update('workerqueue', $fields, ['id' => $id]);
1220 self::$db_duration += (microtime(true) - $stamp);
1221 self::$db_duration_write += (microtime(true) - $stamp);
1225 * Log active processes into the "process" table
1227 * @brief Log active processes into the "process" table
1229 public static function startProcess()
1231 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1233 $command = basename($trace[0]['file']);
1235 Process::deleteInactive();
1237 Process::insert($command);
1241 * Remove the active process from the "process" table
1243 * @brief Remove the active process from the "process" table
1245 * @throws \Exception
1247 public static function endProcess()
1249 return Process::deleteByPid();
1253 * Set the flag if some job is waiting
1255 * @brief Set the flag if some job is waiting
1256 * @param boolean $jobs Is there a waiting job?
1257 * @throws \Exception
1259 public static function IPCSetJobState($jobs)
1261 $stamp = (float)microtime(true);
1262 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1263 self::$db_duration += (microtime(true) - $stamp);
1264 self::$db_duration_write += (microtime(true) - $stamp);
1268 * Checks if some worker job waits to be executed
1270 * @brief Checks if some worker job waits to be executed
1272 * @throws \Exception
1274 public static function IPCJobsExists()
1276 $stamp = (float)microtime(true);
1277 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1278 self::$db_duration += (microtime(true) - $stamp);
1280 // When we don't have a row, no job is running
1281 if (!DBA::isResult($row)) {
1285 return (bool)$row['jobs'];