3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
8 use Friendica\Database\DBA;
10 use Friendica\Model\Process;
11 use Friendica\Util\DateTimeFormat;
12 use Friendica\Util\Network;
15 * @file src/Core/Worker.php
17 * Contains the class for the worker background job processing
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 const FAST_COMMANDS = ['APDelivery', 'Delivery', 'CreateShadowEntry'];
33 private static $up_start;
34 private static $db_duration = 0;
35 private static $db_duration_count = 0;
36 private static $db_duration_write = 0;
37 private static $db_duration_stat = 0;
38 private static $lock_duration = 0;
39 private static $last_update;
40 private static $state;
43 * Processes the tasks that are in the workerqueue table
45 * @param boolean $run_cron Should the cron processes be executed?
47 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
49 public static function processQueue($run_cron = true)
51 // Ensure that all "strtotime" operations do run timezone independent
52 date_default_timezone_set('UTC');
54 self::$up_start = microtime(true);
56 // At first check the maximum load. We shouldn't continue with a high load
57 if (DI::process()->isMaxLoadReached()) {
58 Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
62 // We now start the process. This is done after the load check since this could increase the load.
65 // Kill stale processes every 5 minutes
66 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
67 if (time() > ($last_cleanup + 300)) {
68 DI::config()->set('system', 'worker_last_cleaned', time());
69 self::killStaleWorkers();
72 // Count active workers and compare them with a maximum value that depends on the load
73 if (self::tooMuchWorkers()) {
74 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
78 // Do we have too few memory?
79 if (DI::process()->isMinMemoryReached()) {
80 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
84 // Possibly there are too much database connections
85 if (self::maxConnectionsReached()) {
86 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
90 // Possibly there are too much database processes that block the system
91 if (DI::process()->isMaxProcessesReached()) {
92 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
96 // Now we start additional cron processes if we should do so
102 self::$state = self::STATE_STARTUP;
104 // We fetch the next queue entry that is about to be executed
105 while ($r = self::workerProcess()) {
107 foreach ($r as $entry) {
108 // Assure that the priority is an integer value
109 $entry['priority'] = (int)$entry['priority'];
111 // The work will be done
112 if (!self::execute($entry)) {
113 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
117 // Trying to fetch new processes - but only once when successful
118 if (!$refetched && DI::lock()->acquire('worker_process', 0)) {
119 self::findWorkerProcesses();
120 DI::lock()->release('worker_process');
121 self::$state = self::STATE_REFETCH;
124 self::$state = self::STATE_SHORT_LOOP;
128 // To avoid the quitting of multiple workers only one worker at a time will execute the check
129 if (!self::getWaitingJobForPID()) {
130 self::$state = self::STATE_LONG_LOOP;
132 if (DI::lock()->acquire('worker', 0)) {
133 // Count active workers and compare them with a maximum value that depends on the load
134 if (self::tooMuchWorkers()) {
135 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
136 DI::lock()->release('worker');
141 if (DI::process()->isMinMemoryReached()) {
142 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
143 DI::lock()->release('worker');
146 DI::lock()->release('worker');
150 // Quit the worker once every cron interval
151 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
152 Logger::info('Process lifetime reached, respawning.');
158 // Cleaning up. Possibly not needed, but it doesn't harm anything.
159 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
160 self::IPCSetJobState(false);
162 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
166 * Check if non executed tasks do exist in the worker queue
168 * @return boolean Returns "true" if tasks are existing
171 private static function entriesExists()
173 $stamp = (float)microtime(true);
174 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
175 self::$db_duration += (microtime(true) - $stamp);
180 * Returns the number of deferred entries in the worker queue
182 * @return integer Number of deferred entries in the worker queue
185 private static function deferredEntries()
187 $stamp = (float)microtime(true);
188 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
189 self::$db_duration += (microtime(true) - $stamp);
190 self::$db_duration_count += (microtime(true) - $stamp);
195 * Returns the number of non executed entries in the worker queue
197 * @return integer Number of non executed entries in the worker queue
200 private static function totalEntries()
202 $stamp = (float)microtime(true);
203 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
204 self::$db_duration += (microtime(true) - $stamp);
205 self::$db_duration_count += (microtime(true) - $stamp);
210 * Returns the highest priority in the worker queue that isn't executed
212 * @return integer Number of active worker processes
215 private static function highestPriority()
217 $stamp = (float)microtime(true);
218 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
219 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
220 self::$db_duration += (microtime(true) - $stamp);
221 if (DBA::isResult($workerqueue)) {
222 return $workerqueue["priority"];
229 * Returns if a process with the given priority is running
231 * @param integer $priority The priority that should be checked
233 * @return integer Is there a process running with that priority?
236 private static function processWithPriorityActive($priority)
238 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
239 return DBA::exists('workerqueue', $condition);
243 * Execute a worker entry
245 * @param array $queue Workerqueue entry
247 * @return boolean "true" if further processing should be stopped
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 public static function execute($queue)
254 // Quit when in maintenance
255 if (DI::config()->get('system', 'maintenance', false, true)) {
256 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
260 // Constantly check the number of parallel database processes
261 if (DI::process()->isMaxProcessesReached()) {
262 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
266 // Constantly check the number of available database connections to let the frontend be accessible at any time
267 if (self::maxConnectionsReached()) {
268 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
272 $argv = json_decode($queue["parameter"], true);
274 // Check for existance and validity of the include file
277 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
278 // We constantly update the "executed" date every minute to avoid being killed too soon
279 if (!isset(self::$last_update)) {
280 self::$last_update = strtotime($queue["executed"]);
283 $age = (time() - self::$last_update) / 60;
284 self::$last_update = time();
287 $stamp = (float)microtime(true);
288 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
289 self::$db_duration += (microtime(true) - $stamp);
290 self::$db_duration_write += (microtime(true) - $stamp);
295 self::execFunction($queue, $include, $argv, true);
297 $stamp = (float)microtime(true);
298 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
299 if (DBA::update('workerqueue', ['done' => true], $condition)) {
300 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
302 self::$db_duration = (microtime(true) - $stamp);
303 self::$db_duration_write += (microtime(true) - $stamp);
308 // The script could be provided as full path or only with the function name
309 if ($include == basename($include)) {
310 $include = "include/".$include.".php";
313 if (!validate_include($include)) {
314 Logger::log("Include file ".$argv[0]." is not valid!");
315 $stamp = (float)microtime(true);
316 DBA::delete('workerqueue', ['id' => $queue["id"]]);
317 self::$db_duration = (microtime(true) - $stamp);
318 self::$db_duration_write += (microtime(true) - $stamp);
322 require_once $include;
324 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
326 if (function_exists($funcname)) {
327 // We constantly update the "executed" date every minute to avoid being killed too soon
328 if (!isset(self::$last_update)) {
329 self::$last_update = strtotime($queue["executed"]);
332 $age = (time() - self::$last_update) / 60;
333 self::$last_update = time();
336 $stamp = (float)microtime(true);
337 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
338 self::$db_duration += (microtime(true) - $stamp);
339 self::$db_duration_write += (microtime(true) - $stamp);
342 self::execFunction($queue, $funcname, $argv, false);
344 $stamp = (float)microtime(true);
345 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
346 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
348 self::$db_duration = (microtime(true) - $stamp);
349 self::$db_duration_write += (microtime(true) - $stamp);
351 Logger::log("Function ".$funcname." does not exist");
352 $stamp = (float)microtime(true);
353 DBA::delete('workerqueue', ['id' => $queue["id"]]);
354 self::$db_duration = (microtime(true) - $stamp);
355 self::$db_duration_write += (microtime(true) - $stamp);
362 * Execute a function from the queue
364 * @param array $queue Workerqueue entry
365 * @param string $funcname name of the function
366 * @param array $argv Array of values to be passed to the function
367 * @param boolean $method_call boolean
369 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
371 private static function execFunction($queue, $funcname, $argv, $method_call)
375 $argc = count($argv);
377 Logger::enableWorker($funcname);
379 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
381 $stamp = (float)microtime(true);
383 // We use the callstack here to analyze the performance of executed worker entries.
384 // For this reason the variables have to be initialized.
385 DI::profiler()->reset();
389 $up_duration = microtime(true) - self::$up_start;
391 // Reset global data to avoid interferences
394 // Set the workerLogger as new default logger
396 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
398 $funcname($argv, $argc);
401 Logger::disableWorker();
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.
412 $dbtotal = round(self::$db_duration, 2);
413 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
414 $dbcount = round(self::$db_duration_count, 2);
415 $dbstat = round(self::$db_duration_stat, 2);
416 $dbwrite = round(self::$db_duration_write, 2);
417 $dblock = round(self::$lock_duration, 2);
418 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
419 $exec = round($duration, 2);
421 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
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::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
432 } elseif ($duration > 600) {
433 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
434 } elseif ($duration > 300) {
435 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
436 } elseif ($duration > 120) {
437 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
440 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
442 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
444 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
447 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
453 * 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 = DI::config()->get("system", "max_connections");
463 // Fetch the percentage level where the worker will get active
464 $maxlevel = DI::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 * fix the queue entry if the worker process died
541 private static function killStaleWorkers()
543 $stamp = (float)microtime(true);
544 $entries = DBA::select(
546 ['id', 'pid', 'executed', 'priority', 'parameter'],
547 ['NOT `done` AND `pid` != 0'],
548 ['order' => ['priority', 'created']]
550 self::$db_duration += (microtime(true) - $stamp);
552 while ($entry = DBA::fetch($entries)) {
553 if (!posix_kill($entry["pid"], 0)) {
554 $stamp = (float)microtime(true);
557 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
558 ['id' => $entry["id"]]
560 self::$db_duration += (microtime(true) - $stamp);
561 self::$db_duration_write += (microtime(true) - $stamp);
563 // Kill long running processes
564 // Check if the priority is in a valid range
565 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
566 $entry["priority"] = PRIORITY_MEDIUM;
569 // Define the maximum durations
570 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
571 $max_duration = $max_duration_defaults[$entry["priority"]];
573 $argv = json_decode($entry["parameter"], true);
574 $argv[0] = basename($argv[0]);
576 // How long is the process already running?
577 $duration = (time() - strtotime($entry["executed"])) / 60;
578 if ($duration > $max_duration) {
579 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
580 posix_kill($entry["pid"], SIGTERM);
582 // We killed the stale process.
583 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
584 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
585 $new_priority = $entry["priority"];
586 if ($entry["priority"] == PRIORITY_HIGH) {
587 $new_priority = PRIORITY_MEDIUM;
588 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
589 $new_priority = PRIORITY_LOW;
590 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
591 $new_priority = PRIORITY_NEGLIGIBLE;
593 $stamp = (float)microtime(true);
596 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
597 ['id' => $entry["id"]]
599 self::$db_duration += (microtime(true) - $stamp);
600 self::$db_duration_write += (microtime(true) - $stamp);
602 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);
609 * Checks if the number of active workers exceeds the given limits
611 * @return bool Are there too much workers running?
612 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
614 private static function tooMuchWorkers()
616 $queues = DI::config()->get("system", "worker_queues", 10);
618 $maxqueues = $queues;
620 $active = self::activeWorkers();
622 // Decrease the number of workers at higher load
623 $load = System::currentLoad();
625 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
627 /* Default exponent 3 causes queues to rapidly decrease as load increases.
628 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
629 * For some environments, this rapid decrease is not needed.
630 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
632 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
633 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
634 $queues = intval(ceil($slope * $maxqueues));
638 if (DI::config()->get('system', 'worker_jpm')) {
639 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
640 $jobs_per_minute = [];
641 foreach ($intervals as $interval) {
642 if ($interval == 0) {
645 $interval = (int)$interval;
648 $stamp = (float)microtime(true);
649 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
650 self::$db_duration += (microtime(true) - $stamp);
651 self::$db_duration_stat += (microtime(true) - $stamp);
652 if ($job = DBA::fetch($jobs)) {
653 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
657 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
660 // Create a list of queue entries grouped by their priority
661 $listitem = [0 => ''];
663 $idle_workers = $active;
665 $deferred = self::deferredEntries();
667 if (DI::config()->get('system', 'worker_debug')) {
668 $waiting_processes = 0;
669 // Now adding all processes with workerqueue entries
670 $stamp = (float)microtime(true);
671 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
672 self::$db_duration += (microtime(true) - $stamp);
673 self::$db_duration_stat += (microtime(true) - $stamp);
674 while ($entry = DBA::fetch($jobs)) {
675 $stamp = (float)microtime(true);
676 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
677 self::$db_duration += (microtime(true) - $stamp);
678 self::$db_duration_stat += (microtime(true) - $stamp);
679 if ($process = DBA::fetch($processes)) {
680 $idle_workers -= $process["running"];
681 $waiting_processes += $entry["entries"];
682 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
684 DBA::close($processes);
688 $waiting_processes = self::totalEntries();
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 $waiting_processes -= $deferred;
703 $listitem[0] = "0:" . max(0, $idle_workers);
705 $processlist .= ' ('.implode(', ', $listitem).')';
707 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
708 $top_priority = self::highestPriority();
709 $high_running = self::processWithPriorityActive($top_priority);
711 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
712 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
713 $queues = $active + 1;
717 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
719 // Are there fewer workers running as possible? Then fork a new one.
720 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
721 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
722 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
723 self::IPCSetJobState(true);
730 // if there are too much worker, we don't spawn a new one.
731 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
732 self::IPCSetJobState(false);
735 return $active > $queues;
739 * Returns the number of active worker processes
741 * @return integer Number of active worker processes
744 private static function activeWorkers()
746 $stamp = (float)microtime(true);
747 $count = DBA::count('process', ['command' => 'Worker.php']);
748 self::$db_duration += (microtime(true) - $stamp);
753 * Returns waiting jobs for the current process id
755 * @return array waiting workerqueue jobs
758 private static function getWaitingJobForPID()
760 $stamp = (float)microtime(true);
761 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
762 self::$db_duration += (microtime(true) - $stamp);
763 if (DBA::isResult($r)) {
764 return DBA::toArray($r);
772 * Returns the next jobs that should be executed
774 * @return array array with next jobs
777 private static function nextProcess()
779 $priority = self::nextPriority();
780 if (empty($priority)) {
781 Logger::info('No tasks found');
785 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
788 $stamp = (float)microtime(true);
789 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
790 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
791 self::$db_duration += (microtime(true) - $stamp);
792 while ($task = DBA::fetch($tasks)) {
793 $ids[] = $task['id'];
794 // Only continue that loop while we are storing commands that can be processed quickly
795 $command = json_decode($task['parameter'])[0];
796 if (!in_array($command, self::FAST_COMMANDS)) {
802 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
807 * 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 * 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 $limit = DI::config()->get('system', 'worker_fetch_limit', 1);
895 $stamp = (float)microtime(true);
896 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
897 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
898 self::$db_duration += (microtime(true) - $stamp);
900 while ($task = DBA::fetch($tasks)) {
901 $ids[] = $task['id'];
902 // Only continue that loop while we are storing commands that can be processed quickly
903 $command = json_decode($task['parameter'])[0];
904 if (!in_array($command, self::FAST_COMMANDS)) {
912 $stamp = (float)microtime(true);
913 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
914 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
915 self::$db_duration += (microtime(true) - $stamp);
916 self::$db_duration_write += (microtime(true) - $stamp);
923 * Returns the next worker process
925 * @return string SQL statement
926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
928 public static function workerProcess()
930 // There can already be jobs for us in the queue.
931 $waiting = self::getWaitingJobForPID();
932 if (!empty($waiting)) {
936 $stamp = (float)microtime(true);
937 if (!DI::lock()->acquire('worker_process')) {
940 self::$lock_duration += (microtime(true) - $stamp);
942 $found = self::findWorkerProcesses();
944 DI::lock()->release('worker_process');
947 $stamp = (float)microtime(true);
948 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
949 self::$db_duration += (microtime(true) - $stamp);
950 return DBA::toArray($r);
956 * Removes a workerqueue entry from the current process
961 public static function unclaimProcess()
965 $stamp = (float)microtime(true);
966 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
967 self::$db_duration += (microtime(true) - $stamp);
968 self::$db_duration_write += (microtime(true) - $stamp);
972 * Call the front end worker
975 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
977 public static function callWorker()
979 if (!DI::config()->get("system", "frontend_worker")) {
983 $url = DI::baseUrl() . '/worker';
984 Network::fetchUrl($url, false, 1);
988 * Call the front end worker if there aren't any active
991 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
993 public static function executeIfIdle()
995 if (!DI::config()->get("system", "frontend_worker")) {
999 // Do we have "proc_open"? Then we can fork the worker
1000 if (function_exists("proc_open")) {
1001 // When was the last time that we called the worker?
1002 // Less than one minute? Then we quit
1003 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1007 DI::config()->set("system", "worker_started", time());
1009 // Do we have enough running workers? Then we quit here.
1010 if (self::tooMuchWorkers()) {
1011 // Cleaning dead processes
1012 self::killStaleWorkers();
1013 Process::deleteInactive();
1020 Logger::log('Call worker', Logger::DEBUG);
1021 self::spawnWorker();
1025 // We cannot execute background processes.
1026 // We now run the processes from the frontend.
1027 // This won't work with long running processes.
1030 self::clearProcesses();
1032 $workers = self::activeWorkers();
1034 if ($workers == 0) {
1040 * Removes long running worker processes
1043 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1045 public static function clearProcesses()
1047 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1049 /// @todo We should clean up the corresponding workerqueue entries as well
1050 $stamp = (float)microtime(true);
1051 $condition = ["`created` < ? AND `command` = 'worker.php'",
1052 DateTimeFormat::utc("now - ".$timeout." minutes")];
1053 DBA::delete('process', $condition);
1054 self::$db_duration = (microtime(true) - $stamp);
1055 self::$db_duration_write += (microtime(true) - $stamp);
1059 * Runs the cron processes
1062 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1064 private static function runCron()
1066 Logger::log('Add cron entries', Logger::DEBUG);
1068 // Check for spooled items
1069 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1071 // Run the cron job that calls all other jobs
1072 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1074 // Cleaning dead processes
1075 self::killStaleWorkers();
1079 * Spawns a new worker
1081 * @param bool $do_cron
1083 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1085 public static function spawnWorker($do_cron = false)
1087 $command = 'bin/worker.php';
1089 $args = ['no_cron' => !$do_cron];
1092 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), $a->getBasePath());
1093 $process->run($command, $args);
1095 // after spawning we have to remove the flag.
1096 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1097 self::IPCSetJobState(false);
1102 * Adds tasks to the worker queue
1104 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1106 * next args are passed as $cmd command line
1107 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1108 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1110 * @return boolean "false" if worker queue entry already existed or there had been an error
1111 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1112 * @note $cmd and string args are surrounded with ""
1118 public static function add($cmd)
1120 $args = func_get_args();
1122 if (!count($args)) {
1126 $arr = ['args' => $args, 'run_cmd' => true];
1128 Hook::callAll("proc_run", $arr);
1129 if (!$arr['run_cmd'] || !count($args)) {
1133 $priority = PRIORITY_MEDIUM;
1134 // Don't fork from frontend tasks by default
1135 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1136 $created = DateTimeFormat::utcNow();
1137 $force_priority = false;
1139 $run_parameter = array_shift($args);
1141 if (is_int($run_parameter)) {
1142 $priority = $run_parameter;
1143 } elseif (is_array($run_parameter)) {
1144 if (isset($run_parameter['priority'])) {
1145 $priority = $run_parameter['priority'];
1147 if (isset($run_parameter['created'])) {
1148 $created = $run_parameter['created'];
1150 if (isset($run_parameter['dont_fork'])) {
1151 $dont_fork = $run_parameter['dont_fork'];
1153 if (isset($run_parameter['force_priority'])) {
1154 $force_priority = $run_parameter['force_priority'];
1158 $parameters = json_encode($args);
1159 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1162 // Quit if there was a database error - a precaution for the update process to 3.5.3
1163 if (DBA::errorNo() != 0) {
1168 $added = DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1172 } elseif ($force_priority) {
1173 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1176 // Should we quit and wait for the worker to be called as a cronjob?
1181 // If there is a lock then we don't have to check for too much worker
1182 if (!DI::lock()->acquire('worker', 0)) {
1186 // If there are already enough workers running, don't fork another one
1187 $quit = self::tooMuchWorkers();
1188 DI::lock()->release('worker');
1194 // We tell the daemon that a new job entry exists
1195 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1196 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1200 // Now call the worker to execute the jobs that we just added to the queue
1201 self::spawnWorker();
1207 * Returns the next retrial level for worker jobs.
1208 * This function will skip levels when jobs are older.
1210 * @param array $queue Worker queue entry
1211 * @param integer $max_level maximum retrial level
1212 * @return integer the next retrial level value
1214 private static function getNextRetrial($queue, $max_level)
1216 $created = strtotime($queue['created']);
1217 $retrial_time = time() - $created;
1219 $new_retrial = $queue['retrial'] + 1;
1221 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1222 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1224 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1225 $new_retrial = $retrial;
1228 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1229 return $new_retrial;
1233 * Defers the current worker entry
1235 * @return boolean had the entry been deferred?
1237 public static function defer()
1239 if (empty(DI::app()->queue)) {
1243 $queue = DI::app()->queue;
1245 $retrial = $queue['retrial'];
1247 $priority = $queue['priority'];
1249 $max_level = DI::config()->get('system', 'worker_defer_limit');
1251 $new_retrial = self::getNextRetrial($queue, $max_level);
1253 if ($new_retrial > $max_level) {
1254 Logger::info('The task exceeded the maximum retry count', ['id' => $id, 'created' => $queue['created'], 'old_prio' => $queue['priority'], 'old_retrial' => $queue['retrial'], 'max_level' => $max_level, 'retrial' => $new_retrial]);
1258 // Calculate the delay until the next trial
1259 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1260 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1262 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1263 $priority = PRIORITY_MEDIUM;
1264 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1265 $priority = PRIORITY_LOW;
1266 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1267 $priority = PRIORITY_NEGLIGIBLE;
1270 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1272 $stamp = (float)microtime(true);
1273 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1274 DBA::update('workerqueue', $fields, ['id' => $id]);
1275 self::$db_duration += (microtime(true) - $stamp);
1276 self::$db_duration_write += (microtime(true) - $stamp);
1282 * Log active processes into the "process" table
1284 public static function startProcess()
1286 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1288 $command = basename($trace[0]['file']);
1290 Process::deleteInactive();
1292 Process::insert($command);
1296 * Remove the active process from the "process" table
1299 * @throws \Exception
1301 public static function endProcess()
1303 return Process::deleteByPid();
1307 * Set the flag if some job is waiting
1309 * @param boolean $jobs Is there a waiting job?
1310 * @throws \Exception
1312 public static function IPCSetJobState($jobs)
1314 $stamp = (float)microtime(true);
1315 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1316 self::$db_duration += (microtime(true) - $stamp);
1317 self::$db_duration_write += (microtime(true) - $stamp);
1321 * Checks if some worker job waits to be executed
1324 * @throws \Exception
1326 public static function IPCJobsExists()
1328 $stamp = (float)microtime(true);
1329 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1330 self::$db_duration += (microtime(true) - $stamp);
1332 // When we don't have a row, no job is running
1333 if (!DBA::isResult($row)) {
1337 return (bool)$row['jobs'];